def handle_github(self, data): self.send_response(302) c = Client(auth_endpoint='https://github.com/login/oauth/authorize', client_id=config['github.client_id']) self.send_header('Location', c.auth_uri( redirect_uri='http://localhost/login/github')) self.end_headers()
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)
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)
def handle_instagram(self, data): self.send_response(302) c = Client(auth_endpoint='https://api.instagram.com/oauth/authorize/', client_id=config['instagram.client_id']) self.send_header('Location', c.auth_uri( redirect_uri='http://localhost/login/instagram')) self.end_headers()
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)
def handle_foursquare(self, data): self.send_response(302) c = Client(auth_endpoint='https://foursquare.com/oauth2/authenticate', client_id=config['foursquare.client_id']) self.send_header('Location', c.auth_uri( redirect_uri='http://localhost/login/foursquare')) self.end_headers()
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
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
def handle_stackexchange(self, data): self.send_response(302) c = Client(auth_endpoint='https://stackexchange.com/oauth', client_id=config['stackexchange.client_id']) self.send_header('Location', c.auth_uri( redirect_uri='http://localhost/login/stackexchange')) self.end_headers()
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()
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
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
def handle_deviantart(self, data): self.send_response(302) c = Client( auth_endpoint='https://www.deviantart.com/oauth2/draft15/authorize', client_id=config['deviantart.client_id']) self.send_header('Location', c.auth_uri( redirect_uri=config['deviantart.redirect_uri'])) self.end_headers()
def handle_stackexchange(self, data): self.send_response(302) c = Client(auth_endpoint='https://stackexchange.com/oauth', client_id=config['stackexchange.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/stackexchange')) self.end_headers()
def handle_github(self, data): self.send_response(302) c = Client(auth_endpoint='https://github.com/login/oauth/authorize', client_id=config['github.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/github')) self.end_headers()
def handle_foursquare(self, data): self.send_response(302) c = Client(auth_endpoint='https://foursquare.com/oauth2/authenticate', client_id=config['foursquare.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/foursquare')) self.end_headers()
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
def handle_instagram(self, data): self.send_response(302) c = Client(auth_endpoint='https://api.instagram.com/oauth/authorize/', client_id=config['instagram.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/instagram')) self.end_headers()
def handle_google(self, data): self.send_response(302) c = Client(auth_endpoint='https://accounts.google.com/o/oauth2/auth', client_id=config['google.client_id']) self.send_header('Location', c.auth_uri( scope=config['google.scope'], access_type='offline', redirect_uri='http://localhost/login/google')) self.end_headers()
def authenticate(force=False): """ Returns an oauth token that can be passed to the server for identification. """ if not force: try: cur_time = int(time.time()) access_token, expires_at, refresh_token = get_storage() if cur_time < expires_at - 10: return access_token access_token, expires_in = make_refresh_post(refresh_token) update_storage(access_token, expires_in, refresh_token) return access_token except IOError as _: print('Performing authentication') except Exception as _: print('Performing authentication') print("Please enter your CalNet ID.") calnet_id = input("CalNet ID: ") c = Client(auth_endpoint='https://accounts.google.com/o/oauth2/auth', client_id=CLIENT_ID) url = c.auth_uri(scope="profile email", access_type='offline', name='ok-server', redirect_uri=REDIRECT_URI, login_hint='*****@*****.**' % (calnet_id)) webbrowser.open_new(url) host_name = REDIRECT_HOST port_number = REDIRECT_PORT done = False access_token = None refresh_token = None expires_in = None class CodeHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): """Respond to the GET request made by the OAuth""" path = urlparse(self.path) nonlocal access_token, refresh_token, expires_in, done qs = parse_qs(path.query) code = qs['code'][0] access_token, refresh_token, expires_in = _make_code_post(code) done = True self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(SUCCESS_HTML, "utf-8")) server_address = (host_name, port_number) httpd = http.server.HTTPServer(server_address, CodeHandler) httpd.handle_request() update_storage(access_token, expires_in, refresh_token) return access_token
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
def handle_facebook(self, data): self.send_response(302) c = Client(auth_endpoint='https://www.facebook.com/dialog/oauth', client_id=config['facebook.client_id']) self.send_header('Location', c.auth_uri( scope=config['facebook.scope'], redirect_uri='http://localhost/login/facebook')) self.end_headers()
def handle_deviantart(self, data): self.send_response(302) c = Client( auth_endpoint='https://www.deviantart.com/oauth2/draft15/authorize', client_id=config['deviantart.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri=config['deviantart.redirect_uri'])) self.end_headers()
def handle_google(self, data): self.send_response(302) c = Client(auth_endpoint='https://accounts.google.com/o/oauth2/auth', client_id=config['google.client_id']) self.send_header( 'Location', c.auth_uri(scope=config['google.scope'], access_type='offline', redirect_uri='http://localhost/login/google')) self.end_headers()
def handle_facebook(self, data): self.send_response(302) c = Client(auth_endpoint='https://www.facebook.com/dialog/oauth', client_id=config['facebook.client_id']) self.send_header( 'Location', c.auth_uri(scope=config['facebook.scope'], redirect_uri='http://localhost/login/facebook')) self.end_headers()
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!"
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)
def handle_jawbone(self, data): self.send_response(302) c = Client(auth_endpoint='https://jawbone.com/auth/oauth2/auth', client_id='nEXyCKO3F3s') self.send_header( 'Location', c.auth_uri( scope= 'basic_read extended_read location_read friends_read mood_read mood_write move_read sleep_read sleep_write generic_event_read generic_event_write', redirect_uri='http://localhost/login/jawbone')) self.end_headers()
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)
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)
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)
def resource(self): provider = settings.SANCTION_PROVIDERS[self.name] c = SanctionClient(auth_endpoint=provider['auth_endpoint'], token_endpoint=provider['token_endpoint'], resource_endpoint=provider['resource_endpoint'], client_id=provider['client_id'], client_secret=provider['client_secret']) c.refresh_token = self.refresh_token c.access_token = self.access_token c.token_expires = self.token_expires return c
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)
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)
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)
def openid_authenticate(provider): """return openid authenticate url for client to authenticate :param provider: OAuth2 provider. """ oauth_kwargs = current_app.config.get(str.format('OAUTH_{0}', provider.upper())) if oauth_kwargs is None: abort(404); c = Client(**oauth_kwargs) next_url = get_url(request.args.get('next')) or get_url(request.form.get('next')) or '' return redirect(c.auth_uri(redirect_uri=str.format('{0}/openid/{1}/login?next={2}', current_app.config['KINORSI_SERVER_HOST'], provider, next_url), scope='get_user_info,add_t', scope_delim=','))
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
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
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)
def _redirect(request, provider): p = settings.SANCTION_PROVIDERS[provider] c = SanctionClient(auth_endpoint=p['auth_endpoint'], client_id=p['client_id']) kwargs = p.get('auth_params', {}) kwargs['redirect_uri'] = p['redirect_uri'] if 'scope' in p: kwargs['scope'] = p['scope'] response = redirect(c.auth_uri(**kwargs)) # inject the state query param if getattr(settings, 'SANCTION_USE_CSRF', True): CsrfViewMiddleware().process_view(request, response, [], {}) url = list(urlparse(response['location'])) urlp = dict(parse_qsl(url[4])) urlp.update({'state': csrf.get_token(request)}) url[4] = urlencode(urlp) response['location'] = urlunparse(url) return response
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)
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')
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 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')
def _redirect(request, provider): p = settings.SANCTION_PROVIDERS[provider] c = SanctionClient(auth_endpoint=p['auth_endpoint'], client_id=p['client_id'], token_endpoint=p['token_endpoint'], client_secret=p['client_secret'], resource_endpoint=p['resource_endpoint']) kwargs = p.get('auth_params', {}) response = redirect( c.auth_uri(redirect_uri=p['redirect_uri'], scope=p['scope'] if 'scope' in p else None, **kwargs)) # inject the state query param if getattr(settings, 'SANCTION_USE_CSRF', True): CsrfViewMiddleware().process_view(request, response, [], {}) url = list(urlparse(response['location'])) urlp = dict(parse_qsl(url[4])) urlp.update({'state': csrf.get_token(request)}) url[4] = urlencode(urlp) response['location'] = urlunparse(url) return response
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
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)})
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 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)
def start_github_login(): c = Client( auth_endpoint=GITHUB_AUTH_ENDPOINT, client_id=current_app.config['GITHUB_OAUTH_CLIENT_ID'], ) return redirect(c.auth_uri(scope=GITHUB_SCOPE, state=csrf._get_token(), redirect_uri=OAUTH_REDIRECT_URI))
# get a Client ID and Secret from # https://login.rally1.rallydev.com/accounts/index.html#/clients CLIENT_ID = os.environ.get('CLIENT_ID', '') CLIENT_SECRET = os.environ.get('CLIENT_SECRET', '') # Server URL must match the one specified when creating the client SERVER_URL = os.environ.get('SERVER_URL', '') + "/oauth-redirect" # We will use these to make WSAPI calls RALLY_WSAPI_URL = "https://rally1.rallydev.com" RALLY_USER_URL = RALLY_WSAPI_URL + "/slm/webservice/v2.x/user" RALLY_STORIES_URL = RALLY_WSAPI_URL + "/slm/webservice/v2.x/hierarchicalrequirement" try: c = Client(auth_endpoint = "https://rally1.rallydev.com/login/oauth2/auth", token_endpoint = "https://rally1.rallydev.com/login/oauth2/token", client_id = CLIENT_ID, client_secret = CLIENT_SECRET) except Exception, e: print "Failed to init the OAuth2 Client " + str(e) exit(0) urls = ( '/', 'display_stories', '/login', 'login', '/logout', 'logout', '/oauth-redirect', 'redirect' ) app = web.application(urls, globals())
# However, if there is a .config file, use this instead of os.environ if os.path.exists('.config'): config = toml.load(".config") client_id = config['TDA']['client_id'] client_secret = config['TDA']['refresh_token'] 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:
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)
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')
def setUp(self): self.client = Client(auth_endpoint=AUTH_ENDPOINT, token_endpoint=TOKEN_ENDPOINT, resource_endpoint=RESOURCE_ENDPOINT, client_id=CLIENT_ID)
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))
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)