class AccessTokenCredentialsTests(unittest.TestCase): def setUp(self): access_token = "foo" user_agent = "refresh_checker/1.0" self.credentials = AccessTokenCredentials(access_token, user_agent) def test_token_refresh_success(self): http = HttpMockSequence([ ({'status': '401'}, ''), ]) http = self.credentials.authorize(http) try: resp, content = http.request("http://example.com") self.fail("should throw exception if token expires") except AccessTokenCredentialsError: pass except Exception: self.fail("should only throw AccessTokenCredentialsError") def test_non_401_error_response(self): http = HttpMockSequence([ ({'status': '400'}, ''), ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') self.assertEqual(400, resp.status) def test_auth_header_sent(self): http = HttpMockSequence([ ({'status': '200'}, 'echo_request_headers'), ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') self.assertEqual('Bearer foo', content['Authorization'])
def get(self, request, format=None): """ Return a list of user's emails """ user_social_auth = UserSocialAuth.objects.get(user=self.request.user) credentials = AccessTokenCredentials(user_social_auth.extra_data['access_token'], 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = discovery.build('gmail', 'v1', credentials=credentials) results = service.users().messages().list(userId='me').execute() messages = [] for result in results['messages'][:100]: msg = service.users().messages().get(userId='me', id=result['id']).execute() subject = '' _from = '' for header in msg['payload']['headers']: if header['name'] == 'Subject': subject = header['value'] elif header['name'] == 'From': _from = header['value'] messages.append({'subject': subject, 'from': _from}) return Response(messages)
def __init__(self, config, plugin_config): scopes = ['https://www.googleapis.com/auth/drive'] connection = plugin_config.get("googledrive_connection") self.auth_type = config.get("auth_type") self.write_as_google_doc = config.get( "googledrive_write_as_google_doc") self.nodir_mode = False # Future development if self.auth_type == "oauth": self.access_token = config.get("oauth_credentials")["access_token"] credentials = AccessTokenCredentials(self.access_token, "dss-googledrive-plugin/2.0") http_auth = credentials.authorize(Http()) else: credentials_dict = eval(connection['credentials']) credentials = ServiceAccountCredentials.from_json_keyfile_dict( credentials_dict, scopes) http_auth = credentials.authorize(Http()) self.root_id = config.get("googledrive_root_id") if not self.root_id: self.root_id = gdu.ROOT_ID self.max_attempts = 5 self.root_id = gdu.get_root_id(config) self.drive = build( gdu.API, gdu.API_VERSION, http=http_auth, cache=MemoryCache( ) # Fix for ImportError messages https://github.com/googleapis/google-api-python-client/issues/325 )
def getUser(): 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) people_resource = SERVICE.people() people_document = people_resource.get(userId='me').execute(http=http) return jsonify(people_document) 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 __init__(self, request): self.service = None self.oauth2token = None try: if request.user: provider = request.session.get('social_auth_last_login_backend') social = request.user.social_auth.filter( Q(user_id=request.user.id), Q(uid=request.user.email), Q(provider=provider) ) credential = AccessTokenCredentials( social[0].tokens['access_token'], 'HTTP/1.1' ) http = httplib2.Http() http = credential.authorize(http) self.service = build("calendar", "v3", http=http) self.oauth2token = OAuth2Token( client_id = settings.GOOGLE_OAUTH2_CLIENT_ID, client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET, scope = 'https://apps-apis.google.com/a/feeds/calendar/resource/', access_token = social[0].tokens['access_token'], user_agent='HTTP/1.1' ) except: pass
def Authenticate(self): acc_token = CREDENTIALS['access_token'] user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' credentials = AccessTokenCredentials(acc_token, user_agent) http = httplib2.Http() http = credentials.authorize(http) return build('gmail', 'v1', http=http)
def request_user_info_google(authlogin): """ Makes an HTTP request to the Google+ API to retrieve the user's basic profile information, including full name and photo, and stores it in the Flask session. """ http = httplib2.Http() credentials = AccessTokenCredentials(authlogin, 'user-agent-value') credentials.authorize(http) print "FROM GOOGLE" try: resp, content = http.request( 'https://www.googleapis.com/plus/v1/people/me') if resp.status != 200: raise ErrorException( Error(code=Error_code.INVGRANT, custom_message=str(content))) profil = json.loads(content.decode('utf-8')) print resp, content return profil # mauvais token except Exception as e: print "RAISE EXCEPTION" raise ErrorException(Error(code=Error_code.INVGRANT))
def profile(): access_token = session.get('credentials') credentials = AccessTokenCredentials(access_token, 'user-agent-value') # Only fetch a list of people for connected users. if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response try: # Create a new authorized API client. http = httplib2.Http() http = credentials.authorize(http) people_resource = SERVICE.people() people_document = people_resource.get(userId='me').execute(http=http) gplusId = people_document['id'] user = User.query.filter_by(gplusId=gplusId).count() print user response = make_response('success', 200) response.headers['Content-Type'] = 'application/json' return response except AccessTokenRefreshError: response = make_response(json.dumps('Failed to refresh access token.'), 500) response.headers['Content-Type'] = 'application/json' return response
def post(self): name = self.current_user.name brain_id = self.current_user.brain_id SCOPES = 'https://www.googleapis.com/auth/calendar' APPLICATION_NAME = 'Mind Cloud' print(self.current_user.token) credentials = AccessTokenCredentials( self.current_user.token['access_token'], 'my agent/1.0') print(credentials.invalid) user_id = self.get_secure_cookie("user-id") user = Person.select().where(Person.user_id == user_id.decode())[0] event = self.get_body_argument('event') print(user_id) goal = Goals.create( person_id=brain_id, title=event, achievement=False, ) deadline = self.get_body_argument('deadline') http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) now = datetime.datetime.utcnow().isoformat( ) + 'Z' # 'Z' indicates UTC time created_event = service.events().quickAdd(calendarId='primary', text=event + ' ' + deadline).execute() print(created_event['id']) self.redirect('goals', {'name': name, 'goal': goal})
def _create_remote_playlist(request): # cheking the local playlist result = {'error': None, 'playlist_obj': None} try: youtube_obj = request.user.social_auth.get(provider='google-oauth2') except: return result try: post_data = simplejson.loads(request.body) except: post_data = {} playlist_name = post_data.get('title', None) playlist_is_private = post_data.get('is_private', None) action_pl_update = False user_playlist, pl_created = \ Playlist.objects.get_or_create(user=request.user) if not pl_created: # set last update to now action_pl_update = user_playlist.should_update( playlist_name, playlist_is_private) user_playlist.last_update = datetime.datetime.now() user_playlist.save() else: user_playlist.youtube_pl_name = playlist_name user_playlist.save() result['playlist_obj'] = user_playlist if user_playlist.youtube_pl_id is None and request.method == 'POST': credentials = AccessTokenCredentials( youtube_obj.extra_data.get('access_token'), 'friendlyvibe/1.0') youtube = build( 'youtube', 'v3', http=credentials.authorize(httplib2.Http())) # create the youtube playlist if action_pl_update is False: try: new_playlist = youtube.playlists().insert( part="snippet,status", body=dict( snippet=dict( title=settings.DEFAULT_YOUTUBE_PLNAME, description="A playlist automatically created and managed by friendlyvibe.com" ), status=dict( privacyStatus='private' if playlist_is_private else 'public' ) ) ).execute() user_playlist.youtube_json = simplejson.dumps(new_playlist) user_playlist.youtube_pl_id = new_playlist.get(u'id') user_playlist.youtube_pl_name = playlist_name user_playlist.is_private = playlist_is_private user_playlist.save() except Exception, e: # do some signal here to KNOW the user's youtube account is disconnected result['error'] = str(e)
class AccessTokenCredentialsTests(unittest.TestCase): 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 test_token_refresh_success(self): for status_code in REFRESH_STATUS_CODES: http = HttpMockSequence([({"status": status_code}, b"")]) http = self.credentials.authorize(http) try: resp, content = http.request("http://example.com") self.fail("should throw exception if token expires") except AccessTokenCredentialsError: pass except Exception: self.fail("should only throw AccessTokenCredentialsError") def test_token_revoke_success(self): _token_revoke_test_helper(self, "200", revoke_raise=False, valid_bool_value=True, token_attr="access_token") def test_token_revoke_failure(self): _token_revoke_test_helper(self, "400", revoke_raise=True, valid_bool_value=False, token_attr="access_token") def test_non_401_error_response(self): http = HttpMockSequence([({"status": "400"}, b"")]) http = self.credentials.authorize(http) resp, content = http.request("http://example.com") self.assertEqual(400, resp.status) def test_auth_header_sent(self): http = HttpMockSequence([({"status": "200"}, "echo_request_headers")]) http = self.credentials.authorize(http) resp, content = http.request("http://example.com") self.assertEqual(b"Bearer foo", content[b"Authorization"])
def post_event(request): if request.method == 'POST': event_id = json.loads(request.body) event = Event.objects.get(pk=event_id) # Parameters for event being saved to google calendar event_info = { "end": { "dateTime": event.end_time }, "start": { 'dateTime': event.start_time }, "summary": event.name, "location": event.venue, } # Builds google calendar service with appropriate credentials user_social_auth = request.user.social_auth.filter(provider='google-oauth2').first() 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) service = build(serviceName='calendar', version='v3', http=http, developerKey='HFs_k7g6ml38NKohwrzfi_ii') created_event = service.events().insert(calendarId='primary', body=event_info).execute() return HttpResponse(json.dumps(event_id), content_type='application/json')
def google_oauth(request): if request.user.is_authenticated: return Response({"detail": "You must have to log out first"}) access_token = request.data['access_token'] credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = build('plus', 'v1', http=http) result = service.people().get(userId='me').execute() email = result['emails'][0]['value'] gender = result['gender'] first_name = result['name']['givenName'] last_name = result['name']['familyName'] photo = result['image']['url'] def create_login_token(user): serializer = LoginSerializer() token = create_token(TokenModel, user, serializer) return token try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: user = UserModel(email=email, last_name=last_name, first_name=first_name) user.set_password('password') user.save() token = create_login_token(user) return Response({'token': token.key})
def getUser(): 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) people_resource = SERVICE.people() people_document = people_resource.get(userId='me').execute(http=http) return jsonify(people_document) 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
class AccessTokenCredentialsTests(unittest.TestCase): def setUp(self): access_token = "foo" user_agent = "refresh_checker/1.0" self.credentials = AccessTokenCredentials(access_token, user_agent) def test_token_refresh_success(self): http = HttpMockSequence([ ({'status': '401'}, ''), ]) http = self.credentials.authorize(http) try: resp, content = http.request("http://example.com") self.fail("should throw exception if token expires") except AccessTokenCredentialsError: pass except Exception: self.fail("should only throw AccessTokenCredentialsError") def test_non_401_error_response(self): http = HttpMockSequence([ ({'status': '400'}, ''), ]) http = self.credentials.authorize(http) resp, content = http.request("http://example.com") self.assertEqual(400, resp.status)
def get_service(service: Service, credentials: Credentials, api_key: str = None) -> discovery.Resource: """Fetch a discoverable API service. Create an endpoint to one of the Google services listed in Services.py as a defined service. Only services listed in the Services enum can be used, and they each have a in a ServiceDefinition containing all the information needed to create the service. These parameters are decomposed to a dict of keyword arguments ans passed on to the Google Discovery API. Not all services require an API key, hence it is optional. Args: service (Service): [description] credentials (Credentials): [description] api_key (str, optional): [description]. Defaults to None. Returns: discovery.Resource: a service for REST calls Raises: NotImplementedError: if an invalid service is requested. """ if definition := service.definition: _credentials = \ AccessTokenCredentials(credentials.credentials.token, user_agent='report2bq') auth_https = _credentials.authorize(discovery.httplib2.Http()) service = discovery.build(http=auth_https, cache_discovery=False, developerKey=api_key, **definition.to_args) return service
def get_credentials(self, user_id): with self.conn: result = self.conn.execute( "SELECT access_token, refresh_token from OAuthDetails WHERE google_plus_id=?", (user_id, )) row = result.fetchone() access_token = row[0] refresh_token = row[1] print "tokens", refresh_token http = Http() credentials = AccessTokenCredentials( access_token, "antunovic-calendar-client/1.0") token_info = credentials.get_access_token(http) print "Still okay? ", token_info.expires_in if token_info.expires_in > 60 * 2: return credentials with open("client_secrets.json") as client_secrets_file: data = json.load(client_secrets_file) token_uri = data["web"]["token_uri"] client_id = data["web"]["client_id"] client_secret = data["web"]["client_secret"] google_token_uri = data["web"]["client_id"] return client.OAuth2Credentials(None, client_id, client_secret, refresh_token, None, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI)
def check(): result = lambda ok, text: jsonify({'ok': ok, 'text': text}) if not g.user.phone_info.get('valid'): return result(False, 'invalid phone number') token = g.user.social_auth.one().tokens credentials = AccessTokenCredentials(token, app.config['USER_AGENT']) service = discovery.build('gmail', 'v1', http=credentials.authorize(Http())) inbox = service.users().messages().list(userId='me', q='in:inbox is:unread').execute() data = inbox.get('messages', []) if not data: return result(False, 'no unread messages') msg = service.users().messages().get(userId='me', id=data[0]['id']).execute() subj = [x['value'] for x in msg['payload']['headers'] if x['name'] == 'Subject'] text = msg['snippet'][:160] try: fmt_number = lambda x: '+%s%s' % (x.country_code, x.national_number) client = TwilioRestClient(app.config['TWILIO_ACCOUNT_SID'], app.config['TWILIO_AUTH_TOKEN']) client.messages.create(body=text, to=fmt_number(g.user.phone_info['number']), from_=app.config['TWILIO_NUMBER']) data = (True, subj[0] if subj else None) except Exception, exc: data = (False, str(exc))
def __init__(self): google_auth_manager = GoogleAuthManager() user_agent = 'python-recaller/1.0' credentials = AccessTokenCredentials( google_auth_manager.get_access_token(), user_agent) http = httplib2.Http() http = credentials.authorize(http) self.service = build('calendar', 'v3', http=http)
def get_service(self): """ :return: servicio de drive """ credentials = AccessTokenCredentials(self.token, None) http = httplib2.Http() http = credentials.authorize(http) return build('drive', 'v2', http)
def get_service(self): """ :return: servicio de drive """ credentials = AccessTokenCredentials(self.token, None) http = httplib2.Http() http = credentials.authorize(http) return build('drive', 'v2', http)
def authorized_request(user, url): access_token = get_access_token(user) if access_token: credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) response = do_request(http, url) return response
def connect_helper(user): social = user.social_auth.get(provider='google-oauth2') access_token = social.extra_data.get('access_token') credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = build(serviceName='calendar', version='v3', http=http) return service
class AccessTokenCredentialsTests(unittest.TestCase): 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 test_token_refresh_success(self): for status_code in REFRESH_STATUS_CODES: http = HttpMockSequence([ ({ 'status': status_code }, ''), ]) http = self.credentials.authorize(http) try: resp, content = http.request('http://example.com') self.fail('should throw exception if token expires') except AccessTokenCredentialsError: pass except Exception: self.fail('should only throw AccessTokenCredentialsError') def test_token_revoke_success(self): _token_revoke_test_helper(self, '200', revoke_raise=False, valid_bool_value=True, token_attr='access_token') def test_token_revoke_failure(self): _token_revoke_test_helper(self, '400', revoke_raise=True, valid_bool_value=False, token_attr='access_token') def test_non_401_error_response(self): http = HttpMockSequence([ ({ 'status': '400' }, ''), ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') self.assertEqual(400, resp.status) def test_auth_header_sent(self): http = HttpMockSequence([ ({ 'status': '200' }, 'echo_request_headers'), ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') self.assertEqual('Bearer foo', simplejson.loads(content.decode())['Authorization'])
def get_service(self, serviceName, version): token = self.get_access_token() credentials = AccessTokenCredentials(token, 'Demisto Gmail integration') if PROXY or DISABLE_SSL: http_client = credentials.authorize( self.get_http_client_with_proxy()) return discovery.build(serviceName, version, http=http_client) return discovery.build(serviceName, version, credentials=credentials)
def get_authenticated_service(self): """ Create youtube oauth2 connection """ credentials = AccessTokenCredentials( access_token=self.get_auth_code(), user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' ) return build( 'youtube', 'v3', http=credentials.authorize(httplib2.Http()) )
def get_authenticated_service(): """ Create youtube oauth2 connection """ # make credentials with refresh_token auth credentials = AccessTokenCredentials(access_token=get_auth_code(), user_agent='insta-python/1.0') # create connection to youtube api return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http()))
def get_email(access_token): creds = AccessTokenCredentials(access_token, 'fooapi/0.1') h = creds.authorize(Http()) resp, content = h.request(app.config['GOOGLE_API_INFO_URL']) if resp['status'] != '200': raise UserProfileAccessException('Unable to access the user profile.') data = json.loads(content) return data['email']
def executor(userId): bucket_name = "jingle-skill-bucket" s3 = boto3.client('s3') try: # Download the token. s3.download_file(bucket_name, 'data/' + str(userId) + '/token.pkl', "/tmp/" + str(userId) + '_token.pkl') # Read-in the access token. access_token = pickle.load( open("/tmp/" + str(userId) + '_token.pkl', "rb")) credentials = AccessTokenCredentials(access_token, 'alexa-skill/1.0') http = credentials.authorize(httplib2.Http()) service = build('gmail', 'v1', http=http) try: # Download the existing all_mails object and last_mail_id from the bucket if available. s3.download_file(bucket_name, 'data/' + str(userId) + '/all_mails.pkl', "/tmp/" + str(userId) + '_all_mails.pkl') s3.download_file(bucket_name, 'data/' + str(userId) + '/last_mail_id.pkl', "/tmp/" + str(userId) + '_last_mail_id.pkl') # Read-in both the files. all_mails = pickle.load( open("/tmp/" + str(userId) + '_all_mails.pkl', "rb")) last_mail_id = pickle.load( open("/tmp/" + str(userId) + '_last_mail_id.pkl', "rb")) except: # Read-in both the files. all_mails = None last_mail_id = None last_mail_id, all_mails = get_emails(last_mail_id, all_mails, service) checklist = [] # Get the required information. for i in all_mails: # Construct the summary for each mail object. all_mails[i] = summarize_body(all_mails[i]) # Get the dates for the mail as well. all_mails[i] = end_date_getter(all_mails[i]) # It keeps appending the new checklist tasks to the existing set of checklist tasks across all the sender_email tags. checklist = get_checklist_objects(all_mails[i], checklist) # Write items into the bucket, and notify SQS. write_checklist(checklist, last_mail_id, all_mails, userId) return 'Success!' except: return 'Failue!'
def create_service(userid): """ :param userid: currently logged in user :return: gmail api service instance for making gmail api calls (eg. Sending email in this case ) """ user = User.query.get(int(userid)) data = json.loads(user.tokens) credentials = AccessTokenCredentials(data['access_token'], None) service = build('gmail', 'v1', http=credentials.authorize(Http())) return service
def get_authenticated_service(self, access_token, service='youtube', version='v3'): credentials = AccessTokenCredentials(access_token=access_token, user_agent='Podcast') return build(service, version, cache_discovery=False, http=credentials.authorize(httplib2.Http()))
def get_user_email_from_token(access_token): if debug: print >> sys.stderr,'Called '+sys._getframe().f_code.co_name user_email = None credentials = AccessTokenCredentials(access_token, 'test-user') http = credentials.authorize(httplib2.Http()) user_info_service = build('oauth2', 'v2', http=http) user_info = user_info_service.userinfo().get().execute() if 'email' in user_info: user_email = user_info['email'] return user_email
def __init__(self, access_token, collection_name=''): ''' a method to initialize the driveClient class :param access_token: string with oauth2 access token for users account :param collection_name: [optional] string with name of collection for import ''' title = '%s.__init__' % self.__class__.__name__ # construct input validation model self.fields = jsonModel(self._class_fields) # validate inputs input_fields = { 'access_token': access_token, 'collection_name': collection_name } for key, value in input_fields.items(): object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # construct access token self.access_token = access_token # construct drive client import httplib2 from googleapiclient import discovery from oauth2client.client import AccessTokenCredentials google_credentials = AccessTokenCredentials(self.access_token, 'my-user-agent/1.0') google_http = httplib2.Http() google_http = google_credentials.authorize(google_http) google_drive = discovery.build('drive', 'v3', http=google_http) self.drive = google_drive.files() # construct collection properties self.permissions_write = True self.permissions_content = True self.drive_space = 'drive' self.space_id = '' if collection_name: self.collection_name = collection_name else: self.collection_name = 'My Drive' # construct file object from labpack import __module__ from jsonmodel.loader import jsonLoader drive_rules = jsonLoader(__module__, 'storage/google/drive-rules.json') self.object_file = drive_rules['file_object'] # validate access token self._validate_token()
def dispatch(self): self._checkauth() self._decode() if self._token is None: self.abort(401) else: credentials = AccessTokenCredentials(self._token, "mirror-api-upload-handler/1.0") http = httplib2.Http() http = credentials.authorize(http) http.timeout = 60 self._service = build("mirror", "v1", http=http, discoveryServiceUrl=utils.discovery_service_url) super(UploadHandler, self).dispatch()
def get_client(self): """ Get an authenticated calendar api v3 instance. """ token = self.get_access_token() if self.client is None: credentials = AccessTokenCredentials(token, 'vetware/1.0') # credentials = SignedJwtAssertionCredentials(self.email, self.private_key, # "https://www.googleapis.com/auth/calendar") http = credentials.authorize(Http()) self.client = build('calendar', 'v3', http=http) return self.client
def authenticate(service, discovery, version, sub=None, access_token=None, http=None): """ Authenticate to the Gmail API with the account specified by 'sub'. :param service: The API service object to authentication. :param discovery: The service descriptor file to use for API endpoint discovery. :param version: The version of the Gmail API to authentication to. :param sub: (optional) The user to authenticate the service object to. :param access_token: (optional) The OAuth2 token (usually from the cache) to use for authentication. :param http: Optional HTTP object to use (used in tests). :return: A tuple of (the authenticated credential object, the authenticated http object, and the service object). """ if access_token: credentials = AccessTokenCredentials(access_token, user_agent="mailbeaker/1.0") else: logging.info("No access_token provided, establishing new token.", extra={"email": sub}) key = settings.GOOGLE_OAUTH2_PRIVATE_KEY credentials = \ SignedJwtAssertionCredentials(service_account_name=settings.GOOGLE_OAUTH2_SERVICE_ACCOUNT_EMAIL, private_key=key, scope=settings.GOOGLE_OAUTH2_SCOPE, sub=sub) if not http: # Authorize the httplib2.Http object with our credentials http = httplib2.Http() http = credentials.authorize(http) # We'll read the description of this API's function from # a JSON input file. Normally the client reaches out to either: # - https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest # - https://www.googleapis.com/discovery/v1/apis/admin/directory_v1/rest # ... to get this information via apiclient.discovery.build(), # but that method causes a significant perfomance impact. path = os.path.dirname(os.path.realpath(__file__)) path = os.path.join(path, discovery) discovery = open(path).read() service = build_from_document(discovery, http=http, base="https://www.googleapis.com/") return credentials, http, service
def get_gdoc_resource(klass, gdocs_resource_id, gdocs_access_token=None): http = httplib2.Http() if gdocs_access_token is not None: credentials = AccessTokenCredentials(gdocs_access_token, 'remix-client') credentials.authorize(http) drive = build('drive', 'v2', http=http) # Get the html version of the file md = drive.files().get(fileId=gdocs_resource_id).execute() uri = md['exportLinks']['text/html'] resp, content = drive._http.request(uri) return resp, content, md['title']
def connect_helper(user): c = user.social_auth.get(provider='google-oauth2') access_token = c.tokens['access_token'] credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = build(serviceName='calendar', version='v3', http=http, developerKey='...') return service
def get_authenticated_service(): """ Create youtube oauth2 connection """ # make credentials with refresh_token auth credentials = AccessTokenCredentials(access_token=get_auth_code(), user_agent='insta-python/1.0') # create httplib proxy connection if settings.USE_PROXY: import socks # set socks proxy to ssh tunnel socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'localhost', 1080) # wrap httplib via proxy socks.wrapmodule(httplib2) # create connection to youtube api return build( settings.YOUTUBE_API_SERVICE_NAME, settings.YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http()))
def get_gdoc_resource(klass, gdocs_resource_id, gdocs_access_token=None): http = httplib2.Http() if gdocs_access_token is not None: credentials = AccessTokenCredentials(gdocs_access_token, 'remix-client') credentials.authorize(http) drive = build('drive', 'v2', http=http) # Get the html version of the file md = drive.files().get(fileId=gdocs_resource_id).execute() uri = md['exportLinks']['text/html'] resp, content = drive._http.request(uri) return resp, content, md['title']
def add_to_google_calendar(event_id, selection_source): """ Adds event to user's google calendar Arguments: event_id (str): id of the event being selected selection_source (str): location of link Returns: resp (Flask Response): Varies depending on whether user is logged in """ if current_user.is_authenticated: try: # adds user selection to database selected_event = EventSelection( user_id=current_user.id, event_id=event_id, selection_type='calendar', selection_source=selection_source, date_selected=datetime.datetime.today()) db.session.add(selected_event) db.session.commit() # gets google calendar event of object event = db.session.query(Event).filter_by( id=event_id).one().google_calendar_event # add event to google calendar credentials = AccessTokenCredentials(current_user.token, None) http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) event = service.events().insert(calendarId='primary', body=event).execute() # redirect user to main page flash('Event added to Google Calendar', 'success') resp = make_response(redirect(url_for('all_events_viewer'))) resp.set_cookie('add_event', 'false') resp.set_cookie('scroll_position', 'event_{}'.format(event_id)) return resp # if user token has expired log the user out and redirect to login page except AccessTokenCredentialsError: logout_user() resp = make_response(redirect(url_for('login'))) resp.set_cookie('event_id', event_id) resp.set_cookie('selection_source', selection_source) resp.set_cookie('add_event', 'true') return resp
def loggedin(request): try: link = UserSocialAuth.get_social_auth_for_user(request.user).get().tokens access_token = link['access_token'] # OAuth dance credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = build('calendar', 'v3', http=http) # Snippet that lists all calendar events #request = service.events().list(calendarId='primary') #while request != None: ## Get the next page. #response = request.execute() ## Accessing the response like a dict object with an 'items' key ## returns a list of item objects (events). #for event in response.get('items', []): ## The event object is a dict object with a 'summary' key. #print repr(event.get('summary', 'NO SUMMARY')) + '\n' ## Get the next request object by passing the previous request object to ## the list_next method. #request = service.events().list_next(request, response) #except AccessTokenRefreshError: ## The AccessTokenRefreshError exception is raised if the credentials ## have been revoked by the user or they have expired. #print ('The credentials have been revoked or expired, please re-run' #'the application to re-authorize') # working event event = { 'summary': "summary", 'description': "description", 'start' : { 'dateTime' : "2013-04-01T15:00:00.000Z"}, 'end' : { 'dateTime' : "2013-04-01T17:00:00.000Z"} } #created_event = service.events().insert(calendarId='primary', body=event).execute() #print "Created Event: %s" % created_event['id'] return render_to_response("loggedin.html", RequestContext(request)) except: return render_to_response("main.html", RequestContext(request))
def file_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) body = { 'title': request1.filename, 'description': 'Encrypted', 'mimeType': 'text/plain' } media_body = MediaIoBaseUpload(StringIO.StringIO( request1.filedata), 'text/plain', resumable=False) results = service.files().insert(body=body, media_body=media_body).execute() 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 #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 show(id): access_token = session.get('credentials') gplusId = session.get('gplus_id') if access_token is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return redirect(url_for('users.login')) credentials = AccessTokenCredentials(access_token, 'user-agent-value') # Only fetch a list of people for connected users. if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return redirect(url_for('users.login')) user = User.query.filter_by(gplusId=gplusId).first() pages = getPages() print gplusId # todo check for gplusId too page = Page.query.filter_by(id=id).first() text_elems = page.text_elements.all() page.text_elements = text_elems image_elems = page.image_elements.all() page.image_elements = image_elems return render_template('pages/main.html', pages=pages, page=page, id=id, user=user)
def disconnect(): """Revoke current user's token and reset their session. **Route:** ``/admin/disconnect`` **Methods:** ``GET, POST`` """ # Only disconnect a connected user. credentials = AccessTokenCredentials(session.get('credentials'), request.headers.get('User-Agent')) if credentials is None: return json_error_message('Current user not connected.', 401) # Execute HTTP GET request to revoke current token. access_token = credentials.access_token url = ('https://accounts.google.com/o/oauth2/revoke?token={}'.format( str(access_token))) h = httplib2.Http() result = h.request(url, 'GET')[0] session.pop('gplus_id', None) g.user = None if result['status'] == '200': # Reset the user's session. del session['credentials'] else: # For whatever reason, the given token was invalid. app.logger.error('Failed to revoke token for given user.') # use code=303 to avoid POSTing to the next page. return redirect(url_for('.login'), code=303)
def disonnect(): """ Disconnect a Google + user """ # Only disconnect a connected user. 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 # otherwise, get and revoke the access token access_token = credentials.access_token # make a request to revoke token URL url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] # if the revocation is successfully processed if result['status'] == '200': # Reset the user's session. del session['credentials'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return response
def __init__(self, code): logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level)) params = urllib.urlencode({'code':code, 'client_id': '504754513196-kk98ot5v9ch3tbqsrat55o76gf8gaa9m.apps.googleusercontent.com', 'client_secret': 'TZutxu0ahNhv7eqhhUqcRYdP', 'redirect_uri':"http://flask-ijab.rhcloud.com/oauth2callback", 'grant_type':'authorization_code'}) headers={'content-type':'application/x-www-form-urlencoded'} conn = httplib.HTTPSConnection("accounts.google.com") conn.request("POST", "/o/oauth2/token", params, headers) response = conn.getresponse() res = json.loads(response.read()) if(res.has_key('access_token')): #if self.credentials is None or self.credentials.invalid: #self.credentials = run(FLOW, storage) self.credentials = AccessTokenCredentials(res['access_token'],'my-user-agent/1.0') self.http = httplib2.Http() self.http = self.credentials.authorize(self.http) self.service = build("plus", "v1", http=self.http) self.person=None self.friends=None self.InfoList=None self.progress={'Status':'Not Ready', 'RunningJob':'Nothing', 'Progress':0, 'msg' : 'OK'} else: self.progress={'Status':'error', 'RunningJob':'Nothing', 'Progress':0, 'msg' : str(res)} print str(res)
def _get_drive_service(self): credentials = AccessTokenCredentials.new_from_json(self.auth_token) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) # Refresh the credentials as necessary try: if credentials.access_token_expired: credentials.refresh(http) except: # Something went wrong with automatic refresh; try manually doing it print('Manually refreshing credentials...') flow = OAuth2WebServerFlow(client_id=credentials.client_id, client_secret=credentials.client_secret, scope='https://www.googleapis.com/auth/drive', redirect_uri='urn:ietf:wg:oauth:2.0:oob') auth_uri = flow.step1_get_authorize_url() print('Go to this link in your browser:') print(auth_uri) auth_code = raw_input('Enter the auth code: ') credentials = flow.step2_exchange(auth_code) print('Save the following credentials in the configuration file...') exit(credentials.to_json()) drive_service = build('drive', 'v2', http=http) return drive_service
class AccessTokenCredentialsTests(unittest.TestCase): 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 test_token_refresh_success(self): for status_code in REFRESH_STATUS_CODES: http = HttpMockSequence([ ({'status': status_code}, ''), ]) http = self.credentials.authorize(http) try: resp, content = http.request('http://example.com') self.fail('should throw exception if token expires') except AccessTokenCredentialsError: pass except Exception: self.fail('should only throw AccessTokenCredentialsError') def test_token_revoke_success(self): _token_revoke_test_helper( self, '200', revoke_raise=False, valid_bool_value=True, token_attr='access_token') def test_token_revoke_failure(self): _token_revoke_test_helper( self, '400', revoke_raise=True, valid_bool_value=False, token_attr='access_token') def test_non_401_error_response(self): http = HttpMockSequence([ ({'status': '400'}, ''), ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') self.assertEqual(400, resp.status) def test_auth_header_sent(self): http = HttpMockSequence([ ({'status': '200'}, 'echo_request_headers'), ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') self.assertEqual('Bearer foo', content['Authorization'])
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 sync_youtube_videos(userobj=None): playlist_users = Playlist.objects.exclude(youtube_pl_id__exact=None).\ filter(youtube_last_err=None) playlist_users = Playlist.objects.exclude(youtube_pl_id__exact=None) if userobj: playlist_users = playlist_users.filter(user=userobj) for user_items in playlist_users: userobj = user_items.user.social_auth.get(provider='google-oauth2') credentials = AccessTokenCredentials( userobj.extra_data.get('access_token'), 'friendlyvibe/1.0') youtube = build( 'youtube', 'v3', http=credentials.authorize(httplib2.Http())) for plitem in user_items.playlistitem_set.filter(youtube_synced=None): video_add = {} try: video_add = youtube.playlistItems().insert( part="snippet", body=dict( snippet=dict( playlistId=user_items.youtube_pl_id, resourceId=dict( kind='youtube#video', videoId=plitem.item_obj.source_identifier ), position=0 ) ) ).execute() except AccessTokenCredentialsError, e: # refresh the token strategy = load_strategy(backend='google-oauth2') userobj.refresh_token(strategy) except Exception, e: # record the error so next time we won't attempt to send it plitem.playlist_obj.youtube_last_err = str(e) plitem.playlist_obj.save() # make a note of the successfull answer if video_add.get('id'): plitem.youtube_synced = True plitem.youtube_data = simplejson.dumps(video_add) plitem.youtube_synced = datetime.datetime.now() plitem.save()
def getDriveService(): #Gets the drive service instance using google drive credentials #Takes: nothing #Returns: a drive service instance try: #Google Drive Credentials (unique per account) ClientID = '230798942269.apps.googleusercontent.com' ClientSecret = 'JZ7dyNbQEHQ9XLXHxcFlcAad' OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive' REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' SavedRefreshToken = '1/WjgLdc0RekqCu0s5uae1dJm9ZbmyufQWulsaXdvu3b8' h = Http(disable_ssl_certificate_validation=True) post_data = {'client_id':ClientID, 'client_secret':ClientSecret, 'refresh_token':SavedRefreshToken, 'grant_type':'refresh_token'} headers = {'Content-type': 'application/x-www-form-urlencoded'} resp, content = h.request("https://accounts.google.com/o/oauth2/token", "POST", urlencode(post_data), headers=headers) content2 = content.split() access_token = content2[3] access_token = access_token.replace('"', '') access_token = access_token.replace(',', '') #Exchange the code / access token for credentials credentials = AccessTokenCredentials(access_token, ClientID) #Intialize the drive service and return it http = Http(disable_ssl_certificate_validation=True) http = credentials.authorize(http) return build('drive', 'v2', http=http) #Error may occur if the user's network is down except httplib2.ServerNotFoundError: sys.exit('Can not connect to Google Drive. Please check internet connection.') #Unexpected error may occur except httplib2.HttpLib2Error, e: sys.exit('httplib2 exception: ' + str(e))
def getUserDetails(): access_token = session.get('credentials') credentials = AccessTokenCredentials(access_token, 'user-agent-value') # Only fetch a list of people for connected users. if credentials is None: raise Exception("Current user not connected") try: # Create a new authorized API client. http = httplib2.Http() http = credentials.authorize(http) people_resource = SERVICE.people() people_document = people_resource.get(userId='me').execute(http=http) gplusId = people_document['id'] name = people_document['displayName'] return {'gplusId': gplusId,'name': name} except AccessTokenRefreshError: raise Exception("Failed to refresh access token")
def set(self, **kwargs): kwargs = self.filter(kwargs) db = sqlite3.connect(self.db_path) cursor = db.cursor() #get information from calling android device input = json.loads(json.dumps(kwargs)) try: app = input['app'] preset = input['preset'] accesstoken = input['accesstoken'] except KeyError: cursor.close() db.close() return "error: invalid input" try: radius = input['radius'] except KeyError: radius = -2 #get user id from google with access token try: credentials = AccessTokenCredentials(accesstoken, 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) service = build('oauth2', 'v2', http=http) userinfo = service.userinfo().get().execute() user = hashlib.sha256(userinfo['id']).hexdigest() except oauth2client.client.AccessTokenCredentialsError: cursor.close() db.close() return "error: The access_token is expired or invalid and can't be refreshed" try: cursor.execute("INSERT INTO configuration(app, user, preset, radius) VALUES(?, ?, ?, ?)", (app, user, preset, radius,)) answer = "insert successfull" except sqlite3.IntegrityError: cursor.execute("UPDATE configuration SET preset = ?, radius = ? WHERE app = ? AND user = ?", (preset, radius, app, user, )) answer = "update successfull" db.commit() cursor.close() db.close() return answer
def authenticate(service, discovery, version, sub=None, access_token=None, http=None): """ Authenticate to the Gmail API with the account specified by 'sub'. :param service: The API service object to authentication. :param discovery: The service descriptor file to use for API endpoint discovery. :param version: The version of the Gmail API to authentication to. :param sub: (optional) The user to authenticate the service object to. :param access_token: (optional) The OAuth2 token (usually from the cache) to use for authentication. :param http: Optional HTTP object to use (used in tests). :return: A tuple of (the authenticated credential object, the authenticated http object, and the service object). """ if access_token: credentials = AccessTokenCredentials(access_token, user_agent="mailbeaker/1.0") else: logging.info("No access_token provided, establishing new token.", extra={"email": sub}) key = settings.GOOGLE_OAUTH2_PRIVATE_KEY credentials = \ SignedJwtAssertionCredentials(service_account_name=settings.GOOGLE_OAUTH2_SERVICE_ACCOUNT_EMAIL, private_key=key, scope=settings.GOOGLE_OAUTH2_SCOPE, sub=sub) if not http: # Authorize the httplib2.Http object with our credentials http = httplib2.Http() http = credentials.authorize(http) # We'll read the description of this API's function from # a JSON input file. Normally the client reaches out to either: # - https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest # - https://www.googleapis.com/discovery/v1/apis/admin/directory_v1/rest # ... to get this information via apiclient.discovery.build(), # but that method causes a significant perfomance impact. path = os.path.dirname(os.path.realpath(__file__)) path = os.path.join(path, discovery) discovery = open(path).read() service = build_from_document(discovery, http=http, base="https://www.googleapis.com/") return credentials, http, service
def _authorise(self): """Gets AccessTokenCredentials with the ACCESS_TOKEN and USER_AGENT and authorises a httplib2 http object. If this has already been done, does nothing.""" if self.http is not None: return assert self.ACCESS_TOKEN is not None # if cred.user_agent is not none, then it adds appends the # user-agent to the end of the existing user-agent string # each time request() is called... # ...Until you get a "headers too long" error. # so make it None cred = AccessTokenCredentials(self.ACCESS_TOKEN, None) # NationBuilder has a lot of problems with their SSL certs... self.http = httplib2.Http(disable_ssl_certificate_validation=True) self.http = cred.authorize(self.http)
def file_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) body = {'title':request1.filename, 'description':'Encrypted', 'mimeType':'text/plain'} media_body = MediaIoBaseUpload(StringIO.StringIO(request1.filedata), 'text/plain',resumable=False) results = service.files().insert(body=body,media_body=media_body).execute() 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 #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 show_docs(request): if request.method != 'GET': return HttpResponseServerError("Bad request type: " + request.method) http = httplib2.Http() instance = UserSocialAuth.objects.filter(provider='google-oauth2').get(user=request.user) token = instance.tokens['access_token'] useragent = request.META['HTTP_USER_AGENT'] credentials = AccessTokenCredentials(token, useragent) http = credentials.authorize(http) service = build('drive', 'v2', http=http) apirequest = service.files().list() while apirequest != None: response = apirequest.execute() for file in response.get('items', []): print repr(file.get('title')) + '\n' apirequest = service.files().list_next(apirequest, response) ctx = { 'files': files } return render_to_response('documents.html', ctx, RequestContext(request))