Ejemplo n.º 1
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',
                   client_id=config['foursquare.client_id'],
                   client_secret=config['foursquare.client_secret'],
                   token_transport=token_transport)
        c.request_token(code=data['code'],
                        redirect_uri='http://localhost/login/foursquare')

        self.dump_client(c)
        d = c.request('/users/24700343')
        self.dump_response(d)
Ejemplo n.º 2
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',
            client_id=config['foursquare.client_id'],
            client_secret=config['foursquare.client_secret'],
            token_transport=token_transport
            )
        c.request_token(code=data['code'],
            redirect_uri='http://localhost/login/foursquare')

        self.dump_client(c)
        d = c.request('/users/24700343')
        self.dump_response(d)
Ejemplo n.º 3
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',
                   client_id=config['google.client_id'],
                   client_secret=config['google.client_secret'],
                   token_transport=transport_headers)
        c.request_token(code=data['code'],
                        redirect_uri='http://localhost/login/google')

        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,
                        token_transport='headers')

            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)
Ejemplo n.º 4
0
    def handle_facebook_login(self, data):
        c = Client(
            token_endpoint='https://graph.facebook.com/oauth/access_token',
            resource_endpoint='https://graph.facebook.com',
            client_id=config['facebook.client_id'],
            client_secret=config['facebook.client_secret'])

        c.request_token(code=data['code'],
                        redirect_uri='http://localhost/login/facebook')

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

        try:
            d = c.request('/me/feed',
                          data=bytes(
                              urlencode(
                                  {'message': 'test post from py-sanction'}),
                              'ascii'))
            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(b'Unable to post to your wall')
Ejemplo n.º 5
0
def get_token(grant_type):
    client = Client(token_endpoint=get_config()["42.token_url"],
                    resource_endpoint=get_config()["42.endpoint"],
                    client_id=get_config()["42.client_id"],
                    client_secret=get_config()["42.client_secret"])
    client.request_token(grant_type=grant_type)
    return client
Ejemplo n.º 6
0
def get_token(grant_type):
    client = Client(token_endpoint="https://api.intra.42.fr/oauth/token",
                    resource_endpoint="https://api.intra.42.fr",
                    client_id=os.environ["INTRA_CLIENT_ID"],
                    client_secret=os.environ["INTRA_SECRET"])
    client.request_token(grant_type=grant_type)
    return client
Ejemplo n.º 7
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'])

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

        return model.fetch_user(provider_key, c)
Ejemplo n.º 8
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'])

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

        return model.fetch_user(provider_key, c)
Ejemplo n.º 9
0
class Brightidea(object):

	def __init__(self, auth_endpoint=None, token_endpoint=None,
        client_id=None, client_secret=None, redirect_uri=None, host_name=None):

		self.client = Client(
			token_endpoint=token_endpoint,
			auth_endpoint=auth_endpoint,
			client_id=client_id,
			client_secret=client_secret)

		self.token_time = mktime(gmtime())
		self.client.request_token(grant_type='client_credentials')
		self.client.resource_endpoint = 'https://' + host_name + '/api3'
		self.client.expires_in = 10

	def get(self, model, id):
		return self.call_api('/'+model+'/'+id)

	def list(self, model, values=None, page=None, page_size=None):
		
		url = '/'+model
		if values:
			url += '?' + urllib.urlencode(self.encoded_dict(values))
		if page:
			if '?' in url:
				url += '&' + urllib.quote_plus(page)
			else: 
				url += '?' + urllib.quote_plus(page)
		if page_size:
			if '?' in url:
				url += '&' + urllib.quote_plus(page_size)
			else: 
				url += '?' + urllib.quote_plus(page_size)

		return self.call_api(url)

	def create(self, model, values=None):
		return self.call_api('/'+model, "POST", urllib.urlencode(self.encoded_dict(values)))

	def update(self, model, id, values=None):
		return self.call_api('/'+model+'/'+id, "PUT", urllib.urlencode(self.encoded_dict(values), True))

	def call_api(self, url, method=None, data=None):
		# Check if the token has expired
		if self.client.expires_in-100 + self.token_time <= mktime(gmtime()):
			self.client.request_token(grant_type='client_credentials')

		return self.client.request(url, method, data)

	def encoded_dict(self, in_dict):
		out_dict = {}
		for k, v in in_dict.iteritems():
			if isinstance(v, unicode):
				v = v.encode('utf8')
			elif isinstance(v, str):
				v.decode('utf8')
			out_dict[k] = v
		return out_dict
