def get_creds( self ) -> Tuple[Optional[OAuth2Credentials], Optional[OAuth2Credentials]]: if not self._PATH_CRED_MC.exists() or not self._PATH_CRED_MM.exists(): return None, None return OAuth2Credentials.from_json(self._PATH_CRED_MC.read_text()),\ OAuth2Credentials.from_json(self._PATH_CRED_MM.read_text())
def get_creds( self ) -> Tuple[Optional[OAuth2Credentials], Optional[OAuth2Credentials]]: cred_mc_entity = self._ds.get(self._KEY_CRED_MC) cred_mm_entity = self._ds.get(self._KEY_CRED_MM) if None in (cred_mc_entity, cred_mm_entity): return None, None return OAuth2Credentials.from_json(cred_mc_entity['credentials']),\ OAuth2Credentials.from_json(cred_mm_entity['credentials'])
def login(): '''Login page: this redirect to keycloak if not yet logged in, then print details of the user gathered form the the IdP ''' info = oidc.user_getinfo([ 'preferred_username', 'email', 'sub', ]) username = info.get('preferred_username') email = info.get('email') user_id = info.get('sub') scopes = OAuth2Credentials.from_json( oidc.credentials_store[user_id]).scopes access_token = '' jwt_token = '' if user_id in oidc.credentials_store: try: access_token = OAuth2Credentials.from_json( oidc.credentials_store[user_id] ).access_token # extract access token jwt_token = OAuth2Credentials.from_json( oidc.credentials_store[user_id] ).id_token_jwt # extract jwt token except: print("Can not extract token info") # decode jwt jwt_data = jwt.decode(jwt_token, app.config['SECRET_KEY'], verify=False) print(jwt_data) # Dictinary to pass to the rendered page data = { "username": username, "e-mail": email, "userId": user_id, "scopes": scopes, "access_token": str(access_token), "jwt": jwt_data } # Generating curl string to pass to the rendered page curl_string = 'curl -s -H "Content-Type: application/json" -H "Authorization: Bearer {}" http://localhost:5000/api'.format( access_token) return render_template('login.html', username=username, data=data, curl=curl_string)
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 list_file_in_folder2(request): path_credentials = pathconfigurationfile + "\\" + listconfigurationfile[0] with open(path_credentials) as f: YOUR_ACCESS_TOKEN_IN_JSON_FORMAT = f.readline() gauth = GoogleAuth() gauth.credentials = OAuth2Credentials.from_json( YOUR_ACCESS_TOKEN_IN_JSON_FORMAT) drive = GoogleDrive(gauth) file_list = drive.ListFile({ 'q': "trashed=false", 'corpora': "teamDrive", 'teamDriveId': team_drive_id, 'includeTeamDriveItems': True, 'supportsTeamDrives': True }).GetList() listafile = "" for file1 in file_list: # print('-title: %s, -id: %s, -sharedlink: %s' % (file1['title'], file1['id'], file1['alternateLink'])) listafile += 'title: {}<br>id: {}<br>webContentLink: <a href="{}" target="_blank">webContentLink</a><br>sharedlink: <a href="{}" target="_blank">sharablelink</a><br><br>'.format( file1['title'], file1['id'], file1['webContentLink'], file1['alternateLink']) # print(file1.GetPermissions()) return HttpResponse("<h1>Lista file Team Drive:</h1><br>" + listafile)
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 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 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 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 dashboard(request): # Query Params now = datetime.datetime.utcnow().isoformat() + '-07:00' #California tz offset # Spotify Requests # spotifyCred = get_cred('Jorge Rojas', 'spotify_cred') # print spotifyCred # DEBUG spotifyClient = client.Spotify( auth = spotifyCred ) playlists = spotifyClient.user_playlists( user = '******') # spotify:user:122632253 # print playlists # DEBUG # Calendar Requests # calendarCredJson = get_cred('Jorge Rojas', 'calendar_cred') calendarCred = OAuth2Credentials.from_json(calendarCredJson) http = httplib2.Http() http = calendarCred.authorize(http) service = build('calendar', 'v3', http = http) events = service.events().list( calendarId = '*****@*****.**', orderBy = "startTime", singleEvents = True, maxResults = 10, timeMin = now ).execute() # print events # DEBUG currenttime = datetime.datetime.now() print currenttime context = {'playlists': playlists['items'], 'events':events['items'], 'now':currenttime} return render(request, "dashboard.html", context)
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 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_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 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 __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 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 _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 __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 __init__(self, account_dict=None, account_name=None, userID=None): self.account_dict = account_dict self.account_name = account_name self.userID = userID if userID != None: gauth = GoogleAuth() gauth.credentials = OAuth2Credentials.from_json( decrypt_string(account_dict[account_name]['token'])) global drive self.drive = GoogleDrive(gauth) if account_dict: gauth = GoogleAuth() gauth.credentials = OAuth2Credentials.from_json( decrypt_string(account_dict[account_name]['token'])) global drive drive = GoogleDrive(gauth)
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 __init__(self, credentials): self.credentials = OAuth2Credentials.from_json(credentials) self.name = 'gmail' self.gmail = discovery.build( 'gmail', 'v1', http=self.credentials.authorize(http=httplib2.Http()))
def gdisconnect(): # Only disconnect a connected user credentials = login_session.get('credentials') if not credentials: response = make_response(json.dumps( 'Current user not connected', 401)) response.headers['Content-Type'] = 'application/json' return response else: # Get the credentials object from the JSON string credentials = OAuth2Credentials.from_json(credentials) # Tell Google to revoke the access token access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token={}'.format( access_token) h = httplib2.Http() result = h.request(url, 'GET')[0] # If successful, delete the users session info if result['status'] == '200': response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return response else: # The given token was invalid response = make_response(json.dumps('Failed to revoke for given user'), 400) response.headers['Content-Type'] = 'application/json' return response
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 to_oauth2_creds(self): if self.platform is Platform.YOUTUBE: return OAuth2Credentials.from_json(self.credentials) elif self.platform is Platform.SPOTIFY: return json.loads(self.credentials) else: return None
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 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 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 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 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 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 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 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 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 __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 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 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 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 __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 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 get(self): try: settings = json.loads(self.module.settings) credential = settings["credential"] return OAuth2Credentials.from_json(credential) except (ValueError, KeyError): return None
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_no_unicode_in_request_params(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) http = HttpMock(headers={'status': '200'}) http = credentials.authorize(http) http.request(u'http://example.com', method=u'GET', headers={u'foo': u'bar'}) for k, v in six.iteritems(http.headers): self.assertEqual(six.binary_type, type(k)) self.assertEqual(six.binary_type, type(v)) # Test again with unicode strings that can't simply be converted to ASCII. try: http.request( u'http://example.com', method=u'GET', headers={u'foo': u'\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 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 get(self): try: settings = json.loads(self.module.settings) credential = settings['credential'] return OAuth2Credentials.from_json(credential) except (ValueError, KeyError): return None
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 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 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 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 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 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 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
def locked_get(self): serialized = session.get(_CREDENTIALS_KEY) if serialized is None: return None credentials = OAuth2Credentials.from_json(serialized) credentials.set_store(self) return credentials
def locked_get(self): c = cherrypy.thread_data.db.cursor() c.execute('select credentials from users where id="%s"' % self.id) credentials = c.fetchone() if credentials: credentials = OAuth2Credentials.from_json(credentials[0]) credentials.set_store(self) return credentials return None