def get_unknown_service(cls, credentials: Credentials, **kwargs: Mapping[str, Any]): """Fetch a discoverable API service. If this is not the case (or, upon attempting to is the service an authorization error is raised) the service can be cleared and forced to reload. Args: Returns: service: a service for REST calls """ credentials.get_credentials() _credentials = AccessTokenCredentials( credentials.token_details['access_token'], user_agent='report2bq') https = discovery.httplib2.Http() auth_https = _credentials.authorize(https) service = discovery.build(http=https, cache_discovery=False, **kwargs) return service
def __init__(self, user): self._user = user self._name = user.email self._error = False dev_key = config['GOOGLE_DEVELOPERS_KEY'] try: credentials = AccessTokenCredentials(user.access_token, 'intranet/1.0') except Exception as e: self._error = True EXCEPTION("Can't refresh token for user %s: %s" % (user.email, e)) return http = httplib2.Http() http = credentials.authorize(http) self._service = build(serviceName='calendar', version='v3', http=http, developerKey=dev_key)
def authenticate_google_docs(): """ Authenticate to the google docs api and return a gspread object Further reference to how to generate various codes http://www.indjango.com/access-google-sheets-in-python-using-gspread/ """ data = { 'refresh_token': config.refresh_token, 'client_id': config.client_id, 'client_secret': config.client_secret, 'grant_type': 'refresh_token', } req = requests.post('https://accounts.google.com/o/oauth2/token', data=data) gdoc = gspread.authorize( AccessTokenCredentials( ast.literal_eval(req.text)['access_token'], 'Test')) return gdoc
def get_service_object(self, name): service = GoogleAnalyticsHook._services[name] if self.connection.password: credentials = AccessTokenCredentials(self.connection.password, 'Airflow/1.0') elif hasattr(self, 'client_secrets'): credentials = ServiceAccountCredentials.from_json_keyfile_dict( self.client_secrets, service.scopes) elif hasattr(self, 'file_location'): credentials = ServiceAccountCredentials.from_json_keyfile_name( self.file_location, service.scopes) else: raise ValueError('No valid credentials could be found') logging.info(credentials.client_id) # http = credentials.authorize(httplib2.Http()) return build('analyticsreporting', service.version, credentials=credentials, cache_discovery=False)
def fileask_authed(self, request1): if request1.times == 1: current_user = endpoints.get_current_user() if "HTTP_AUTHORIZATION" in os.environ: (tokentype, token) = os.environ["HTTP_AUTHORIZATION"].split(" ") credentials = AccessTokenCredentials(token, 'my-user-agent/1.0') http = httplib2.Http() #http = credentials.authorize(http) service = discovery.build('drive', 'v2', http=http) #storage = StorageByKeyName(CredentialsModel, current_user.user_id(), 'credentials') #credentials = storage.get() http = credentials.authorize(http) items = service.files().list(q="title = '" + request1.filename + "'").execute()['items'] #drive_files = service.files().list(q="title = 'dan'").execute() download_url = items[0].get('downloadUrl') resp, content = service._http.request(download_url) fileReturn = FileResponse() fileReturn.filename = request1.filename fileReturn.filedata = content fileReturn.user = (current_user.email() if current_user is not None else 'Anonymous') return fileReturn #Greeting(message='hello %s' % (email,)) else: dbx = dropbox.Dropbox('REPLACE THIS WITH YOUR DROPBOX API KEY') #dbx.users_get_current_account() fileplus = '/' + request1.filename + '.txt' dbx.files_upload(StringIO.StringIO(request1.filedata), fileplus) fileReturn = FileResponse() fileReturn.filename = request1.filename fileReturn.filedata = request1.filedata fileReturn.user = (current_user.email() if current_user is not None else 'Anonymous') return fileReturn
def gdisconnect(): # Only disconnect a connected user. credentials = AccessTokenCredentials(login_session['credentials'], 'user-agent-value') if credentials is None: response = make_response(json.dumps('Current user not ' 'connected.'), 401) response.headers['Content-Type'] = 'application/json' return response 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] reason = h.request(url, 'GET')[1] if result['status'] == '200': # Reset the user's sesson. del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['image'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' flash("You have successfully logged out.") return redirect(url_for('show_homepage')) else: # For whatever reason, the given token was invalid. response = make_response( json.dumps( 'Failed to revoke token for given ' 'user. reason: ' '{reason}'.format(reason=reason), 400)) response.headers['Content-Type'] = 'application/json' return response
def showme(): now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time token = json.loads( base64.urlsafe_b64decode( str(request.cookies.get('suez_authentication_key')) ) ) credentials = AccessTokenCredentials( token.get("access_token"), 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = build('calendar', 'v3', http=http) response = [] response.append('<html><body>') response.append('Getting the upcoming 10 events<br><br>') eventsResult = service.events().list( calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = eventsResult.get('items', []) if not events: response.append('No upcoming events found.') return '<br>'.join(response) for event in events: start = event['start'].get('dateTime', event['start'].get('date')) response.append("<div>%s %s</div>" % (start, event['summary'])) return ''.join(response)
def gdisconnect(): # Only disconnect a connected user. # credentials = login_session.get('credentials') credentials = AccessTokenCredentials(login_session.get('credentials'), 'user-agent-value') if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response access_token = credentials.access_token # print "access_token: " + 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': response = make_response( json.dumps('Failed to revoke for a given user.'), 400) response.headers['Content-Type'] = 'application/json' return response
def authentication(request): global service, currentId utc_tz = tz.gettz('UTC') india_tz = tz.gettz('Asia/Kolkata') SCOPES = ['https://mail.google.com/'] session = request.session.get('creds', None) creds = None if session is not None: creds = session[0] time = session[1] creds = AccessTokenCredentials(creds, 'user-agent-value') now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") newTime = datetime.strptime(now, "%Y-%m-%d %H:%M:%S") - datetime.strptime( time, "%Y-%m-%d %H:%M:%S") newTimeInSec = newTime.total_seconds() minutes = newTimeInSec / 60 if minutes > 50: flow = InstalledAppFlow.from_client_config(oauthKey, SCOPES) creds = flow.run_local_server(port=0) request.session['creds'] = [ creds.token, datetime.now().strftime("%Y-%m-%d %H:%M:%S") ] else: flow = InstalledAppFlow.from_client_config(oauthKey, SCOPES) creds = flow.run_local_server(port=0) request.session['creds'] = [ creds.token, datetime.now().strftime("%Y-%m-%d %H:%M:%S") ] service = build('gmail', 'v1', credentials=creds) response = service.users().getProfile(userId="me").execute() currentId = response['emailAddress'] return redirect("/table/")
def build_from_access_token(self, access_token): """ Instantiates the REST API client for the Proximity API. Full PyDoc for this client is available here: https://developers.google.com/resources/api-libraries/documentation/proximitybeacon/v1beta1/python/latest/index.html Args: access_token: a valid access token for the Proximity API. Returns: self, with a ready-to-use PB API client. """ if self._client is not None: return self._client credentials = AccessTokenCredentials(access_token, 'python-api-client/1.0') http_auth = credentials.authorize(Http()) self._client = build(PROXIMITY_API_NAME, PROXIMITY_API_VERSION, http=http_auth, cache_discovery=False, discoveryServiceUrl=DISCOVERY_URI) return self
def _get_google_provider(project_id, auth_token): if not project_id: raise BadRequest('Missing required field `extensions.projectId`.') if not auth_token: if _requires_auth(): raise BadRequest('Missing required field `authToken`.') return google.GoogleJobProvider(False, False, project_id) resp = requests.post('https://www.googleapis.com/oauth2/v2/tokeninfo', params={ 'access_token': auth_token, }) if resp.status_code != 200: raise Unauthorized('failed to validate auth token') current_app.logger.info('user "%s" signed in', resp.json().get('email')) try: credentials = AccessTokenCredentials(auth_token, 'user-agent') return google.GoogleJobProvider(False, False, project_id, credentials=credentials) except AccessTokenCredentialsError as e: raise Unauthorized('Invalid authentication token:{}.'.format(e))
def create_event(request): tokens = UserSocialAuth.get_social_auth_for_user(request.user).get().tokens creds = AccessTokenCredentials(tokens, request.META['HTTP_USER_AGENT']) service = build('calendar', 'v3', credentials=creds) calendar_list = service.calendarList().list().execute() calendar_exists = False for calendar in calendar_list['items']: if calendar['summary'] == "Plants": calendar['backgroundColor'] = "#44a653" updated_calendar_list_entry = service.calendarList().update( calendarId=calendar['id'], body=calendar, colorRgbFormat=True).execute() calendar_exists = True created_calendar = calendar if not calendar_exists: calendar = { "kind": "calendar#calendar", "summary": "Plants", } created_calendar = service.calendars().insert(body=calendar).execute() calendar_id = created_calendar["id"] selected_plants = request.POST.getlist('checked_plant') colors = service.colors().get().execute() color_ids_list = [] for color_id in colors['event']: color_ids_list.append(color_id) print(color_id) random.shuffle(color_ids_list) color_pool = cycle(color_ids_list) event_summaries = [] page_token = None while True: events = service.events().list(calendarId=calendar_id, pageToken=page_token).execute() for event in events['items']: print(event['summary']) event_summaries.append(event['summary']) page_token = events.get('nextPageToken') if not page_token: break for plant in selected_plants: plant_color = next(color_pool) plant_obj = Plant.objects.get(name=plant) if plant_obj.start_indoors_begin != "": indoors_begin_list = plant_obj.start_indoors_begin.split("-") if indoors_begin_list[0] == "Jan": start_indoors_begin = "2019-01-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Feb": start_indoors_begin = "2019-02-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Mar": start_indoors_begin = "2019-03-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Apr": start_indoors_begin = "2019-04-" + indoors_begin_list[1] elif indoors_begin_list[0] == "May": start_indoors_begin = "2019-05-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Jun": start_indoors_begin = "2019-06-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Jul": start_indoors_begin = "2019-07-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Aug": start_indoors_begin = "2019-08-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Sep": start_indoors_begin = "2019-09-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Oct": start_indoors_begin = "2019-10-" + indoors_begin_list[1] elif indoors_begin_list[0] == "Nov": start_indoors_begin = "2019-11-" + indoors_begin_list[1] else: start_indoors_begin = "2019-12-" + indoors_begin_list[1] indoors_end_list = plant_obj.start_indoors_end.split("-") if indoors_end_list[0] == "Jan": start_indoors_end = "2019-01-" + indoors_end_list[1] elif indoors_end_list[0] == "Feb": start_indoors_end = "2019-02-" + indoors_end_list[1] elif indoors_end_list[0] == "Mar": start_indoors_end = "2019-03-" + indoors_end_list[1] elif indoors_end_list[0] == "Apr": start_indoors_end = "2019-04-" + indoors_end_list[1] elif indoors_end_list[0] == "May": start_indoors_end = "2019-05-" + indoors_end_list[1] elif indoors_end_list[0] == "Jun": start_indoors_end = "2019-06-" + indoors_end_list[1] elif indoors_end_list[0] == "Jul": start_indoors_end = "2019-07-" + indoors_end_list[1] elif indoors_end_list[0] == "Aug": start_indoors_end = "2019-08-" + indoors_end_list[1] elif indoors_end_list[0] == "Sep": start_indoors_end = "2019-09-" + indoors_end_list[1] elif indoors_end_list[0] == "Oct": start_indoors_end = "2019-10-" + indoors_end_list[1] elif indoors_end_list[0] == "Nov": start_indoors_end = "2019-11-" + indoors_end_list[1] else: start_indoors_end = "2019-12-" + indoors_end_list[1] indoors_event = { 'colorId': plant_color, 'summary': plant_obj.name + " start indoors", 'start': { 'date': start_indoors_begin, 'timeZone': 'America/New_York', }, 'end': { 'date': start_indoors_end, 'timeZone': 'America/New_York', }, 'recurrence': ['RRULE:FREQ=YEARLY'], } if indoors_event["summary"] not in event_summaries: event = service.events().insert(calendarId=calendar_id, body=indoors_event).execute() if plant_obj.start_outdoors_begin != "": outdoors_begin_list = plant_obj.start_outdoors_begin.split("-") if outdoors_begin_list[0] == "Jan": start_outdoors_begin = "2019-01-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Feb": start_outdoors_begin = "2019-02-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Mar": start_outdoors_begin = "2019-03-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Apr": start_outdoors_begin = "2019-04-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "May": start_outdoors_begin = "2019-05-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Jun": start_outdoors_begin = "2019-06-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Jul": start_outdoors_begin = "2019-07-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Aug": start_outdoors_begin = "2019-08-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Sep": start_outdoors_begin = "2019-09-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Oct": start_outdoors_begin = "2019-10-" + outdoors_begin_list[1] elif outdoors_begin_list[0] == "Nov": start_outdoors_begin = "2019-11-" + outdoors_begin_list[1] else: start_outdoors_begin = "2019-12-" + outdoors_begin_list[1] outdoors_end_list = plant_obj.start_outdoors_end.split("-") if outdoors_end_list[0] == "Jan": start_outdoors_end = "2019-01-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Feb": start_outdoors_end = "2019-02-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Mar": start_outdoors_end = "2019-03-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Apr": start_outdoors_end = "2019-04-" + outdoors_end_list[1] elif outdoors_end_list[0] == "May": start_outdoors_end = "2019-05-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Jun": start_outdoors_end = "2019-06-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Jul": start_outdoors_end = "2019-07-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Aug": start_outdoors_end = "2019-08-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Sep": start_outdoors_end = "2019-09-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Oct": start_outdoors_end = "2019-10-" + outdoors_end_list[1] elif outdoors_end_list[0] == "Nov": start_outdoors_end = "2019-11-" + outdoors_end_list[1] else: start_outdoors_end = "2019-12-" + outdoors_end_list[1] outdoors_event = { 'colorId': plant_color, 'summary': plant_obj.name + " start outdoors", 'start': { 'date': start_outdoors_begin, 'timeZone': 'America/New_York', }, 'end': { 'date': start_outdoors_end, 'timeZone': 'America/New_York', }, 'recurrence': ['RRULE:FREQ=YEARLY'], } if outdoors_event["summary"] not in event_summaries: event = service.events().insert(calendarId=calendar_id, body=outdoors_event).execute() if plant_obj.transplant_begin != "": transplant_begin_list = plant_obj.transplant_begin.split("-") if transplant_begin_list[0] == "Jan": transplant_begin = "2019-01-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Feb": transplant_begin = "2019-02-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Mar": transplant_begin = "2019-03-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Apr": transplant_begin = "2019-04-" + transplant_begin_list[1] elif transplant_begin_list[0] == "May": transplant_begin = "2019-05-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Jun": transplant_begin = "2019-06-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Jul": transplant_begin = "2019-07-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Aug": transplant_begin = "2019-08-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Sep": transplant_begin = "2019-09-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Oct": transplant_begin = "2019-10-" + transplant_begin_list[1] elif transplant_begin_list[0] == "Nov": transplant_begin = "2019-11-" + transplant_begin_list[1] else: transplant_begin = "2019-12-" + transplant_begin_list[1] transplant_end_list = plant_obj.transplant_end.split("-") if transplant_end_list[0] == "Jan": transplant_end = "2019-01-" + transplant_end_list[1] elif transplant_end_list[0] == "Feb": transplant_end = "2019-02-" + transplant_end_list[1] elif transplant_end_list[0] == "Mar": transplant_end = "2019-03-" + transplant_end_list[1] elif transplant_end_list[0] == "Apr": transplant_end = "2019-04-" + transplant_end_list[1] elif transplant_end_list[0] == "May": transplant_end = "2019-05-" + transplant_end_list[1] elif transplant_end_list[0] == "Jun": transplant_end = "2019-06-" + transplant_end_list[1] elif transplant_end_list[0] == "Jul": transplant_end = "2019-07-" + transplant_end_list[1] elif transplant_end_list[0] == "Aug": transplant_end = "2019-08-" + transplant_end_list[1] elif transplant_end_list[0] == "Sep": transplant_end = "2019-09-" + transplant_end_list[1] elif transplant_end_list[0] == "Oct": transplant_end = "2019-10-" + transplant_end_list[1] elif transplant_end_list[0] == "Nov": transplant_end = "2019-11-" + transplant_end_list[1] else: transplant_end = "2019-12-" + transplant_end_list[1] transplant_event = { 'colorId': plant_color, 'summary': plant_obj.name + " transplant", 'start': { 'date': transplant_begin, 'timeZone': 'America/New_York', }, 'end': { 'date': transplant_end, 'timeZone': 'America/New_York', }, 'recurrence': ['RRULE:FREQ=YEARLY'], } if transplant_event["summary"] not in event_summaries: event = service.events().insert( calendarId=calendar_id, body=transplant_event).execute() if plant_obj.start_indoors_fall_begin != "": indoors_fall_begin_list = plant_obj.start_indoors_fall_begin.split( "-") if indoors_fall_begin_list[0] == "Jan": start_indoors_fall_begin = "2019-01-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Feb": start_indoors_fall_begin = "2019-02-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Mar": start_indoors_fall_begin = "2019-03-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Apr": start_indoors_fall_begin = "2019-04-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "May": start_indoors_fall_begin = "2019-05-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Jun": start_indoors_fall_begin = "2019-06-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Jul": start_indoors_fall_begin = "2019-07-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Aug": start_indoors_fall_begin = "2019-08-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Sep": start_indoors_fall_begin = "2019-09-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Oct": start_indoors_fall_begin = "2019-10-" + indoors_fall_begin_list[ 1] elif indoors_fall_begin_list[0] == "Nov": start_indoors_fall_begin = "2019-11-" + indoors_fall_begin_list[ 1] else: start_indoors_fall_begin = "2019-12-" + indoors_fall_begin_list[ 1] indoors_fall_end_list = plant_obj.start_indoors_fall_end.split("-") if indoors_fall_end_list[0] == "Jan": start_indoors_fall_end = "2019-01-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Feb": start_indoors_fall_end = "2019-02-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Mar": start_indoors_fall_end = "2019-03-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Apr": start_indoors_fall_end = "2019-04-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "May": start_indoors_fall_end = "2019-05-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Jun": start_indoors_fall_end = "2019-06-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Jul": start_indoors_fall_end = "2019-07-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Aug": start_indoors_fall_end = "2019-08-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Sep": start_indoors_fall_end = "2019-09-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Oct": start_indoors_fall_end = "2019-10-" + indoors_fall_end_list[1] elif indoors_fall_end_list[0] == "Nov": start_indoors_fall_end = "2019-11-" + indoors_fall_end_list[1] else: start_indoors_fall_end = "2019-12-" + indoors_fall_end_list[1] indoors_fall_event = { 'colorId': plant_color, 'summary': plant_obj.name + " start indoors fall", 'start': { 'date': start_indoors_fall_begin, 'timeZone': 'America/New_York', }, 'end': { 'date': start_indoors_fall_end, 'timeZone': 'America/New_York', }, 'recurrence': ['RRULE:FREQ=YEARLY'], } if indoors_fall_event["summary"] not in event_summaries: event = service.events().insert( calendarId=calendar_id, body=indoors_fall_event).execute() if plant_obj.transplant_fall_begin != "": transplant_fall_begin_list = plant_obj.transplant_fall_begin.split( "-") if transplant_fall_begin_list[0] == "Jan": transplant_fall_begin = "2019-01-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Feb": transplant_fall_begin = "2019-02-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Mar": transplant_fall_begin = "2019-03-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Apr": transplant_fall_begin = "2019-04-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "May": transplant_fall_begin = "2019-05-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Jun": transplant_fall_begin = "2019-06-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Jul": transplant_fall_begin = "2019-07-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Aug": transplant_fall_begin = "2019-08-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Sep": transplant_fall_begin = "2019-09-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Oct": transplant_fall_begin = "2019-10-" + transplant_fall_begin_list[ 1] elif transplant_fall_begin_list[0] == "Nov": transplant_fall_begin = "2019-11-" + transplant_fall_begin_list[ 1] else: transplant_fall_begin = "2019-12-" + transplant_fall_begin_list[ 1] transplant_fall_end_list = plant_obj.transplant_fall_end.split("-") if transplant_fall_end_list[0] == "Jan": transplant_fall_end = "2019-01-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Feb": transplant_fall_end = "2019-02-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Mar": transplant_fall_end = "2019-03-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Apr": transplant_fall_end = "2019-04-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "May": transplant_fall_end = "2019-05-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Jun": transplant_fall_end = "2019-06-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Jul": transplant_fall_end = "2019-07-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Aug": transplant_fall_end = "2019-08-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Sep": transplant_fall_end = "2019-09-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Oct": transplant_fall_end = "2019-10-" + transplant_fall_end_list[1] elif transplant_fall_end_list[0] == "Nov": transplant_fall_end = "2019-11-" + transplant_fall_end_list[1] else: transplant_fall_end = "2019-12-" + transplant_fall_end_list[1] transplant_fall_event = { 'colorId': plant_color, 'summary': plant_obj.name + " transplant fall", 'start': { 'date': transplant_fall_begin, 'timeZone': 'America/New_York', }, 'end': { 'date': transplant_fall_end, 'timeZone': 'America/New_York', }, 'recurrence': ['RRULE:FREQ=YEARLY'], } if transplant_fall_event["summary"] not in event_summaries: event = service.events().insert( calendarId=calendar_id, body=transplant_fall_event).execute() if plant_obj.start_outdoors_fall_begin != "": outdoors_fall_begin_list = plant_obj.start_outdoors_fall_begin.split( "-") if outdoors_fall_begin_list[0] == "Jan": start_outdoors_fall_begin = "2019-01-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Feb": start_outdoors_fall_begin = "2019-02-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Mar": start_outdoors_fall_begin = "2019-03-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Apr": start_outdoors_fall_begin = "2019-04-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "May": start_outdoors_fall_begin = "2019-05-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Jun": start_outdoors_fall_begin = "2019-06-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Jul": start_outdoors_fall_begin = "2019-07-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Aug": start_outdoors_fall_begin = "2019-08-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Sep": start_outdoors_fall_begin = "2019-09-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Oct": start_outdoors_fall_begin = "2019-10-" + outdoors_fall_begin_list[ 1] elif outdoors_fall_begin_list[0] == "Nov": start_outdoors_fall_begin = "2019-11-" + outdoors_fall_begin_list[ 1] else: start_outdoors_fall_begin = "2019-12-" + outdoors_fall_begin_list[ 1] outdoors_fall_end_list = plant_obj.start_outdoors_fall_end.split( "-") if outdoors_fall_end_list[0] == "Jan": start_outdoors_fall_end = "2019-01-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Feb": start_outdoors_fall_end = "2019-02-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Mar": start_outdoors_fall_end = "2019-03-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Apr": start_outdoors_fall_end = "2019-04-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "May": start_outdoors_fall_end = "2019-05-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Jun": start_outdoors_fall_end = "2019-06-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Jul": start_outdoors_fall_end = "2019-07-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Aug": start_outdoors_fall_end = "2019-08-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Sep": start_outdoors_fall_end = "2019-09-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Oct": start_outdoors_fall_end = "2019-10-" + outdoors_fall_end_list[1] elif outdoors_fall_end_list[0] == "Nov": start_outdoors_fall_end = "2019-11-" + outdoors_fall_end_list[1] else: start_outdoors_fall_end = "2019-12-" + outdoors_fall_end_list[1] outdoors_fall_event = { 'colorId': plant_color, 'summary': plant_obj.name + " start outdoors fall", 'start': { 'date': start_outdoors_fall_begin, 'timeZone': 'America/New_York', }, 'end': { 'date': start_outdoors_fall_end, 'timeZone': 'America/New_York', }, 'recurrence': ['RRULE:FREQ=YEARLY'], } if outdoors_fall_event["summary"] not in event_summaries: event = service.events().insert( calendarId=calendar_id, body=outdoors_fall_event).execute() return redirect(home)
def gconnect(): if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter'), 401) response.headers['Content-tyoe'] = 'application/json' return response code = request.data # Obtain Credentials from Google try: oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response(json.dumps('Auth Code Upgradation Failure'), 401) response.headers['Content-tyoe'] = 'application/json' return response # Extract Access token from credentials access_token = credentials.access_token url = 'https://www.googleapis.com/oauth2/v2/tokeninfo?access_token=' url = url + access_token h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1].decode('utf-8')) # If error in extracting credentials, report error if result.get('error') is not None: response - make_response(json.dumps(result.get('error')), 500) response.headers['Content-tyoe'] = 'application/json' # Extract G+ ID from credentials gplus_id = credentials.id_token['sub'] # If credentials and access tokens don't match, throw error if result['user_id'] != gplus_id: response = make_response(json.dumps("Token ID mismatch"), 401) response.headers['Content-tyoe'] = 'application/json' return response if result['issued_to'] != CLIENT_ID: response = make_response(json.dumps('Client ID mismatch'), 401) response.headers['Content-tyoe'] = 'application/json' return response # Check if the user is already logged in by peeking at login_session # If so, return success stored_credentials = login_session.get('credentials') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response(json.dumps('User is already logged in'), 200) response.headers['Content-tyoe'] = 'application/json' # Store valid credentials in local Flask's loggin_session login_session['credentials'] = credentials.access_token credentials = AccessTokenCredentials(login_session['credentials'], 'user-agent-value') login_session['gplus_id'] = gplus_id # Extract user info from obtained credentials userinfo_url = ("https://www.googleapis.com/oauth2/v2/userinfo") params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = json.loads(answer.text) # Parse obtained information in JSON format and store login_session['username'] = data["name"] login_session['picture'] = data["picture"] login_session['email'] = data["link"] # Check if user had logged in before and is simply revisiting user_id = getUserId(login_session['email']) # If user_id does not exists in USER table, create a new user if not user_id: user_id = createUser(login_session) login_session['user_id'] = user_id # Log new user connects app.logger.info("New User Connected: ID = {}".format(user_id)) return "Done: 200"
def profile(request): """User logs in through google using python social login. Once the user is logged in, google calendar information is pulled from there account. Records of free times are created based on the time in betweeen events""" # Pulls information from database about the user user_social_auth = request.user.social_auth.get(provider='google-oauth2') access_token = user_social_auth.extra_data['access_token'] calID=user_social_auth.uid credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') http= httplib2.Http() http = credentials.authorize(http) # Builds service for google calendar service = build(serviceName='calendar', version='v3', http=http, developerKey='HFs_k7g6ml38NKohwrzfi_ii') current_datetime = datetime.datetime.now().isoformat()[:-3] + 'Z' calendar2 = service.events().list(calendarId=calID, timeMin=current_datetime, singleEvents=True, orderBy='startTime').execute() print calendar2 # Loops through events and determines the time your calendar event ends, and how much time you have until your # next one for i in range(len(calendar2['items'])-1): next_start = calendar2['items'][i + 1]['start']['dateTime'] current_end = calendar2['items'][i]['end']['dateTime'] event = (str(calendar2['items'][i]['summary'])) # Converts unicode information from Google into datetime objects curent_event_end_dateTime = datetime.datetime.strptime(current_end, '%Y-%m-%dT%H:%M:%S-07:00') next_event_start_dateTime = datetime.datetime.strptime(next_start, '%Y-%m-%dT%H:%M:%S-07:00') #find todays date current_date = datetime.datetime.now() #only allow freetimes for the next four weeks # if next_event_start_dateTime <= current_date + datetime.timedelta(weeks=4): # Currently only working with free slots greater than 3 hours difference = next_event_start_dateTime - curent_event_end_dateTime if difference >= datetime.timedelta(hours=3): # If freetime block is greater than 1 day, will create separate blocks of free time for each day if difference >= datetime.timedelta(days=1): hours_added = 12 for j in range(difference.days): if j == 0: free_start_dateTime = curent_event_end_dateTime free_end_dateTime = free_start_dateTime+relativedelta(hours=7) free_time_start = free_start_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00') free_time_end = free_end_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00') free_time_amount = free_end_dateTime - free_start_dateTime else: free_start_dateTime = curent_event_end_dateTime + relativedelta(hours=hours_added) free_end_dateTime = free_start_dateTime + relativedelta(hours=14) free_time_start = free_start_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00') free_time_end = free_end_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00') free_time_amount = free_end_dateTime - free_start_dateTime hours_added += 26 print free_time_end FreeTimes.objects.create( user=request.user, free_time_start=free_time_start, free_time_end=free_time_end, free_time_amount=free_time_amount, previous_event=event, free_start_dateTime=free_start_dateTime, free_end_dateTime=free_end_dateTime ) else: FreeTimes.objects.create( user=request.user, free_time_start=current_end, free_time_end=next_start, free_time_amount=difference, previous_event=event, free_start_dateTime=curent_event_end_dateTime, free_end_dateTime=next_event_start_dateTime ) # else: # pass # Deletes any duplicate free times in database for current user duplicate_freeTimes = FreeTimes.objects.filter(user=request.user) for row in duplicate_freeTimes: if duplicate_freeTimes.filter(free_start_dateTime=row.free_start_dateTime).count() > 1: row.delete() success = {'success': 'success'} return HttpResponse(json.dumps(success), content_type="application/json")
def create_moment(title, blob_key, message): """ Insert a moment on a Google + user's profile """ # check that the user is signed in user_agent = request.headers.get('User-Agent') credentials = AccessTokenCredentials(session.get('credentials'), user_agent) if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response try: # authorize an instance of Http with a set of credentials http = httplib2.Http() http = credentials.authorize(http) # create image_url image_url = request.url_root + 'img/' + blob_key # create a moment moment = { "type": "http://schemas.google.com/AddActivity", "target": { "id": "target-id-1", "type": "http://schemas.google.com/AddActivity", "name": title, "description": message, "image": image_url } } if blob_key is not None: # create the url from which the image can be retrieved image_url = request.url_root + 'img/' + blob_key # create a moment with an image moment = { "type": "http://schemas.google.com/AddActivity", "target": { "id": "target-id-1", "type": "http://schemas.google.com/AddActivity", "name": title, "description": message, "image": image_url } } else: moment = { "type": "http://schemas.google.com/AddActivity", "target": { "id": "target-id-1", "type": "http://schemas.google.com/AddActivity", "name": title, "description": message } } # insert the moment on the user's profile google_request = SERVICE.moments().insert(userId='me', collection='vault', body=moment) result = google_request.execute(http=http) response = make_response(render_template("uploaded.html")) response.headers['Content-Type'] = 'text/html' return response except AccessTokenRefreshError: response = make_response(json.dumps('Failed to refresh access token.'), 500) response.headers['Content-Type'] = 'application/json' return response except AccessTokenCredentialsError: response = make_response( json.dumps( 'Access token is invalid or expired and cannot be refreshed.'), 500) response.headers['Content-Type'] = 'application/json' return response
def gconnect(): # connect to gmail account if request.args.get('state') != timelogin['state']: # check for token behave = make_response(json.dumps('Invalid state parameter.'), 401) behave.headers['Content-Type'] = 'application/json' return behave code = request.data try: oauth_flow = flow_from_clientsecrets('vidi.json', scope='') oauth_flow.redirect_uri = 'postmessage' infor = oauth_flow.step2_exchange(code) except FlowExchangeError: behave = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) behave.headers['Content-Type'] = 'application/json' return behave access_token = infor.access_token # Check whether access token is valid. url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: behave = make_response(json.dumps(result.get('error')), 500) behave.headers['Content-Type'] = 'application/json' return behave # Verify that the access token is used for the intended user. gplus_id = infor.id_token['sub'] if result['user_id'] != gplus_id: behave = make_response( json.dumps("Token's user ID doesn't match given user ID."), 401) behave.headers['Content-Type'] = 'application/json' return behave # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: behave = make_response( json.dumps("Token's client ID does not match app's."), 401) print "Token's client ID does not match app's." behave.headers['Content-Type'] = 'application/json' return behave stored_credentials = timelogin.get('credentials') stored_gplus_id = timelogin.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: behave = make_response( json.dumps('Current user is already connected.'), 200) behave.headers['Content-Type'] = 'application/json' return behave timelogin[ 'credentials'] = infor.access_token # It stores the access_token to be used later timelogin['gplus_id'] = gplus_id access_token = AccessTokenCredentials( timelogin['credentials'], 'user-agent-value') # used for returning credential object # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': infor.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() timelogin['username'] = data['name'] timelogin['picture'] = data['picture'] timelogin['email'] = data['email'] user_id = getUserID(timelogin['email']) #check whether user exist if not user_id: user_id = createUser(timelogin) timelogin['user_id'] = user_id output = '' output += '<h1>Welcome, ' output += timelogin['username'] output += '!</h1>' output += '<img src="' output += timelogin['picture'] output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> ' flash("you are now logged in as %s" % timelogin['username']) print "done!" return output
def _create_context(project_id): creds = AccessTokenCredentials('test_token', 'test_ua') return google.datalab.Context(project_id, creds)
def _create_context(): project_id = 'test' creds = AccessTokenCredentials('test_token', 'test_ua') return datalab.context.Context(project_id, creds)
def parse_mail(email, token): credentials = AccessTokenCredentials(token, 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = discovery.build('gmail', 'v1', http=http) try: results = service.users().messages().list(userId=email, labelIds=[label_id_one], q=query).execute() if results['resultSizeEstimate'] != 0: mssg_list = results['messages'] final_list = [] for mssg in mssg_list: temp_dict = {} m_id = mssg['id'] # get id of individual message message = service.users().messages().get( userId=email, id=m_id).execute() # fetch the message using API payld = message['payload'] # get payload of the message headr = payld['headers'] # get header of the payload for one in headr: # getting the Subject if one['name'] == 'Subject': msg_subject = one['value'] temp_dict['Subject'] = msg_subject else: pass for two in headr: # getting the date if two['name'] == 'Date': msg_date = two['value'] date_parse = (parser.parse(msg_date)) m_date = (date_parse.date()) temp_dict['Date'] = str(m_date) else: pass for three in headr: # getting the Sender if three['name'] == 'From': msg_from = three['value'] temp_dict['Sender'] = msg_from else: pass temp_dict['Snippet'] = message[ 'snippet'] # fetching message snippet try: # Fetching message body mssg_parts = payld['parts'] # fetching the message parts part_one = mssg_parts[ 0] # fetching first element of the part part_body = part_one[ 'body'] # fetching body of the message part_data = part_body[ 'data'] # fetching data from the body part_data1 = payld['parts'][0]['body']['data'] clean_one = part_data1.replace( "-", "+") # decoding from Base64 to UTF-8 clean_one = clean_one.replace( "_", "/") # decoding from Base64 to UTF-8 clean_two = base64.b64decode(bytes( clean_one, 'UTF-8')) # decoding from Base64 to UTF-8 soup = BeautifulSoup(clean_two, "lxml") mssg_body = soup.body() temp_dict['Message_body'] = mssg_body except: pass temp_dict['Attachments'] = {} for part in message['payload']['parts']: if part['filename']: if 'data' in part['body']: data = part['body']['data'] else: att_id = part['body']['attachmentId'] att = service.users().messages().attachments().get( userId=email, messageId=m_id, id=att_id).execute() data = att['data'] file_data = base64.urlsafe_b64decode( data.encode('UTF-8')) path = os.path.join(store_dir, part['filename']) with open(path, 'wb') as f: f.write(file_data) temp_dict['Attachments'][part['filename']] = att_id final_list.append( temp_dict ) # This will create a dictonary item in the final list return final_list else: return "No message with matching key words!" except HttpError as error: return 'An error occurred: %s' % error
def _get_http(self, access_token): credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') # we use caching, as suggested in # https://developers.google.com/api-client-library/python/guide/performance return credentials.authorize(httplib2.Http(cache=".cache"))
def google_drive(): creds = None if os.path.exists('token'): with open('token', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: try: flow = InstalledAppFlow.from_client_secrets_file( os.path.join( settings.BASE_DIR, '<CredentialsJsonFile>' ), SCOPES) except Exception as e: print(str( e)) try: flow.redirect_uri = GOOGLE_DRIVE['redirect_uri'] crd = flow.fetch_token(code='<givencode>') except Exception as e: print(str( e)) google_credentials = AccessTokenCredentials(crd['access_token'], 'my-user-agent/1.0') google_http = httplib2.Http() google_http = google_credentials.authorize(google_http) service = build('drive', 'v3', http=google_http) # calling all files in google drive try: results = service.files().list(q="mimeType = 'application/vnd.google-apps.folder' and trashed = false and name= '<foldername in google drive>'", fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) except Exception as e: print(str( e)) if not items: # creating folder in a google drive file_metadata = { 'name': '<Folder Name>', 'mimeType': 'application/vnd.google-apps.folder' } file = service.files().create(body=file_metadata, fields='id').execute() folder_id = file.get('id') else: for item in items: folder_id = item['id'] # creating subfolder in a folder projectfolder = { 'name': '<SubFolder Name>', 'mimeType': "application/vnd.google-apps.folder" } rawfolder = { 'name': 'raw', 'mimeType': "application/vnd.google-apps.folder" } if folder_id: projectfolder['parents'] = [folder_id] try: project_folder = service.files().create(body = projectfolder).execute() except Exception as e: print(str( e)) try: rawfolder['parents'] = [project_folder['id']] except Exception as e: print(str( e)) raw_folder = service.files().create(body = rawfolder).execute() try: batch = service.new_batch_http_request(callback=callback) except Exception as e: print(str( e)) domain_permission = { 'type': 'anyone', 'role': 'writer', 'kind': 'drive#permission' } try: batch.add(service.permissions().create( fileId=project_folder['id'], body=domain_permission, fields='id', )) except Exception as e: print(str( e)) try: batch.execute() except Exception as e: print(str( e)) return data
def _init_service(self, token=None): token = token or self.source.get('access_token') creds = AccessTokenCredentials(token, 'panoply/1.0') http = creds.authorize(http=httplib2.Http()) self._service = build('drive', 'v3', http=http)
def gconnect(): if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter'), 401) response.headers['Content-Type'] = 'application/json' return response code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort if result.get('error') is not None: response = make_response(json.dump(resul.get('error')), 500) response.headers['Content-Type'] = 'application/json' # Verify that the access token is used for the intended user gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response( json.dumps("Token's user ID doesn't match given user ID"), 401) response.headers['Content-Type'] = 'application/json' return response # Check to see if user is already logged in stored_credentials = login_session.get('credentials') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response( json.dumps('Current user is already connected'), 200) response.headers['Content-Type'] = 'application/json' return response # store only the access_token login_session['credentials'] = credentials.access_token # return credential object credentials = AccessTokenCredentials(login_session['credentials'], 'user-agent-value') login_session['gplus_id'] = gplus_id # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] output = '' output += '<h1>Welcome, ' output += login_session['username'] output += '!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> ' flash("you are now logged in as %s" % login_session['username']) print "done!" return output
def __init__(self, access_token=None): self.credentials = AccessTokenCredentials(access_token, user_agent='') self._http = self.credentials.authorize(httplib2.Http()) self.gmail_service = build('gmail', 'v1', http=self._http)
def setUp(self): creds = AccessTokenCredentials('test_token', 'test_ua') context = datalab.context.Context(PROJECT, creds) self.query = gcm.Query(METRIC_TYPE, context=context)
def gconnect(): # Validate state token if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response # Obtain authorization code code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is used for the intended user. gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response( json.dumps("Token's user ID doesn't match given user ID."), 401) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is valid for this app. if result['issued_to'] != client_secrets['client_id']: response = make_response( json.dumps("Token's client ID does not match app's."), 401) print("Token's client ID does not match app's.") response.headers['Content-Type'] = 'application/json' return response stored_credentials = AccessTokenCredentials( login_session.get('access_token'), 'user-agent-value') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response( json.dumps('Current user is already connected.'), 200) response.headers['Content-Type'] = 'application/json' return response # Store the access token in the session for later use. login_session['access_token'] = credentials.access_token login_session['gplus_id'] = gplus_id # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] # ADD PROVIDER TO LOGIN SESSION login_session['provider'] = 'google' # see if user exists, if it doesn't make a new one user_id = getUserID(data["email"]) if not user_id: user_id = createUser(login_session) login_session['user_id'] = user_id return 'logged in'
def _create_context(self): project_id = 'test' creds = AccessTokenCredentials('test_token', 'test_ua') return gcp.Context(project_id, creds)
def readmail(secret_auth): password=secret_auth user_id = 'me' label_id_one = 'INBOX' label_id_two = 'UNREAD' credentials = AccessTokenCredentials(password,'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) GMAIL = discovery.build('gmail', 'v1', http=http) unread_msgs = GMAIL.users().messages().list(userId='me',labelIds=[label_id_one, label_id_two]).execute() mssg_list = unread_msgs['messages'] print ("Total unread messages in inbox: ", str(len(mssg_list))) final_list = [ ] for mssg in mssg_list: temp_dict = { } m_id = mssg['id'] # get id of individual message message = GMAIL.users().messages().get(userId=user_id, id=m_id).execute() # fetch the message using API payld = message['payload'] # get payload of the message headr = payld['headers'] # get header of the payload for one in headr: # getting the Subject if one['name'] == 'Subject': msg_subject = one['value'] temp_dict['Subject'] = msg_subject else: pass for two in headr: # getting the date if two['name'] == 'Date': msg_date = two['value'] date_parse = (parser.parse(msg_date)) m_date = (date_parse.date()) temp_dict['Date'] = str(m_date) else: pass for three in headr: # getting the Sender if three['name'] == 'From': msg_from = three['value'] temp_dict['Sender'] = msg_from else: pass temp_dict['Snippet'] = message['snippet'] # fetching message snippet try: # Fetching message body mssg_parts = payld['parts'] # fetching the message parts part_one = mssg_parts[0] # fetching first element of the part part_body = part_one['body'] # fetching body of the message part_data = part_body['data'] # fetching data from the body clean_one = part_data.replace("-","+") # decoding from Base64 to UTF-8 clean_one = clean_one.replace("_","/") # decoding from Base64 to UTF-8 clean_two = base64.b64decode (bytes(clean_one, 'UTF-8')) # decoding from Base64 to UTF-8 soup = BeautifulSoup(clean_two , "lxml" ) mssg_body = soup.body() # mssg_body is a readible form of message body # depending on the end user's requirements, it can be further cleaned # using regex, beautiful soup, or any other method temp_dict['Message_body'] = mssg_body except Exception as e: print(e) print (temp_dict) final_list.append(temp_dict) # This will create a dictonary item in the final list print ("Total messaged retrived: ", str(len(final_list))) ''' The final_list will have dictionary in the following format: { 'Sender': '"email.com" <*****@*****.**>', 'Subject': 'Lorem ipsum dolor sit ametLorem ipsum dolor sit amet', 'Date': 'yyyy-mm-dd', 'Snippet': 'Lorem ipsum dolor sit amet' 'Message_body': 'Lorem ipsum dolor sit amet'} The dictionary can be exported as a .csv or into a databse ''' #exporting the values as .csv with open('CSV_NAME.csv', 'w', encoding='utf-8', newline = '') as csvfile: fieldnames = ['Sender','Subject','Date','Snippet','Message_body'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ',') writer.writeheader() for val in final_list: writer.writerow(val)
def setUp(self): access_token = 'foo' user_agent = 'refresh_checker/1.0' self.credentials = AccessTokenCredentials(access_token, user_agent, revoke_uri=GOOGLE_REVOKE_URI)
def gconnect(): '''handles approval of google oauth''' print('POST /gconnect received') # Validate the state token if request.args.get('state') != login_session['state']: print('login_session["state"] was: {}'.format(login_session['state'])) print('request.args.get("state") was: {}'.format( request.args.get('state'))) print('invalid state parameter') response = make_response(json.dumps('Invalid state parameter'), 401) response.headers['Content-Type'] = 'application/json' return response # If it passes that, then we next obtain a one-time authorisation code. print("state parameter was valid. Obtaining a one-time authorisation code") code = request.data # this will only happen if the if statement above is false # i.e. IFF the state variable matches correctly. # code is then the one-time code received back from google. print("\nGoogle One-time auth code is: {}".format(code.decode())) try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('google_client_secret.json', scope='') # creates an oauth_flow object and adds the client_secrets info to it # client_secrets.json was the json object downloaded from # console.developers.google.com for your app # needed to add some redirect uri s to the google api, # and then re-download as it was causing errors. oauth_flow.redirect_uri = 'postmessage' # this specifies it is the one time code flow # that the server will be sending off. credentials = oauth_flow.step2_exchange(code) # this initiates the exchange with the step2_exchange module, # passing in the secret info. print('\nGoogle: Successfully updated the authorization code into' 'a credentials object') # it exchanges the authorisation code for a credentials object. # If all goes well the response from Google will be a credentials object # that will be stored in the variable 'credentials' except FlowExchangeError: logging.error('FlowExchangeError triggered') logging.error(FlowExchangeError) response = make_response( json.dumps('Failed to upgrade the authorization code'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid access_token = credentials.access_token logging.info('Google access_token is: {}'.format(access_token)) url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={}'. format(access_token)) # append the access token to the url and Google apiserver # will check to see if it is valid. h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1].decode()) # If there was an error in the access token info, abort if result.get('error') is not None: logging.error('There was an error in the Google Access token') logging.error(result['error']) response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' return response else: logging.info('Google Access token info has no error') # Verify that the access token is used for the intended user: gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response( json.dumps("Token's user ID does not match given User ID"), 401) response.headers['Content-Type'] = 'application/json' return response else: logging.info("Token's user ID MATCHES given User ID") # Verify that the access token is valid for this app if result['issued_to'] != GOOGLE_CLIENT_ID: response = make_response( json.dumps("Google Token's client ID does not match app's"), 401) logging.error("Google Token's client ID does not match app's") response.headers['Content-Type'] = 'application/json' return response else: logging.info("Google Token's client ID matches this current app's\ Google Client ID") # Check to see if user is already logged in stored_credentials = login_session.get('credentials') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response( json.dumps('Current user is already connected'), 200) response.headers['Content-Type'] = 'application/json' # Assuming all the if statements are passed - you have not returned # a response and the access token is valid # Store the access token in the session for later use login_session['provider'] = 'google' login_session['credentials'] = credentials.access_token # NOTE this is different to Udacity course - storing only the access token # Not entirely sure why - see https://github.com/udacity/ud330/issues/4 # for discussion. Post by Linus Dong fixed it. # return credential object credentials = AccessTokenCredentials(login_session['credentials'], 'user-agent-value') login_session['gplus_id'] = gplus_id # Get user info userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo' params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = json.loads(answer.text) logging.info("\nGoogle user info is: ") logging.info(data) login_session['username'] = data["name"] login_session['picture'] = data["picture"] login_session['email'] = data['email'] # see if user exists in our database. If it doesn't, make a new one user_id = get_user_id(login_session['email']) if not user_id: user_id = create_user(login_session) logging.info('User was NOT in database, so user was created') else: logging.info('User was already in database, so no changes made') login_session['user_id'] = user_id logging.info('login_session is: {}'.format(login_session)) logging.info("login_session['user_id'] is: {}".format( login_session['user_id'])) return login_welcome(login_session['username'], login_session['picture'])