Ejemplo n.º 10
0
def _make_code_post(code):
    client = Client(
        token_endpoint='https://accounts.google.com/o/oauth2/token',
        resource_endpoint='https://www.googleapis.com/oauth2/v1',
        client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    params = {"redirect_uri": REDIRECT_URI}
    client.request_token(code=code, **params)
    return client.access_token, client.refresh_token, client.expires_in
Ejemplo n.º 11
0
def make_refresh_post(refresh_token):
    client = Client(
        token_endpoint='https://accounts.google.com/o/oauth2/token',
        resource_endpoint='https://www.googleapis.com/oauth2/v1',
        client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    params = {"grant_type": "refresh_token"}
    client.request_token(refresh_token=refresh_token, **params)
    return client.access_token, client.expires_in
Ejemplo n.º 12
0
def make_refresh_post(refresh_token):
    client = Client(
        token_endpoint='https://accounts.google.com/o/oauth2/token',
        resource_endpoint='https://www.googleapis.com/oauth2/v1',
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET)
    params = {"grant_type": "refresh_token"}
    client.request_token(refresh_token=refresh_token, **params)
    return client.access_token, client.expires_in
Ejemplo n.º 13
0
def _make_code_post(code, redirect_uri):
    client = Client(
        token_endpoint='https://accounts.google.com/o/oauth2/token',
        resource_endpoint='https://www.googleapis.com/oauth2/v1',
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET)
    params = {"redirect_uri": redirect_uri}
    client.request_token(code=code, **params)
    return client.access_token, client.refresh_token, client.expires_in
Ejemplo n.º 14
0
def finish_github_login():
    c = Client(token_endpoint=GITHUB_TOKEN_ENDPOINT,
        resource_endpoint=GITHUB_RESOURCE_ENDPOINT,
        client_id=current_app.config['GITHUB_OAUTH_CLIENT_ID'],
        client_secret=current_app.config['GITHUB_OAUTH_CLIENT_SECRET'],
    )
    c.request_token(code=request.args['code'], redirect_uri=OAUTH_REDIRECT_URI)
    user_data = c.request('/user')
    print("USER:"******"Hello person!"
Ejemplo n.º 15
0
    def handle_github_login(self, data):
        c = Client(token_endpoint='https://github.com/login/oauth/access_token',
            resource_endpoint='https://api.github.com',
            client_id=config['github.client_id'],
            client_secret=config['github.client_secret'])
        c.request_token(code=data['code'],
            redirect_uri='http://localhost/login/github')

        self.dump_client(c)
        data = c.request('/user')
        self.dump_response(data)
Ejemplo n.º 16
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',
            client_id=config['instagram.client_id'],
            client_secret=config['instagram.client_secret'])
        c.request_token(code=data['code'],
            redirect_uri='http://localhost/login/instagram')

        self.dump_client(c)
        data = c.request('/users/self')['data']
        self.dump_response(data)
Ejemplo n.º 17
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',
            client_id=config['instagram.client_id'],
            client_secret=config['instagram.client_secret'])
        c.request_token(code=data['code'],
                        redirect_uri='http://localhost/login/instagram')

        self.dump_client(c)
        data = c.request('/users/self')['data']
        self.dump_response(data)
Ejemplo n.º 18
0
    def handle_github_login(self, data):
        c = Client(
            token_endpoint='https://github.com/login/oauth/access_token',
            resource_endpoint='https://api.github.com',
            client_id=config['github.client_id'],
            client_secret=config['github.client_secret'])
        c.request_token(code=data['code'],
                        redirect_uri='http://localhost/login/github')

        self.dump_client(c)
        data = c.request('/user')
        self.dump_response(data)
Ejemplo n.º 19
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',
            client_id=config['deviantart.client_id'],
            client_secret=config['deviantart.client_secret'])
        c.request_token(code=data['code'],
                        redirect_uri=config['deviantart.redirect_uri'])

        self.dump_client(c)
        data = c.request('/user/whoami')
        self.dump_response(data)
Ejemplo n.º 20
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',
            client_id=config['deviantart.client_id'],
            client_secret=config['deviantart.client_secret'])
        c.request_token(code=data['code'],
            redirect_uri=config['deviantart.redirect_uri'])

        self.dump_client(c)
        data = c.request('/user/whoami')
        self.dump_response(data)
Ejemplo n.º 21
0
def openid_login(provider):
    """Return OAuth2 login view for the given provider.

    :param provider: OAuth2 provider.
    """

    # get parser for provider
    parser = eval(str.format('{0}_parser', provider.lower()))
    code = request.args.get('code')
    oauth_kwargs = current_app.config[str.format('OAUTH_{0}', provider.upper())]
    c = Client(**oauth_kwargs)
    # get request token
    c.request_token(parser=parser, redirect_uri=current_app.config['KINORSI_SERVER_HOST'], grant_type='authorization_code', code=code)

    if hasattr(c, 'error') and c.error != 0:
        current_app.logger.info(c.error_description)
        return redirect(url_for_security('login'))
    else:
        session[u'access_token'] = c.access_token
        session[u'refresh_token'] = c.refresh_token
        session[u'expires_in'] = c.expires_in
        # get open id
        res = c.request("/oauth2.0/me", parser=parser)
        res['oauth_consumer_key'] = res['client_id']
        # get nickname.
        user_info = c.request('/user/get_user_info?' + urllib.urlencode(res), method='GET', parser=parser)
        # 看看是不是已经在数据库中了,没有就写一个
        security = current_app.extensions['security']
        datastore = security.datastore
        user = datastore.find_user(openid=res['openid'], provider=provider.lower())
        if user is None:
            user = datastore.create_user(openid=res['openid'], provider=provider.lower(), nickname=user_info['nickname'], avatar=user_info['figureurl_qq_1'])
            datastore.commit()
        else:
            pass
            #print 'user :'******'is here'

        login_user(user)

        next_url = get_url(request.args.get('next')) or get_url(request.form.get('next')) \
            or current_app.extensions['security'].post_login_view or ''

        # 如果用户没有绑定,可以让用户尝试进行首次的帐号绑定。如果不绑也可以在以后再绑
        # 2014-12-5 先去掉绑定功能。不然似乎有点复杂过头了。
        if user.bind_username is None and user.bind_email is None and (user.bind_remind is None or user.bind_remind ):
            form_class = _security.login_form
            form = form_class()
            form.next.data = next_url

            return render_template('security/bind_user.html', bind_form=form)

        return redirect(next_url)
Ejemplo n.º 22
0
    def handle_jawbone_login(self, data):
        c = Client(token_endpoint='https://jawbone.com/auth/oauth2/token',
                   client_id='nEXyCKO3F3s',
                   client_secret='c9a66fc619ccb0e7c2c4e90e59200dfba8aea5de',
                   token_transport=transport_headers)
        c.request_token(grant_type='authorization_code', code=data['code'])
        #createInfo(c.access_token,c.token_expires)
        createDb = sqlite3.connect('key.db')
        updateInfo(c.access_token, c.token_expires)
        createDb.commit()

        #queryCurs.execute('UPDATE * FROM userinfo')

        self.dump_client(c)
        return
