def __init__(self, oauth_credentials, tokeninfo): OAuth2Credentials.__init__(self, oauth_credentials.access_token, oauth_credentials.client_id, oauth_credentials.client_secret, oauth_credentials.refresh_token, oauth_credentials.token_expiry, oauth_credentials.token_uri, oauth_credentials.user_agent, oauth_credentials.id_token) self.tokeninfo = tokeninfo
def connect(self, include_guest=False): try: credentials_json = self.parser.get("google_drive", "credentials_json") credentials = OAuth2Credentials.from_json(credentials_json) http = httplib2.Http() http = credentials.authorize(http) self.drive_service = build('drive', 'v2', http=http) if include_guest: guest_credentials_json = self.parser.get("google_drive", "guest_credentials_json") guest_credentials = OAuth2Credentials.from_json(guest_credentials_json) guest_http = httplib2.Http() guest_http = credentials.authorize(guest_http) self.guest_drive_service = build('drive', 'v2', http=guest_http) except Exception as e: print type(e), e
def refresh_cache(): wf = Workflow() # Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets( config.CLIENT_SECRET_FILE, scope=config.OAUTH_SCOPE) http = httplib2.Http() try: credentials = OAuth2Credentials.from_json( wf.get_password('gmail_credentials')) if credentials is None or credentials.invalid: credentials = run(flow, PseudoStorage(), http=http) wf.save_password('gmail_credentials', credentials.to_json()) wf.logger.debug('Credentials securely updated') # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http) wf.cache_data('gmail_list', get_list(wf, http, gmail_service)) except PasswordNotFound: wf.logger.debug('Credentials not found') credentials = run(flow, PseudoStorage(), http=http) wf.save_password('gmail_credentials', credentials.to_json()) wf.logger.debug('New Credentials securely saved')
def google_events(self): if not self.google_key: return [] credentials = OAuth2Credentials.from_json(self.google_key) http = httplib2.Http() http = credentials.authorize(http) service = build("calendar", "v3", http=http) calendar_list = service.calendarList().list().execute() ids = [x['id'] for x in calendar_list['items']] all_events = [] for calendar_id in ids: page_token = None while True: events = service.events().list(calendarId='primary', pageToken=page_token).execute() all_events += events['items'] page_token = events.get('nextPageToken') if not page_token: break print str(all_events) for e in all_events: if 'date' in e['start']: e['start_time'] = parser.parse(e['start']['date']).replace(tzinfo=None) else: e['start_time'] = parser.parse(e['start']['dateTime']).replace(tzinfo=None) if 'date' in e['end']: e['end_time'] = parser.parse(e['end']['date']).replace(tzinfo=None) else: e['end_time'] = parser.parse(e['end']['dateTime']).replace(tzinfo=None) all_events = [x for x in all_events if x['start_time'] > datetime.datetime(month=2, day=10, year=2014)] return all_events
def gdisconnect(): # Only disconnect a connected user. credentials = OAuth2Credentials.from_json(login_session.get('credentials')) if credentials is None: response = make_response(json.dumps( 'Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response # Execute HTTP GET request to revoke current token. access_token = credentials.access_token url = ('https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token) h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] del login_session['user_id'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' # return response return redirect('/catalog') else: # For invalid token response = make_response( json.dumps('Failed to revoke for given user.', 400)) response.headers['Content-Type'] = 'application/json' return response
def refresh_cache(labels=None): labels = labels if labels is not None else config.SYSTEM_LABELS.keys() flow = flow_from_clientsecrets( config.CLIENT_SECRET_FILE, scope=config.OAUTH_SCOPE) http = httplib2.Http() try: credentials = OAuth2Credentials.from_json( WF.get_password('gmail_credentials')) if credentials is None or credentials.invalid: credentials = run(flow, PseudoStorage(), http=http) WF.save_password('gmail_credentials', credentials.to_json()) WF.logger.debug('Credentials securely updated') http = credentials.authorize(http) gmail_service = build('gmail', 'v1', http=http) for label in labels: WF.cache_data('gmail_%s' % label.lower(), get_list(http, gmail_service, label)) sleep(2) if not WF.cached_data_fresh('gmail_labels', max_age=300): WF.cache_data('gmail_labels', get_labels(gmail_service)) except PasswordNotFound: WF.logger.debug('Credentials not found') credentials = run(flow, PseudoStorage(), http=http) WF.save_password('gmail_credentials', credentials.to_json()) WF.logger.debug('New Credentials securely saved') except httplib2.ServerNotFoundError: WF.logger.debug('ServerNotFoundError')
def __init__(self, oauth2_credentials=None, api_key=None, oauth_access_token=None): """ :param oauth2_credentials: JSON representation of Coinbase oauth2 credentials :param api_key: Coinbase API key """ #Set up our requests session self.session = requests.session() #Set our Content-Type self.session.headers.update({'content-type': 'application/json'}) if oauth2_credentials: #CA Cert Path ca_directory = os.path.abspath(__file__).split('/')[0:-1] ca_path = '/'.join(ca_directory) + '/ca_certs.txt' #Set CA certificates (breaks without them) self.http = httplib2.Http(ca_certs=ca_path) #Create our credentials from the JSON sent self.oauth2_credentials = OAuth2Credentials.from_json(oauth2_credentials) #Check our token self.token_expired = False try: self._check_oauth_expired() except AccessTokenCredentialsError: self.token_expired = True #Apply our oAuth credentials to the session self.oauth2_credentials.apply(headers=self.session.headers) #Set our request parameters to be empty self.global_request_params = {} elif api_key: if isinstance(api_key, basestring): #Set our API Key self.api_key = api_key #Set our global_request_params self.global_request_params = {'api_key':api_key} else: print "Your api_key must be a string" elif oauth_access_token: if isinstance(oauth_access_token, basestring): self.oauth_access_token = oauth_access_token self.global_request_params = {'access_token': oauth_access_token} else: print "Oauth access token must be a string" else: print "You must pass either an api_key, oauth_credentials, or oauth_access_token."
def _retrieve_userinfo(self): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') return None # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None http = httplib2.Http() credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) logger.debug('Retrieved user info: %s' % content) info = json.loads(content) g._oidc_userinfo = info return info
def test(): if not current_user.google_key: return redirect(url_for('send_google')) credentials = OAuth2Credentials.from_json(current_user.google_key) if credentials is None or credentials.invalid == True: return redirect(url_for('send_google')) http = httplib2.Http() http = credentials.authorize(http) service = build("calendar", "v3", http=http) calendar_list = service.calendarList().list().execute() import ipdb ipdb.set_trace() ids = [x['id'] for x in calendar_list['items']] for calendar_id in ids: page_token = None while True: events = service.events().list(calendarId='primary', pageToken=page_token).execute() for event in events['items']: print event['summary'] page_token = events.get('nextPageToken') if not page_token: break return str(calendar_list) + '\n' + str(current_user.facebook_me())
def set_credentials(self, json): """ Set credentials from stored credentails json. Should be used for the following requests, where authorization is already done in the first request. """ self.credentials = OAuth2Credentials.from_json(json) self.access_token = self.credentials.access_token
def dummy_view(request): print 'in dummy view' print request print request.user print 'x'*50 print request.session.get('drive_credentials', None) print 'x'*50 from apiclient.http import MediaIoBaseDownload from apiclient.discovery import build from oauth2client.client import OAuth2Credentials credentials = request.session.get('drive_credentials', None) credentials = OAuth2Credentials.from_json(credentials) http_auth = credentials.authorize(httplib2.Http()) drive_service = build('drive', 'v3', http=http_auth) all_files = json.loads(request.POST.get('transfers')) print all_files for file_id, file_name in all_files.items(): drive_request = drive_service.files().get_media(fileId=file_id) with open(os.path.join(settings.TEMP_DIR, file_name), 'wb') as fh: downloader = MediaIoBaseDownload(fh, drive_request) done = False while done is False: status, done = downloader.next_chunk() return HttpResponse('')
def init_creds(credsb64): GDriveSync.LOCAL_TZ_OFFSET = GDriveSync.local_time_offset() if GDriveSync.CREDSB64 == credsb64: return creds_json = base64.b64decode(credsb64) creds = OAuth2Credentials.from_json(creds_json) GDriveSync.CREDS = creds GDriveSync.CREDSB64 = credsb64 gauth = GoogleAuth() gauth.settings = { 'client_config_backend': 'settings', 'client_config_file': 'client_secrets.json', 'save_credentials': False, 'oauth_scope': ['https://www.googleapis.com/auth/drive'], 'client_config': { 'client_id': creds.client_id, 'client_secret': creds.client_secret, 'auth_uri': GOOGLE_AUTH_URI, 'token_uri': GOOGLE_TOKEN_URI, 'revoke_uri': GOOGLE_REVOKE_URI, 'redirect_uri': 'http://juliabox.org/jboxauth/google/' } } gauth.LoadClientConfigSettings() gauth.credentials = creds GDriveSync.GAUTH = gauth GDriveSync.DRIVE = GoogleDrive(gauth)
def refreshtasks(): oauth = OAuth2Credentials.from_json(session['credentials']) http = httplib2.Http() http = oauth.authorize(http) taskservice = build('tasks', 'v1').tasks().list(tasklist='@default').execute(http=http) tasks = taskservice.get('items', []) return json.dumps(tasks)
def addtask(): oauth = OAuth2Credentials.from_json(session['credentials']) http = httplib2.Http() http = oauth.authorize(http) taskservice = build('tasks', 'v1').tasks().list(tasklist='@default').execute(http=http) session['tasklists'] = taskservice.get('items', []) return redirect(request.referrer)
def hello_me(): """Example for protected endpoint that extracts private information from the OpenID Connect id_token. Uses the accompanied access_token to access a backend service. """ info = oidc.user_getinfo( ['given_name', 'preferred_username', 'email', 'sub']) print('info: {}'.format(info)) given_name = info.get('given_name') preferred_username = info.get('preferred_username') email = info.get('email') userid = info.get('sub') greeting = '' if userid in oidc.credentials_store: try: from oauth2client.client import OAuth2Credentials access_token = OAuth2Credentials.from_json( oidc.credentials_store[userid]).access_token print('access_token=<{}>').format(access_token) headers = {'Authorization': 'Bearer %s' % (access_token)} # YOLO greeting = requests.get('http://localhost:8080/api', headers=headers).text except: print("Could not access greeting-service") greeting = "Hello {} [{}]".format(given_name, preferred_username) return (""" {} - your email is {}, your your userid is {}! <ul> <li><a href="/">Home</a></li> <li><a href="//localhost:8080/auth/realms/datalayer/account?referrer=datalayer&referrer_uri=http://localhost:8080/private&">Account</a></li> </ul> """.format(greeting, email, userid))
def logout(): access_token = OAuth2Credentials.from_json(login_session['credentials']).access_token #print 'In gdisconnect access token is %s', % access_token print login_session['username'] if access_token is None: print 'Access Token is None' response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] print 'result is ' print result if result['status'] == '200': del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return redirect(url_for('showCatalog')) else: response = make_response(json.dumps('Failed to revoke token for given user.', 400)) response.headers['Content-Type'] = 'application/json' return response
def gdisconnect(): # Only disconnect a connected user. credentials = login_session.get('credentials') if credentials is None: response = make_response( json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response oatuh2credentials = OAuth2Credentials.from_json(credentials) access_token = oatuh2credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': # Reset the user's sesson. del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return redirect("/restaurant") else: # For whatever reason, the given token was invalid. response = make_response( json.dumps('Failed to revoke token for given user.', 400)) response.headers['Content-Type'] = 'application/json' return response
def bq_choose_project(request): account = request.user.account credentials = Credentials.from_json(account.credentials) http_auth = credentials.authorize(httplib2.Http()) bigquery_service = build("bigquery", "v2", http=http_auth) results = bigquery_service.projects().list().execute() return render(request, "accounts/choose-project.html", dict(projects=results.get("projects", [])))
def test_json_credentials_storage(self): access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) m = mox.Mox() m.StubOutWithMock(keyring, 'get_password') m.StubOutWithMock(keyring, 'set_password') keyring.get_password('my_unit_test', 'me').AndReturn(None) keyring.set_password('my_unit_test', 'me', credentials.to_json()) keyring.get_password('my_unit_test', 'me').AndReturn(credentials.to_json()) m.ReplayAll() s = Storage('my_unit_test', 'me') self.assertEquals(None, s.get()) s.put(credentials) restored = s.get() self.assertEqual('foo', restored.access_token) self.assertEqual('some_client_id', restored.client_id) m.UnsetStubs() m.VerifyAll()
def action(self): credentials = OAuth2Credentials.from_json(shared.client_credentials) gc = gspread.authorize(credentials) # get worksheet sh = gc.open(shared.update_gsheet['filename']) worksheet = sh.get_worksheet(0) # data datalist = shared.update_gsheet['data'] # loop through each data for row row = 1 for k in range(0, len(datalist)): col_num = len(datalist[k]) col_letter = chr(ord('A') + col_num - 1) row_range = 'A{row}:{col}{row}'.format(row=row, col=col_letter) cell_list = worksheet.range(row_range) # loop through data and write in cell for i in range(0, len(cell_list)): cell_list[i].value = datalist[k][i] worksheet.update_cells(cell_list) row += 1
def __init__(self, oauth2_credentials=None, api_key=None, api_secret=None): #CA Cert Path ca_directory = os.path.abspath(__file__).split('/')[0:-1] ca_path = '/'.join(ca_directory) + '/ca_certs.txt' #Set CA certificates (breaks without them) self.http = httplib2.Http(ca_certs=ca_path) self.oauth2_credentials = None self.api_key = api_key self.api_secret = api_secret if oauth2_credentials is not None: if not oauth2_supported: raise RuntimeError('oauth2 is not supported in this environment') #Create our credentials from the JSON sent self.oauth2_credentials = \ OAuth2Credentials.from_json(oauth2_credentials) #Check our token self.token_expired = False try: self._check_oauth_expired() except AccessTokenCredentialsError: self.token_expired = True elif api_key and api_secret is None: warn("API key authentication without a secret has been deprecated" " by Coinbase- you should use a new key with a secret!")
def load_credentials(self, client_id, client_secret): app_root = os.path.realpath(os.path.join(__file__, '..', '..', '..')) credentials_file = os.path.join(app_root, 'data', 'credentials.json') try: with open(credentials_file, 'r') as f: credentials = OAuth2Credentials.new_from_json(f.read()) except IOError: flow = OAuth2WebServerFlow( client_id, client_secret, 'https://www.googleapis.com/auth/drive.readonly', 'urn:ietf:wg:oauth:2.0:oob', ) self._notice('Go to the following link in your browser: %s', flow.step1_get_authorize_url()) code = raw_input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) with open(credentials_file, 'w') as f: f.write(credentials.to_json()) if not credentials: raise CommandError('Error load credentials') return credentials
def FetchAccessToken(self): """Fetches an access token from the provider's token endpoint. Fetches an access token from this client's OAuth2 provider's token endpoint. Returns: The fetched AccessToken. """ try: http = self.CreateHttpRequest() credentials = OAuth2Credentials(None, self.client_id, self.client_secret, self.refresh_token, None, self.token_uri, None) credentials.refresh(http) return AccessToken(credentials.access_token, credentials.token_expiry, datetime_strategy=self.datetime_strategy) except AccessTokenRefreshError, e: if 'Invalid response 403' in e.message: # This is the most we can do at the moment to accurately detect rate # limiting errors since they come back as 403s with no further # information. raise GsAccessTokenRefreshError(e) elif 'invalid_grant' in e.message: LOG.info(""" Attempted to retrieve an access token from an invalid refresh token. Two common cases in which you will see this error are: 1. Your refresh token was revoked. 2. Your refresh token was typed incorrectly. """) raise GsInvalidRefreshTokenError(e) else: raise
def update_google_analytics(date, **kw): creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None) if not creds_data: log.critical('Failed to update global stats: ' 'GOOGLE_ANALYTICS_CREDENTIALS not set') return creds = OAuth2Credentials( *[creds_data[k] for k in ('access_token', 'client_id', 'client_secret', 'refresh_token', 'token_expiry', 'token_uri', 'user_agent')]) h = httplib2.Http() creds.authorize(h) service = build('analytics', 'v3', http=h) domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN profile_id = get_profile_id(service, domain) if profile_id is None: log.critical('Failed to update global stats: could not access a Google' ' Analytics profile for ' + domain) return datestr = date.strftime('%Y-%m-%d') try: data = service.data().ga().get(ids='ga:' + profile_id, start_date=datestr, end_date=datestr, metrics='ga:visits').execute() # Storing this under the webtrends stat name so it goes on the # same graph as the old webtrends data. p = ['webtrends_DailyVisitors', data['rows'][0][0], date] except Exception, e: log.critical( 'Fetching stats data for %s from Google Analytics failed: %s' % e) return
def logout(self): """ Request the browser to please forget the cookie we set, to clear the current session. Note that as described in [1], this will not log out in the case of a browser that doesn't clear cookies when requested to, and the user could be automatically logged in when they hit any authenticated endpoint. [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023 .. versionadded:: 1.0 """ # TODO: Add single logout from oauth2client.client import OAuth2Credentials info = self.user_getinfo(['name', 'email', 'sub']) user_id = info.get('sub') id_token_jwt = OAuth2Credentials.from_json( self.credentials_store[user_id]).id_token_jwt if type(self.client_secrets.get('post_logout_redirect_uris')) == str: post_logout_redirect_uri = self.client_secrets.get( 'post_logout_redirect_uris') else: post_logout_redirect_uri = self.client_secrets.get( 'post_logout_redirect_uris')[0] url = self.client_secrets.get( 'logout_uri' ) + '?' + 'id_token_hint=' + id_token_jwt + '&client_id=' + self.client_secrets.get( 'client_id' ) + '&post_logout_redirect_uri=' + post_logout_redirect_uri self._set_cookie_id_token(None) return redirect(url)
def GetCredentials(self): """Fetches a credentials objects from the provider's token endpoint.""" access_token = self.GetAccessToken() credentials = OAuth2Credentials( access_token.token, self.client_id, self.client_secret, self.refresh_token, access_token.expiry, self.token_uri, None) return credentials
def logout(): """End the request user's OpenIDConnect-authenticated session.""" try: # Get ID for request user (i.e. the 'Subject' of the credentials) subject_identifier = oidc.user_getfield("sub") # Retrieve OIDC authentication details from in-memory credentials store json_oidc_credentials = oidc.credentials_store[subject_identifier] oauth2_credentials = OAuth2Credentials.from_json(json_oidc_credentials) # Select the JSON Web Token (JWT) to expire with the issuer. id_token_jwt = oauth2_credentials.token_response["id_token"] # Find the base URL for the credentials issuer oidc_credentials_issuer_uri = oauth2_credentials.id_token["iss"] # Build OIDC-spec Logout URL which explicitly declares the token to expire logout_url = f"{oidc_credentials_issuer_uri}/v1/logout?id_token_hint={id_token_jwt}" # Expire local session oidc.logout() # Expire upstream session return redirect(logout_url) except KeyError: # Session details not available in local cache # Request user will be redirected through the auth server, back to the logout endpoint in a hairpin maneuver. # The purpose of this is to trigger the callback from the auth server to the OIDC endpoint out-of-band, with the # session details for the request user so that the local cache will have enough information to fully terminate # the upstream session. return oidc.redirect_to_auth_server(url_for(".logout"))
def google_calendar_credentials(self, key): """Loads and refreshes Google Calendar API credentials.""" # Look up the user from the key. user = self.user(key) if not user: return None # Load the credentials from storage. try: json = user.get('google_calendar_credentials') except KeyError: warning('Failed to load Google Calendar credentials.') return None # Use the valid credentials. credentials = OAuth2Credentials.from_json(json) if credentials and not credentials.invalid: return credentials # Handle invalidation and expiration. if credentials and credentials.access_token_expired: try: info('Refreshing Google Calendar credentials.') credentials.refresh(build_http()) return credentials except HttpAccessTokenRefreshError as e: warning('Google Calendar refresh failed: %s' % e) # Credentials are missing or refresh failed. warning('Deleting Google Calendar credentials.') self.delete_google_calendar_credentials(key) return None
def fs(self): gauth = GoogleAuth() gauth.credentials = OAuth2Credentials.from_json(credentials) gauth.client_config = client_config gauth.settings["client_config_backend"] = "settings" drive = GoogleDrive(gauth) return GoogleDriveFS(drive)
def test_convert(creds_json, sa_config_json): oauth = OAuth2Credentials.from_json(json.dumps(creds_json)) sa = ServiceAccountCredentials.from_json_keyfile_dict(sa_config_json) assert isinstance(util.convert_credentials(oauth), credentials.Credentials) assert isinstance(util.convert_credentials(sa), service_account.Credentials)
def gdisconnect(): # Only disconnect a connected user serialized_credentials = websession.get('credentials') credentials = None if serialized_credentials: try: credentials = OAuth2Credentials.from_json(serialized_credentials) except ValueError as e: pass if not credentials: print('Debug/gdisconnect - no credentials present, aborting...') response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response try: credentials.revoke(httplib2.Http()) print('User credentials successfully revoked') except TokenRevokeError as e: print('User credential revocation failed: {}'.format(e)) response = make_response(json.dumps('Failed to revoke token for given user.'), 400) response.headers['Content-Type'] = 'application/json' return response
def getCredentials(self, authorization_code=None): if self._credentials is None: db_settings = self.getDB().settings auth = db_settings.find_one( {'gdrive_credentials': { "$exists": True }}) if auth is not None: self._credentials = OAuth2Credentials.new_from_json( auth.get('gdrive_credentials')) else: auth = {} if self._credentials is not None and self._credentials.access_token_expired: self._credentials.refresh(httplib2.Http()) auth['gdrive_credentials'] = self._credentials.to_json() db_settings.save(auth) if self._credentials is None: try: self._credentials = self.exchange_code(authorization_code) except CodeExchangeException, error: error.authorization_url = self.get_authorization_url() raise error auth['gdrive_credentials'] = self._credentials.to_json() db_settings.save(auth)
def gdisconnect(): credentials = OAuth2Credentials.from_json(login_session.get('credentials')) if credentials is None: response = make_response(json.dumps('Current user not connected'), 401) response.headers['Content-Type'] = 'application/json' return response access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] response = make_response(json.dumps('User disconnected'), 200) response.headers['Content-Type'] = 'application/json' return response else: response = make_response(json.dumps('failed to logout'), 400) response.headers['Content-Type'] = 'application/json' return response
def credentials_from_refresh_token(token): # why doesn't Google provide this!? cred_json = { "_module": "oauth2client.client", "token_expiry": "2000-01-01T00:13:37Z", # to refresh now "access_token": 'bogus', "token_uri": "https://accounts.google.com/o/oauth2/token", "invalid": False, "token_response": { "access_token": 'bogus', "token_type": "Bearer", "expires_in": 3600, "refresh_token": token }, "client_id": oauth.client_id, "id_token": None, "client_secret": oauth.client_secret, "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "_class": "OAuth2Credentials", "refresh_token": token, "user_agent": None } return OAuth2Credentials.new_from_json(json.dumps(cred_json))
def character_post(): """ accept a post from the character page """ credentials = OAuth2Credentials.from_json(session['credential']) try: if request.form.get ('new', False): new_name = request.form.get ('new-name').strip () new_color = request.form.get ('color') if new_name == '': kwargs = {'msg': "character name can't be blank"} return redirect(url_for('character_select', **kwargs)) character = GLOEBIT.create_character \ (credentials, {'name':new_name, 'color':new_color}) session['character-name'] = character['name'] session['character-id'] = character['id'] else: characters = GLOEBIT.user_characters (credentials) for character in characters: if request.form.get ('select-'+character['id'], False): session['character-name'] = character['name'] session['character-id'] = character['id'] if request.form.get ('delete-'+character['id'], False): GLOEBIT.delete_character (credentials, character['id']) return redirect(url_for('character_select')) except gloebit.CharacterAccessError, exn: kwargs = {'msg': str (exn)} return redirect(url_for('character_select', **kwargs))
def __init__(self, credentials=None): """Initialize Client API object for Compute Engine manipulation. If authorized HTTP is not given by parameter, it uses user ID stored in Memcache and fetches credentials for that user. Args: credentials: OAuth2 credentials of current user. """ if credentials: user_id = users.get_current_user().user_id() credentials_in_json = credentials.to_json() authorized_user = AuthorizedUserId.get_or_insert( self.USER_ID_KEY, user_id=user_id, credentials=db.Text(credentials_in_json)) memcache.set(self.USER_CREDENTIALS_KEY, credentials_in_json) if (authorized_user.user_id != user_id or str(authorized_user.credentials) != credentials_in_json): authorized_user.user_id = user_id authorized_user.credentials = db.Text(credentials_in_json) authorized_user.put() else: credentials_in_json = memcache.get(self.USER_CREDENTIALS_KEY) if not credentials_in_json: authorized_user = AuthorizedUserId.get_by_key_name(self.USER_ID_KEY) credentials_in_json = str(authorized_user.credentials) credentials = OAuth2Credentials.from_json(credentials_in_json) self.compute_api = build('compute', self.COMPUTE_API_VERSION, http=credentials.authorize(httplib2.Http()))
def youtube_credentials(access_token,refresh_token,token_expiry): client=YOUTUBE_INFO # credentials = AccessTokenCredentials(access_token,'tunesmash-agent/1.0') credentials = OAuth2Credentials(client_id=client['id'],client_secret=client['secret'],refresh_token=refresh_token,token_uri='https://www.googleapis.com/oauth2/v4/token',user_agent='ts-ipython',access_token=access_token,token_expiry=token_expiry) http = httplib2.Http() credentials.refresh(http) return credentials
def _onCredentialsPollBodyReady(self, body): if self._canceled: Log.d("Auth Request canceled") return result = json.loads(body) error = result.get("error", None) if error: if error == "authorization_pending": print "not ready, yet" reactor.callLater(self._user_code.interval, self._pollForResult) elif error == "slow_down": print "too fast, slowing down" self._device_code.interval = self._device_code.interval * 2 elif error == "expired_token": self._onError(self.ERROR_CREDENTIALS_REQUEST_EXPIRED) else: print result self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error) elif "access_token" in result: access_token = result.get("access_token") refresh_token = result.get("refresh_token") token_expiry = str( int(time()) + int(result.get("expires_in")) ) self._credentials = OAuth2Credentials(access_token, self.CLIENT_ID, self.CLIENT_SECRET, refresh_token, token_expiry, self.AUTH_REQUEST_URI, self.USER_AGENT) for fnc in self.onCredentialsReady: fnc(self._credentials) else: self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error)
def gdisconnect(): # Only disconnect a connected user. credentials = OAuth2Credentials.from_json(login_session.get('credentials')) if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response # Execute HTTP GET request to revoke current token. access_token = credentials.access_token url = ('https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token) h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] del login_session['user_id'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' # return response return redirect('/catalog') else: # For invalid token response = make_response( json.dumps('Failed to revoke for given user.', 400)) response.headers['Content-Type'] = 'application/json' return response
def _get_credentials(credentials=None): """ Checks environment in order of precedence: - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to a file with stored credentials information. - Google App Engine (production and testing) Returns: (OAuth2Credentials or GoogleCredentials) """ if not credentials: if os.environ.get('JPY_USER'): # we are running in datalab, so derive the user credentials from the environment # This is required for datalab to work as the user credentials are only set in the environment if not os.environ.get('REFRESH_TOKEN') or not os.environ.get( "CLIENT_ID") or not os.environ.get("CLIENT_SECRET"): raise RuntimeError( "Not all required environment variables are found: REFRESH_TOKEN, CLIENT_ID, CLIENT_SECRET" ) return OAuth2Credentials( access_token=None, client_id=os.environ['CLIENT_ID'], client_secret=os.environ['CLIENT_SECRET'], refresh_token=os.environ['REFRESH_TOKEN'], token_uri=ExternalService._get_token_uri( os.environ['TOKEN_URI']), token_expiry=None, user_agent='Python client library') else: credentials = GoogleCredentials.get_application_default() if credentials.create_scoped_required(): credentials = credentials.create_scoped(SCOPES) return credentials if not credentials: raise RuntimeError("Could not find proper credentials!") return credentials
def get(self): try: settings = json.loads(self.module.settings) credential = settings['credential'] return OAuth2Credentials.from_json(credential) except (ValueError, KeyError): return None
def test_unicode_header_checks(self): access_token = u'foo' client_id = u'some_client_id' client_secret = u'cOuDdkfjxxnv+' refresh_token = u'1/0/a.df219fjls0' token_expiry = str(datetime.datetime.utcnow()) token_uri = str(GOOGLE_TOKEN_URI) revoke_uri = str(GOOGLE_REVOKE_URI) user_agent = u'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) # First, test that we correctly encode basic objects, making sure # to include a bytes object. Note that oauth2client will normalize # everything to bytes, no matter what python version we're in. http = credentials.authorize(HttpMock(headers={'status': '200'})) headers = {u'foo': 3, b'bar': True, 'baz': b'abc'} cleaned_headers = {b'foo': b'3', b'bar': b'True', b'baz': b'abc'} http.request(u'http://example.com', method=u'GET', headers=headers) for k, v in cleaned_headers.items(): self.assertTrue(k in http.headers) self.assertEqual(v, http.headers[k]) # Next, test that we do fail on unicode. unicode_str = six.unichr(40960) + 'abcd' self.assertRaises( NonAsciiHeaderError, http.request, u'http://example.com', method=u'GET', headers={u'foo': unicode_str})
def setUp(self): gauth = GoogleAuth() gauth.credentials = OAuth2Credentials.from_json(credentials) gauth.client_config = client_config gauth.settings["client_config_backend"] = "settings" drive = GoogleDrive(gauth) self.fs = GoogleDriveFS(drive)
def test_no_unicode_in_request_params(self): access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = str(datetime.datetime.utcnow()) token_uri = str(GOOGLE_TOKEN_URI) revoke_uri = str(GOOGLE_REVOKE_URI) user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) http = HttpMock(headers={'status': '200'}) http = credentials.authorize(http) http.request('http://example.com', method='GET', headers={'foo': 'bar'}) for k, v in http.headers.items(): self.assertEqual(str, type(k)) self.assertEqual(str, type(v)) # Test again with unicode strings that can't simple be converted to ASCII. try: http.request( 'http://example.com', method='GET', headers={'foo': '\N{COMET}'}) self.fail('Expected exception to be raised.') except NonAsciiHeaderError: pass self.credentials.token_response = 'foobar' instance = OAuth2Credentials.from_json(self.credentials.to_json()) self.assertEqual('foobar', instance.token_response)
def set_google_credentials(strategy, details, response, user=None, *args, **kwargs): """ Saves google credentials to work with API """ if user: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(response.get('expires_in'))) id_token = _extract_id_token(response.get('id_token')) credential = OAuth2Credentials( access_token=response.get('access_token'), client_id=settings.GOOGLE_OAUTH2_CLIENT_ID, client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET, refresh_token=response.get('refresh_token'), token_expiry=token_expiry, token_uri=GOOGLE_TOKEN_URI, user_agent=None, revoke_uri=GOOGLE_REVOKE_URI, id_token=id_token, token_response=response) google_credential, is_created = GoogleCredentials.objects.get_or_create( user=user) google_credential.credential = credential google_credential.save()
def gdisconnect(): # Only disconnect a connected user. credentials = login_session.get('credentials') if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response oatuh2credentials = OAuth2Credentials.from_json(credentials) access_token = oatuh2credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': # Reset the user's sesson. del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return redirect("/restaurant") else: # For whatever reason, the given token was invalid. response = make_response( json.dumps('Failed to revoke token for given user.', 400)) response.headers['Content-Type'] = 'application/json' return response
def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: if self._access_token: logger.debug("Found api access token") return self._access_token credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) logger.debug("Getting access token from credential store") logger.debug(str(credentials.to_json())) access_token = credentials.access_token if not self.validate_token(access_token): raise AccessTokenCredentialsError( "The access_token is expired or invalid and can't be refreshed." ) return access_token except (KeyError, AccessTokenCredentialsError) as e: logger.debug("Expired ID token, credentials missing", exc_info=True) if not self.is_api_request(): return self.redirect_to_auth_server(request.url) return None
def test_pickle_and_json_interop(self): # Write a file with a pickled OAuth2Credentials. access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) f = open(FILENAME, 'w') pickle.dump(credentials, f) f.close() # Storage should be not be able to read that object, as the capability to # read and write credentials as pickled objects has been removed. s = Storage(FILENAME) read_credentials = s.get() self.assertEquals(None, read_credentials) # Now write it back out and confirm it has been rewritten as JSON s.put(credentials) f = file(FILENAME) data = simplejson.load(f) f.close() self.assertEquals(data['access_token'], 'foo') self.assertEquals(data['_class'], 'OAuth2Credentials') self.assertEquals(data['_module'], OAuth2Credentials.__module__)
def hello_me(): """Example for protected endpoint that extracts private information from the OpenID Connect id_token. Uses the accompanied access_token to access a backend service. """ info = oidc.user_getinfo(['preferred_username', 'email', 'sub']) username = info.get('preferred_username') email = info.get('email') user_id = info.get('sub') if user_id in oidc.credentials_store: try: from oauth2client.client import OAuth2Credentials access_token = OAuth2Credentials.from_json( oidc.credentials_store[user_id]).access_token print('access_token=<%s>' % access_token) headers = {'Authorization': 'Bearer %s' % (access_token)} # YOLO greeting = requests.get('http://localhost:8080/greeting', headers=headers).text except: print("Could not access greeting-service") greeting = "Hello %s" % username return ("""%s your email is %s and your user_id is %s! <ul> <li><a href="/">Home</a></li> <li><a href="//localhost:8080/auth/realms/test/account?referrer=flask-app&referrer_uri=http://localhost:5000/private&">Account</a></li> <li> TOKEN: %s</li> </ul>""" % (greeting, email, user_id, access_token))
def test_multistore_file(self): access_token = 'foo' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' client_id = 'some_client_id' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) store = multistore_file.get_credential_storage( FILENAME, credentials.client_id, credentials.user_agent, ['some-scope', 'some-other-scope']) store.put(credentials) credentials = store.get() self.assertNotEquals(None, credentials) self.assertEquals('foo', credentials.access_token) store.delete() credentials = store.get() self.assertEquals(None, credentials) if os.name == 'posix': self.assertEquals('0600', oct(stat.S_IMODE(os.stat(FILENAME).st_mode)))
def get(self): try: settings = json.loads(self.module.settings) credential = settings["credential"] return OAuth2Credentials.from_json(credential) except (ValueError, KeyError): return None
def test_simple(self, step2_exchange): access_token = 'b' * 40 refresh_token = 'c' * 40 step2_exchange.return_value = OAuth2Credentials( access_token, current_app.config['GOOGLE_CLIENT_ID'], current_app.config['GOOGLE_CLIENT_SECRET'], refresh_token, datetime(2013, 9, 19, 22, 15, 22), GOOGLE_TOKEN_URI, 'foo/1.0', revoke_uri=GOOGLE_REVOKE_URI, id_token={ 'hd': 'example.com', 'email': '*****@*****.**', }, ) resp = self.client.get('/auth/complete/?code=abc') step2_exchange.assert_called_once_with('abc') assert resp.status_code == 302 assert resp.headers[ 'Location'] == 'http://localhost/?finished_login=success' user = User.query.filter(User.email == '*****@*****.**', ).first() assert user
def renew_creds(creds): creds = OAuth2Credentials.from_json(json.dumps(creds)) http = httplib2.Http( disable_ssl_certificate_validation=True) # pass cacerts otherwise creds.refresh(http) creds = json.loads(creds.to_json()) return creds
def test_to_from_json(self): json = self.credentials.to_json() instance = OAuth2Credentials.from_json(json) self.assertEqual(OAuth2Credentials, type(instance)) instance.token_expiry = None self.credentials.token_expiry = None self.assertEqual(instance.__dict__, self.credentials.__dict__)
def loadCredentials(self, userId): db = mongo() account = db.accounts.find_one({'user': userId, 'name': 'google'}) if account is not None: jsonCredentials = account['jsonCredentials'] return OAuth2Credentials.from_json(jsonCredentials) else: return False
def creds(self): """Returns an oauth2client.OAuth2Credentials. """ if self.creds_model: return db.get(self.creds_model.to_old_key()).credentials else: # TODO: remove creds_json return OAuth2Credentials.from_json(self.creds_json)
def authenticate_saved(self): try: f = open(self.cred_path, 'rb') json = f.read() self.credentials = OAuth2Credentials.from_json(json) except ValueError as e: logger.error('unable to load credentials: {}'.format(e)) self.authenticate_new()
def gdisconnect(): ''' Method for invalidating stored google's access token ''' credentials = OAuth2Credentials.from_json(login_session.get('credentials')) access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] return result
def locked_get(self): serialized = session.get('google_oauth2_credentials') if serialized is None: return None credentials = OAuth2Credentials.from_json(serialized) credentials.set_store(self) return credentials