def get_provider_user_id(response, **kwargs): if response: credentials = googleoauth.AccessTokenCredentials( access_token=response['access_token'], user_agent='') profile = _get_api(credentials).userinfo().get().execute() return profile['id'] return None
def append_to_gsheet(output_data=[], gsheet_id=args['gsheet_id'], range_name=RANGE_NAME): # Setup the Sheets API token = session['oauth_token'] creds = client.AccessTokenCredentials(token['access_token'], headers['User-Agent']) # if not creds or creds.invalid: # flow = client.flow_from_clientsecrets('client_secret.json', scope) # creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API body = {'values': output_data} try: result = service.spreadsheets().values().append( spreadsheetId=gsheet_id, range=range_name, valueInputOption='USER_ENTERED', body=body).execute() message = ('{0} rows updated.'.format( DictQuery(result).get('updates/updatedRows'))) return message except Exception as err: traceback.print_exc() return json.loads(err.content.decode('utf-8'))['error']['message']
def get_connection_values(response, **kwargs): if not response: return None access_token = response['access_token'] credentials = googleoauth.AccessTokenCredentials( access_token=access_token, user_agent='' ) http = httplib2.Http() http = credentials.authorize(http) api = googleapi.build('plus', 'v1', http=http) profile = api.people().get(userId='me').execute() return dict( provider_id=config['id'], provider_user_id=profile['id'], access_token=access_token, secret=None, display_name=profile['displayName'], profile_url=profile['url'], image_url=profile['image']['url'] )
def login(): group_email = flask.request.args.get('group') flask.session['group_email'] = group_email if 'oauth_token' not in flask.session: scheme = os.environ['wsgi.url_scheme'] host = os.environ['HTTP_HOST'] redirect_uri = '{}://{}{}'.format(scheme, host, groupkit.REDIRECT_URI_PATH) google = requests_oauthlib.OAuth2Session(CLIENT_ID, scope=SCOPE, redirect_uri=redirect_uri) authorization_url, state = google.authorization_url( AUTH_BASE_URL, approval_prompt='auto') # auto, force flask.session['oauth_callback_redirect'] = flask.request.url flask.session['oauth_state'] = state return flask.redirect(authorization_url) token = flask.session['oauth_token'] access_token = token['access_token'] credentials = client.AccessTokenCredentials(access_token, USER_AGENT) user_info = groupkit.get_user_info(credentials) email = user_info['email'] group = flask.session['group_email'] result = groupkit.is_user_in_group(email, group, credentials) content = 'Is {} in {}? -> {}'.format(email, group, result) resp = flask.Response(content) resp.headers['Content-Type'] = 'text/plain' return resp
def main(): logging.basicConfig(level=logging.DEBUG) ip_endpoint = '/instance/network-interfaces/0/access-configs/0/external-ip' ip_address = metaquery(METADATA_SERVER + ip_endpoint) token_data = metaquery(METADATA_SERVER + '/instance/service-accounts/default/token') project_id = metaquery(METADATA_SERVER + '/project/project-id') sql_name = metaquery(METADATA_SERVER + '/instance/attributes/sql-name') if token_data and sql_name and ip_address: http = httplib2.Http() j = json.loads(token_data) credentials = oauth2_client.AccessTokenCredentials( j['access_token'], 'my-user-agent/1.0') cloudsql = api_discovery.build('sqladmin', 'v1beta4', http=credentials.authorize(http)) patch_response = server_authorization(cloudsql=cloudsql, ip_address=ip_address, project_id=project_id, sql_name=sql_name) if patch_response: logging.debug(patch_response) else: logging.debug( "Giving up, could not complete the patch authorization.") else: logging.debug('There was an error contacting the metadata server.')
def getCredentials(accessToken, userAgent): try: credentials = client.AccessTokenCredentials(accessToken, userAgent); return credentials; except client.AccessTokenCredentialsError as err: # print(err); return;
def get_profile(self, raw_data): access_token = raw_data['access_token'] import oauth2client.client as googleoauth import apiclient.discovery as googleapi import httplib2 credentials = googleoauth.AccessTokenCredentials( access_token=access_token, user_agent='') http = httplib2.Http() http = credentials.authorize(http) api = googleapi.build('plus', 'v1', http=http) profile = api.people().get(userId='me').execute() name = profile.get('name') image_url = "" if profile.get('image', {}).get("url"): image_url = profile.get('image', {}).get("url").replace("sz=50", "sz=100") data = { 'provider': "Google", 'profile_id': profile['id'], 'username': None, "email": profile.get('emails')[0]["value"], 'access_token': access_token, 'secret': None, "first_name": name.get("givenName"), "last_name": name.get("familyName"), 'cn': profile.get('displayName'), 'profile_url': profile.get('url'), 'image_url': image_url, "gender": profile.get("gender") } return ExternalProfile(str(profile['id']), data, raw_data)
def __create_service(self): token = self.__read_token() credentials = client.AccessTokenCredentials(token, 'plan-fierce') service = build(self.api_service_name, self.api_version, credentials=credentials) return service
def add_meal(request): social = request.user.social_auth.get(provider='google-oauth2') access_token = social.extra_data['access_token'] # payload = { # "access_token": social.extra_data["access_token"], # "refresh_token": social.extra_data["refresh_token"], # "token_uri": social.extra_data["token_uri"], # } credentials = client.AccessTokenCredentials(access_token, 'eudaemo') year = '2019' month = '3' day = '28' GMT_OFF = '-07:00' EVENT = { 'summary': "doing the other thing", 'start': { 'dateTime': year + "-" + month + "-" + day + 'T20:00:00%s' % GMT_OFF }, 'end': { 'dateTime': year + "-" + month + "-" + day + 'T20:30:00%s' % GMT_OFF }, 'description': 'three eggs, \n pepper, salt, butter, olive oil, beans, cumin, oranges, peanut butter, crushed red pepper, asparagus' } service = build('calendar', 'v3', credentials=credentials) event = service.events().insert(calendarId='primary', body=EVENT).execute() print(event) return render(request, 'core/home.html')
def main(argv): http = httplib2.Http() token_uri = '%s/%s/token' % (METADATA_SERVER, SERVICE_ACCOUNT) resp, content = http.request(token_uri, method='GET', body=None, headers={'Metadata-Flavor': 'Google'}) if resp.status == 200: d = json.loads(content) access_token = d['access_token'] # Save the access token credentials = oauth2_client.AccessTokenCredentials( access_token, 'my-user-agent/1.0') client = api_discovery.build('storage', _API_VERSION, http=credentials.authorize(http)) try: fields_to_return = 'nextPageToken,items(bucket,name,metadata(my-key))' req = client.objects().list( bucket=_BUCKET_NAME, fields=fields_to_return, # optional maxResults=42) # optional # If you have too many items to list in one request, list_next() will # automatically handle paging with the pageToken. while req is not None: resp = req.execute() print(json.dumps(resp, indent=2)) req = client.objects().list_next(req, resp) except oauth2_client.AccessTokenRefreshError: print("The credentials have been revoked or expired, please re-run" "the application to re-authorize") else: print(resp.status)
def get_api(connection, **kwargs): credentials = googleoauth.AccessTokenCredentials(access_token=getattr( connection, 'access_token'), user_agent='') http = httplib2.Http() http = credentials.authorize(http) return googleapi.build('plus', 'v1', http=http)
def get_messages(self): # Get GMail message account = AccountAssociation.objects.first() credentials = client.AccessTokenCredentials(account.access_token, '') http = credentials.authorize(Http()) service = build('gmail', 'v1', http=http) message_list = service.users().messages().list(userId="me").execute() return message_list
def StartDrive(token): credentials = client.AccessTokenCredentials( token, 'my-user-agent/1.0') # obtaining credentials from the accesstoken http = httplib2.Http() http = credentials.authorize( http) # authentication of the user credentials DRIVE = discovery.build('drive', 'v3', http=http) # making of the DRIVE object return DRIVE
def get_gdrive_credentials(gms_ctx, app_id, app_sig): gdrive_token = get_gdrive_access_token(gms_ctx, app_id, app_sig) print(('GDrive token: %s' % gdrive_token)) if gdrive_token is None: return None cred = client.AccessTokenCredentials(gdrive_token, 'Mozilla/5.0 compatible') cred.scopes.add(DRIVE_FILE) cred.scopes.add(DRIVE_APPDATA) return cred
def get_provider_user_id(response, **kwargs): if response: credentials = googleoauth.AccessTokenCredentials( access_token=response['access_token'], user_agent='') http = httplib2.Http() http = credentials.authorize(http) api = googleapi.build('plus', 'v1', http=http) profile = api.people().get(userId='me').execute() return profile['id'] return None
def create_service(access_token): """ Function to create Google API client to access Calendar Input: Google Client Access Token Output: Google Calendar Build Object """ credentials = client.AccessTokenCredentials( access_token, 'calendar', ) service = build('calendar', 'v3', credentials=credentials) return service
def __init__(self, token=None): Sync.__init__(self) credentials = client.AccessTokenCredentials(token, 'clarify-google') authorized_http = credentials.authorize(Http()) classroom_client = build('classroom', 'v1', http=authorized_http) self.staff_id = None self.user_profile = None self.client = classroom_client self.sections = {}
def main() -> None: credentials = client.AccessTokenCredentials( ACCESS_TOKEN, 'my-calendar-bot/1.0', ) service = build('calendar', 'v3', credentials=credentials) event_bukovel_path = os.path.abspath("../Meta class/uz_bukovel_event.json") event_bukovel_obj = Event.from_file(event_bukovel_path) event = service.events().insert(calendarId='primary', body=event_bukovel_obj).execute() print(F'Event summary: {event.get("summary")}')
def _get_service(cls, token, service_name="calendar", version="v3"): try: oauth2 = ApiService.get_by_user(token) if oauth2: json = oauth2.json credentials = client.OAuth2Credentials.from_json(json) else: credentials = client.AccessTokenCredentials(token, '') http = credentials.authorize(httplib2.Http()) service = discovery.build(service_name, version, http=http) return service except: return None
def availability_by_day(): """ This fucntion expects email in request body This function first get day (return error if day is not present) Then creates rfc date from day. After that It gets user's main calendar and find all the enents from calendar. After finding all the events it finds available slots via calling find_slots method. """ output = dict() status = 422 day = request.args.get('day', default="", type=str) data = json.loads(request.data.decode('utf-8')) unique_url = data.get("unique_url", None) my_user = User.fetch_user_by_url(unique_url) token = my_user["access_token"] client_email = data.get("email", None) if day == "" or not token or not client_email: output["error"] = "Missing day or Access Token or Email" else: try: start_time, end_time = User.get_user_start_end_time( client_email) if end_time == "00:00": end_time = "23:59" p_time = datetime.fromtimestamp(float(day)) requested_day = p_time.strftime("%A") day_from_db = my_user["availability"]["days"][requested_day+"s"] if day_from_db: time_min = str(datetime( p_time.year, p_time.month, p_time.day, int(start_time[0:2]), int(start_time[3:]), 00).isoformat()) + "Z" time_max = str(datetime( p_time.year, p_time.month, p_time.day, int(end_time[0:2]), int(end_time[3:]), 59).isoformat()) + "Z" credentials = client.AccessTokenCredentials( token, 'my-user-agent') service = build('calendar', 'v3', credentials=credentials) result = service.calendarList().list().execute() calendar_id = result['items'][0]['id'] body = {"timeMin": time_min, "items": [{"id": calendar_id}], "timeMax": time_max} calendars_result = service.freebusy().query(body=body).execute() free_slots_arr = find_slots( calendars_result["calendars"].get(client_email).get("busy"), time_min, time_max) free_slots_in_ts = convert_to_unix_time(free_slots_arr) output["result"] = free_slots_in_ts status = 200 else: output["result"] = [] except Exception as e: output['error'] = f'{e}' status = 500 return jsonify(output), status
def _FetchCredentialWithSso(sso_cli, sso_email, scopes): """Fetch a credential with access_token fetched from the sso CLI.""" commands = [sso_cli, sso_email] + scopes try: process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, _ = process.communicate() if process.returncode != 0: raise Exception except: raise ValueError('Failed to fetch OAuth token by SSO.') return client.AccessTokenCredentials(result.strip(), _DEFAULT_USER_AGENT)
def _Refresh(self): # If our access token is close to expiring, request a new one and generate # new credentials. if self._expiration_seconds_utc <= time.time() + self._BUFFER_SECONDS: content = GetAccessTokenContent() if not content: raise _AuthenticatorError( 'Request for access token was unsuccessful') self._expiration_seconds_utc = time.time() + content['expires_in'] self._access_token = content['access_token'] self._credentials = oauth2_client.AccessTokenCredentials( self._access_token, gcloud_constants.USER_AGENT) self._refresh_number += 1 return self._credentials
def test_access_token_credentials(self): access_token = 'foo' user_agent = 'refresh_checker/1.0' credentials = client.AccessTokenCredentials(access_token, user_agent) storage = file.Storage(FILENAME) credentials = storage.put(credentials) credentials = storage.get() self.assertIsNotNone(credentials) self.assertEquals('foo', credentials.access_token) self.assertTrue(os.path.exists(FILENAME)) if os.name == 'posix': # pragma: NO COVER mode = os.stat(FILENAME).st_mode self.assertEquals('0o600', oct(stat.S_IMODE(mode)))
def getMyAuthService(service_name='bigquery', service_version='v2'): http = httplib2.Http() token_uri = '%s/%s/token' % (METADATA_SERVER, SERVICE_ACCOUNT) resp, content = http.request(token_uri, method='GET', body=None, headers={'Metadata-Flavor': 'Google'}) if resp.status == 200: d = json.loads(content) access_token = d['access_token'] # Save the access token credentials = oauth2_client.AccessTokenCredentials( access_token, 'my-user-agent/1.0') AUTH_HTTP = credentials.authorize(http) return build(service_name, service_version, http=AUTH_HTTP) else: comm.printException(comm.pathToSaveauthErrors, errString="AUTHENTICATION RESPONSE STATUS: " + resp.status) pass
def get_connection_values(response, **kwargs): if not response: return None access_token = response['access_token'] credentials = googleoauth.AccessTokenCredentials(access_token=access_token, user_agent='') profile = _get_api(credentials).userinfo().get().execute() return dict( provider_id=config['id'], provider_user_id=profile['id'], access_token=access_token, secret=None, display_name=profile['name'], full_name=profile['name'], profile_url=profile.get('link'), image_url=profile.get('picture'), email=profile.get('email'), )
def _ConstructJwtCredential(json_keyfile, audience): with open(json_keyfile, 'r') as json_keyfile_obj: client_credentials = json.load(json_keyfile_obj) pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, client_credentials['private_key']) jwt_header = { "alg": "RS256", "typ": "JWT", "kid": client_credentials['private_key_id'] } # Use time 1 minute before now to avoid clock skew with Google servers current_time = int(time.time()) - 60 jwt_payload = { "iss": client_credentials['client_email'], "sub": client_credentials['client_email'], "aud": audience, "iat": current_time, "exp": current_time + 3600 } jwt_header_base64 = base64.urlsafe_b64encode( json.dumps(jwt_header, separators=(',', ':')).encode('utf-8')).decode().strip('=') jwt_payload_base64 = base64.urlsafe_b64encode( json.dumps(jwt_payload, separators=(',', ':')).encode('utf-8')).decode().strip('=') jwt_base_string = jwt_header_base64 + '.' + jwt_payload_base64 jwt_signature = base64.urlsafe_b64encode( crypto.sign(pkey, jwt_base_string, "sha256")).decode().strip('=') jwt = jwt_base_string + '.' + jwt_signature return client.AccessTokenCredentials(jwt, _DEFAULT_USER_AGENT)
def get_connection_values(response, **kwargs): if not response: return None access_token = response['access_token'] credentials = googleoauth.AccessTokenCredentials(access_token=access_token, user_agent='') http = httplib2.Http() http = credentials.authorize(http) api = googleapi.build('plus', 'v1', http=http) profile = api.people().get(userId='me').execute() given_name = profile['name']['givenName'] family_name = profile['name']['familyName'] return dict(provider_id=config['id'], provider_user_id=profile['id'], access_token=access_token, secret=None, display_name='%s %s' % (given_name, family_name), full_name='%s %s' % (given_name, family_name), profile_url=profile.get('link'), image_url=profile.get('picture'))
def get_plus_service(googleuser): cred = client.AccessTokenCredentials(googleuser.access_token, 'web client') http_auth = cred.authorize(httplib2.Http()) plus_service = discovery.build('plus', 'v1', http=http_auth) return plus_service
def get_credentials(googleuser): return client.AccessTokenCredentials(googleuser.access_token, 'web client')
def get_credentials(access_token): credentials = client.AccessTokenCredentials(access_token, USER_AGENT) return credentials