Ejemplo n.º 23
0
    def handle_jawbone_login(self, data):
        c = Client(token_endpoint='https://jawbone.com/auth/oauth2/token',
                   client_id='nEXyCKO3F3s',
                   client_secret='c9a66fc619ccb0e7c2c4e90e59200dfba8aea5de',
                   token_transport=transport_headers)
        c.request_token(grant_type='authorization_code', code=data['code'])

        #createInfo(c.access_token,c.token_expires)
        query = DatabaseManager('key.db')
        #maybe check if table doesn't exist and create it in DBMR__init__)
        query.updateInfo("UPDATE userinfo SET key = ?, expires = ?",
                         c.access_token, c.token_expires)
        del query

        self.dump_client(c)
        return
Ejemplo n.º 24
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',
            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)),
            redirect_uri='http://localhost/login/stackexchange')

        self.dump_client(c)
        data = c.request('/me?{}'.format(urlencode({
            'site': 'stackoverflow.com',
            'key': config['stackexchange.key']
            })), parser=lambda c: loads(self._gunzip(c).decode(
                'utf-8')))['items'][0]

        self.dump_response(data)
Ejemplo n.º 25
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',
            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)),
                        redirect_uri='http://localhost/login/stackexchange')

        self.dump_client(c)
        data = c.request('/me?{}'.format(
            urlencode({
                'site': 'stackoverflow.com',
                'key': config['stackexchange.key']
            })),
                         parser=lambda c: loads(
                             self._gunzip(c).decode('utf-8')))['items'][0]

        self.dump_response(data)
Ejemplo n.º 26
0
    def handle_facebook_login(self, data):
        c = Client(
            token_endpoint='https://graph.facebook.com/oauth/access_token',
            resource_endpoint='https://graph.facebook.com',
            client_id=config['facebook.client_id'],
            client_secret=config['facebook.client_secret'])

        c.request_token(code=data['code'],
            redirect_uri='http://localhost/login/facebook')

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

        try:
            d = c.request('/me/feed', data=bytes(urlencode({
                'message': 'test post from py-sanction'
            }), 'ascii'))
            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(
                b'Unable to post to your wall')
Ejemplo n.º 27
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',
            client_id=config['google.client_id'],
            client_secret=config['google.client_secret'],
            token_transport=transport_headers)
        c.request_token(code=data['code'],
            redirect_uri='http://localhost/login/google')

        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,
                token_transport='headers')

            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)
Ejemplo n.º 28
0
def make_bc_call(request_url):
    """
    Uses stored credentials to try and make Brightcove API calls
    :param request_url:
    :return:
    """
    token_request_url = "https://oauth.brightcove.com/v3/access_token"
    resource_base = "https://data.brightcove.com/"

    for credential in BCCredentials.objects.all():
        content = None
        try:
            client = Client(
                token_endpoint=token_request_url,
                resource_endpoint=resource_base,
                client_id=credential.client_id,
                client_secret=credential.client_secret, )
            client.request_token(grant_type='client_credentials')
            content = client.request(request_url)
            break
        except Exception as e:
            pass

        return content
Ejemplo n.º 29
0
class Yelp3Client:
    def __init__(self, client_id, client_secret):
        self.client = Client(
            token_endpoint="https://api.yelp.com/oauth2/token",
            resource_endpoint="https://api.yelp.com/v3",
            client_id=client_id,
            client_secret=client_secret)

    def refreshAccessToken(self):
        if self.client.access_token is not None:
            from datetime import datetime, timedelta
            from time import mktime
            now = mktime(datetime.utcnow().timetuple()) + 60
            if now <= self.client.token_expires:
                return self.client.access_token
        self.client.request_token(grant_type="client_credentials")
        return self.client.access_token

    def request(self, endpoint):
        access_token = self.refreshAccessToken()
        return self.client.request(
            endpoint,
            method="GET",
            headers={'Authorization': 'Bearer {0}'.format(access_token)})
Ejemplo n.º 30
0
def main():

    # instantiating a client to process OAuth2 response
    c = Client(
        auth_endpoint=auth_endpoint,
        token_endpoint=token_endpoint,
        resource_endpoint=resource_endpoint,
        client_id=client_id,
        client_secret=client_secret,
        token_transport=transport_headers)

    # 3-legged (read/write)
    scope_req = 'public rides.read rides.request'
    url = c.auth_uri(scope=scope_req, scope_delim=' ', state='asdf')

    print "Welcome to the API client tool for"
    print ""
    print "    IIIII7MMMMMMMMMMMMMMMMMMM7IIIIIII7MMMMMM"
    print "    IIIII7MMMMMMMMMMMMMMMMMIIIIIIIIIIII7MMMM"
    print "    IIIII7MMMMMMMMMMMMMMMMIIIIIIIIIIIIIIIMMM"
    print "    IIIII7MMMMMMMMMMMMMMMMIIIIII7M7IIIIIIMMM"
    print "    IIIII7MIIIIIIMNIIIIIZDIIIIINMMMZIIIIIIIM"
    print "    IIIII7MIIIIIIMNIIIIIZ8IIIIIMMMM8IIIIIIIM"
    print "    IIIII7MIIIIIIMNIIIIIZ8IIIIIIIIN8IIIIIIIM"
    print "    IIIII7MIIIIIIMNIIIIIZ8IIIIIIIIN8IIIIIMMM"
    print "    IIIII7MIIIIIIMNIIIIIZ8IIIIIIIIN8IIIIIMMM"
    print "    IIIII7MIIIIIIMIIIIIIZ8IIIII777NMIIIII7MM"
    print "    IIIII7MIIIIIIIIIIIIIZ8IIIIIMMMMMIIIIIIID"
    print "    IIIIIIMIIIIIIIIIIIIIZ8IIIIIMMMMMMIIIIIID"
    print "    MIIIII7MIIIIIIIIIIIIO8III7MMMMMMMMMIIIID"
    print "    MMD7IIIMMMMMMMIIIIIIMD78MMMMMMMMMMMMMMOD"
    print "    MMMMMMMMNIIIIIIIIIIIMMMMMMMMMMMMMMMMMMMM"
    print "    MMMMMMMMNIIIIIIIIIIMMMMMMMMMMMMMMMMMMMMM"
    print "    MMMMMMMMNIIIIIIII7MMMMMMMMMMMMMMMMMMMMMM"
    print "    MMMMMMMMMMMZ78MMMMMMMMMMMMMMMMMMMMMMMMMM"
    print ""
    print "STEP 1: Authenticate a user by opening this URL in a browser (Command + Double Click):\n\n%s" % url
    print ""
    code = raw_input("STEP 2: After authenticating, paste the 'code' parameter in the redirect URL here: ")

    result = c.request_token(grant_type='authorization_code', code=code)

    print "\nSTEP 3: There is no Step 3. You are now authenticated to the Lyft API. Congratulations!"

    print "\nEnter a URI to start testing. Some examples:\n\n\t%s --> ETA for location\n\t%s --> Rides for location" % (example_url_eta, example_url_rides)

    command = raw_input(prompt)

    while command != 'Q':

        try:

            method = "GET"
            data = None

            if " " in command:
                (method, command, data) = command.split(" ")

            result = c.request(command, method=method, data=data)
            pretty(result)

        except Exception as ex:

            import traceback
            traceback.print_exc()

        command = raw_input(prompt)
