def _set_credentials(self): # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: self.credentials = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not self.credentials or not self.credentials.valid: if self.credentials and self.credentials.expired and self.credentials.refresh_token: self.credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_config( { "installed": { "client_id": self.client_id, "project_id": "ceasaro-sas", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_secret": self.client_secret, "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"] } }, SCOPES) self.credentials = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(self.credentials, token)
def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" client_config = ClientConfigBuilder( client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id, client_secret=client_secret) flow = InstalledAppFlow.from_client_config(client_config.Build(), scopes=scopes) # Note that from_client_config will not produce a flow with the # redirect_uris (if any) set in the client_config. This must be set # separately. flow.redirect_uri = _REDIRECT_URI auth_url, _ = flow.authorization_url(prompt='consent') print('Log into the Google Account you use to access your AdWords account ' 'and go to the following URL: \n%s\n' % auth_url) print( 'After approving the token enter the verification code (if specified).' ) code = input('Code: ').strip() try: flow.fetch_token(code=code) except InvalidGrantError as ex: print('Authentication has failed: %s' % ex) sys.exit(1) print('Access token: %s' % flow.credentials.token) print('Refresh token: %s' % flow.credentials.refresh_token)
def login(): client_id = "769904540573-knscs3mhvd56odnf7i8h3al13kiqulft.apps.googleusercontent.com" client_secret = "D2F1D--b_yKNLrJSPmrn2jik" environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1" # Don't use in Web apps scopes = [ "https://spreadsheets.google.com/feeds/", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/analytics.readonly", "https://www.googleapis.com/auth/webmasters.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/youtube.readonly" ] client_config = { "installed": { "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob"], "client_id": client_id, "client_secret": client_secret } } flow = InstalledAppFlow.from_client_config(client_config, scopes) credentials = flow.run_console() credentials.access_token = credentials.token with open("credentials.pickle", "wb") as output_file: pickle.dump(credentials, output_file) return credentials
def get_credentials(): from google_auth_oauthlib.flow import InstalledAppFlow SCOPES = ['https://www.googleapis.com/auth/drive.file'] client_config = { "installed": { "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"], "client_id": get_ecredentials('yatch'), "client_secret": get_ecredentials('bakery') } } flow = InstalledAppFlow.from_client_config(client_config, SCOPES) print('\n') try: credentials = flow.run_console( authorization_prompt_message='Please visit the below URL to get ' 'autorization\ncode to authorize Google Drive access\n\n{url}', authorization_code_message='\nAuthorization Code\n' ) client_config['installed']['refresh_token'] = credentials.refresh_token client_config['installed'].pop('client_id') client_config['installed'].pop('client_secret') backup_options['oauth'] = client_config['installed'] except Exception as e: error_and_exit( '\nAn Error occured while authenticating Gdrive access\n{0}'.format(e)) return credentials
def run_flow(self): with open(self.client_secret, 'r') as file: client_config = json.load(file) flow = InstalledAppFlow.from_client_config(client_config, self.scopes) if self.server_port is None: raise ValueError( "server_port not specified. Usual values are: 8080, 8000, 8888" ) num_fails = 0 success = False while not success: try: self.credentials = InstalledAppFlow.run_local_server( flow, port=self.server_port) success = True LOG.info( f"Failed to start the local server {num_fails} times.") except OSError as err: self.server_port += 1 num_fails += 1 if num_fails > 100: LOG.error( "Failed to start the local server more than 100 times." ) raise err # save obtained credentials for faster authorization next time self.save_credentials()
def handle(self, *args, **options): """ Run the command """ oauth_config = { "installed": { "client_id": settings.YT_CLIENT_ID, "project_id": settings.YT_PROJECT_ID, "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_secret": settings.YT_CLIENT_SECRET, "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"], } } flow = InstalledAppFlow.from_client_config( oauth_config, [ "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtube.upload", ], ) credentials = flow.run_console() self.stdout.write("YT_ACCESS_TOKEN={}\nYT_REFRESH_TOKEN={}\n".format( credentials.token, credentials.refresh_token))
def login(token=None, client_secret=None): """ Logs the user in and returns a service resource object """ token = local.get_token("drive_token") # dict/json format client_secret = local.get_token('oauth') # dict/json format creds = None _SCOPES = ["https://www.googleapis.com/auth/drive"] if token: creds = Credentials.from_authorized_user_info(token, _SCOPES) # If there are no (valid) credentials available, let the user log in. # Click http link if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: # cred_json = "" flow = InstalledAppFlow.from_client_config(client_secret, _SCOPES) creds = flow.run_local_server(port=0) print(creds.to_json()) service = build('drive', 'v3', credentials=creds) return service
async def generate_credentials(gdrive): """ - Only generate once for long run - """ if helper.get_credentials(str(gdrive.from_id)) is not None: await gdrive.edit("`Anda sudah mengotorisasi token...`") await asyncio.sleep(1.5) await gdrive.delete() return False """ - Generate credentials - """ if G_DRIVE_DATA is not None: try: configs = json.loads(G_DRIVE_DATA) except json.JSONDecodeError: await gdrive.edit( "`[AUTENTIKASi - ERROR]`\n\n" "`Status` : **BAD**\n" "`Alasan` : **G_DRIVE_DATA** entitas tidak valid!" ) return False else: """ - Only for old user - """ if G_DRIVE_CLIENT_ID is None and G_DRIVE_CLIENT_SECRET is None: await gdrive.edit( "`[AUTENTIKASi - ERROR]`\n\n" "`Status` : **BAD**\n" "`Alasan` : Lord, tolong ambil **G_DRIVE_DATA** " "[Disini](https://telegra.ph/How-To-Setup-Google-Drive-04-03)" ) return False configs = { "installed": { "client_id": G_DRIVE_CLIENT_ID, "client_secret": G_DRIVE_CLIENT_SECRET, "auth_uri": GOOGLE_AUTH_URI, "token_uri": GOOGLE_TOKEN_URI, } } await gdrive.edit("`Membuat kredensial...`") flow = InstalledAppFlow.from_client_config( configs, SCOPES, redirect_uri=REDIRECT_URI ) auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent") msg = await gdrive.respond("`Buka grup BOTLOG Anda untuk mengautentikasi token...`") async with gdrive.client.conversation(BOTLOG_CHATID) as conv: url_msg = await conv.send_message( "Silakan buka URL ini:\n" f"{auth_url}\notorisasi lalu balas kodenya" ) r = conv.wait_event(events.NewMessage(outgoing=True, chats=BOTLOG_CHATID)) r = await r code = r.message.message.strip() flow.fetch_token(code=code) creds = flow.credentials await asyncio.sleep(3.5) await gdrive.client.delete_messages(gdrive.chat_id, msg.id) await gdrive.client.delete_messages(BOTLOG_CHATID, [url_msg.id, r.id]) """ - Unpack credential objects into strings - """ creds = base64.b64encode(pickle.dumps(creds)).decode() await gdrive.edit("`Kredensial dibuat...`") helper.save_credentials(str(gdrive.from_id), creds) await gdrive.delete() return
def newCredentials(scopes, credPath): trace = sys.gettrace() if trace is not None: #debugger is on, not getting flow return None clientSecretsEncrypted = f'{cfg.modulePath}/yt_api/encrypted/encrypted_client_secrets' decrypted = getDecryptedProxy(clientSecretsEncrypted).decode('utf8') clientConfig = json.loads(decrypted) flow = InstalledAppFlow.from_client_config(clientConfig, scopes=scopes) prompt = '\nMake sure you are using sync-dl which you Installed via pip.\nIf not, then this api key may be stolen! \n\nAuthentificate at:\n{url}' # start local server on localhost, port 8080 flow.run_local_server(prompt='consent', authorization_prompt_message=prompt, open_browser=False) credentials = flow.credentials if os.path.exists(credPath): os.remove(credPath) with open(credPath, "wb") as f: pickle.dump(credentials, f) cfg.logger.info("Authentification Completed!") return credentials
def get_connection(self): """This Method uses the credentials.json file to establish connection with google spreadsheet API. """ try: creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists("token.pickle"): with open("token.pickle", "rb") as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config( self.credentials_json, self.SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open("token.pickle", "wb") as token: pickle.dump(creds, token) service = build("sheets", "v4", credentials=creds) # Call the Sheets API sheet = service.spreadsheets() return sheet except Exception as e: print(e) return False
def service_setup(): """ setup the service object for use by the rest of the script don't really know how that works, but that's the thing that has the api endpoints attached to it. Gotta authNZ first, then instantiate it todo param'z this for service, etc.? :return: """ # get the creds file - it's a bunch of info in addition to the # client ID and secret with open('creds.json', 'rb') as credfile: creds = json.load(credfile) creds['installed']['client_id'] = Config.api_client_id creds['installed']['client_secret'] = Config.api_secret creds['installed']['project_id'] = Config.api_project_id flow = InstalledAppFlow.from_client_config(creds, Config.api_scopes) # todo extract token (access token) and refresh token, store in env for later use - figure out how to use creds = flow.run_local_server(port=0) service = build('gmail', 'v1', credentials=creds) return service
async def generate_credentials(gdrive): """ - Only generate once for long run - """ if helper.get_credentials(str(gdrive.from_id)) is not None: await gdrive.edit("`Token já autorizado...`") await asyncio.sleep(1.5) await gdrive.delete() return False """ - Generate credentials - """ if G_DRIVE_DATA is not None: try: configs = json.loads(G_DRIVE_DATA) except json.JSONDecodeError: await gdrive.edit("`[AUTENTICAÇÃO - ERRO]`\n\n" "`Status` : **FALHA**\n" "`Motivo` : **G_DRIVE_DATA** elemento inválido!") return False else: """ - Only for old user - """ if G_DRIVE_CLIENT_ID is None and G_DRIVE_CLIENT_SECRET is None: await gdrive.edit( "`[AUTENTICAÇÃO - ERRO]`\n\n" "`Status` : **FALHA**\n" "`Motivo` : obtenha sua **G_DRIVE_DATA** " "[aqui](https://telegra.ph/How-To-Setup-Google-Drive-04-03)") return False configs = { "installed": { "client_id": G_DRIVE_CLIENT_ID, "client_secret": G_DRIVE_CLIENT_SECRET, "auth_uri": GOOGLE_AUTH_URI, "token_uri": GOOGLE_TOKEN_URI, } } await gdrive.edit("`Criando credenciais...`") flow = InstalledAppFlow.from_client_config(configs, SCOPES, redirect_uri=REDIRECT_URI) auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent") msg = await gdrive.respond( "`Vá para o seu grupo BOTLOG para autenticar o token...`") async with gdrive.client.conversation(BOTLOG_CHATID) as conv: url_msg = await conv.send_message( "Vá para este URL:\n" f"{auth_url}\nautorize e responda com o código") r = conv.wait_event( events.NewMessage(outgoing=True, chats=BOTLOG_CHATID)) r = await r code = r.message.message.strip() flow.fetch_token(code=code) creds = flow.credentials await asyncio.sleep(3.5) await gdrive.client.delete_messages(gdrive.chat_id, msg.id) await gdrive.client.delete_messages(BOTLOG_CHATID, [url_msg.id, r.id]) """ - Unpack credential objects into strings - """ creds = base64.b64encode(pickle.dumps(creds)).decode() await gdrive.edit("`Credenciais criadas...`") helper.save_credentials(str(gdrive.from_id), creds) await gdrive.delete() return
def rerequest_creds_if_needed(creds): # If there are no (valid) credentials available # Let the user log in if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: # Build the Flow instance flow = InstalledAppFlow.from_client_config(FLOW_CRED_JSON, SCOPES) # Initialize it for the authorization URL request flow.authorization_url( access_type='offline', prompt='consent', approval_prompt='force', # Enable incremental authorization. include_granted_scopes='true') # Fill in the redirect URL parameter flow.redirect_uri = GAUTH_REDIRECT_URI # Get the authorization URL and return it for rerequest return (creds, ) + flow.authorization_url() # Return empty str if no rerequest is necessary return ( creds, None, None, )
def fetch_gcal_auth_creds(code, user): # Build instance of Flow flow = InstalledAppFlow.from_client_config(FLOW_CRED_JSON, SCOPES) # Fill in the redirect URL parameter flow.redirect_uri = GAUTH_REDIRECT_URI # return False, 'Going to fetch the code: ' + code, # Pass Google API the code to get credentials in Flow param "credentials" fetch_result = flow.fetch_token(**{'code': code}) # return False, 'Fetched: ' + str(fetch_result), # If fetch failed if fetch_result is None: # Stop the process & with returned code & error return False, 'Fetch failed with code: ' + str(code), user_creds = GoogleCreds.create(flow.credentials, user) user_creds.save() # if user_google_creds.user_id is None: # user_google_creds.user = User(username=str(datetime.now())) # user_google_creds.user.save() return True, 'Everything looks more or less fine' # # Save the credentials for the next run # with open(TOKEN_PICKLE, 'wb') as token: # pickle.dump(flow.credentials, token) # # If all is OK return True and no message # return True, '' # If we're here, something have gone wrong return False, '',
def oauth2_authorization_url(self): """ If Google flow auth2 credential need to be generated from the scratch, provide the user redirect url to move user to, to confirm app access to his data :return: - Google Authorization url (str), if it was pulled from Google for this user successfully - None if something went wrong """ # Build the Google Oauth2 Flow instance flow = InstalledAppFlow.from_client_config(FLOW_CRED_JSON, SCOPES) # Initialize it for the authorization URL request flow.authorization_url( access_type='offline', prompt='consent', approval_prompt='force', # Enable incremental authorization. include_granted_scopes='true') # Fill in the redirect URL parameter flow.redirect_uri = GAUTH_REDIRECT_URI # Get the authorization URL and fresh reds authorization_url, code = flow.authorization_url() if code: return authorization_url else: return None
def __init__(self) -> None: self.flow = InstalledAppFlow.from_client_config( { 'installed': { 'client_id': get_key('client_id'), 'project_id': get_key('project_id'), 'auth_uri': get_key('auth_uri'), 'token_uri': get_key('token_uri'), 'auth_provider_x509_cert_url': get_key('auth_provider_x509_cert_url'), 'client_secret': get_key('client_secret'), } }, SCOPES, redirect_uri=get_key('redirect_uri'), ) self.credentials = Credentials( None, refresh_token=get_key('refresh_token'), token_uri='https://accounts.google.com/o/oauth2/token', client_id=get_key('client_id'), client_secret=get_key('client_secret'), ) self.build = generate_build(self.credentials) self.channel_id = channels_list_by_id( self.build, part='snippet,contentDetails,statistics', mine='True', )['items'][0]['id']
def youtube_authenticate(): os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name = "youtube" api_version = "v3" client_secrets_file = client_secret creds = None # the file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first time if os.path.exists("token.pickle"): with open("token.pickle", "rb") as token: creds = pickle.load(token) # if there are no (valid) credentials availablle, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: #flow = InstalledAppFlow.from_client_secrets_file(client_secrets_file, SCOPES) flow = InstalledAppFlow.from_client_config(client_secrets_file, SCOPES) creds = flow.run_local_server(port=0) # save the credentials for the next run with open("token.pickle", "wb") as token: pickle.dump(creds, token) return build(api_service_name, api_version, credentials=creds)
def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" client_config = ClientConfigBuilder( client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id, client_secret=client_secret) flow = InstalledAppFlow.from_client_config( client_config.Build(), scopes=scopes) # Note that from_client_config will not produce a flow with the # redirect_uris (if any) set in the client_config. This must be set # separately. flow.redirect_uri = _REDIRECT_URI auth_url, _ = flow.authorization_url(prompt='consent') print ('Log into the Google Account you use to access your DFP account' 'and go to the following URL: \n%s\n' % (auth_url)) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: flow.fetch_token(code=code) except InvalidGrantError as ex: print 'Authentication has failed: %s' % ex sys.exit(1) print 'Access token: %s' % flow.credentials.token print 'Refresh token: %s' % flow.credentials.refresh_token
def update_google_creds( creds=None, client_config=None, client_config_filename='credentials.json', dump_token=False, pickle_path='token.pickle', scopes=SCOPES, ): """ Open the login page for the user """ if not creds and os.path.exists(pickle_path): with open(pickle_path, 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: if client_config is not None: flow = InstalledAppFlow.from_client_config(client_config, scopes) else: flow = InstalledAppFlow.from_client_secrets_file(client_config_filename, scopes) creds = flow.run_local_server(port=53021) # Save the credentials for the next run if dump_token: with open(pickle_path, 'wb') as token: pickle.dump(creds, token) return creds
def get_refresh_token(credentials_file): with open(credentials_file, 'r') as f: credentials = yaml.safe_load(f) client_config = { 'installed': { 'client_id': credentials['adwords']['client_id'], 'client_secret': credentials['adwords']['client_secret'], 'auth_uri': 'https://accounts.google.com/o/oauth2/auth', 'token_uri': 'https://accounts.google.com/o/oauth2/token', } } flow = InstalledAppFlow.from_client_config( client_config, scopes=['https://www.googleapis.com/auth/adwords']) flow.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob' auth_url, _ = flow.authorization_url(prompt='consent') print('Log into the Google Account you use to access your AdWords account ' 'and go to the following URL: \n%s\n' % auth_url) print( 'After approving the token enter the verification code (if specified).' ) code = input('Code: ').strip() try: flow.fetch_token(code=code) except InvalidGrantError as ex: print('Authentication has failed: %s' % ex) sys.exit(1) credentials['adwords']['refresh_token'] = flow.credentials.refresh_token with open(credentials_file, 'w') as f: yaml.dump(credentials, f, default_flow_style=False)
def get_resource(config, scopes, cache_dir: str): """Returns configured resource for connection to api """ creds = None token_file = pathlib.Path(cache_dir) / 'token.pickle' # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first time. if pathlib.Path(token_file).exists(): with token_file.open('rb') as token: creds = pickle.load(token) if creds.scopes != scopes: creds = None # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(config, scopes) creds = flow.run_local_server(port=0) # Save the credentials for the next run with token_file.open('wb') as token: pickle.dump(creds, token) return build(PEOPLE, 'v1', credentials=creds)
def __init__(self): """Shows basic usage of the Gmail API. Lists the user's Gmail labels. """ self.creds = None self._Configuration = API_CONFIGURATIONS # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: self.creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not self.creds or not self.creds.valid: if self.creds and self.creds.expired and self.creds.refresh_token: self.creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config( self._Configuration.google, SCOPES) self.creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(self.creds, token) self.service = build('gmail', 'v1', credentials=self.creds)
def main(): """ Opens a new tab browser to get the user consent permission to read and update his Google Sheet data. """ parser = ArgumentParser() parser.add_argument('--config-file', '-c', help='Path to configuration file.', required=True) args = parser.parse_args() os.environ['CONFIGURATION_FILE_PATH'] = args.config_file global_settings = get_settings(should_set_environment_settings=False) google_oauth_credentials = global_settings.get('GOOGLE_OAUTH_CREDENTIALS', None) if not google_oauth_credentials: print('Google oAuth credentials were not provided.') exit() try: flow = InstalledAppFlow.from_client_config(google_oauth_credentials, SCOPES) credentials = flow.run_local_server() if not credentials: raise GoogleApiCredentialsError('Credentials object is empty.') store_credentials_as_dict('google-oauth-credentials.json', credentials) except Exception as error: raise error
async def generate_credentials(gdrive): """ - Only generate once for long run - """ if helper.get_credentials(str(gdrive.from_id)) is not None: await gdrive.edit("`You already authorized token...`") await asyncio.sleep(1.5) await gdrive.delete() return False """ - Generate credentials - """ if G_DRIVE_DATA is not None: try: configs = json.loads(G_DRIVE_DATA) except json.JSONDecodeError: await gdrive.edit( "`[AUTHENTICATE - ERROR]`\n\n" "`Status` : **BAD**\n" "`Reason` : **G_DRIVE_DATA** entity is not valid!" ) return False else: """ - Only for old user - """ if G_DRIVE_CLIENT_ID is None and G_DRIVE_CLIENT_SECRET is None: await gdrive.edit( "`[AUTHENTICATE - ERROR]`\n\n" "`Status` : **BAD**\n" "`Reason` : please get your **G_DRIVE_DATA** " "[here](https://telegra.ph/How-To-Setup-Google-Drive-04-03)" ) return False configs = { "installed": { "client_id": G_DRIVE_CLIENT_ID, "client_secret": G_DRIVE_CLIENT_SECRET, "auth_uri": GOOGLE_AUTH_URI, "token_uri": GOOGLE_TOKEN_URI, } } await gdrive.edit("`Creating credentials...`") flow = InstalledAppFlow.from_client_config( configs, SCOPES, redirect_uri=REDIRECT_URI ) auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent") msg = await gdrive.respond("`Go to your BOTLOG group to authenticate token...`") async with gdrive.client.conversation(BOTLOG_CHATID) as conv: url_msg = await conv.send_message( "Please go to this URL:\n" f"{auth_url}\nauthorize then reply the code" ) r = conv.wait_event(events.NewMessage(outgoing=True, chats=BOTLOG_CHATID)) r = await r code = r.message.message.strip() flow.fetch_token(code=code) creds = flow.credentials await asyncio.sleep(3.5) await gdrive.client.delete_messages(gdrive.chat_id, msg.id) await gdrive.client.delete_messages(BOTLOG_CHATID, [url_msg.id, r.id]) """ - Unpack credential objects into strings - """ creds = base64.b64encode(pickle.dumps(creds)).decode() await gdrive.edit("`Credentials created...`") helper.save_credentials(str(gdrive.from_id), creds) await gdrive.delete() return
def main(): """ Shows basic usage of the Gmail API. Lists the user's Gmail labels. """ creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config( CLIENT_CONFIG, SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # creds_to_save = {} # print(creds_to_save.update(CLIENT_CONFIG['installed'])) # creds_to_save = creds_to_save.update(CLIENT_CONFIG['installed']).update(creds.to_json()) print("''''''''''''''''''''''''''''''''''''''''''''''") # print(CLIENT_CONFIG['installed']) # print(creds.to_json()) pprint.pprint({ **CLIENT_CONFIG['installed'], **json.loads(creds.to_json()), **{'delete_emails': False}}) print("''''''''''''''''''''''''''''''''''''''''''''''") service = build('gmail', 'v1', credentials=creds) '''
def gsheet_service(self): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ conf = self.config creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config( conf.credentials, conf.scope) creds = flow.run_local_server() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build(conf.service, conf.discovery_version, credentials=creds) return service
def youtube_link_or_none(request, user) -> Union[str, None]: try: credentials_from_db = YoutubeCredentials.objects.get(user_id=user.id) except YoutubeCredentials.DoesNotExist: credentials_from_db = None if credentials_from_db is not None and \ is_user_youtube_auth_valid(model_to_dict(credentials_from_db)): return None flow = InstalledAppFlow.from_client_config( settings.YOUTUBE_SECRET, scopes=settings.YOUTUBE_SCOPES ) flow.redirect_uri = settings.YOUTUBE_AUTH_REDIRECT youtube_link = flow.authorization_url() client_id = parse_qs(urlparse(youtube_link[0]).query)['client_id'][0] if credentials_from_db is not None: credentials_from_db.client_id = client_id credentials_from_db.save() else: YoutubeCredentials( user=user, client_id=client_id ).save() return youtube_link[0]
def CredentialsFlowWrapper(client, credentials_only=False, **kwargs): # relax scope comparison, order and default scopes are not critical os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1' # parse credentials from file or json if RE_CREDENTIALS_JSON.match(client): client_json = json.loads(client) else: with open(client, 'r') as json_file: client_json = json.load(json_file) if credentials_only: return client_json else: if 'installed' in client_json: flow = InstalledAppFlow.from_client_config(client_json, APPLICATION_SCOPES, **kwargs) else: flow = Flow.from_client_config(client_json, APPLICATION_SCOPES, **kwargs) flow.user_agent = APPLICATION_NAME return flow
def refresh_oauth_token(): """Retrieve and display the access and refresh token.""" client_config = ClientConfigBuilder( client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=config.oauth2_client_id(), client_secret=config.oauth2_client_secret()) flow = InstalledAppFlow.from_client_config( client_config.build(), scopes=['https://www.googleapis.com/auth/adwords']) flow.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob' authorize_url, _ = flow.authorization_url(prompt='consent') print( 'Log into the Google Account you use to access your Google Ads 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: flow.fetch_token(code=code) except InvalidGrantError as ex: print('Authentication has failed: %s' % ex) sys.exit(1) print('Access token: %s' % flow.credentials.token) print('Refresh token: %s' % flow.credentials.refresh_token)
def acquire(self): """Acquire a new Google token.""" flow = GoogleInstalledAppFlow.from_client_config(self.config, scopes=self.scopes) creds = flow.run_console() self._token = self._parse(creds)
def google_credentials(scopes): # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the Google API Console at # https://console.developers.google.com/. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets aws_api = BotoWrapper('jongwony-private') credential_path = 'google/.credentials' credentials = aws_api.deserialize(credential_path) # If there are no (valid) credentials available, let the user log in. if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: with open('client_secrets.json') as f: config = json.load(f) flow = InstalledAppFlow.from_client_config( config, scopes=scopes, redirect_uri='http://localhost:8080') credentials = flow.run_local_server() # Save the credentials for the next run aws_api.serialize(credential_path, credentials) return credentials