def get_credentials(self): """ Taken from: taken from https://developers.google.com/google-apps/calendar/quickstart/python 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. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'table-for-2.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.OAuth2WebServerFlow( client_id=MATCHING_KEY, client_secret=MATCHING_SECRET, scope='https://www.googleapis.com/auth/calendar', redirect_uris= 'http://localhost, https://tablefortwo.herokuapp, http://tablefortwo.herokuapp' ) flow.user_agent = APPLICATION_NAME if flags: flags.noauth_local_webserver = True credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials
def main(): flow = client.OAuth2WebServerFlow( client_id=credentials.client_id, # client id client_secret=credentials.client_secret, # client secret scope=credentials.scopes, user_agent='Python Developement Client Library', redirect_uri=credentials.redirect_uri, access_type='offline') authorize_url = flow.step1_get_authorize_url() print( 'Log into the Google Account you use to access your Analytics account' 'and go to the following URL: \n{}\n\nAfter approving the token enter ' 'the verification code (if specified).'.format(authorize_url)) code = input('Code: ').strip() try: credential = flow.step2_exchange(code) printtext = ( 'OAuth 2.0 authorization successful!\n\n' 'Your access token is:\n {}\n\nYour refresh token is:\n {}'.format( credential.access_token, credential.refresh_token)) print(printtext) except: sys.exit(1)
def main(application_name, client_id, client_secret, scope, user_agent): """Retrieve credentials and create an DfpClient. Args: client_id: Your client id retrieved from the Google Developers Console. client_secret: Your client secretretrieved from the Google Developers Console. user_agent: A semi-unique string identifying this client. """ flow = client.OAuth2WebServerFlow(client_id=client_id, client_secret=client_secret, scope=[scope], user_agent=user_agent, redirect_uri='urn:ietf:wg:oauth:2.0:oob') authorize_url = flow.step1_get_authorize_url() print( 'Log into the Google Account you use to access your Dfp account' 'and go to the following URL: \n%s\n' % (authorize_url)) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: credential = flow.step2_exchange(code) except client.FlowExchangeError, e: print 'Authentication has failed: %s' % e sys.exit(1)
def _make_flow(request, scopes, return_url=None): """Creates a Web Server Flow Args: request: A Django request object. scopes: the request oauth2 scopes. return_url: The URL to return to after the flow is complete. Defaults to the path of the current request. Returns: An OAuth2 flow object that has been stored in the session. """ # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() request.session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url, }) flow = client.OAuth2WebServerFlow( client_id=django_util.oauth2_settings.client_id, client_secret=django_util.oauth2_settings.client_secret, scope=scopes, state=state, redirect_uri=request.build_absolute_uri( reverse("google_oauth:callback"))) flow_key = _FLOW_KEY.format(csrf_token) request.session[flow_key] = jsonpickle.encode(flow) return flow
async def create_token_file(message): # Run through the OAuth flow and retrieve credentials flow = client.OAuth2WebServerFlow(G_PHOTOS_CLIENT_ID, G_PHOTOS_CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() async with userge.conversation(message.chat.id, timeout=60) as conv: await conv.send_message( "Go to the following link in " f"your browser: {authorize_url} and reply the code") response = await conv.get_response(mark_read=True) # LOG.info(response.stringify()) code = response.text.strip() credentials = flow.step2_exchange(code) storage = file.Storage(TOKEN_FILE_NAME) storage.put(credentials) imp_gsem = await conv.send_document(document=TOKEN_FILE_NAME) await imp_gsem.reply_text( "please set <code>G_PHOTOS_AUTH_TOKEN_ID</code> = " f"<u>{imp_gsem.message_id}</u> ..!" "\n\n<i>This is only required, " "if you are running in an ephimeral file-system</i>.", parse_mode="html") return storage
def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" flow = client.OAuth2WebServerFlow(client_id=client_id, client_secret=client_secret, scope=scopes, user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') authorize_url = flow.step1_get_authorize_url() print('Log into the Google Account you use to access your AdWords account' 'and go to the following URL: \n%s\n' % (authorize_url)) print( 'After approving the token enter the verification code (if specified).' ) code = input('Code: ').strip() try: credential = flow.step2_exchange(code) except client.FlowExchangeError as e: print('Authentication has failed: %s' % e) sys.exit(1) else: print('OAuth2 authorization successful!\n\n' 'Your access token is:\n %s\n\nYour refresh token is:\n %s' % (credential.access_token, credential.refresh_token))
async def authsheets(self, ctx): """Authorize GSheets to use the Google Sheets API.""" flow = client.OAuth2WebServerFlow(**FLOW_KWARGS) authorize_url = flow.step1_get_authorize_url() info_message = ("Use the link below to authorize the cog to communicate with Google Sheets, " "then copy the code you recieve and paste it here.") warn_message = ("**NOTE**: It is not recommended to authorize the cog using " "your personal Google Account; it is best to create a new Google Account, " "and share any Sheets you would like to access with that google account.") embed = discord.Embed(title="Authorize GSheets", url=authorize_url, description=warn_message) try: await self.bot.say(info_message, embed=embed) except discord.errors.Forbidden: await self.bot.say("\n\n".join(info_message, authorize_url, warn_message)) resp = await self.bot.wait_for_message(author=ctx.message.author) credentials = None if resp: try: code = resp.content http = httplib2.Http() credentials = flow.step2_exchange(code, http=http) except client.FlowExchangeError as e: await self.bot.say("Authentication has failed: {}".format(e.args[0])) return self.gc = GSheetsClient(credentials) store = Storage(CREDENTIAL_PATH) store.put(credentials) credentials.set_store(store) await self.bot.say("Authentication successful.")
def authorize_app(): """Redirect to Google API auth page to authorize. This handler should be splitted by two according to steps: - OAuth step 1 - OAuth step 2 Note: will be splitted in the scope of GGRC-4311 """ if 'credentials' in flask.session: return render_template("gdrive/auth_gdrive.haml") flow = client.OAuth2WebServerFlow( settings.GAPI_CLIENT_ID, settings.GAPI_CLIENT_SECRET, scope=_GOOGLE_API_GDRIVE_SCOPE, redirect_uri=flask.url_for("authorize_app", _external=True), auth_uri=_GOOGLE_AUTH_URI, token_uri=_GOOGLE_TOKEN_URI, ) if 'code' not in flask.request.args: state = str(uuid.uuid4()) auth_uri = flow.step1_get_authorize_url(state=state) flask.session['state'] = state return flask.redirect(auth_uri) # Cross Site Request Forgery (XRSF) guard. if flask.request.args['state'] != flask.session['state']: raise Unauthorized('Wrong state.') auth_code = flask.request.args["code"] credentials = flow.step2_exchange(auth_code) flask.session['credentials'] = credentials.to_json() return render_template("gdrive/auth_gdrive.haml")
def get_authorized_http(): """Create an httplib2.Http wrapped with OAuth credentials. This checks the user's configuration directory for stored credentials. If found, it uses them. If not found, this opens a browser window to prompt the user to sign in and authorize access to the user's email address, then stores the credentials. Returns: The wrapped Http instance. """ # TODO: make config dir path overrideable at the command line # TODO: command line option to disable browser prompt (and just fail) user_config_path = os.path.expanduser(USER_CONFIG_DIR) if not os.path.exists(user_config_path): os.makedirs(user_config_path) credentials_path = os.path.join(user_config_path, CREDENTIALS_FILENAME) storage = file.Storage(credentials_path) credentials = storage.get() if credentials is None or credentials.invalid: flow = client.OAuth2WebServerFlow( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope='https://www.googleapis.com/auth/userinfo.email') credentials = tools.run(flow, storage) http = credentials.authorize(httplib2.Http()) return http
def _GetCredentialsVia3LO(client_info, credentials_filename=None): credential_store = _GetCredentialStore(credentials_filename, client_info['client_id'], client_info['scope']) credentials = credential_store.get() if credentials is None or credentials.invalid: for _ in range(10): # If authorization fails, we want to retry, rather # than let this cascade up and get caught elsewhere. # If users want out of the retry loop, they can ^C. try: flow = client.OAuth2WebServerFlow(**client_info) flags, _ = tools.argparser.parse_known_args( ['--noauth_local_webserver']) credentials = tools.run_flow(flow, credential_store, flags) break except (SystemExit, client.FlowExchangeError) as e: # Here SystemExit is "no credential at all", and the # FlowExchangeError is "invalid" -- usually because # you reused a token. pass except httplib2.HttpLib2Error as e: raise ValueError('Communication error creating credentials:' '{}'.format(e)) else: credentials = None return credentials
def get_or_create_credentials(scope, storage_key=DEFAULT_STORAGE_KEY): key_file = os.getenv('AUTH_KEY_FILE') # If AUTH_KEY_FILE is unset, use default auth key file if it exists. if not key_file and os.path.exists(DEFAULT_AUTH_KEY_FILE): key_file = DEFAULT_AUTH_KEY_FILE if key_file: key_file = os.path.expanduser(key_file) return ( service_account.ServiceAccountCredentials.from_json_keyfile_name( key_file, scope)) if appengine and utils.is_appengine(): return appengine.AppAssertionCredentials(scope) credentials, storage = get_credentials_and_storage(scope, storage_key=storage_key) if credentials is None: parser = tools.argparser if os.getenv('INTERACTIVE_AUTH'): args = [] else: args = ['--noauth_local_webserver'] flags, _ = parser.parse_known_args(args) flow = client.OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, scope, redirect_uri=REDIRECT_URI) credentials = tools.run_flow(flow, storage, flags) # run_flow changes the logging level, so change it back. logging.getLogger().setLevel(getattr(logging, 'INFO')) return credentials
def MakeApiRequest(): flow = client.OAuth2WebServerFlow( OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, SCOPES, approval_prompt='force') flow.redirect_uri = client.OOB_CALLBACK_URN authorize_url = flow.step1_get_authorize_url() print( 'Go to the following link in your browser:\n\n' ' %s\n' % authorize_url) # pylint:disable=raw_input-builtin code = raw_input('Enter verification code: ').strip() try: creds = flow.step2_exchange(code) except client.FlowExchangeError as e: print('Authentication has failed: %s' % e) return None, None http_auth = creds.authorize(httplib2.Http()) resp, content = http_auth.request( "https://chromeperf.appspot.com/api/alerts/bug_id/713717", method="POST", headers={'Content-length': 0}) return (resp, content)
def main(): """Prompt the user for information to generate and output a refresh token.""" print( 'Please enter your OAuth 2.0 Client ID and Client Secret.\n' 'These values can be generated from the Google Cloud Console - ' 'https://cloud.google.com/console - under the APIs & auth tab.\n' 'Please use a Client ID for installed applications.') client_id = raw_input('Client ID: ').strip() client_secret = raw_input('Client Secret: ').strip() product = ChooseProduct() flow = client.OAuth2WebServerFlow(client_id=client_id, client_secret=client_secret, scope=[ scope[1] for scope in PRODUCT_TO_OAUTH_SCOPE if scope[0] == product ][0], user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') authorize_url = flow.step1_get_authorize_url() print( 'Log into the Google Account you use to access your %s account and go ' 'to the following URL: \n%s\n' % (product, authorize_url)) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: credential = flow.step2_exchange(code) except client.FlowExchangeError, e: print 'Authentication has failed: %s' % e sys.exit(1)
def AddAccount(storage, userid=None): # pragma: no cover """Adds an account to the configuration file Args: storage: storage, instance of storage to store credentials in. userid: string, reference for the account Returns: credentials: A credentials instance with the account details """ if userid == None: userid = raw_input("Name for this user account ( eg [email protected] )? ") while True: flow = client.OAuth2WebServerFlow(client_id=Auth.clientid, client_secret=Auth.clientsecret, scope='https://www.googleapis.com/auth/cloudprint', user_agent=userid) auth_uri = flow.step1_get_authorize_url() print("Open this URL, grant access to CUPS Cloud Print, then provide the code displayed : \n\n" + auth_uri + "\n") code = raw_input('Code from Google: ') try: print("") credentials = flow.step2_exchange(code) storage.put(credentials) # fix permissions try: os.chmod(Auth.config, 0640) os.chown(Auth.config, 0, Auth.GetLPID()) except: sys.stderr.write("DEBUG: Cannot alter file permissions\n") return credentials except Exception as e: print("\nThe code does not seem to be valid ( " + str(e) + " ), please try again.\n")
def test_callback_works(self, jsonpickle_mock): request = self.factory.get('oauth2/oauth2callback', data={ 'state': json.dumps(self.fake_state), 'code': 123 }) self.session['google_oauth2_csrf_token'] = self.CSRF_TOKEN flow = client.OAuth2WebServerFlow( client_id='clientid', client_secret='clientsecret', scope=['email'], state=json.dumps(self.fake_state), redirect_uri=request.build_absolute_uri("oauth2/oauth2callback")) name = 'google_oauth2_flow_{0}'.format(self.CSRF_TOKEN) pickled_flow = object() self.session[name] = pickled_flow flow.step2_exchange = mock.Mock() jsonpickle_mock.decode.return_value = flow request.session = self.session request.user = self.user response = views.oauth2_callback(request) self.assertIsInstance(response, http.HttpResponseRedirect) self.assertEqual( response.status_code, django.http.HttpResponseRedirect.status_code) self.assertEqual(response['Location'], self.RETURN_URL) jsonpickle_mock.decode.assert_called_once_with(pickled_flow)
def googlelogin(request): print("Inside GoogleLogin method") flow = client.OAuth2WebServerFlow( client_id=settings.SOCIAL_AUTH_GOOGLE_KEY, client_secret=settings.SOCIAL_AUTH_GOOGLE_SECRET, scope='email', redirect_uri='http://localhost:8000/googlelogin', _external=True) flow.params["include_granted_scopes"] = "true" flow.params["access_type"] = 'offline' print("Reached here") if "code" not in request.GET: print("Inside if block") auth_uri = flow.step1_get_authorize_url() print("AUth URI is :" + auth_uri) return HttpResponseRedirect(auth_uri) else: print("Inside else block") auth_code = request.GET["code"] print(auth_code) credentials = flow.step2_exchange(auth_code) credentials = json.loads(credentials.to_json()) email = credentials["id_token"]["email"] print("Email is" + email) return HttpResponseRedirect( reverse('polls:index')) #request, 'createpolls/createpoll.html')
def test_callback_handles_bad_flow_exchange(self, jsonpickle_mock): request = self.factory.get('oauth2/oauth2callback', data={ "state": json.dumps(self.fake_state), "code": 123 }) self.session['google_oauth2_csrf_token'] = self.CSRF_TOKEN flow = client.OAuth2WebServerFlow( client_id='clientid', client_secret='clientsecret', scope=['email'], state=json.dumps(self.fake_state), redirect_uri=request.build_absolute_uri('oauth2/oauth2callback')) session_key = 'google_oauth2_flow_{0}'.format(self.CSRF_TOKEN) pickled_flow = object() self.session[session_key] = pickled_flow def local_throws(code): raise client.FlowExchangeError('test') flow.step2_exchange = local_throws jsonpickle_mock.decode.return_value = flow request.session = self.session response = views.oauth2_callback(request) self.assertIsInstance(response, http.HttpResponseBadRequest) jsonpickle_mock.decode.assert_called_once_with(pickled_flow)
def __init__(self, group_id, *args, **kwargs): self.group_id = group_id self.client_id = kwargs.get('client_id') self.client_secret = kwargs.get('client_secret') scope = 'https://www.googleapis.com/auth/apps.groups.migration' storage = Storage('.credentials') credentials = storage.get() if not credentials or credentials.invalid: # Request client id and secret if not ready if not self.client_id: self.client_id = input('Enter client_id: ') if not self.client_secret: self.client_secret = input('Enter client_secret: ') flow = client.OAuth2WebServerFlow(client_id, client_secret, scope) credentials = tools.run(flow, storage) http = credentials.authorize(httplib2.Http()) self.service = discovery.build('groupsmigration', 'v1', http=http) # By default list all available emails self.query = kwargs.get('query', 'ALL') # self.query = Q(seen=False) # Create the error mbox self.error_mbox = mailbox.mbox('errors.mbox')
def _generate_refresh_token(self): flow = client.OAuth2WebServerFlow( client_id=self.__client_id, client_secret=self.__client_secret, scope=[SCOPE], user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') authorize_url = flow.step1_get_authorize_url() print( f'Log into the Google Account you use to access your AdWords account and go to the following URL: \n{authorize_url}\n' ) print( 'After approving the token enter the verification code (if specified).' ) code = input('Code: ').strip() try: credential = flow.step2_exchange(code) LOGGER.info( f'Please copy the following to config, access_token : {credential.access_token}, refresh_token : {credential.refresh_token}' ) except client.FlowExchangeError as flow_exchange_error: print('Authentication has failed: %s' % flow_exchange_error)
def GenerateRefreshToken(): """Prompt the user for information to generate and output a refresh token.""" print( 'Please enter your OAuth 2.0 Client ID and Client Secret.\n' 'These values can be generated from the Google APIs Console, ' 'https://code.google.com/apis/console under the API Access tab.\n' 'Please use a Client ID for installed applications.') client_id = '800523524577.apps.googleusercontent.com' client_secret = '4AoEFfQChNlQOuY4H6MRcsHE' product = ChooseProduct() flow = client.OAuth2WebServerFlow(client_id=client_id, client_secret=client_secret, scope=PRODUCT_TO_OAUTH_SCOPE[product], user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') authorize_url = flow.step1_get_authorize_url() print( 'Log into the Google Account you use to access your %s account and go ' 'to the following URL: \n%s\n' % (product, authorize_url)) webbrowser.open_new_tab(authorize_url) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: credential = flow.step2_exchange(code) except client.FlowExchangeError, e: print 'Authentication has failed: %s' % e sys.exit(1)
async def create_token_file(token_file, event): # Run through the OAuth flow and retrieve credentials flow = client.OAuth2WebServerFlow( G_PHOTOS_CLIENT_ID, G_PHOTOS_CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI, ) authorize_url = flow.step1_get_authorize_url() async with event.client.conversation(event.chat_id, timeout=600) as conv: await conv.send_message("Pergi Ke " "Linknya Dan Ikuti " f"Browser Anda Lord: {authorize_url} Dan " "Balas Kode") response = await conv.wait_event( events.NewMessage(outgoing=True, chats=BOTLOG_CHATID)) # logger.info(response.stringify()) code = response.message.message.strip() credentials = flow.step2_exchange(code) storage = file.Storage(token_file) storage.put(credentials) imp_gsem = await conv.send_message(file=token_file) await imp_gsem.reply( "Mohon Setel Heroku ENV " "<code>G_PHOTOS_AUTH_TOKEN_ID</code> " "= " f"<u>{imp_gsem.id}</u> ..!" "\n\n<i>Ini Hanya Di Perlukan, " "Jika Anda Menjalankan Ephimeral File-System</i>.", parse_mode="html", ) return storage
def _init_service(self): """ Handle oauth's shit (copy-paste from http://code.google.com/apis/tasks/v1/using.html) Yes I do publish a secret key here, apparently it is normal http://stackoverflow.com/questions/7274554/why-google-native-oauth2-flow-require-client-secret """ storage = oauth2client.file.Storage(utils.save_data_path("gtasks_oauth.dat")) credentials = storage.get() if not credentials or credentials.invalid: flow = client.OAuth2WebServerFlow( client_id='617841371351.apps.googleusercontent.com', client_secret='_HVmphe0rqwxqSR8523M6g_g', scope='https://www.googleapis.com/auth/tasks', user_agent='michel/0.0.1') flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args("") credentials = tools.run_flow(flow, storage, flags) http = httplib2.Http() http = credentials.authorize(http) self._service = discovery.build(serviceName='tasks', version='v1', http=http, cache_discovery=False) if self._list_name is None or self._list_name == "default": self._list_id = "@default" else: tasklists = self._service.tasklists().list().execute() for tasklist in tasklists['items']: if tasklist['title'] == self._list_name: self._list_id = tasklist['id'] break if not self._list_id: raise Exception('ERROR: No google task-list named "{0}"'.format(self._list_name))
def main(application_name, client_id, client_secret, scope): """Retrieve and display a refresh token. Args: client_id: retrieved from the Google Developers Console. client_secret: retrieved from the Google Developers Console. scope: Scope used for authorization. """ flow = client.OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope=[scope], user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') authorize_url = flow.step1_get_authorize_url() print ('Log into the Google Account you use to access your DFP account' 'and go to the following URL: \n%s\n' % (authorize_url)) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: credential = flow.step2_exchange(code) except client.FlowExchangeError, e: print 'Authentication has failed: %s' % e sys.exit(1)
def flow(self, callback_url): return client.OAuth2WebServerFlow( client_id=self.client_id, client_secret=self.secret, scope=['profile', 'email'], redirect_uri=callback_url, )
def get_or_create_credentials(scope, storage_key=DEFAULT_STORAGE_KEY): key_file = os.getenv('AUTH_KEY_FILE') # If AUTH_KEY_FILE is unset, use default auth key file if it exists. if not key_file and os.path.exists(DEFAULT_AUTH_KEY_FILE): key_file = DEFAULT_AUTH_KEY_FILE if key_file: key_file = os.path.expanduser(key_file) return ( service_account.ServiceAccountCredentials.from_json_keyfile_name( key_file, scope)) credentials, storage = get_credentials_and_storage(scope, storage_key=storage_key) if credentials is None: parser = tools.argparser if os.getenv('INTERACTIVE_AUTH'): args = [] else: args = ['--noauth_local_webserver'] flags, _ = parser.parse_known_args(args) flow = client.OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, scope, redirect_uri=REDIRECT_URI) credentials = tools.run_flow(flow, storage, flags) # run_flow changes the logging level, so change it back. logging.getLogger().setLevel(getattr(logging, 'INFO')) # Avoid logspam by logging the email address only once. if hasattr(credentials, 'id_token') and credentials.id_token: email = credentials.id_token.get('email') global _LAST_LOGGED_EMAIL if email and _LAST_LOGGED_EMAIL != email: logging.info('Authorizing using -> {}'.format(email)) _LAST_LOGGED_EMAIL = email return credentials
def AddAccount(storage, userid=None): """Adds an account to the configuration file Args: storage: storage, instance of storage to store credentials in. userid: string, reference for the account Returns: credentials: A credentials instance with the account details """ if userid == None: userid = raw_input( "Name for this user account ( eg [email protected] )? ") while True: flow = client.OAuth2WebServerFlow( client_id=Auth.clientid, client_secret=Auth.clientsecret, scope=['https://www.googleapis.com/auth/cloudprint'], user_agent=userid) auth_uri = flow.step1_get_authorize_url() print "Open this URL, grant access to CUPS Cloud Print, then provide the code displayed : \n\n" + auth_uri + "\n" code = raw_input('Code from Google: ') try: print "" credentials = flow.step2_exchange(code) storage.put(credentials) # fix permissions Utils.FixFilePermissions(Auth.config) return credentials except Exception as e: print "\nThe code does not seem to be valid ( " + str( e) + " ), please try again.\n"
async def create_token_file(token_file, event): # Run through the OAuth flow and retrieve credentials flow = client.OAuth2WebServerFlow(Config.G_PHOTOS_CLIENT_ID, Config.G_PHOTOS_CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() async with event.client.conversation(event.chat_id, timeout=600) as conv: await conv.send_message("Go to " "the following link in " f"your browser: {authorize_url} and " "reply the code") response = await conv.wait_event( events.NewMessage(outgoing=True, chats=Config.PRIVATE_GROUP_BOT_API_ID)) # logger.info(response.stringify()) code = response.message.message.strip() credentials = flow.step2_exchange(code) storage = file.Storage(token_file) storage.put(credentials) imp_gsem = await conv.send_message(file=token_file) await imp_gsem.reply( "please set " "<code>G_PHOTOS_AUTH_TOKEN_ID</code> " "= " f"<u>{imp_gsem.id}</u> ..!" "\n\n<i>This is only required, " "if you are running in an ephimeral file-system</i>.", parse_mode="html") return storage
def login_oauth2callback(): """ TODO: More thought needs to be put into these google flows once the app google flows are finalized. """ flow = client.OAuth2WebServerFlow(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope='profile') flow.redirect_uri = url_for('login_oauth2callback', _external=True) authorization_response = request.args.get('code') login_credentials = flow.step2_exchange(authorization_response) token = json.loads(login_credentials.to_json())['id_token_jwt'] idinfo = get_idinfo(token) # Get the permanent Google profile dictionary if idinfo: flask.session['user_id'] = idinfo['sub'] # Get the permanent Google id flask.session['user_name'] = idinfo['name'] flask.session['user_picture'] = idinfo['picture'] flask.session['user_email'] = idinfo['email'] user = get_or_create_user(db.session, User, idinfo['sub']) return redirect(url_for('index')) return 'Error logging in, please try again.'
def _make_flow(self, return_url=None, **kwargs): """Creates a Web Server Flow""" # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url }) kw = self.flow_kwargs.copy() kw.update(kwargs) extra_scopes = kw.pop('scopes', []) scopes = set(self.scopes).union(set(extra_scopes)) flow = client.OAuth2WebServerFlow(client_id=self.client_id, client_secret=self.client_secret, scope=scopes, state=state, redirect_uri=url_for( 'oauth2.callback', _external=True), **kw) flow_key = _FLOW_KEY.format(csrf_token) session[flow_key] = pickle.dumps(flow) return flow
def googleEmailLogin(): flow = client.OAuth2WebServerFlow( client_id=app.config["GOOGLE_CLIENT_ID"], client_secret=app.config["GOOGLE_CLIENT_SECRET"], scope='https://www.googleapis.com/auth/gmail.readonly', redirect_uri=url_for('pages.googleEmailLogin', _external=True)) flow.params[INCLUDE_GRANTED_SCOPES] = "true" flow.params[ACCESS_TYPE] = 'offline' if AUTH_CODE not in request.args: app.logger.debug("User " + current_user.email + " trying to provide email access") auth_uri = flow.step1_get_authorize_url() return redirect(auth_uri) else: auth_code = request.args.get(AUTH_CODE) credentials = flow.step2_exchange(auth_code) credentials = json.loads(credentials.to_json()) user = current_user user.googleAccessToken = credentials[GOOGLE_ACCESS_TOKEN] user.googleRefreshToken = credentials[GOOGLE_REFRESH_TOKEN] user.googleTokenExpiry = credentials[GOOGLE_TOKEN_EXPIRY] user.googleTokenURI = credentials[GOOGLE_TOKEN_URI] user.googleRevokeURI = credentials[GOOGLE_REVOKE_URI] user.googleEmailAccess = True user.save() app.logger.debug("User " + user.email + " provided email access") return redirect(url_for('pages.home'))