Ejemplo n.º 31
0
        redirect_uri = config['TDA']['redirect_uri']

    token_url = 'https://api.tdameritrade.com/v1/oauth2/token'       # token url - issues access tokens

    base_url = 'https://api.tdameritrade.com/v1/marketdata'

    # Instantiate a client to request an access token

    # this requires a previously issued refresh token
    # stored as an environment variable, e.g. client_secret = os.environ.get('autoTraderToken')
    c = Client(token_endpoint=token_url, resource_endpoint=base_url, client_id=client_id, \
               client_secret=client_secret)
    # Request an access token
    # Requests are throttled to 120 requests / minute or 1 request every 0.5 sec
    # Excessive token requests will be discouraged by TD Ameritrade - i.e. rate limiting by IP address, etc.
    c.request_token(grant_type='refresh_token', refresh_token=client_secret, redirect_uri=redirect_uri)

    # Price History API Request
    # ref for stocks: https://www.barchart.com/stocks/most-active/price-volume-leaders
    symbol = args.symbol

    #data1 = api_pricehistory(symbol)

    today = dt.now()
    marketStart = dt.combine(date.today(), datetime.time(0, 2))
    marketEnd =  dt.combine(date.today(), datetime.time(0, 3))
    if today > marketStart and today < marketEnd:
        print("Market open! :)")
        market_open = True
    else:
        print("Market closed :(")
Ejemplo n.º 32
0
def main():
    # script constants
    settings_filename = os.path.join(expanduser("~"), ".tstool.settings")
    master_client_id = '9161C1CB042E40F185771DD52A39048E'
    client_id = '4A2D7960D87346B995D34CA44F636E3A'
    client_secret = '24B87340107A49A385F6678C4E9062A8'

    shelf = shelve.open(settings_filename)
    if('secret' in shelf and 'email' in shelf):
        master_secret=shelf["secret"]
        email=shelf["email"]
    else:
        #get master secret through api
        client = Client(
            token_endpoint="https://auth.brightidea.com/_oauth2/token",
            client_id=client_id,
            client_secret=client_secret)
        client.resource_endpoint = 'https://bi.brightidea.com/api3'
        username = raw_input("Please enter your idea space account email: ")
        password = raw_input("Enter your password: "******"/apiAccount/"+master_client_id)
        master_secret = master_account["apiAccount"]["secret"]
        email=username

        shelf["secret"]=master_secret
        shelf["email"]=username
        shelf.sync()

    #Determine the browser
    if(sys.argv[1] == "chrome"):
        shelf["browser"]="chrome"
        shelf.sync()
        print("Browser is changed to Chrome")
        sys.exit()
    elif(sys.argv[1] == "safari"):
        shelf["browser"]="safari"
        shelf.sync()
        print("Browser is changed to Safari")
        sys.exit()
    elif(sys.argv[1] == "firefox"):
        shelf["browser"]="firefox"
        shelf.sync()
        print("Browser is changed to firefox")
        sys.exit()
    elif(sys.argv[1] == "custom"):
        shelf["browser"]="custom"
        shelf.sync()
        print("Browser is changed to custom")
        sys.exit()

    if('browser' in shelf):
        browser = shelf["browser"]
    else:
        browser = "safari"

    inputURL = urlparse(sys.argv[1])
    targetURL = urllib.quote(sys.argv[1])

    # API config
    bi = Brightidea(token_endpoint="https://"+inputURL.hostname+"/_oauth2/token",
    	client_id=master_client_id,
    	client_secret=master_secret,
        host_name=inputURL.hostname)

    access_token = bi.client.access_token

    login_url = "https://"+inputURL.hostname+"/api3/session/me?access_token="+access_token+"&target="+targetURL+"&email="+email
    
    if(sys.platform == "darwin"):
        if(browser == "safari"):
            call(["open","-a","Safari",login_url])
        elif(browser == "chrome"):
            call(["open","-a","Google Chrome",login_url])
    elif(sys.platform == "linux2"):
        if(browser == "chrome"):
            call(['google-chrome', login_url])
        elif(browser == "firefox"):
            call(['google-chrome', login_url])
        elif(browser == "custom"):
            print(login_url)
Ejemplo n.º 33
0
from sanction import Client

# The URL for access token requests
token_request_url = "https://oauth.brightcove.com/v3/access_token"

# Client ID and secret

# Your Client ID from your client credential
client_id = "762df048-1d42-468c-9d18-f023d524f94f"

# Your Client Secret from your client credential
client_secret = "s728iZUVU3YbBSJC4to_9UhYgVrxIVvIQL3OkypMSOudWg02lZk3tNDbPESUAiup0uJV_rBinbyQ70Vh7FSWLA"

# The base URL of the resource server
# The URL below is for the example resource server
resource_base = "https://data.brightcove.com/"

