示例#1
0
    def handle_facebook_login(self, data):
        c = Client(
            token_endpoint='https://graph.facebook.com/oauth/access_token',
            resource_endpoint='https://graph.facebook.com',
            redirect_uri='http://localhost/login/facebook',
            client_id=config['facebook.client_id'],
            client_secret=config['facebook.client_secret'])

        c.request_token(code=data['code'],
            parser=lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        d = c.request('/me')
        self.dump_response(d)

        try:
            d = c.request('/me/feed', data=urlencode({
                'message': 'test post from py-sanction'
            }))
            self.wfile.write(
                'I posted a message to your wall (in sandbox mode, nobody '
                'else will see it)'.encode(ENCODING_UTF8))
        except:
            self.wfile.write(
                'Unable to post to your wall')
示例#2
0
    def authenticate(self, code=None, provider_key=None):
        """ Django API function, authenticating a user

        Authentication method required of a Django authentication backend. If
        successful, this method will retrieve an access token from the
        provider.

        :note: A method ``fetch_user`` is expected as a static function on the
               custom user class. This is responsible for retrieiving the
               actual user instance required by the Django backend. It will
               receive the ``provider_key`` and an instance of a sanction
               client (which should contain the access token)

        :param code: The code returned by the OAuth 2.0 provider once the user
                     has given your application authorization.
        :param provider_key: The key for the provider sending authorization
                             data. This should match the keys used in your
                             settings file for ``SANCTION_PROVIDERS``.
        """
        model = get_user_model()
        provider = settings.SANCTION_PROVIDERS[provider_key]

        c = SanctionClient(token_endpoint=provider['token_endpoint'],
                           resource_endpoint=provider['resource_endpoint'],
                           auth_endpoint=provider['auth_endpoint'],
                           client_id=provider['client_id'],
                           client_secret=provider['client_secret'],
                           redirect_uri=provider['redirect_uri'])

        c.request_token(code=code, parser=provider.get('parser', None))

        return model.fetch_user(provider_key, c)
示例#3
0
	def handle_facebook_login(self, data):
		self.send_response(200)
		self.send_header("Content-type", "text/html")
		self.log_message(self.path)
		self.end_headers()

		c = Client(
			token_endpoint="https://graph.facebook.com/oauth/access_token",
			resource_endpoint="https://graph.facebook.com",
			redirect_uri="http://localhost:8080/login/facebook",
			client_id=config["facebook.client_id"],
			client_secret=config["facebook.client_secret"])
		c.request_token(data=data, 
			parser = lambda data: dict(parse_qsl(data)))

		d = c.request("/me")

		self.wfile.write("Access token: %s<br>" % c.access_token)
		self.wfile.write("First name: %s<br>" % d["first_name"])
		self.wfile.write("Last name: %s<br>" % d["last_name"])
		self.wfile.write("Email: %s<br>" % d["email"])

		# to see a wall post in action, uncomment this
		try:
			d = c.request("/me/feed", data=urlencode({
				"message": "test post from py-sanction"
			}))
			self.wfile.write(
				"I posted a message to your wall (in sandbox mode, nobody else will see it)")
		except:
			self.wfile.write(
				"Unable to post to your wall")
示例#4
0
	def handle_foursquare_login(self, data):
		self.send_response(200)
		self.send_header("Content-type", "text/html")
		self.log_message(self.path)
		self.end_headers()

		c = Client(
			token_endpoint="https://foursquare.com/oauth2/access_token",
			resource_endpoint="https://api.foursquare.com/v2",
			redirect_uri="http://localhost:8080/login/foursquare",
			client_id=config["foursquare.client_id"],
			client_secret=config["foursquare.client_secret"],
			)
		c.access_token_key = "oauth_token"
		c.request_token(data=data)

		d = c.request("/users/24700343")

		self.wfile.write("Access token: %s<br>" % c.access_token)
		self.wfile.write("First name: %s<br>" % 
			d["response"]["user"]["firstName"])
		self.wfile.write("Last name: %s<br>" % 
			d["response"]["user"]["lastName"])
		self.wfile.write("Email: %s<br>" % 
			d["response"]["user"]["contact"]["email"])
示例#5
0
    def handle_foursquare_login(self, data):
        def token_transport(url, access_token, data=None, method=None):
            parts = urlsplit(url)
            query = dict(parse_qsl(parts.query))
            query.update({
                'oauth_token': access_token
            })
            url = urlunsplit((parts.scheme, parts.netloc, parts.path,
                urlencode(query), parts.fragment))
            try:
                req = Request(url, data=data, method=method)
            except TypeError:
                req = Request(url, data=data)
                req.get_method = lambda: method
            return req

        c = Client(
            token_endpoint='https://foursquare.com/oauth2/access_token',
            resource_endpoint='https://api.foursquare.com/v2',
            redirect_uri='http://localhost/login/foursquare',
            client_id=config['foursquare.client_id'],
            client_secret=config['foursquare.client_secret'],
            token_transport=token_transport
            )
        c.request_token(code=data['code'])

        self.dump_client(c)
        d = c.request('/users/24700343')
        self.dump_response(d)
示例#6
0
    def authenticate(self, code=None, provider_key=None):
        """ Django API function, authenticating a user

        Authentication method required of a Django authentication backend. If
        successful, this method will retrieve an access token from the
        provider.

        :note: A method ``fetch_user`` is expected as a static function on the
               custom user class. This is responsible for retrieiving the
               actual user instance required by the Django backend. It will
               receive the ``provider_key`` and an instance of a sanction
               client (which should contain the access token)

        :param code: The code returned by the OAuth 2.0 provider once the user
                     has given your application authorization.
        :param provider_key: The key for the provider sending authorization
                             data. This should match the keys used in your
                             settings file for ``SANCTION_PROVIDERS``.
        """
        model = get_user_model()
        provider = settings.SANCTION_PROVIDERS[provider_key]
        
        c = SanctionClient(token_endpoint=provider['token_endpoint'],
            resource_endpoint=provider['resource_endpoint'],
            auth_endpoint=provider['auth_endpoint'],
            client_id=provider['client_id'],
            client_secret=provider['client_secret'],
            redirect_uri=provider['redirect_uri'])

        c.request_token(code=code, parser=provider.get('parser', None))

        return model.fetch_user(provider_key, c)
示例#7
0
文件: tests.py 项目: brianru/sanction
    def test_request_token(self):
        c = Client(token_endpoint=token_endpoint)

        try:
            c.request_token()
            self.fail()
        except:
            pass
示例#8
0
文件: dreamon.py 项目: fugu13/dreamon
def callback():
    client = Client(token_endpoint='https://api.sandbox.slcedu.org/api/oauth/token',
        resource_endpoint='https://api.sandbox.slcedu.org/api/rest/v1',
        client_id=client_id, client_secret=shared_secret,
        redirect_uri='http://slcgoals.cloudapp.net/callback')
    client.request_token(code=request.args['code'])
    access_token = client.access_token
    login_user(load_user(access_token))
    return redirect('/')
示例#9
0
	def test_request_token(self):
		# i don't want to bother mocking an oauth2 server, so i'm just going
		# to test failure cases and rely on manual testing for correct ones

		c = Client()
		try:
			c.request_token({ "error": "something bad happened" })
			self.fail("shouldn't hit here")
		except IOError:
			pass
示例#10
0
    def handle_instagram_login(self, data):
        c = Client(token_endpoint="https://api.instagram.com/oauth/access_token",
            resource_endpoint="https://api.instagram.com/v1",
            redirect_uri="http://localhost/login/instagram",
            client_id=config["instagram.client_id"],
            client_secret=config["instagram.client_secret"])
        c.request_token(code=data["code"])

        self.dump_client(c)
        data = c.request("/users/self")["data"]
        self.dump_response(data)
示例#11
0
    def handle_instagram_login(self, data):
        c = Client(token_endpoint='https://api.instagram.com/oauth/access_token',
            resource_endpoint='https://api.instagram.com/v1',
            redirect_uri='http://localhost/login/instagram',
            client_id=config['instagram.client_id'],
            client_secret=config['instagram.client_secret'])
        c.request_token(code=data['code'])

        self.dump_client(c)
        data = c.request('/users/self')['data']
        self.dump_response(data)
示例#12
0
    def handle_deviantart_login(self, data):
        c = Client(
            token_endpoint='https://www.deviantart.com/oauth2/draft15/token',
            resource_endpoint='https://www.deviantart.com/api/draft15',
            redirect_uri=config['deviantart.redirect_uri'],
            client_id=config['deviantart.client_id'],
            client_secret=config['deviantart.client_secret'])
        c.request_token(code=data['code'])

        self.dump_client(c)
        data = c.request('/user/whoami')
        self.dump_response(data)
示例#13
0
    def handle_bitly_login(self, data):
        c = Client(token_endpoint="https://api-ssl.bitly.com/oauth/access_token",
            resource_endpoint="https://api-ssl.bitly.com",
            redirect_uri="http://localhost/login/bitly",
            client_id=config["bitly.client_id"],
            client_secret=config["bitly.client_secret"])
        c.request_token(code=data["code"],
            parser=lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        data = c.request("/v3/user/info")["data"]
        self.dump_response(data)
示例#14
0
    def handle_bitly_login(self, data):
        c = Client(token_endpoint='https://api-ssl.bitly.com/oauth/access_token',
            resource_endpoint='https://api-ssl.bitly.com',
            redirect_uri='http://localhost/login/bitly',
            client_id=config['bitly.client_id'],
            client_secret=config['bitly.client_secret'])
        c.request_token(code=data['code'],
            parser=lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        data = c.request('/v3/user/info')['data']
        self.dump_response(data)
示例#15
0
    def handle_deviantart_login(self, data):
        c = Client(
            token_endpoint="https://www.deviantart.com/oauth2/draft15/token",
            resource_endpoint="https://www.deviantart.com/api/draft15",
            redirect_uri=config["deviantart.redirect_uri"],
            client_id=config["deviantart.client_id"],
            client_secret=config["deviantart.client_secret"])
        c.request_token(code=data["code"])

        self.dump_client(c)
        data = c.request("/user/whoami")
        self.dump_response(data)
示例#16
0
    def handle_github_login(self, data):
        c = Client(token_endpoint="https://github.com/login/oauth/access_token",
            resource_endpoint="https://api.github.com",
            redirect_uri="http://localhost/login/github",
            client_id=config["github.client_id"],
            client_secret=config["github.client_secret"])
        c.request_token(code=data["code"],
            parser=lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        data = c.request("/user")
        self.dump_response(data)
示例#17
0
    def handle_github_login(self, data):
        c = Client(token_endpoint='https://github.com/login/oauth/access_token',
            resource_endpoint='https://api.github.com',
            redirect_uri='http://localhost/login/github',
            client_id=config['github.client_id'],
            client_secret=config['github.client_secret'])
        c.request_token(code=data['code'],
            parser=lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        data = c.request('/user')
        self.dump_response(data)
示例#18
0
文件: tests.py 项目: brianru/sanction
    def test_facebook_client_credentials(self):
        c = Client(
            token_endpoint="https://graph.facebook.com/oauth/access_token",
            resource_endpoint="https://graph.facebook.com",
            client_id="285809954824916",
            client_secret="d985f6a3ecaffd11d61b3cd026b8753a")

        self.assertEquals(c.access_token, None)
        c.request_token(parser=lambda data: dict(parse_qsl(data)),
            grant_type="client_credentials")
        self.assertIsNotNone(c.access_token)

        data = c.request("/app")
        self.assertEquals(data["name"], "sanction")
示例#19
0
    def handle_foursquare_login(self, data):
        c = Client(
            token_endpoint="https://foursquare.com/oauth2/access_token",
            resource_endpoint="https://api.foursquare.com/v2",
            redirect_uri="http://localhost/login/foursquare",
            client_id=config["foursquare.client_id"],
            client_secret=config["foursquare.client_secret"],
            )
        c.access_token_key = "oauth_token"
        c.request_token(code=data["code"])

        self.dump_client(c)
        d = c.request("/users/24700343")
        self.dump_response(d)
示例#20
0
    def handle_foursquare_login(self, data):
        c = Client(
            token_endpoint='https://foursquare.com/oauth2/access_token',
            resource_endpoint='https://api.foursquare.com/v2',
            redirect_uri='http://localhost/login/foursquare',
            client_id=config['foursquare.client_id'],
            client_secret=config['foursquare.client_secret'],
            )
        c.access_token_key = 'oauth_token'
        c.request_token(code=data['code'])

        self.dump_client(c)
        d = c.request('/users/24700343')
        self.dump_response(d)
示例#21
0
    def handle_stackexchange_login(self, data):
        c = Client(token_endpoint='https://stackexchange.com/oauth/access_token',
            resource_endpoint='https://api.stackexchange.com/2.0',
            redirect_uri='http://localhost/login/stackexchange',
            client_id=config['stackexchange.client_id'],
            client_secret=config['stackexchange.client_secret'])

        c.request_token(code=data['code'],
            parser = lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        data = c.request('/me', qs={
            'site': 'stackoverflow.com',
            'key': config['stackexchange.key']
            }, parser=lambda c: loads(self.__gunzip(c)))['items'][0]

        self.dump_response(data)
示例#22
0
    def handle_stackexchange_login(self, data):
        c = Client(token_endpoint="https://stackexchange.com/oauth/access_token",
            resource_endpoint="https://api.stackexchange.com/2.0",
            redirect_uri="http://localhost/login/stackexchange",
            client_id=config["stackexchange.client_id"],
            client_secret=config["stackexchange.client_secret"])

        c.request_token(code=data["code"],
            parser = lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        data = c.request("/me", qs={
            "site": "stackoverflow.com",
            "key": config["stackexchange.key"]
            }, parser=lambda c: loads(self.__gunzip(c)))["items"][0]

        self.dump_response(data)
示例#23
0
	def handle_bitly_login(self, data):
		self.send_response(200)
		self.send_header("Content-type", "text/html")
		self.log_message(self.path)
		self.end_headers()

		c = Client(token_endpoint="https://api-ssl.bitly.com/oauth/access_token",
			resource_endpoint="https://api-ssl.bitly.com",
			redirect_uri="http://localhost:8080/login/bitly",
			client_id=config["bitly.client_id"],
			client_secret=config["bitly.client_secret"])
		c.request_token(data=data,
			parser = lambda data: dict(parse_qsl(data)))

		self.wfile.write("Access token: %s<br>" % c.access_token)

		data = c.request("/v3/user/info")["data"]
		self.wfile.write("Full name: %s<br>" % data["full_name"])
		self.wfile.write("Member since: %s<br>" % data["member_since"])
示例#24
0
	def handle_instagram_login(self, data):
		self.send_response(200)
		self.send_header("Content-type", "text/html")
		self.log_message(self.path)
		self.end_headers()

		c = Client(token_endpoint="https://api.instagram.com/oauth/access_token",
			resource_endpoint="https://api.instagram.com/v1",
			redirect_uri="http://localhost:8080/login/instagram",
			client_id=config["instagram.client_id"],
			client_secret=config["instagram.client_secret"])
		c.request_token(data=data)

		self.wfile.write("Access token: %s<br>" % c.access_token)

		data = c.request("/users/self")["data"]
		self.wfile.write("Full name: %s<br>" % data["full_name"])
		self.wfile.write("User name: %s<br>" % data["username"])
		self.wfile.write("Profile picture: <img src='%s' /><br>" % data["profile_picture"])
示例#25
0
	def handle_google_login(self, data):
		self.send_response(200)
		self.send_header("Content-type", "text/html")
		self.log_message(self.path)
		self.end_headers()

		c = Client(token_endpoint="https://accounts.google.com/o/oauth2/token",
			resource_endpoint="https://www.googleapis.com/oauth2/v1",
			redirect_uri="http://localhost:8080/login/google",
			client_id=config["google.client_id"],
			client_secret=config["google.client_secret"])
		c.request_token(data=data)

		self.wfile.write("Access token: %s<br>" % c.access_token)

		data = c.request("/userinfo")
		self.wfile.write("First name: %s<br>" % data["name"])
		self.wfile.write("Last name: %s<br>" % data["family_name"])
		self.wfile.write("Email: %s<br>" % data["email"])
示例#26
0
	def handle_github_login(self, data):
		self.send_response(200)
		self.send_header("Content-type", "text/html")
		self.log_message(self.path)
		self.end_headers()

		c = Client(token_endpoint="https://github.com/login/oauth/access_token",
			resource_endpoint="https://api.github.com",
			redirect_uri="http://localhost:8080/login/github",
			client_id=config["github.client_id"],
			client_secret=config["github.client_secret"])
		c.request_token(data=data,
			parser = lambda data: dict(parse_qsl(data)))

		self.wfile.write("Access token: %s<br>" % c.access_token)

		data = c.request("/user")
		self.wfile.write("Full name: %s<br>" % data["name"])
		self.wfile.write("Location: %s<br>" % data["location"])
		self.wfile.write("Hireable: %s<br>" % data["hireable"])
示例#27
0
def shoe():
    if 'shoe_client' in session:
        c = session['shoe_client']
    else:
        c = Client(
            auth_endpoint=AUTH_URL,
            token_endpoint=TOKEN_URL,
            resource_endpoint=API_BASE,
            redirect_uri=REDIRECT_URL,
            client_id=CLIENT_ID,
            client_secret=CLIENT_KEY
        )

    if hasattr(c, 'refresh_token'):
        c.request_token(grant_type="refresh_token",
                        refresh_token=c.refresh_token)
        # XXX: Refactor this to be only when we're expired or something.

    session['shoe_client'] = c
    return c
示例#28
0
    def handle_google_login(self, data):
        c = Client(token_endpoint="https://accounts.google.com/o/oauth2/token",
            resource_endpoint="https://www.googleapis.com/oauth2/v1",
            redirect_uri="http://localhost/login/google",
            client_id=config["google.client_id"],
            client_secret=config["google.client_secret"])
        c.request_token(code=data["code"])

        self.dump_client(c)
        data = c.request("/userinfo")
        self.dump_response(data)

        if hasattr(c, "refresh_token"):
            rc = Client(token_endpoint=c.token_endpoint,
                client_id=c.client_id,
                client_secret=c.client_secret,
                resource_endpoint=c.resource_endpoint)

            rc.request_token(grant_type="refresh_token", 
                refresh_token=c.refresh_token)
            self.wfile.write("<p>post refresh token:</p>")
            self.dump_client(rc)
示例#29
0
    def handle_google_login(self, data):
        c = Client(token_endpoint='https://accounts.google.com/o/oauth2/token',
            resource_endpoint='https://www.googleapis.com/oauth2/v1',
            redirect_uri='http://localhost/login/google',
            client_id=config['google.client_id'],
            client_secret=config['google.client_secret'])
        c.request_token(code=data['code'])

        self.dump_client(c)
        data = c.request('/userinfo')
        self.dump_response(data)

        if hasattr(c, 'refresh_token'):
            rc = Client(token_endpoint=c.token_endpoint,
                client_id=c.client_id,
                client_secret=c.client_secret,
                resource_endpoint=c.resource_endpoint)

            rc.request_token(grant_type='refresh_token', 
                refresh_token=c.refresh_token)
            self.wfile.write('<p>post refresh token:</p>'.encode(ENCODING_UTF8))
            self.dump_client(rc)
示例#30
0
    def handle_facebook_login(self, data):
        c = Client(
            token_endpoint="https://graph.facebook.com/oauth/access_token",
            resource_endpoint="https://graph.facebook.com",
            redirect_uri="http://localhost/login/facebook",
            client_id=config["facebook.client_id"],
            client_secret=config["facebook.client_secret"])

        c.request_token(code=data["code"],
            parser=lambda data: dict(parse_qsl(data)))

        self.dump_client(c)
        d = c.request("/me")
        self.dump_response(d)

        try:
            d = c.request("/me/feed", data=urlencode({
                "message": "test post from py-sanction"
            }))
            self.wfile.write(
                "I posted a message to your wall (in sandbox mode, nobody else will see it)")
        except:
            self.wfile.write(
                "Unable to post to your wall")
示例#31
0
def refresh_access_token(request, credential_uid):
     
    args = dict(request.REQUEST.iteritems())

    credentials = get_credentials(credential_uid)        
    if credentials is None:
        return HttpResponse(content="Application identifier not found", status=404)
       
    try:
        refresh_token = args['refresh_token']   
    except KeyError:
        return HttpResponse(content="Refresh token not provided", status=404)
        
    #provide addtional parameters needed to refresh token     
    params = {'grant_type': "refresh_token",
              'refresh_token': refresh_token}
    
    #initialize client with needed values 
    c = Client(   
        token_endpoint = credentials.token_endpoint,       
        client_id = credentials.app_api_key,
        client_secret = credentials.app_secret,)                    

    #request a new access token 
    c.request_token(token_response_parser, **params)
            
    #to check if we received a new refresh token as well
    if hasattr(c, 'refresh_token'):
        new_refresh_token = c.refresh_token        
    else:
        new_refresh_token = ""
     
    json_response = json.dumps({"access_token": c.access_token,
                                "refresh_token": new_refresh_token })
     
    return HttpResponse(json_response, "application/json")