def from_user_credentials_json(cls, user_credentials_json): """ Return a resource object from json of user credentials. """ try: credentials = Credentials.new_from_json(user_credentials_json) except(ValueError): # when user passed dict instead of json credentials = Credentials.new_from_json( json.dumps(user_credentials_json)) return cls.from_credentials_object(credentials)
def get(self): # credentials = sessions.get_store(request=self.request).get_session().get('credentials') credentials = self.session.get('credentials') credentials = Credentials.new_from_json(credentials) logging.debug("nawwwwww") logging.debug(credentials) # credentials = credentials[0].from_json() # logging.debug(credentials) # logging.debug("F**K") # Only fetch a list of people for connected users. if credentials is None: logging.debug("creds = none!") self.response.headers['Content-Type'] = 'application/json' self.response.status = 401 self.response.out.write(json.dumps('Current user not connected.')) try: # Create a new authorized API client. http = httplib2.Http() http = credentials.authorize(http) # Get a list of people that this user has shared with this app. google_request = SERVICE.people().list(userId='me', collection='visible') result = google_request.execute(http=http) logging.debug(json.dumps(result)) self.response.headers['Content-Type'] = 'application/json' self.response.status = 200 self.response.out.write(json.dumps(result)) except AccessTokenRefreshError: self.response.headers['Content-Type'] = 'application/json' self.response.status = 500 self.response.out.write(json.dumps('Failed to refresh access token.'))
def handler(event, context): print event calendarId = getConfigValue('GoogleCalendarId') credentialJson = getConfigValue('GoogleOAuth2Credentials') discordWebhookUri = getConfigValue('DiscordWebhookUri') credentials = Credentials.new_from_json(credentialJson) http_auth = credentials.authorize(httplib2.Http()) calendar = build('calendar', 'v3', http=http_auth) header = getConfigValue('header') content = textblockStart + header footer = getConfigValue('footer') + textblockEnd for item in calendar.events().list(calendarId=calendarId, timeMin=now(), timeMax=week(), singleEvents=True, orderBy='startTime').execute()['items']: itemContent = "" itemContent = itemContent + 'Title:\t' + item['summary'] + '\n' itemContent = itemContent + 'Start:\t' + format_time( item['start']['dateTime']) + '\n' itemContent = itemContent + 'End:\t' + format_time( item['end']['dateTime']) + '\n' if ('description' in item): itemContent = itemContent + item['description'] + '\n' itemContent = itemContent + '\n' if ((len(itemContent) + len(content) + len(footer)) >= 2000): r = requests.post(discordWebhookUri, data={'content': content + textblockEnd}) content = textblockStart + itemContent else: content = content + itemContent r = requests.post(discordWebhookUri, data={'content': content + footer})
def get_credentials(): with open(REGISTERED_CREDENTIALS_JSON) as f: registered_credentials = json.load(f) return [ Credentials.new_from_json(credential) for credential in registered_credentials ]
def test_get_access_token_on_refresh(self): app_identity_stub = self.AppIdentityStubImpl() apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service", app_identity_stub) apiproxy_stub_map.apiproxy.RegisterStub( 'memcache', memcache_stub.MemcacheServiceStub()) scope = [ "http://www.googleapis.com/scope", "http://www.googleapis.com/scope2"] credentials = AppAssertionCredentials(scope) http = httplib2.Http() credentials.refresh(http) self.assertEqual('a_token_123', credentials.access_token) json = credentials.to_json() credentials = Credentials.new_from_json(json) self.assertEqual( 'http://www.googleapis.com/scope http://www.googleapis.com/scope2', credentials.scope) scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2" credentials = AppAssertionCredentials(scope) http = httplib2.Http() credentials.refresh(http) self.assertEqual('a_token_123', credentials.access_token) self.assertEqual( 'http://www.googleapis.com/scope http://www.googleapis.com/scope2', credentials.scope)
def test_serialize_deserialize(self, get_metadata): credentials = AppAssertionCredentials() credentials_from_json = Credentials.new_from_json( credentials.to_json()) self.assertEqual( credentials.service_account_info, credentials_from_json.service_account_info)
def test_to_from_json(self): c = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) json = c.to_json() c2 = Credentials.new_from_json(json) self.assertEqual(c.access_token, c2.access_token)
def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials Raises: CredentialsFileSymbolicLinkError if the file is a symbolic link. """ credentials = None self._validate_file() try: f = open(self._filename, "rb") content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials
def disconnect(request): # Check to make sure the user is logged in url = redirect_if_not_logged_in(request) if url is not None: return url # Only disconnect a connected user. creditionals_in_json = request.session['credentials'] if creditionals_in_json is None: # Trying to disconnect a connected user so some sort of error probably occured return redirect(reverse("ding:error_401")) # Retrieve the dcredentials object credentials = Credentials.new_from_json(creditionals_in_json) # Execute HTTP GET request to revoke current token. access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': # Reset the user's session. del request.session['credentials'] request.session.delete() # Redirect back to sign in page url = reverse("ding:disconnect_sign_in") return redirect(url) else: # For whatever reason, the given token was invalid. error = {'error_type': 400, 'request_path': request.path} return render(request, 'ding/error.html', error, status=400)
def authorize_installed_app(scope, env_key): """Prepare oAuth2 credentials for an installed app. Args: env_key: The environment variable from which to read the credentials. scope: The scope needed. (Only used here for documentation purposes.) Returns: An authorized httplib2.Http() instance. """ content = os.getenv(env_key) if not content: raise RuntimeError( 'Missing credentials for %s' % env_key) try: credentials = Credentials.new_from_json(content) if credentials.invalid: raise ValueError() except ValueError: raise RuntimeError( 'Invalid credentials for %s' % env_key) return credentials.authorize(httplib2.Http())
def run(): if "creds" in session: creds = Credentials.new_from_json(session["creds"]) #Tracks2Cal(creds).run() return "DONE", 200 else: return render_template("error.html", message="No auth token found")
def test_to_json_and_from_json(self): credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) json = credentials.to_json() credentials_from_json = Credentials.new_from_json(json) self.assertEqual(credentials.access_token, credentials_from_json.access_token)
def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials Raises: CredentialsFileSymbolicLinkError if the file is a symbolic link. """ credentials = None self._validate_file() try: f = open(self._filename, 'rb') content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials
def getDriveList(): global drivecredentials global drive_service if (drive_service is None): if (drivecredentials is None): driveauthfile = open('drivecredentials.txt', 'r') drivecredentials = Credentials.new_from_json(driveauthfile.read()) driveauthfile.close() http = httplib2.Http() http = drivecredentials.authorize(http) drive_service = build('drive', 'v2', http=http) #Variable donde almacenaremos todos los ficheros listados resultados = [] page_token = None siguiente_pagina = True while siguiente_pagina: parametros = {} #Comprobar si hay otra pagina if page_token: parametros['pageToken'] = page_token #Ejecutamos la consulta files = drive_service.files().list(**parametros).execute() #Concatenamos los resultados con los de la página anterior resultados.extend(files['items']) #Guardamos el token de la página siguiente page_token = files.get('nextPageToken') #Comprobamos si hay que continuar if not page_token: siguiente_pagina = False #Procesamos los resultados, almacenando la información relevante respuesta = [] for elemento in resultados: try: respuesta.extend([{ 'id': elemento['id'], 'filename': elemento['title'], 'link': elemento['alternateLink'], 'size': elemento['fileSize'], 'remove_link': 'remove_drive_file?id=' + elemento['id'] }]) except: respuesta.extend([{ 'id': elemento['id'], 'filename': elemento['title'], 'link': elemento['alternateLink'], 'size': 0, 'remove_link': 'remove_drive_file?id=' + elemento['id'] }]) return json.dumps(respuesta)
def get_credentials(): if __cache.has_key('credentials'): return __cache['credentials'] elif os.path.exists('%s/.googledrive'%os.environ['HOME'] ): ss = open('%s/.googledrive'%os.environ['HOME']).read() credentials = Credentials.new_from_json( ss ) else: # Copy your credentials from the APIs Console CLIENT_ID = 'your client id' CLIENT_SECRET = 'your client secrete' REDIRECT_URI = 'your redirect uri' # Check https://developers.google.com/drive/scopes for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive' # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() print 'Go to the following link in your browser: ' + authorize_url code = raw_input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) f = open('%s/.googledrive'%os.environ['HOME'], 'w') f.write(credentials.to_json()) f.close() return credentials
def get_access_token(): if not settings.GOOGLE_API_CREDENTIALS or settings.GOOGLE_API_CREDENTIALS == "": print ">>> ERR >>> GOOGLE_API_CREDENTIALS not defined" credential = Credentials.new_from_json(settings.GOOGLE_API_CREDENTIALS) http = httplib2.Http() credential._refresh(http.request) return credential.access_token
def calendar(): query = session.query(Buy) last = query.filter(bool(Buy.buy_id)).count() even_cal = query.filter(Buy.buy_id == last).one() new = even_cal.data_time_city query = session.query(User) add_tok = query.filter(User.username == even_cal.temp).one() credentials = Credentials.new_from_json(add_tok.token) http = credentials.authorize(httplib2.Http()) service = build('calendar', 'v3', http=http) event = { 'summary': text(3), 'location': even_cal.adress_city, 'description': even_cal.menu, 'start': { 'dateTime': new, 'timeZone': 'Europe/Kiev', }, 'end': { 'dateTime': new, 'timeZone': 'Europe/Kiev', }, } event = service.events().insert(calendarId='primary', body=event).execute() return json.dumps(event)
def disconnect(request): # Check to make sure the user is logged in url = redirect_if_not_logged_in(request) if url is not None: return url # Only disconnect a connected user. creditionals_in_json = request.session['credentials'] if creditionals_in_json is None: # Trying to disconnect a connected user so some sort of error probably occured return redirect(reverse("ding:error_401")) # Retrieve the dcredentials object credentials = Credentials.new_from_json(creditionals_in_json) # Execute HTTP GET request to revoke current token. access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': # Reset the user's session. del request.session['credentials'] request.session.delete() # Redirect back to sign in page url = reverse("ding:disconnect_sign_in"); return redirect(url) else: # For whatever reason, the given token was invalid. error = {'error_type': 400, 'request_path': request.path} return render(request, 'ding/error.html', error, status=400)
def add_calendar_event(request, event): flags = tools.argparser.parse_args([]) storage = Storage('static/calendar.dat') FLOW = OAuth2WebServerFlow( client_id=settings.MEETUP_CLIENT_ID, client_secret=settings.MEETUP_CLIENT_SECRET, scope='https://www.googleapis.com/auth/calendar', user_agent=settings.MEETUP_CLIENT_NAME, ) credentials = request.session.get('calendar_auth', None) if not credentials: credentials = tools.run_flow(FLOW, storage, flags) else: credentials = Credentials.new_from_json(credentials) service = build('calendar', 'v3', credentials=credentials) # Add event to the calendar event = service.events().insert(calendarId='primary', body=event).execute() if request.user.email != event['creator']['email']: service.events().delete(calendarId='primary', eventId=event['id']).execute() raise CalendarException( "Meetup registration email does not match the calendar email!") request.session['calendar_auth'] = credentials.to_json() print('Event created: %s' % (event.get('htmlLink')))
def __init__(self, client_secret_file, oauth_scope_key, re_autheticate=False): if(not oauth_scope_key in self.scopes): self.oauth_scope = self.scopes['READ_ONLY']; else: self.oauth_scope = self.scopes[oauth_scope_key] self.client_secret_file_data = self.get_client_secret_file(client_secret_file) self.client_id = self.client_secret_file_data['installed']['client_id'] self.client_secret = self.client_secret_file_data['installed']['client_secret'] self.redirect_uri = self.client_secret_file_data['installed']['redirect_uris'][0] #Authenticate # check whether or not trying to authenticate again if os.path.isfile(self.credentials_file) and not re_autheticate: credentials_file_data = self.get_client_credentials() credentials = Credentials.new_from_json(credentials_file_data) else: # client needs to manually get credentials flow = OAuth2WebServerFlow(self.client_id, self.client_secret, self.oauth_scope, redirect_uri=self.redirect_uri) #access_type='offline') authorize_url = flow.step1_get_authorize_url() flow.step1_get_authorize_url() log('Go to the following link in your browser: ' + authorize_url) code = raw_input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) # store credentials for next authorization self.set_client_credentials(credentials) self.set_drive_service(credentials)
def test_to_from_json(self): c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b']) json = c.to_json() c2 = Credentials.new_from_json(json) self.assertEqual(c.access_token, c2.access_token)
def get_oauth(): try: logger.info("using existing OAuth credentials") credentials = Credentials.new_from_json(open(OAUTH_FILE,'r').read()) http_auth = credentials.authorize(httplib2.Http()) except: http_auth = setup_oauth() return http_auth
def __create_service(): with open('credentials', 'rw') as f: credentials = Credentials.new_from_json(f.read()) http = httplib2.Http() http = credentials.authorize(http) return build('calendar', 'v3', http=http)
def __init__(self): YOUTUBE_DATA_API_NAME = "youtube" YOUTUBE_DATA_API_VERSION = "v3" content = os.environ['YT'] credentials = Credentials.new_from_json(content) http = httplib2.Http() http = credentials.authorize(http) self.youtube = build(YOUTUBE_DATA_API_NAME, YOUTUBE_DATA_API_VERSION, http=http)
def get_user_credentials(self): j_credentials = self.memcache_session.get(self.CREDENTIALS_KEY) if j_credentials is None: return credentials = Credentials.new_from_json(j_credentials) if not credentials.invalid: return credentials
def user_info(creds=None): if creds is None: creds = session['google_creds'] creds = Credentials.new_from_json(creds) user_info_service = build('oauth2', 'v2', http=creds.authorize(httplib2.Http())) user_info = user_info_service.userinfo().get().execute() if user_info and user_info.get('id'): return user_info
def locked_get(self): credentials = None if not pkg_resources.resource_exists(__name__, self._filename): return super(Storage, self).locked_get() content = pkg_resources.resource_string(__name__, self._filename) credentials = Credentials.new_from_json(content) credentials.set_store(self) return credentials
def get_stored_credentials(user_id): """Retrieved stored credentials for the provided user ID. Args: user_id: User's ID. Returns: Stored oauth2client.client.OAuth2Credentials if found, None otherwise. """ # # To instantiate an OAuth2Credentials instance from a Json # representation, use the oauth2client.client.Credentials.new_from_json # class method. user = engine.query(User).filter(userId=user_id).first() if user: user_dict = user.__dict__ if user_dict['credentials']: # credentials = Credentials.new_from_json(user['credentials']) credentials = json.loads(user_dict['credentials']) token_expiry = credentials['token_expiry'] dexp = parser.parse(str(token_expiry)) dexp = dexp.replace(tzinfo=None) dnow = datetime.now() if dexp > dnow: return Credentials.new_from_json(user_dict['credentials']) else: status_code, data = renew_access_token( client_id=credentials['client_id'], client_secret=credentials['client_secret'], refresh_token=credentials['refresh_token'], ) if status_code == INT_OK: credentials['access_token'] = data['access_token'] credentials['token_expiry'] = datetime_util( datetime.now() + timedelta(seconds=float(str(data['expires_in'])))) credentials = Credentials.new_from_json( json_encode(credentials)) user.update_credentials(credentials.to_json()) user.sync() return credentials else: return None else: return None return None
def get_google_code(): credentials = None if 'google_cred' in session: credentials = Credentials.new_from_json(session['google_cred']) if credentials is None or credentials.invalid == True: return FLOW.step1_get_authorize_url()
def get_authorize_http(): """ Method which is helpful to get authorize http from your credentials. Can be used for make some service from google api """ json = db(GoogleToken).first().credentials cred = Credentials() credentials = cred.new_from_json(json) http = httplib2.Http() http = credentials.authorize(http) return http
def _set_expiration_to_long_time(self, creds): cred_str = creds.to_json() cred_json = json.loads(cred_str) # incase it might have an expiration if(cred_json['token_expiry'] is not None): return creds cred_json['token_expiry'] = '2100-01-01T00:00:01Z' cred_new_json = json.dumps(cred_json) return Credentials.new_from_json(cred_new_json)
def _set_expiration_to_long_time(self, creds): cred_str = creds.to_json() cred_json = json.loads(cred_str) # incase it might have an expiration if (cred_json['token_expiry'] is not None): return creds cred_json['token_expiry'] = '2100-01-01T00:00:01Z' cred_new_json = json.dumps(cred_json) return Credentials.new_from_json(cred_new_json)
def gdisconnect(): credentials = login_session.get("credentials") and Credentials.new_from_json(login_session.get("credentials")) if credentials is None: flash("User Not Logged In!") return redirect(url_for("homepageRoute")) access_token = credentials.access_token url = "https://accounts.google.com/o/oauth2/revoke?token=%s" % access_token h = httplib2.Http() result = h.request(url, "GET")[0]
def test_credentials_to_from_json(self): credentials = self._make_credentials() json = credentials.to_json() restored = Credentials.new_from_json(json) self.assertEqual(credentials._private_key_pkcs12, restored._private_key_pkcs12) self.assertEqual(credentials._private_key_password, restored._private_key_password) self.assertEqual(credentials._kwargs, restored._kwargs)
def __init__(self, credentials, user_email=None): if credentials: self.service = build_service(Credentials.new_from_json(credentials)) else: logging.error('This user failed in credentials error %s and email %s' % (credentials, user_email)) auth_url = 'no_url' if user_email: auth_url = get_authorization_url(user_email, 1) raise GetCredentialsException(auth_url)
def http_and_service(): import httplib2 from apiclient.discovery import build from oauth2client.client import Credentials with open('credentials.json','r') as ff: credentials = Credentials.new_from_json(ff.read()) http = httplib2.Http() http = credentials.authorize(http) return http, build('drive', 'v2', http=http)
def __build_client_credentials(service_name, user_settings=None): if user_settings is None: user_settings = threading.current_thread().settings client_credentials = user_settings.get(CREDENTIALS.CLIENT, None) if not client_credentials: raise MissingCredentialsException credentials_json = client_credentials.get(service_name, None) if not credentials_json: raise MissingCredentialsException return Credentials.new_from_json(json_data=credentials_json)
def http_and_service(): import httplib2 from apiclient.discovery import build from oauth2client.client import Credentials with open('credentials.json', 'r') as ff: credentials = Credentials.new_from_json(ff.read()) http = httplib2.Http() http = credentials.authorize(http) return http, build('drive', 'v2', http=http)
def test_credentials_to_from_json(self): private_key = datafile("privatekey.p12") credentials = SignedJwtAssertionCredentials( "*****@*****.**", private_key, scope="read+write", prn="*****@*****.**" ) json = credentials.to_json() restored = Credentials.new_from_json(json) self.assertEqual(credentials.private_key, restored.private_key) self.assertEqual(credentials.private_key_password, restored.private_key_password) self.assertEqual(credentials.kwargs, restored.kwargs)
def get_cred_storage(db, userId): #get from db user = db.session.query(User).get(str(userId)) credentials = Credentials.new_from_json(str(user.google_cred)) #refresh http = httplib2.Http() credentials.refresh(http) return credentials
def from_dict(container): """ Create a Credentials object from a dictionary. The dictionary is first converted to JSON by the native implementation to ensure it is converted correctly and make updates to the oauth2client module easier. """ jsonRepr = simplejson.dumps(container) return Credentials.new_from_json(jsonRepr)
def __init__(self, project): credentials = Credentials.new_from_json(project.credentials) authed_http = credentials.authorize(httplib2.Http()) self.service = build(self.API_NAME, self.API_VERSION, http=authed_http) self.profile_id = project.profile_id self.creatives = {} self.placements = {} self.campaigns = {} self.ads = {}
def oauth_credentials_are_valid(self, credentials_json): if not credentials_json: return False try: credentials = Credentials.new_from_json(credentials_json) except Exception: return False if credentials is None or credentials.invalid: return False return True
def locked_get(self): credentials = None try: credentials = Credentials.new_from_json(self.couchdrop_storage_entity["google_credentials"]) credentials.set_store(self) except ValueError as e: print "ERROR while request for google credentials. Err: %s" % (str(e)) raise Exception("Failed to retrieve google credentials") return credentials
def get_authenticated_services(): json = load_credentials('Youtube_API') credentials = Credentials.new_from_json(json) http = credentials.authorize(httplib2.Http()) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=http) youtube_analytics = build(YOUTUBE_ANALYTICS_API_SERVICE_NAME, YOUTUBE_ANALYTICS_API_VERSION, http=http) return (youtube, youtube_analytics)
def get_gcloud_oauth2_creds(): gcfp = '~/.config/gcloud/credentials' credfn = os.path.expanduser(gcfp) if not os.path.exists(credfn): msg = "[edx2bigquery] Authentication error! You have specified USE_GCLOUD_AUTH in the configuration, but do not have gcloud authentication available.\n" msg += " Please authenticate using 'gcloud auth login' before running this." print msg raise Exception(msg) gcloud_cred = json.loads(open(credfn).read())['data'][0]['credential'] credentials = Credentials.new_from_json(json.dumps(gcloud_cred)) return credentials
def setup_api_service(): secret_data = None with open(CLIENT_SECRETS) as f: secret_data = f.read() credentials = Credentials.new_from_json(secret_data) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) drive_service = build('drive', 'v2', http=http) return drive_service
def tick(self, config): Logger.Info('%s - tick - started - with config: %s' % (__name__, config)) keywords = [e for e in config['elements'] if e['name'] == 'keywords'][0]['value'] credentials = Credentials.new_from_json([e for e in config['elements'] if e['name'] == 'oauth2'][0]['value']) http = credentials.authorize(httplib2.Http()) service = build('plus', 'v1', http=http) response = service.activities().search(query=keywords).execute() Logger.Debug('%s - tick - JSON response: %s' % (__name__, response)) content = [self._map_googleplus_item_to_content_item(config, item) for item in response['items']] Logger.Info('%s - tick - finished' % __name__) return content
def make_value_from_datastore(self, value): logger.info("make: Got type " + str(type(value))) if value is None: return None if len(value) == 0: return None try: credentials = Credentials.new_from_json(value) except ValueError: credentials = None return credentials
def build_service(self, user_id): http = httplib2.Http() creds_json = self.get_stored_creds(user_id) self.refresh_token(creds_json, user_id) #Need to load credentials again after being refreshed. creds_json = self.get_stored_creds(user_id) credentials = Creds_obj.new_from_json(json.dumps(creds_json)) http = credentials.authorize(http) return build('drive','v2',http=http)