# Create the OAuth2 client object
client = Client(token_endpoint=token_request_url,
                resource_endpoint=resource_base,
                client_id=client_id,
                client_secret=client_secret)

# Request the access token into the client object
client.request_token(grant_type='client_credentials')

# Now make the resource request
# The path below is for the example resource server
print client.request(
    '/analytics-api/videocloud/account/12345/report?dimensions=video,player')
Ejemplo n.º 34
0
class TestClient(TestCase):
    def setUp(self):
        self.client = Client(auth_endpoint=AUTH_ENDPOINT,
            token_endpoint=TOKEN_ENDPOINT,
            resource_endpoint=RESOURCE_ENDPOINT,
            client_id=CLIENT_ID)

    def test_init(self):
        map(lambda c: self.assertEqual(*c),
            ((self.client.auth_endpoint, AUTH_ENDPOINT),
            (self.client.token_endpoint, TOKEN_ENDPOINT),
            (self.client.resource_endpoint, RESOURCE_ENDPOINT),
            (self.client.client_id, CLIENT_ID),))

    def test_auth_uri(self):
        parsed = urlparse(self.client.auth_uri(redirect_uri=REDIRECT_URI))
        qs = dict(parse_qsl(parsed.query))

        map(lambda c: self.assertEqual(*c),
            ((qs['redirect_uri'], REDIRECT_URI),
            (qs['response_type'], 'code'),
            (qs['client_id'], CLIENT_ID)))

        parsed = urlparse(self.client.auth_uri(scope=SCOPE))
        qs = dict(parse_qsl(parsed.query))

        self.assertEqual(qs['scope'], SCOPE)

        parsed = urlparse(self.client.auth_uri(state=STATE))
        qs = dict(parse_qsl(parsed.query))

        self.assertEqual(qs['state'], STATE)

    @with_patched_client(json.dumps({
        'access_token':'test_token',
        'expires_in': 300,
    }))
    def test_request_token_json(self):
        self.client.request_token()
        self.assertEqual(self.client.access_token, 'test_token')

        self.client.request_token(redirect_uri=REDIRECT_URI)
        self.assertEqual(self.client.access_token, 'test_token')

    @with_patched_client('access_token=test_token')
    def test_request_token_url(self):
        self.client.request_token()
        self.assertEqual(self.client.access_token, 'test_token')

    @with_patched_client(json.dumps({
        'access_token': 'refreshed_token',
    }))
    def test_refresh_token(self):
        self.client.refresh_token = 'refresh_token'
        self.client.refresh()
        self.assertEqual(self.client.access_token, 'refreshed_token')

    @with_patched_client(json.dumps({
        'userid': 1234
    }))
    def test_request(self):
        self.client.access_token = 'foo'
        data = self.client.request('/foo')
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(zlib.compress(json.dumps({
        'userid': 1234
    }).encode('utf8')))
    def test_request_custom_parser(self):
        def _decompress(buf):
            return json.loads(zlib.decompress(buf).decode())

        self.client.access_token = 'foo'
        data = self.client.request('/foo', parser=_decompress)
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({
        'userid': 1234
    }))
    def test_request_transport_headers(self):
        self.client.token_transport = transport_headers 
        self.client.access_token = 'foo'
        data = self.client.request('/foo')
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({
        'userid': 1234
    }), headers={
        'Content-Type': 'text/html; charset=utf-8',
    })
    def test_request_with_charset(self):
        self.client.access_token = 'foo'
        data = self.client.request('/foo')
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({
        'userid': 1234
    }))
    def test_custom_transport(self):
        def _transport(url, access_token, data=None, method=None,
            headers=None):

            self.assertEqual(url, 'http://example.com/resource/foo')
            self.assertEqual(access_token, 'foo')

        self.client.access_token = 'foo'
        self.client.token_transport = _transport
        data = self.client.request('/foo', headers={
            'Content-Type': 'application/json'})

        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({
        'userid': 1234
    }))
    def test_query_transport_with_headers(self):
        self.client.access_token = 'foo'
        data = self.client.request('/foo', headers={'Content-Type':
            'application/json'})

        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({
        'userid': 1234
    }))
    def test_header_transport_with_headers(self):
        self.client.access_token = 'foo'
        self.client.token_transport = transport_headers 
        data = self.client.request('/foo', headers={'Content-Type':
            'application/json'})

        self.assertEqual(data['userid'], 1234)
Ejemplo n.º 35
0
from sanction import Client

# instantiating a client to process OAuth2 response
client = Client(
    token_endpoint="http://karl.novareto.de:8085/token",
    resource_endpoint="http://karl.novareto.de:8085/resource",
    client_id="novareto",
    client_secret="test")

