def get(self): devices = None updated = 'Never' linkkey = self.request.get('id') fetcherror = 'Key not found' domainname = None if linkkey is not None: customerlink = CustomerLink.get_by_id(int(linkkey)) if customerlink is not None: domainname = customerlink.domainname try: authstorage = StorageByKeyName(CredentialsModel, customerlink.linkeduserid, 'credentials') credentials = authstorage.get() http = httplib2.Http() http = credentials.authorize(http) authstorage.put(credentials) active_users = get_active_users(customerlink.customerid, http) devices = get_devices(active_users, http) updated = datetime.now().strftime('%a, %d %b %Y, %H:%M UTC') fetcherror = None except: fetcherror = traceback.format_exc() variables = { 'linkkey': linkkey, 'domainname': domainname, 'devices': devices, 'updated': updated, 'fetcherror': fetcherror } self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(variables))
def update_calendar(self, calendar_service): """Updates the user's calendar""" # Check if this user is an expert and has an id if self.user_id and self.is_expert: credentials = StorageByKeyName( CredentialsModel, self.user_id, 'credentials').get() if credentials is not None: if credentials.invalid: logging.error("Credentials invalid for %s" % self.email) # return try: email = self.email # Authorize takes care of refreshing an expired token http = credentials.authorize(httplib2.Http()) now = datetime.utcnow().replace(microsecond=0) tomorrow = now + timedelta(days=1) body = {} body['timeMax'] = tomorrow.isoformat() + 'Z' body['timeMin'] = now.isoformat() + 'Z' body['items'] = [{'id': email}] response = calendar_service.freebusy().query(body=body).execute(http=http) logging.info(response) if response.get('calendars') and response['calendars'].get(email) and response['calendars'][email].get('busy') and not response['calendars'][email].get('errors'): # Store the busy schedule logging.info('storing busy schedule') self.busy_time = json.dumps(response['calendars'][email]['busy']) self.put() except AccessTokenRefreshError: logging.error('AccessTokenRefreshError for user id ' + self.user_id)
def get(self): credentials = StorageByKeyName(Credentials, "key_for_credentials", 'credentials').get() PageOutput = "" PageOutput += "<br><br>" if not credentials or credentials.invalid or credentials.refresh_token is None: PageOutput += "Missing OAuth 2.0 Credentials" else: if credentials.refresh_token is not None: PageOutput += "This app has someone's " + str(len(credentials.refresh_token)) + " character refresh token on file!" else: PageOutput += "I can not find your refresh token!" PageOutput += "<br><br>" http = httplib2.Http() http = credentials.authorize(http) resp, content = http.request("https://www.googleapis.com/tasks/v1/users/@me/lists", "GET") ResultObj = json.loads(content) PageOutput += "The account authorizing this app has " + str(len(ResultObj['items'])) + " task list(s)." PageOutput += "<br><br><br>" PageOutput += "<a href='/oauth2authorize'>Authorize</a><br>" PageOutput += "<a href='/'>Check</a><br>" PageOutput += "<a href='/oauth2revoke'>Revoke</a><br>" self.response.out.write(PageOutput)
def _delete_creds(userid): storage = StorageByKeyName(CredentialsNDBModel, userid, "credentials") if storage.get(): credentials = storage.locked_delete() return True return False
def get(self): gcp_cred_storage = StorageByKeyName(GcpCredentials, self.user_bundle.user.user_id(), 'credentials') gcp_creds = gcp_cred_storage.get() if gcp_creds is None: if ann_config.oauth_decorator.has_credentials(): gcp_creds = ann_config.oauth_decorator.credentials gcp_cred_storage.put(gcp_creds) else: self.template_values.update({ "auth_url": ann_config.oauth_decorator.authorize_url(), }) path = os.path.join( os.path.dirname(__file__), '../templates/gcp_authorization_request.html') self.response.write(template.render(path, self.template_values)) return None http = gcp_creds.authorize(httplib2.Http()) resp, content = http.request('http://www.google.com/cloudprint/search') response_json = json.loads(content) printers = response_json["printers"] self.template_values.update({ "printers": printers, }) path = os.path.join(os.path.dirname(__file__), '../templates/printer_add.html') self.response.write(template.render(path, self.template_values))
def get(self): user = users.get_current_user() credentials = StorageByKeyName( Credentials, user.user_id(), 'credentials').get() if credentials is None or credentials.invalid == True: flow = OAuth2WebServerFlow( # Visit https://code.google.com/apis/console to # generate your client_id, client_secret and to # register your redirect_uri. client_id='<YOUR CLIENT ID HERE>', client_secret='<YOUR CLIENT SECRET HERE>', scope='https://www.googleapis.com/auth/buzz', user_agent='buzz-cmdline-sample/1.0', domain='anonymous', xoauth_displayname='Google App Engine Example App') callback = self.request.relative_url('/auth_return') authorize_url = flow.step1_get_authorize_url(callback) memcache.set(user.user_id(), pickle.dumps(flow)) self.redirect(authorize_url) else: http = httplib2.Http() http = credentials.authorize(http) service = build("buzz", "v1", http=http) activities = service.activities() activitylist = activities.list(scope='@consumption', userId='@me').execute() path = os.path.join(os.path.dirname(__file__), 'welcome.html') logout = users.create_logout_url('/') self.response.out.write( template.render( path, {'activitylist': activitylist, 'logout': logout }))
def get_credentials(user_id): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ storage = StorageByKeyName(CredentialsNDBModel, user_id, 'credentials') credentials = storage.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets( CLIENT_SECRET_FILE, SCOPES, redirect_uri=ridelisterconfig['ridelister']['callbackurl'], # redirect_uri="https://localhost:8080/oauth2callback", ) # Todo - Look this one up... flow.user_agent = APPLICATION_NAME # credentials = tools.run_flow(flow, storage) # print('Storing credentials') auth_uri = str(flow.step1_get_authorize_url()) return credentials
def _get_creds(userid): """ We store the credentials by google userid from the users api. """ storage = StorageByKeyName(CredentialsNDBModel, userid, "credentials") credentials = storage.get() return credentials
def get(self): gcp_cred_storage = StorageByKeyName(GcpCredentials, self.user_bundle.user.user_id(), 'credentials') gcp_creds = gcp_cred_storage.get() if gcp_creds is None: if ann_config.oauth_decorator.has_credentials(): gcp_creds = ann_config.oauth_decorator.credentials gcp_cred_storage.put(gcp_creds) else: self.template_values.update({ "auth_url": ann_config.oauth_decorator.authorize_url(), }) path = os.path.join(os.path.dirname(__file__), '../templates/gcp_authorization_request.html') self.response.write(template.render(path, self.template_values)) return None http = gcp_creds.authorize(httplib2.Http()) resp, content = http.request('http://www.google.com/cloudprint/search') response_json = json.loads(content) printers = response_json["printers"] self.template_values.update({ "printers": printers, }) path = os.path.join(os.path.dirname(__file__), '../templates/printer_add.html') self.response.write(template.render(path, self.template_values))
def _deliver_test(self): """Print to the admins printer.""" gcp_cred_storage = StorageByKeyName(GcpCredentials, self.user.user_id(), 'credentials') gcp_creds = gcp_cred_storage.get() if not gcp_creds: return self.redirect("/printers/add") account = Account.get_or_insert(self.user_bundle.user.user_id()) printers = Printer.query(Printer.owner == account.key).fetch(1000) PrintJobEnqueuer.enqueue_to_printers( printers, self.request.get("deliver_title"), self.request.get("deliver_url") ) self.template_values.update({ "deliver_title": self.request.get("deliver_title"), "deliver_url": self.request.get("deliver_url"), "printer_names": [printer.display_name for printer in printers] }) path = os.path.join(os.path.dirname(__file__), '../templates/admin_deliver.html') self.response.write(template.render(path, self.template_values))
def create_playlist(self): ''' Creates a new playlist on YouTube and persist it as a Playlist instance in datastore. ''' now_date = datetime.now().date() print "create_playlist start" credentials = StorageByKeyName( CredentialsModel, self.user_id, 'credentials').get() print "create_playlist got creds" http = credentials.authorize(Http()) print "create_playlist authorized creds" request = YOUTUBE.playlists().insert( part="snippet,status", body={'snippet': {'title': "DailyGrooves %s" % now_date, 'description': "DailyGrooves %s" % now_date}, 'status': {'privacyStatus': 'public'} } ) response = request.execute(http=http) print "create_playlist executed req" self.playlist_id = response["id"] playlist = Playlist(id=self.playlist_id, date=datetime.now()) playlist.put() print "Playlist: http://www.youtube.com/id?list=%s" % self.playlist_id
def get(self): try: # Read server-side OAuth 2.0 credentials from datastore and # raise an exception if credentials not found. credentials = StorageByKeyName(CredentialsModel, USER_AGENT, 'credentials').locked_get() if not credentials or credentials.invalid: raise Exception('missing OAuth 2.0 credentials') # Authorize HTTP session with server credentials and obtain # access to prediction API client library. http = credentials.authorize(httplib2.Http()) service = build('prediction', 'v1.5', http=http) papi = service.trainedmodels() # Build prediction data (csvInstance) dynamically based on form input. vals = [] body = {'input' : {'csvInstance' : [str(self.request.get('text'))] }} # Make a prediction and return JSON results to Javascript client. ret = papi.predict(id='bullying', body=body).execute() print ret self.response.headers['Content-Type'] = 'application/javascript' self.response.out.write(json.dumps(ret)) except Exception, err: # Capture any API errors here and pass response from API back to # Javascript client embedded in a special error indication tag. err_str = str(err) if err_str[0:len(ERR_TAG)] != ERR_TAG: err_str = ERR_TAG + err_str + ERR_END self.response.out.write(err_str)
def post(self): data = json.loads(self.request.body) # Returns a 403 Forbidden (authenticating will make no difference) if data.get('verifyToken') != 'I_AM_YOUR_FATHER': logging.error('Unauthorized request to the subscription endpoint.') return self.abort(403) # Get the credentials, you could also check credentials.refresh_token is not None self.user_id = data.get('userToken') credentials = StorageByKeyName(CredentialsModel, self.user_id, 'credentials').get() if not credentials: logging.error('Authentication is required and has failed.') return self.abort(401) # http was previously authorized by the decorator self.http = credentials.authorize(httplib2.Http()) try: # Handle the appropriate type of subscription if data.get('collection') == 'locations': self._handle_location(data) elif data.get('collection') == 'timeline': self._handle_timeline(data) except Exception as e: logging.error('Failed SubscriptionHandler for user_id %s: %s', (self.user_id, str(e)))
def get(self): user = users.get_current_user() user_id = user.user_id() credentials = StorageByKeyName( Credentials,user_id, 'credentials').get() lCred = LinkedInCred.get_by_key_name(user_id) if credentials is None or credentials.invalid == True: callback = self.request.relative_url('/oauth2callback') authorize_url = FLOW.step1_get_authorize_url(callback) memcache.set(user_id + 'goog', pickle.dumps(FLOW)) self.redirect(authorize_url) elif lCred is None: user = users.get_current_user() request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken' client = oauth.Client(consumer) callback = self.request.relative_url('/linkedin') resp,content = client.request(request_token_url,"POST",body=urllib.urlencode({'oauth_callback':callback})) request_token = dict(cgi.parse_qsl(content)) memcache.set(user_id + 'linked',pickle.dumps(request_token)) authorize_url = 'https://api.linkedin.com/uas/oauth/authorize?oauth_token=%s&oauth_callback=%s' % (request_token['oauth_token'],'http://localhost:8080/linkedin') self.redirect(authorize_url) else: http = httplib2.Http() http = credentials.authorize(http) service = build("calendar", "v3", http=http) date = datetime.now() rfc_stamp = rfc3339(date) events = service.events().list(calendarId='primary',singleEvents=True,orderBy='startTime', maxResults=5,timeMin=rfc_stamp).execute() s = Sentinal(lCred.user_key,lCred.user_secret) sidebar = [] getID = self.request.get('getID') sq = None for event in events['items']: if getID == event['id']: sq = event['summary'] sidebar.append({'id':event['id'],'name':event['summary']}) if sq is None: getID = sidebar[0]['id'] sq = sidebar[0]['name'] entities = sq.split(',') cache_get = memcache.get(getID) if cache_get: resp = pickle.loads(cache_get) else: if(len(entities) < 2): self.redirect('http://i.imgur.com/mvXs4.png') return resp = s.createResponse(sidebar,entities[0],entities[1]) memcache.set(getID,pickle.dumps(resp),time=600) path = os.path.join(os.path.dirname(__file__),'tesdex.html') self.response.out.write(template.render(path,resp))
def create_playlist(self, playlistName, epochValue): ''' Creates a new playlist on YouTube with given name and persist it as a MonthlyPlaylist instance in datastore. ''' print "create_playlist start" credentials = StorageByKeyName( CredentialsModel, self.user_id, 'credentials').get() print "create_playlist got creds" http = credentials.authorize(Http()) print "create_playlist authorized creds" request = YOUTUBE.playlists().insert( part="snippet,status", body=dict( snippet=dict( title=playlistName, description="Songs added in %s" % playlistName ), status=dict( privacyStatus="public" ) ) ) response = request.execute(http=http) print "create_playlist executed req" playlist_id = response["id"] playlist = MonthlyPlaylist(id=playlist_id, name=playlistName, epochVal=epochValue, date=datetime.now(), counter=0) playlist.put() print "Playlist created: http://www.youtube.com/id?list=%s" % playlist_id self.memcache_today_playlists() return playlist
def create_playlist(self): ''' Creates a new playlist on YouTube and persist it as a Playlist instance in datastore. ''' now_date = datetime.now().date() print "create_playlist start" credentials = StorageByKeyName(CredentialsModel, self.user_id, 'credentials').get() print "create_playlist got creds" http = credentials.authorize(Http()) print "create_playlist authorized creds" request = YOUTUBE.playlists().insert( part="snippet,status", body={ 'snippet': { 'title': "DailyGrooves %s" % now_date, 'description': "DailyGrooves %s" % now_date }, 'status': { 'privacyStatus': 'public' } }) response = request.execute(http=http) print "create_playlist executed req" self.playlist_id = response["id"] playlist = Playlist(id=self.playlist_id, date=datetime.now()) playlist.put() print "Playlist: http://www.youtube.com/id?list=%s" % self.playlist_id
def get(self): service = None user = users.get_current_user() user_id = user.user_id() credentials = StorageByKeyName( Credentials,user_id, 'credentials').get() if credentials is None or credentials.invalid == True: callback = self.request.relative_url('/oauth2callback') authorize_url = FLOW.step1_get_authorize_url(callback) memcache.set(user_id + 'goog', pickle.dumps(FLOW)) return self.redirect(authorize_url) else: http = httplib2.Http() http = credentials.authorize(http) service = build("drive", "v2", http=http) file_entry = retrieve_file_by_name(service,'SleepTime by.txt')[0] print type(file_entry) #print file_entry['exportLinks']['application/pdf'] #f = get_file(service,file_entry['id']) tsv_data = download_file(service,file_entry) read_into_db(tsv_data) self.response.write('Hello world!')
def store_credentials(gplus_id, test, credentials): """Stores credentials for the provide Google+ User ID to Datastore""" if test is not None: storage = StorageByKeyName(utils.TestUser, gplus_id, "credentials") else: storage = StorageByKeyName(utils.User, gplus_id, "credentials") storage.put(credentials)
def post(self): calendaruserid = self.request.get('calendaruserid') calendarid = self.request.get('calendarid') creds = StorageByKeyName(Credentials, calendaruserid, 'credentials').get() http = httplib2.Http() http = creds.authorize(http) service = build(serviceName='calendar', version='v3', http=http, developerKey='AIzaSyD51wdv-kO02p29Aog7OXmL2eEG0F5ngZM') events = service.events().list(calendarId=calendarid).execute() for event in events['items']: if str(datetime.date.today()) == event['start']['date']: filterdiclist = [{'operator' : 'userid = ', 'value' : calendaruserid},{'operator' : 'notificationsetting = ', 'value' : 'Yes'}] query = dbQuery() user_list = query.get_results(userProfile, 1, filterdiclist) mail.send_mail(sender="*****@*****.**", to=user_list[0].emailaddress, subject="Here is your run today!", body=""" Dear """ + user_list[0].firstname + """ """ + user_list[0].lastname + """ Your run today is the following: """ + event['summary'] + """ Thanks! The race date setter app!""" )
def get_credentials(gplus_id, test): """Retrieves credentials for the provided Google+ User ID from the Datastore""" if test is not None: storage = StorageByKeyName(utils.TestUser, gplus_id, "credentials") else: storage = StorageByKeyName(utils.User, gplus_id, "credentials") credentials = storage.get() return credentials
def get_credentials(gplus_id, test): """Retrieves credentials for the provided Google+ User ID from the Datastore""" if test is not None: storage = StorageByKeyName(TestUser, gplus_id, "credentials") else: storage = StorageByKeyName(User, gplus_id, "credentials") credentials = storage.get() return credentials
def test_get_and_put_simple(self): storage = StorageByKeyName(CredentialsModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) self.credentials.set_store(storage) self.credentials._refresh(_http_request) credmodel = CredentialsModel.get_by_key_name('foo') self.assertEqual('bar', credmodel.credentials.access_token)
def oauth2redirect(request): user = users.get_current_user() storage = StorageByKeyName(CredentialsModel, user.user_id(), 'credentials') credentials = storage.get() # if not credentials or not credentials.refresh_token: # return __initial_oauth_flow(request, approval_prompt='force') # Use approval_prompt='force' to ensure the refresh token is good. return __initial_oauth_flow(request, approval_prompt='force')
def test_get_and_put_simple(self): storage = StorageByKeyName(CredentialsModel, "foo", "credentials") self.assertEqual(None, storage.get()) self.credentials.set_store(storage) self.credentials._refresh(_http_request) credmodel = CredentialsModel.get_by_key_name("foo") self.assertEqual("bar", credmodel.credentials.access_token)
def get_posts(self, migration, scan_url=None): """Fetches a page of posts. Args: migration: Migration scan_url: string, the API URL to fetch the current page of posts. If None, starts at the beginning. Returns: (posts, next_scan_url). posts is a sequence of Migratables. next_scan_url is a string, the API URL to use for the next scan, or None if there is nothing more to scan. """ # TODO: expose as options # https://dev.googleplus.com/docs/api/1.1/get/statuses/user_timeline # get this user's OAuth credentials credentials = StorageByKeyName(CredentialsModel, self.gae_user_id, 'credentials').get() if not credentials: logging.error('Giving up: credentials not found for user id %s.', self.gae_user_id) self.error(299) return # TODO: convert scan_url to paging param(s) # if not scan_url: # scan_url = API_POSTS_URL % self.key().name() # gp = as_googleplus.GooglePlus(None) # resp = json.loads(gp.urlfetch(scan_url)) # fetch the json stream and convert it to atom. # (if i use collection 'user' instead of 'public', that would get *all* # posts, not just public posts, but that's not allowed yet. :/ ) resp = json_service.activities().list(userId='me', collection='public')\ .execute(credentials.authorize(httplib2.Http())) posts = [] for post in resp['items']: id = post['id'] app = post.get('source') if app and app in APPLICATION_BLACKLIST: logging.info('Skipping post %d', id) continue posts.append(GooglePlusPost(key_name_parts=(str(id), migration.key().name()), json_data=json.dumps(post))) next_scan_url = None # if posts: # scan_url + '&max_id=%s' % posts[-1].id() # # XXX remove # if posts and posts[-1].data()['created_time'] < '2013-01-01': # next_scan_url = None # # XXX return posts, next_scan_url
def get_posts(self, migration, scan_url=None): """Fetches a page of posts. Args: migration: Migration scan_url: string, the API URL to fetch the current page of posts. If None, starts at the beginning. Returns: (posts, next_scan_url). posts is a sequence of Migratables. next_scan_url is a string, the API URL to use for the next scan, or None if there is nothing more to scan. """ # TODO: expose as options # https://dev.googleplus.com/docs/api/1.1/get/statuses/user_timeline # get this user's OAuth credentials credentials = StorageByKeyName(CredentialsModel, self.gae_user_id, "credentials").get() if not credentials: logging.error("Giving up: credentials not found for user id %s.", self.gae_user_id) self.error(299) return # TODO: convert scan_url to paging param(s) # if not scan_url: # scan_url = API_POSTS_URL % self.key().name() # gp = as_googleplus.GooglePlus(None) # resp = json.loads(gp.urlfetch(scan_url)) # fetch the json stream and convert it to atom. # (if i use collection 'user' instead of 'public', that would get *all* # posts, not just public posts, but that's not allowed yet. :/ ) resp = ( json_service.activities() .list(userId="me", collection="public") .execute(credentials.authorize(httplib2.Http())) ) posts = [] for post in resp["items"]: id = post["id"] app = post.get("source") if app and app in APPLICATION_BLACKLIST: logging.info("Skipping post %d", id) continue posts.append(GooglePlusPost(key_name_parts=(str(id), migration.key().name()), json_data=json.dumps(post))) next_scan_url = None # if posts: # scan_url + '&max_id=%s' % posts[-1].id() # # XXX remove # if posts and posts[-1].data()['created_time'] < '2013-01-01': # next_scan_url = None # # XXX return posts, next_scan_url
def _get_cat_fact_insert_request(self, userid, body): """Poll Twitter feed for the provided user.""" try: creds = StorageByKeyName(UserSettings, userid, 'credentials').get() creds.refresh(httplib2.Http()) service = util.create_service('mirror', 'v1', creds) return service.timeline().insert(body=body) except AccessTokenRefreshError: logging.error('Unable to refresh token for user %s', userid) return None
def acquireLatestCredentials(user_id): """Returns credentials, and refreshes them if necessary.""" storage = StorageByKeyName(CredentialsModel, user_id, 'credentials') credentials = storage.get() if credentials.access_token_expired: logging.info('Credentials expired. Attempting to refresh...') credentials.refresh(httplib2.Http()) storage.put(credentials) logging.info('Successfully refreshed access token!') return credentials
def get(self): flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, scope=' '.join(SCOPES), redirect_uri=REDIRECT_URI) flow.params['access_type'] = 'offline' credentials = flow.step2_exchange(self.request.get('code')) storage = StorageByKeyName(AdminCredentialsModel, 'theadminaccount', 'credentials') storage.put(credentials) self.redirect('/')
def build_gmail_service_for_user(userId): if not Constants.TEST_CONTEXT: storage = StorageByKeyName(CredentialsModel, userId, "credentials") credentials = storage.get() return GmailService(credentials) else: with open("gmailytics/test/credentials.json") as f: data = f.read() credentials = OAuth2Credentials.from_json(data) return GmailService(credentials)
def get(self): # check if credential already setup credentials = StorageByKeyName(CredentialsModel, USER_AGENT, 'credentials').locked_get() if not credentials or credentials.invalid: flow = OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope=scope, user_agent=USER_AGENT, access_type = 'offline', approval_prompt='force', redirect_uri=self.request.relative_url('/auth_return') ) authorize_url = flow.step1_get_authorize_url() memcache.set('a', pickle.dumps(flow)) self.redirect(authorize_url) else: try: #"2nd around after getting auth, now do the query" print("2nd around after getting auth, now do the query\n") # read query.csv returns list of query bodys bodyitems = readquery('query.csv') print("query lines: " +json.dumps(bodyitems) +'\n') http = credentials.authorize(httplib2.Http()) service = build('prediction', 'v1.6', http=http) for items in bodyitems: result = service.trainedmodels().predict( project=projid, id=modelid, body=items).execute() querystring = json.dumps(items['input']['csvInstance']) if 'outputValue' in result: resultitem = json.dumps(result['outputValue']) else: resultitem = json.dumps(result['outputLabel']) response_result = 'Result: ' + resultitem # cant write in appengine outputdata(result, 'output') print(querystring + " " +response_result +'\n') self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(querystring + " " +response_result +'\n') except Exception, err: err_str = str(err) self.response.out.write(err_str)
def GetCodeCredentials(self): """Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0. The authorization code is extracted form the URI parameters. If it is absent, None is returned immediately. Otherwise, if it is present, it is used to perform step 2 of the OAuth 2.0 web server flow. Once a token is received, the user information is fetched from the userinfo service and stored in the session. The token is saved in the datastore against the user ID received from the userinfo service. Args: request: HTTP request used for extracting an authorization code and the session information. Returns: OAuth2.0 credentials suitable for authorizing clients or None if Authorization could not take place. """ # Other frameworks use different API to get a query parameter. logging.debug('Get credentials from URL') code = self.request.get('code') if not code: logging.debug('No code in URL') # returns None to indicate that no code was passed from Google Drive. return None # Auth flow is a controller that is loaded with the client information, # including client_id, client_secret, redirect_uri etc oauth_flow = self.CreateOAuthFlow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: logging.debug('Oauth flow step2 exchange') creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None # Create an API service that can use the userinfo API. Authorize it with our # credentials that we gained from the code exchange. ut users_service = self.CreateService('oauth2', 'v2', creds) # Make a call against the userinfo service to retrieve the user's information. # In this case we are interested in the user's "id" field. user = users_service.userinfo().get().execute() userid = user['id'] # Store the user id in the user's cookie-based session. self.session['userid'] = userid # Store the credentials in the data store using the userid as the key. logging.debug('Saving credentials and email in datastore') StorageByKeyName(Credentials, userid, 'credentials').put(creds) StorageByKeyName(RegisteredUser, userid, 'email').put(user['email']) return creds
def test_get_and_put_ndb(self): # Start empty storage = StorageByKeyName(CredentialsNDBModel, "foo", "credentials") self.assertEqual(None, storage.get()) # Refresh storage and retrieve without using storage self.credentials.set_store(storage) self.credentials._refresh(_http_request) credmodel = CredentialsNDBModel.get_by_id("foo") self.assertEqual("bar", credmodel.credentials.access_token) self.assertEqual(credmodel.credentials.to_json(), self.credentials.to_json())
def test_get_and_put_ndb(self): # Start empty storage = StorageByKeyName(CredentialsNDBModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) # Refresh storage and retrieve without using storage self.credentials.set_store(storage) self.credentials._refresh(_http_request) credmodel = CredentialsNDBModel.get_by_id('foo') self.assertEqual('bar', credmodel.credentials.access_token) self.assertEqual(credmodel.credentials.to_json(), self.credentials.to_json())
def get_access_token(): """Used to check app activation and append token to urls""" # Check if access token is in storage storage = StorageByKeyName(CredentialsModel, 'token', 'credentials') credentials = storage.get() if not credentials: return False return credentials.access_token
def _refresh_oauth2_token(credentials, userid): """ This updates the token via the OAuth2Credentials code and modifies the httplib2.Http.request stuff. We store the updated credentials for later. """ http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) storage = StorageByKeyName(CredentialsNDBModel, userid, 'credentials') storage.put(credentials) return credentials
def EndpointsGetAuthorizedHttp(): """Sign an Http with user credentials. Returns: Http: An authorized Http connection. """ user = users.get_current_user() storage = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials') credentials = storage.get() http = Http() return credentials.authorize(http)
def test_get_and_put_mixed_db_storage_ndb_get(self): # Start empty storage = StorageByKeyName(CredentialsModel, "foo", "credentials") self.assertEqual(None, storage.get()) # Set DB store and refresh to add to storage self.credentials.set_store(storage) self.credentials._refresh(_http_request) # Retrieve same key from NDB model to confirm mixing works credmodel = CredentialsNDBModel.get_by_id("foo") self.assertEqual("bar", credmodel.credentials.access_token) self.assertEqual(self.credentials.to_json(), credmodel.credentials.to_json())
class OAuthCodeExchangeHandler(webapp2.RequestHandler): """Request handler for OAuth 2.0 code exchange.""" @errors.error_aware def post(self): """Handle code exchange.""" self._process_request_body() self._exchange_code() user = self._create_user() util.write_response(self, user.to_dict()) def _process_request_body(self): """Parse the request body.""" try: request = json.loads(self.request.body) self._code = request.get('code') if not self._code: raise errors.BadRequestError('`code` attribute is required') self._timezone_offset = request.get( 'timezoneOffset', DEFAULT_TIMEZONE_OFFSET) except ValueError: raise errors.BadRequestError('Unsupported request body') def _exchange_code(self): """Retrieve credentials for the current user.""" oauth_flow = self._create_oauth_flow() # Perform the exchange of the code. try: creds = oauth_flow.step2_exchange(self._code) except FlowExchangeError, e: raise errors.InternalServerError('Unable to exchange code: ', e.message) # Verify that the token has been issued for our application. self._userid = util.verify_token(creds.access_token) if not self._userid: raise errors.BadRequestError('Unknown client ID') # Verify that we can retrieve valid refresh token for the current user. if creds.refresh_token: # Store the credentials in the data store using the userid as the key. StorageByKeyName( model.UserSettings, self._userid, 'credentials').put(creds) else: # Look for existing credentials in our datastore. creds = StorageByKeyName( model.UserSettings, self._userid, 'credentials').get() if not creds or not creds.refresh_token: raise errors.UnauthorizedError('No refresh token') return creds
def test_get_and_put_mixed_db_storage_ndb_get(self): # Start empty storage = StorageByKeyName(CredentialsModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) # Set DB store and refresh to add to storage self.credentials.set_store(storage) self.credentials._refresh(_http_request) # Retrieve same key from NDB model to confirm mixing works credmodel = CredentialsNDBModel.get_by_id('foo') self.assertEqual('bar', credmodel.credentials.access_token) self.assertEqual(self.credentials.to_json(), credmodel.credentials.to_json())
def post(self): try: # Read server-side OAuth 2.0 credentials from datastore and # raise an exception if credentials not found. credentials = StorageByKeyName(CredentialsModel, USER_AGENT, 'credentials').locked_get() if not credentials or credentials.invalid: raise Exception('missing OAuth 2.0 credentials') # Authorize HTTP session with server credentials and obtain # access to prediction API client library. http = credentials.authorize(httplib2.Http()) service = build('prediction', 'v1.6', http=http) # Read and parse JSON model description data. models = parse_json_file(MODELS_FILE) # Get reference to user's selected model. model_name = self.request.get('model') model = models[model_name] # Build prediction data (csvInstance) dynamically based on form input. vals = [] for field in model['fields']: label = field['label'] val = self.request.get(label).encode('utf-8') vals.append(val) body = {'input': {'csvInstance': vals}} logging.info('model:' + model_name + ' body:' + str(body)) # Make a prediction and return JSON results to Javascript client. if model['type'] == 'hosted': ret = service.hostedmodels().predict( project=model['project'], hostedModelName=model['hostedModelName'], body=body).execute() if model['type'] == 'trained': ret = service.trainedmodels().predict(id=model['id'], project=model['project'], body=body).execute() self.response.out.write(json.dumps(ret)) except Exception, err: # Capture any API errors here and pass response from API back to # Javascript client embedded in a special error indication tag. err_str = str(err) if err_str[0:len(ERR_TAG)] != ERR_TAG: err_str = ERR_TAG + err_str + ERR_END self.response.out.write(err_str)
def oauth2callback(request): user = users.get_current_user() flow = pickle.loads(memcache.get(user.user_id())) try: credentials = flow.step2_exchange(request.GET) request.session['credentials'] = credentials storage = StorageByKeyName(CredentialsModel, user.user_id(), 'credentials') storage.put(credentials) redirect = request.session.get('redirect', '/') return HttpResponseRedirect(redirect) except FlowExchangeError: logger.exception('Failed to authenticate') return HttpResponseRedirect(reverse(settings.OAUTH_FAILED_REDIRECT))
def getService(): flow = flow_from_clientsecrets( 'client_secrets.json', scope='https://www.googleapis.com/auth/youtube', redirect_uri='http://localhost:8080/oauth2callback') user = users.get_current_user() storage = StorageByKeyName(CredentialsModel, user.user_id(), 'credentials') credentials = storage.get() http = httplib2.Http() http = credentials.authorize(http) authenticated_service = build('youtube', 'v3', http=http) return authenticated_service
def GetSessionCredentials(self): """Get OAuth 2.0 credentials for an HTTP session. If the user has a user id stored in their cookie session, extract that value and use it to load that user's credentials from the data store. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ # Try to load the user id from the session session = sessions.LilCookies(self, SESSION_SECRET) userid = session.get_secure_cookie(name='userid') if not userid: # return None to indicate that no credentials could be loaded from the # session. return None # Load the credentials from the data store, using the userid as a key. creds = StorageByKeyName(Credentials, userid, 'credentials').get() # if the credentials are invalid, return None to indicate that the credentials # cannot be used. if creds and creds.invalid: return None return creds
def GetSessionCredentials(self): """Get OAuth 2.0 credentials for an HTTP session. If the user has a user id stored in their cookie session, extract that value and use it to load that user's credentials from the data store. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ # Try to load the user id from the session userid = None if 'userid' in self.session: logging.debug('Get credentials for %s from session', userid) userid = self.session['userid'] if not userid: # return None to indicate that no credentials could be loaded from the # session. return None # Load the credentials from the data store, using the userid as a key. logging.debug('Get credentials for %s from datastore', userid) creds = StorageByKeyName(Credentials, userid, 'credentials').get() # if the credentials are invalid, return None to indicate that the credentials # cannot be used. if creds and creds.invalid: logging.debug('Invalid credentials') return None return creds
def get_credentials(self, check_cookie=True): if check_cookie: creds = self.get_session_credentials() if creds: return creds code = self.request.REQUEST.get('code', '') if not code: return None oauth_flow = self.CreateOAuthFlow() try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None users_service = CreateService('oauth2', 'v2', creds) info = users_service.userinfo().get().execute() self.userid = info.get('id') email = info.get('email') created, self.prefs = get_or_create(Preferences, queries=(('userid =', self.userid), ), defaults={ 'userid': self.userid, 'email': email }) if created: self.prefs.put() StorageByKeyName(Credentials, self.userid, 'credentials').put(creds) return creds
def get_authorized_client(self): """Create an authorize service instance. The service can only ever retrieve the credentials from the session. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). Returns: Authorized service or redirect to authorization flow if no credentials. """ # For the service, the session holds the credentials logging.debug('Creating authorized Evernote client instance') creds = self.get_session_credentials() client = self.get_client() if creds: # If the session contains credentials, use them to create a Drive service # instance. client.token = creds return client elif 'oauth_token' in self.session and 'oauth_token_secret' in self.session and self.request.get('oauth_verifier'): # If no credentials could be loaded from the session, redirect the user to # the authorization page. access_token = client.get_access_token(self.session['oauth_token'], self.session['oauth_token_secret'], self.request.get('oauth_verifier')) user_store = client.get_user_store() self.session['evernote_user_id'] = str(user_store.getUser().id) StorageByKeyName(EvernoteCredentials, self.session['evernote_user_id'], 'credentials').put(access_token) return client else: return None
def post(self): gcp_cred_storage = StorageByKeyName(GcpCredentials, self.user_bundle.user.user_id(), 'credentials') gcp_creds = gcp_cred_storage.get() if not gcp_creds: return self.redirect("/printers/add") printer = Printer.get_by_id(int(self.request.get("printer_key_id"))) PrintJobEnqueuer.enqueue_to_printer( printer, "Distributed Press Test Print", "http://distributedpress.appspot.com") self.redirect("/dashboard")
def build_service_account_credentials(scope, user=None): """ Builds service account credentials using the configuration stored in :mod:`~ferris3.settings` and masquerading as the provided user. """ if not SignedJwtAssertionCredentials: raise EnvironmentError( "Service account can not be used because PyCrypto is not available. Please install PyCrypto." ) config = _get_config() if not isinstance(scope, (list, tuple)): scope = [scope] key = _generate_storage_key(config['client_email'], scope, user) storage = StorageByKeyName(ServiceAccountStorage, key, 'credentials') creds = SignedJwtAssertionCredentials( service_account_name=config['client_email'], private_key=config['private_key'], scope=scope, prn=user) creds.set_store(storage) return creds
def get(self): """Handle code exchange.""" code = self.request.get('code') if not code: # TODO: Display error. return None oauth_flow = self.create_oauth_flow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: # TODO: Display error. return None users_service = util.create_service('oauth2', 'v2', creds) # TODO: Check for errors. user = users_service.userinfo().get().execute() userid = user.get('id') # Store the credentials in the data store using the userid as the key. # TODO: Hash the userid the same way the userToken is. StorageByKeyName(Credentials, userid, 'credentials').put(creds) logging.info('Successfully stored credentials for user: %s', userid) util.store_userid(self, userid) self._perform_post_auth_tasks(userid, creds) self.redirect('http://www.glasseats.com/thank-you/')
def _insert_item_all_users(self): """Insert a timeline item to all authorized users.""" logging.info('Inserting timeline item to all users') users = Credentials.all() total_users = users.count() if total_users > 10: return 'Total user count is %d. Aborting broadcast to save your quota' % ( total_users) body = { 'text': 'Hello Everyone!', 'notification': { 'level': 'DEFAULT' } } batch_responses = _BatchCallback() batch = BatchHttpRequest(callback=batch_responses.callback) for user in users: creds = StorageByKeyName(Credentials, user.key().name(), 'credentials').get() mirror_service = util.create_service('mirror', 'v1', creds) batch.add(mirror_service.timeline().insert(body=body), request_id=user.key().name()) batch.execute(httplib2.Http()) return 'Successfully sent cards to %d users (%d failed).' % ( batch_responses.success, batch_responses.failure)
def handle(self, playlist_id): try: self.playlist_metadata = model.PlaylistMetadata.gql( "WHERE playlist_id = :1", playlist_id)[0] except IndexError: self.error(404) self.response.out.write("Party Playlist Picker does not know about playlist %s." % escape(playlist_id)) return if users.get_current_user() != self.playlist_metadata.owner: if self.request.get("uuid", -1) != self.playlist_metadata.uuid: self.error(401) self.response.out.write("You are not authorized to view this page.") return owner_id = self.playlist_metadata.owner.user_id() owner_credentials = StorageByKeyName(CredentialsModel, owner_id, 'credentials').get() self.owner_oauth_token = owner_credentials.access_token try: me = memcacheutils.cache_call( key=self.oauth2_decorator.credentials.access_token, namespace="oauth2_token_to_user", time=memcacheutils.USER_EXPIRATION_SECS, f=lambda: googleplusutils.service.people().get(userId="me").execute( webutils.create_authorized_http_with_timeout( self.oauth2_decorator.credentials))) except HttpError, e: if e.resp['status'] == 404: webutils.render_to_response(self, "no_profile.html") return raise
def get_session_credentials(self): if 'evernote_user_id' in self.session: user_id = self.session['evernote_user_id'] return StorageByKeyName(EvernoteCredentials, user_id, 'credentials').get() else: return None