client.request_token(grant_type='client_credentials')
data = client.request('/')
print data
Ejemplo n.º 36
0
def main():
    # script constants
    settings_filename = os.path.join(expanduser("~"), ".tstool.settings")
    
    browsers = ['safari', 'chrome', 'firefox', 'clipboard']

    args = getArgs()
    env = args.env if args.env else ''

    if(env == "test"):
        master_client_id = '0414db0b148d483eb781a00ee970efc3'
        client_id = '9e9fb27d0e5b488eb5b70322cb65e0de'
        client_secret = 'd9fde1beae694aa2a2f727b791b6012b'
        domain = 'brightideatest'
        resource_endpoint = 'https://auth.brightideatest.com/api3'
    else:
        master_client_id = '9161C1CB042E40F185771DD52A39048E'
        client_id = '4A2D7960D87346B995D34CA44F636E3A'
        client_secret = '24B87340107A49A385F6678C4E9062A8'
        domain = 'brightidea'
        resource_endpoint = 'https://bi.brightidea.com/api3'


    shelf = shelve.open(settings_filename)
    if(env+'secret' in shelf and 'email' in shelf):
        master_secret=shelf[env+"secret"]
        email=shelf["email"]
    else:
        #get master secret through api
        client = Client(
            token_endpoint="https://auth."+domain+".com/_oauth2/token",
            client_id=client_id,
            client_secret=client_secret)
        client.resource_endpoint = resource_endpoint
        username = raw_input("Please enter your idea space account email: ")
        password = getpass.getpass('Enter your password: '******'password',username=username,password=password)

        master_account = client.request("/apiAccount/"+master_client_id)
        master_secret = master_account["apiAccount"]["secret"]
        email=username

        shelf[env+"secret"]=master_secret
        shelf["email"]=username
        shelf.sync()

    #Determine the browser
    if(args.command in browsers):
        shelf["browser"]=args.command
        shelf.sync()
        print("Browser is changed to "+args.command)
        sys.exit()

    if('browser' in shelf):
        browser = shelf["browser"]
    else:
        browser = "chrome"

    inputURL = urlparse(args.command)
    targetURL = urllib.quote(args.command)

    # API config
    bi = Brightidea(token_endpoint="https://"+inputURL.hostname+"/_oauth2/token",
    	client_id=master_client_id,
    	client_secret=master_secret,
        host_name=inputURL.hostname)

    access_token = bi.client.access_token

    login_url = "https://"+inputURL.hostname+"/api3/session/me?access_token="+access_token+"&target="+targetURL+"&email="+email

    if(args.admin):
        login_url += "&admin=1"

    if(args.email):
        login_url += "&email="+args.email

    if(args.screen_name):
        login_url += "&screen_name="+args.screen_name

    openBrowser(browser, login_url)
Ejemplo n.º 37
0
class DAExplorer():
    """API object for searching and downloading Deviations via DeviantArt."""

    MAX_ITEMS_PER_REQUEST = 20  # Defined by DeviantArt API

    def __init__(self, credentials, target_user):
        """
        Open an API handle for the explorer.
        :param credentials: Credentials to use in this session.
        :param target_user: str for user to explore in this session.
        """
        if not type(credentials) is Credentials:
            raise DAExplorerException(
                "Argument 'credentials' must be type Credentials.")
        if not type(target_user) is str:
            raise DAExplorerException(
                "Argument 'target_user' must be type str.")

        # Define all class members
        self.oauth = None
        self.user = target_user

        # @todo move away from sanction oauth2 library, make this (and callers) async
        self.oauth = Client(
            auth_endpoint="https://www.deviantart.com/oauth2/authorize",
            token_endpoint="https://www.deviantart.com/oauth2/token",
            resource_endpoint="https://www.deviantart.com/api/v1/oauth2",
            client_id=credentials.client_id,
            client_secret=credentials.client_secret)
        try:
            self.oauth.request_token(grant_type="client_credentials")
        except HTTPError as e:
            if e.code == 401:
                raise DAExplorerException("Unauthorized. Check credentials. " +
                                          str(e))
            else:
                raise DAExplorerException("Error authorizing: " + str(e))

        self._check_creds()
        self._check_user()

    def _api(self, endpoint, get_data=dict(), post_data=dict()):
        """
        Helper method to make a DeviantArt API call.
        :param endpoint: The endpoint to make the API call to.
        :param get_data: dict - data send through GET
        :param post_data: dict - data send through POST
        """

        # @todo move away from sanction oauth2 library, make this (and callers) async

        if get_data:
            request_parameter = "{}?{}".format(endpoint, urlencode(get_data))
        else:
            request_parameter = endpoint
        try:
            encdata = urlencode(post_data, True).encode('utf-8')
            response = self.oauth.request(request_parameter, data=encdata)
        except HTTPError as e:
            response = json.loads(e.read().decode("utf-8"))
            if "error" in response:
                raise DAExplorerException("DA API error: " +
                                          response["error_description"])
            else:
                raise DAExplorerException("HTTP error with request: " + str(e))
        return response

    def _check_creds(self):
        """
        Helper method to call DeviantArt API's "/placebo" to validate credentials.
        Raises exception if credentials invalid.
        """
        return self._api("/placebo")

    def _check_user(self):
        """
        Helper method to call DeviantArt API function "/user/profile/{username}" for current user.
        Raises exception if user does not exist.
        """
        return self._api(f"/user/profile/{self.user}")

    def _get_gallery_folders(self, page_idx):
        """
        Helper method to call DeviantArt API function "/gallery/folders".
        :param page_idx: int Index of the page to fetch, pagelen MAX_ITEMS_PER_REQUEST.
        :return dict Response from the API.
        """
        return self._api("/gallery/folders",
                         get_data={
                             "username": self.user,
                             "offset":
                             page_idx * DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "limit": DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "mature_content": True
                         })

    def _get_collection_folders(self, page_idx):
        """
        Helper method to call DeviantArt API function "/collections/folders".
        :param page_idx: int Index of the page to fetch, pagelen MAX_ITEMS_PER_REQUEST.
        :return dict Response from the API.
        """

        return self._api("/collections/folders",
                         get_data={
                             "username": self.user,
                             "offset":
                             page_idx * DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "limit": DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "mature_content": True
                         })

    def _get_gallery_all(self, page_idx):
        """
        Helper method to call DeviantArt API function "/gallery/all".
        :param page_idx: int Index of the page to fetch, pagelen MAX_ITEMS_PER_REQUEST.
        :return dict Response from the API.
        """
        return self._api("/gallery/all",
                         get_data={
                             "username": self.user,
                             "offset":
                             page_idx * DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "limit": DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "mature_content": True
                         })

    def _get_gallery_folder(self, folderid, page_idx):
        """
        Helper method to call DeviantArt API function "/gallery/{folderid}".
        :param folderid: str GUID for the folder to index into.
        :param page_idx: int Index of the page to fetch, pagelen MAX_ITEMS_PER_REQUEST.
        :return dict Response from the API.
        """
        return self._api(f"/gallery/{folderid}",
                         get_data={
                             "username": self.user,
                             "mode": "newest",
                             "offset":
                             page_idx * DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "limit": DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "mature_content": True
                         })

    def _get_collection_folder(self, folderid, page_idx):
        """
        Helper method to call DeviantArt API function "/collections/{folderid}".
        :param folderid: str GUID for the folder to index into.
        :param page_idx: int Index of the page to fetch, pagelen MAX_ITEMS_PER_REQUEST.
        :return dict Response from the API.
        """
        return self._api(f"/collections/{folderid}",
                         get_data={
                             "username": self.user,
                             "offset":
                             page_idx * DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "limit": DAExplorer.MAX_ITEMS_PER_REQUEST,
                             "mature_content": True
                         })

    def _download_deviation(self, deviationid):
        """
        Helper method to call DeviantArt API function "/deviation/download/{deviationid}".
        :param deviationid: str GUID for the Deviation to identify.
        :return dict Response from the API.
        """
        return self._api(f"/deviation/download/{deviationid}")

    def list_folders(self, source, page_idx):
        """
        Fetch up to MAX_ITEMS_PER_REQUEST Folders for current user.
        :param source: Source in which to index Folders.
        :param page_idx: int Index of Folder set to fetch.
        :return List of Folders at current index (or None if index is out of bounds).
        """
        if not type(source) is Source:
            raise DAExplorerException("Argument 'source' must be type Source.")
        if not type(page_idx) is int:
            raise DAExplorerException("Argument 'page_idx' must be type int.")

        output = []
        response = None
        if source is Source.GALLERY:
            response = self._get_gallery_folders(page_idx)
        elif source is Source.COLLECTION:
            response = self._get_collection_folders(page_idx)
        # End condition: no more Folders to find
        if response == None or (not response["has_more"]
                                and len(response["results"]) == 0):
            return None

        for folder_info in response["results"]:
            output.append(Folder())
            folder = output[-1]
            folder.folderid = folder_info["folderid"]
            folder.name = folder_info["name"]

        return {"output": output, "has_more": response["has_more"]}

    def list_deviations(self, source, folder, page_idx):
        """
        Fetch up to MAX_ITEMS_PER_REQUEST Deviations in specified Folder for current user.
        :param source: Source in which to index Folders.
        :param folder: Folder object to be indexed into. Must be generated from this API.
            If source is GALLERY and this parameter is None, this method will search
            'gallery/all'. If source is COLLECTION and this parameter is None, this method
            will return None.
        :param page_idx : int Index of Deviation set to fetch.
        :return List of Deviations at current index (or None if index is out of bounds).
        """
        if not type(source) is Source:
            raise DAExplorerException("Argument 'source' must be type Source.")
        if not type(folder) is Folder and folder != None:
            print(type(folder))
            print(type(folder) is None)
            raise DAExplorerException(
                "Argument 'folder' must be type Folder or None.")
        if not type(page_idx) is int:
            raise DAExplorerException("Argument 'page_idx' must be type int.")

        output = []
        response = None
        if source is Source.GALLERY:
            if folder is None:
                response = self._get_gallery_all(page_idx)
            else:
                response = self._get_gallery_folder(folder.folderid, page_idx)
        elif source is Source.COLLECTION:
            if folder is None:
                return output
            else:
                response = self._get_collection_folder(folder.folderid,
                                                       page_idx)

        # End condition: no more Deviations to find
        if response == None or (not response["has_more"]
                                and len(response["results"]) == 0):
            return None

        for dev_info in response["results"]:
            output.append(Deviation())
            dev = output[-1]
            dev.deviationid = dev_info["deviationid"]
            dev.is_downloadable = dev_info["is_downloadable"]
            if "content" in dev_info:
                dev.preview_src = dev_info["content"]["src"]

        return output

    async def download_deviation(self, deviation, full_path):
        """
        Download the requested Deviation.
        :param deviation: Deviation object to download. Must be generated from this API.
        :param full_path: path-like object (excluding file name) in which to store result.
        """
        if not type(deviation) is Deviation:
            raise DAExplorerException(
                "Argument 'deviation' must be type Deviation.")
        try:
            url_targ = ""
            deviation_raw = {}
            if deviation.is_downloadable:
                deviation_raw = self._download_deviation(deviation.deviationid)
                url_targ = deviation_raw["src"]
            elif deviation.preview_src:
                # Deviation can't be downloaded at highest resolution, so fetch the preview
                url_targ = deviation.preview_src
            else:
                # Deviation has no image content to be downloaded
                return
            os.makedirs(Path(full_path),
                        exist_ok=True)  # Ensure the output path exists
            async with aiohttp.ClientSession() as session:
                async with session.get(url_targ) as resp:
                    if resp.status == 200:  # HTTP success
                        extension = mimetypes.guess_extension(
                            resp.content_type, strict=False)
                        if not extension:
                            # Do it the hackish way if mimetypes can't figure it out
                            extension = "." + url_targ.split("/")[-1].split(
                                ".")[1].split("?")[0]
                        filename = ''
                        if deviation.is_downloadable:
                            filename = deviation_raw['filename']
                        else:
                            filename = url_targ.split("/")[-1].split("?")[0]
                        f = await aiofiles.open(
                            Path(full_path).joinpath(filename), mode='wb')
                        await f.write(await resp.read())
                        await f.close()
        except Exception as e:
            raise DAExplorerException("Error downloading deviation " +
                                      str(deviation.deviationid) + ": " +
                                      str(e))
Ejemplo n.º 38
0
class API(object):
    """ Global Sensor Networks api client object
    """

    def __init__(self, service_url=None, client_id=None, client_secret=None, redirect_uri=None):
        """ Instantiates a GSN API client to authorize and authenticate a user
        :param service_url: The authorization endpoint provided by GSN
                            services.
        :param client_id: The client ID.
        :param client_secret: The client secret.
        """
        assert service_url is not None
        assert client_id is not None and client_secret is not None

        self.client = Client(token_endpoint="{}/oauth2/token".format(service_url),
                             resource_endpoint="{}/api".format(service_url),
                             client_id=client_id, client_secret=client_secret,
                             token_transport=transport_headers
                             )
        self.client.request_token(grant_type='client_credentials', redirect_uri=redirect_uri)

        assert hasattr(self.client, 'expires_in')

        self.expiration = time.time() + self.client.expires_in

    def refresh_token(self):
        """ Renew the access token by submitting a request with the previously
        received refresh_token
        """
        assert hasattr(self.client, 'refresh_token')

        self.client.refresh()

        self.expiration = time.time() + self.client.expires_in

    def get_latest_values(self, vs_name=None):
        """ Query the API to get the latest values of a given virtual sensor.
        :param vs_name: The name of the virtual sensor.
        :returns: A Sensor object.
        """
        assert vs_name is not None
        if self.expiration <= time.time():
            self.refresh_token()
        try:
            data = self.client.request("/sensors/{}?latestValues=True".format(vs_name))
        except:
            self.refresh_token()
            try:
                data = self.client.request("/sensors/{}?latestValues=True".format(vs_name))
            except:
                return None
        return Sensor(geojson_object=data)

    def push_values(self, sensor_data=None):
        """ Push sensor data into GSN's API. The corresponding virtual sensor
         must be of type zeromq-push.
        :param sensor_data: A Sensor object containing the sensor values.
        :returns: The server response.
        """

        assert sensor_data is not None
        if self.expiration <= time.time():
            self.refresh_token()
        try:
            res = self.client.request("/sensors/{}/data".format(sensor_data.name),
                                      data=sensor_data.to_geojson().encode('utf_8'),
                                      headers={'Content-type': 'application/json'})
        except:
            self.refresh_token()
            try:
                res = self.client.request("/sensors/{}/data".format(sensor_data.name),
                                          data=sensor_data.to_geojson().encode('utf_8'),
                                          headers={'Content-type': 'application/json'})
            except HTTPError as e:
                return e.readlines()
        return res
Ejemplo n.º 39
0
class TestClient(TestCase):
    def setUp(self):
        self.client = Client(auth_endpoint=AUTH_ENDPOINT,
                             token_endpoint=TOKEN_ENDPOINT,
                             resource_endpoint=RESOURCE_ENDPOINT,
                             client_id=CLIENT_ID)

    def test_init(self):
        map(lambda c: self.assertEqual(*c), (
            (self.client.auth_endpoint, AUTH_ENDPOINT),
            (self.client.token_endpoint, TOKEN_ENDPOINT),
            (self.client.resource_endpoint, RESOURCE_ENDPOINT),
            (self.client.client_id, CLIENT_ID),
        ))

    def test_auth_uri(self):
        parsed = urlparse(self.client.auth_uri(redirect_uri=REDIRECT_URI))
        qs = dict(parse_qsl(parsed.query))

        map(lambda c: self.assertEqual(*c),
            ((qs['redirect_uri'], REDIRECT_URI), (qs['response_type'], 'code'),
             (qs['client_id'], CLIENT_ID)))

        parsed = urlparse(self.client.auth_uri(scope=SCOPE))
        qs = dict(parse_qsl(parsed.query))

        self.assertEqual(qs['scope'], SCOPE)

        parsed = urlparse(self.client.auth_uri(state=STATE))
        qs = dict(parse_qsl(parsed.query))

        self.assertEqual(qs['state'], STATE)

    @with_patched_client(
        json.dumps({
            'access_token': 'test_token',
            'expires_in': 300,
        }))
    def test_request_token_json(self):
        self.client.request_token()
        self.assertEqual(self.client.access_token, 'test_token')

        self.client.request_token(redirect_uri=REDIRECT_URI)
        self.assertEqual(self.client.access_token, 'test_token')

    @with_patched_client('access_token=test_token')
    def test_request_token_url(self):
        self.client.request_token()
        self.assertEqual(self.client.access_token, 'test_token')

    @with_patched_client(json.dumps({
        'access_token': 'refreshed_token',
    }))
    def test_refresh_token(self):
        self.client.refresh_token = 'refresh_token'
        self.client.refresh()
        self.assertEqual(self.client.access_token, 'refreshed_token')

    @with_patched_client(json.dumps({'userid': 1234}))
    def test_request(self):
        self.client.access_token = 'foo'
        data = self.client.request('/foo')
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(
        zlib.compress(json.dumps({
            'userid': 1234
        }).encode('utf8')))
    def test_request_custom_parser(self):
        def _decompress(buf):
            return json.loads(zlib.decompress(buf).decode())

        self.client.access_token = 'foo'
        data = self.client.request('/foo', parser=_decompress)
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({'userid': 1234}))
    def test_request_transport_headers(self):
        self.client.token_transport = transport_headers
        self.client.access_token = 'foo'
        data = self.client.request('/foo')
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({'userid': 1234}),
                         headers={
                             'Content-Type': 'text/html; charset=utf-8',
                         })
    def test_request_with_charset(self):
        self.client.access_token = 'foo'
        data = self.client.request('/foo')
        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({'userid': 1234}))
    def test_custom_transport(self):
        def _transport(url,
                       access_token,
                       data=None,
                       method=None,
                       headers=None):

            self.assertEqual(url, 'http://example.com/resource/foo')
            self.assertEqual(access_token, 'foo')

        self.client.access_token = 'foo'
        self.client.token_transport = _transport
        data = self.client.request(
            '/foo', headers={'Content-Type': 'application/json'})

        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({'userid': 1234}))
    def test_query_transport_with_headers(self):
        self.client.access_token = 'foo'
        data = self.client.request(
            '/foo', headers={'Content-Type': 'application/json'})

        self.assertEqual(data['userid'], 1234)

    @with_patched_client(json.dumps({'userid': 1234}))
    def test_header_transport_with_headers(self):
        self.client.access_token = 'foo'
        self.client.token_transport = transport_headers
        data = self.client.request(
            '/foo', headers={'Content-Type': 'application/json'})

        self.assertEqual(data['userid'], 1234)