def __init__(self, root=None, credentials=None, thread_synchronize=True): """Initialize a GoogleDriveFS instance.""" self._root = root def _getDateTimeFromString(time): # Parses string into datetime object if time: return datetime.datetime.strptime( time, "%Y, %m, %d, %H, %M, %S, %f") else: return None if credentials is None: # Get credentials need to build the google drive service if ("GD_ACCESS_TOKEN" not in os.environ or "GD_CLIENT_ID" not in os.environ or "GD_CLIENT_SECRET" not in os.environ or "GD_TOKEN_EXPIRY" not in os.environ or "GD_TOKEN_URI" not in os.environ, "GD_REFRESH_TOKEN" not in os.environ): raise CreateFailedError("You need to set:\n" "GD_ACCESS_TOKEN, " "GD_CLIENT_ID, " "GD_CLIENT_SECRET " "GD_TOKEN_EXPIRY, " "GD_REFRESH_TOKEN, " "GD_TOKEN_URI in os.environ") else: self._credentials = OAuth2Credentials( os.environ.get('GD_ACCESS_TOKEN'), os.environ.get('GD_CLIENT_ID'), os.environ.get('GD_CLIENT_SECRET'), os.environ.get('GD_REFRESH_TOKEN'), _getDateTimeFromString(os.environ.get('GD_TOKEN_EXPIRY')), os.environ.get('GD_TOKEN_URI'), None) else: self._credentials = OAuth2Credentials( credentials.get('access_token'), credentials.get('client_id'), credentials.get('client_secret'), credentials.get('refresh_token'), _getDateTimeFromString(credentials.get('token_expiry')), credentials.get('token_uri'), None) self.client = GoogleDriveClient(self._credentials) if self._root is None or root == '' or self._root == "/": # Root fix, if root is not set get the root folder id # from the user information returned by 'about' about = self.client.about() self._root = about.get("rootFolderId") # Initialize super class FS super(self.__class__, self).__init__(thread_synchronize=thread_synchronize)
def refresh_tokens(self): """ Refreshes self.access_token and updates self.token_expiry. Returns True if refresh was successful, False otherwise. """ lock_id = "refresh_tokens:%s" % self.pk with lock(lock_id, steal_after_ms=6000): self.refresh_from_db() if self._oauth_tokens_are_valid(): # pragma: no cover return credentials = OAuth2Credentials( self.access_token, settings.GOOGLE_OAUTH2_CLIENT_ID, settings.GOOGLE_OAUTH2_CLIENT_SECRET, self.refresh_token, self.token_expiry, 'https://accounts.google.com/o/oauth2/token', 'YouJudge Client') # Do a refresh - this should update access_token and token_expiry try: credentials.refresh(httplib2.Http(proxy_info=None, timeout=5)) except AccessTokenRefreshError as e: logging.error("Couldn't refresh oauth tokens for user {}. " "Error was {}".format(self, e)) return with transaction.atomic(): self.refresh_from_db() if credentials.access_token != self.access_token: self.access_token = credentials.access_token self.token_expiry = credentials.token_expiry.replace( tzinfo=pytz.UTC) self.save()
def set_google_credentials(strategy, details, response, user=None, *args, **kwargs): """ Saves google credentials to work with API """ if user: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(response.get('expires_in'))) id_token = _extract_id_token(response.get('id_token')) credential = OAuth2Credentials( access_token=response.get('access_token'), client_id=settings.GOOGLE_OAUTH2_CLIENT_ID, client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET, refresh_token=response.get('refresh_token'), token_expiry=token_expiry, token_uri=GOOGLE_TOKEN_URI, user_agent=None, revoke_uri=GOOGLE_REVOKE_URI, id_token=id_token, token_response=response) google_credential, is_created = GoogleCredentials.objects.get_or_create( user=user) google_credential.credential = credential google_credential.save()
def test_multistore_file(self): access_token = 'foo' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' client_id = 'some_client_id' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) store = multistore_file.get_credential_storage( FILENAME, credentials.client_id, credentials.user_agent, ['some-scope', 'some-other-scope']) store.put(credentials) credentials = store.get() self.assertNotEquals(None, credentials) self.assertEquals('foo', credentials.access_token) store.delete() credentials = store.get() self.assertEquals(None, credentials) if os.name == 'posix': self.assertEquals('0600', oct(stat.S_IMODE(os.stat(FILENAME).st_mode)))
def test_no_unicode_in_request_params(self): access_token = u'foo' client_id = u'some_client_id' client_secret = u'cOuDdkfjxxnv+' refresh_token = u'1/0/a.df219fjls0' token_expiry = str(datetime.datetime.utcnow()) token_uri = str(GOOGLE_TOKEN_URI) revoke_uri = str(GOOGLE_REVOKE_URI) user_agent = u'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) http = HttpMock(headers={'status': '200'}) http = credentials.authorize(http) http.request(u'http://example.com', method=u'GET', headers={u'foo': u'bar'}) for k, v in six.iteritems(http.headers): self.assertEqual(six.binary_type, type(k)) self.assertEqual(six.binary_type, type(v)) # Test again with unicode strings that can't simply be converted to ASCII. try: http.request( u'http://example.com', method=u'GET', headers={u'foo': u'\N{COMET}'}) self.fail('Expected exception to be raised.') except NonAsciiHeaderError: pass self.credentials.token_response = 'foobar' instance = OAuth2Credentials.from_json(self.credentials.to_json()) self.assertEqual('foobar', instance.token_response)
def _onCredentialsPollBodyReady(self, body): if self._canceled: Log.d("Auth Request canceled") return result = json.loads(body) error = result.get("error", None) if error: if error == "authorization_pending": print "not ready, yet" reactor.callLater(self._user_code.interval, self._pollForResult) elif error == "slow_down": print "too fast, slowing down" self._device_code.interval = self._device_code.interval * 2 elif error == "expired_token": self._onError(self.ERROR_CREDENTIALS_REQUEST_EXPIRED) else: print result self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error) elif "access_token" in result: access_token = result.get("access_token") refresh_token = result.get("refresh_token") token_expiry = str( int(time()) + int(result.get("expires_in")) ) self._credentials = OAuth2Credentials(access_token, self.CLIENT_ID, self.CLIENT_SECRET, refresh_token, token_expiry, self.AUTH_REQUEST_URI, self.USER_AGENT) for fnc in self.onCredentialsReady: fnc(self._credentials) else: self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error)
def _get_credentials(credentials=None): """ Checks environment in order of precedence: - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to a file with stored credentials information. - Google App Engine (production and testing) Returns: (OAuth2Credentials or GoogleCredentials) """ if not credentials: if os.environ.get('JPY_USER'): # we are running in datalab, so derive the user credentials from the environment # This is required for datalab to work as the user credentials are only set in the environment if not os.environ.get('REFRESH_TOKEN') or not os.environ.get( "CLIENT_ID") or not os.environ.get("CLIENT_SECRET"): raise RuntimeError( "Not all required environment variables are found: REFRESH_TOKEN, CLIENT_ID, CLIENT_SECRET" ) return OAuth2Credentials( access_token=None, client_id=os.environ['CLIENT_ID'], client_secret=os.environ['CLIENT_SECRET'], refresh_token=os.environ['REFRESH_TOKEN'], token_uri=ExternalService._get_token_uri( os.environ['TOKEN_URI']), token_expiry=None, user_agent='Python client library') else: credentials = GoogleCredentials.get_application_default() if credentials.create_scoped_required(): credentials = credentials.create_scoped(SCOPES) return credentials if not credentials: raise RuntimeError("Could not find proper credentials!") return credentials
def FetchAccessToken(self): """Fetches an access token from the provider's token endpoint. Fetches an access token from this client's OAuth2 provider's token endpoint. Returns: The fetched AccessToken. """ try: http = self.CreateHttpRequest() credentials = OAuth2Credentials(None, self.client_id, self.client_secret, self.refresh_token, None, self.token_uri, None) credentials.refresh(http) return AccessToken(credentials.access_token, credentials.token_expiry, datetime_strategy=self.datetime_strategy) except AccessTokenRefreshError, e: if 'Invalid response 403' in e.message: # This is the most we can do at the moment to accurately detect rate # limiting errors since they come back as 403s with no further # information. raise GsAccessTokenRefreshError(e) elif 'invalid_grant' in e.message: LOG.info(""" Attempted to retrieve an access token from an invalid refresh token. Two common cases in which you will see this error are: 1. Your refresh token was revoked. 2. Your refresh token was typed incorrectly. """) raise GsInvalidRefreshTokenError(e) else: raise
def download_sheet_with_user(user, filename='membership.csv'): """ Download the membership with a user's credentials :type user: users.models.User :param user: :return: boolean of successful download """ try: social = UserSocialAuth.get_social_auth_for_user(user).get() except UserSocialAuth.DoesNotExist: return False extra = social.extra_data expiry = datetime.utcnow() + timedelta(seconds=int(extra['expires'])) credentials = OAuth2Credentials(extra['access_token'], settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY, settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET, extra['refresh_token'], expiry, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI) service = build_service_from_credentials(credentials) try: file = service.files().get( fileId=settings.GOOGLE_MEMBERSHIP_FILE_ID).execute() except googleapiclient.errors.HttpError: return False url = file['exportLinks']['text/csv'] resp, content = service._http.request(url) open(filename, 'wb').write(content) return True
def __init__(self, client_id, client_secret, project_name, credential_store='phosting.dat', service_acct=False): ''' Constructor ''' self.project_name = project_name self._empty_owner_value = '----' with open(credential_store) as data_file: creds_data = json.load(data_file) credentials = OAuth2Credentials( None, creds_data['client_id'], creds_data['client_secret'], creds_data['refresh_token'], None, 'https://accounts.google.com/o/oauth2/token', 'python-issue-tracker-manager/2.0') if credentials is None or credentials.invalid == True: api_scope = 'https://www.googleapis.com/auth/projecthosting' credentials = self._authenticate(storage=None, service_acct=service_acct, client_id=client_id, client_secret=client_secret, api_scope=api_scope) http = httplib2.Http() http = credentials.authorize(http) discovery_url = ('https://www.googleapis.com/discovery/v1/apis/{api}/' '{apiVersion}/rest') self.client = build_client(discovery_url, http, 'projecthosting', 'v2')
def __init__(self): auth = dict(settings.DFP_HEADERS) auth['oauth2credentials'] = OAuth2Credentials( None, auth['clientId'], auth['clientSecret'], auth['refreshToken'], datetime.datetime(1980, 1, 1, 12), _GOOGLE_OAUTH2_ENDPOINT, 'Google Ads* Python Client Library') self.client = DfpClient(headers=auth, config=settings.DFP_CONFIG)
def test_read_only_file_fail_lock(self): access_token = 'foo' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' client_id = 'some_client_id' credentials = OAuth2Credentials( access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) open(FILENAME, 'a+b').close() os.chmod(FILENAME, 0400) store = multistore_file.get_credential_storage( FILENAME, credentials.client_id, credentials.user_agent, ['some-scope', 'some-other-scope']) store.put(credentials) if os.name == 'posix': self.assertTrue(store._multistore._read_only) os.chmod(FILENAME, 0600)
def get_user_credentials(client_service, client_id, client_secret): """Retrives the clients credentials from storage""" storage = DjangoORMStorage(Credentials, "id", client_service, "credential") local_credentials = storage.get( ) # load the user's credentials from storage if local_credentials: credentials = OAuth2Credentials( access_token=local_credentials.access_token, client_id=client_id, client_secret=client_secret, refresh_token=local_credentials.refresh_token, token_expiry=local_credentials.token_expiry, token_uri=local_credentials.token_uri, user_agent=local_credentials.user_agent, scopes=settings.GOOGLE_OAUTH2_CLIENT['scope']) try: if credentials.access_token_expired: credentials.refresh(httplib2.Http()) # Refresh access token storage.put(credentials) return credentials except AccessTokenRefreshError: # The access token is stale. Should be storing the refresh tokens? return None else: return None
def _login_account(self): db = dbprovider.DB() access_token = db.get_provider_token('googledrive') self.logger.debug("GDrive: " + str(access_token)) if access_token is None: # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, SCOPE, REDIRECT_URI) flow.params['access_type'] = 'offline' flow.params['approval_prompt'] = 'force' authorize_url = flow.step1_get_authorize_url() print 'Go to the following link in your browser: ' + authorize_url code = raw_input('Enter verification code: ').strip() #access_token= raw_input('Enter code: ').strip() credentials = flow.step2_exchange(code) access_token = credentials.access_token refresh_token = credentials.refresh_token token_expiry = credentials.token_expiry db.set_provider_token('googledrive', access_token, refresh_token, token_expiry) else: access_token = str(access_token) refresh_token = db.get_provider_refresh_token('googledrive') token_expiry = db.get_provider_token_expiry('googledrive') db.shutdown_database() return OAuth2Credentials(access_token, CLIENT_ID, CLIENT_SECRET, refresh_token, token_expiry, TOKEN_URI, 'my-user-agent/1.0')
def initialize_adsense_reporting(): credentials = None if os.environ['PYTHON_ENV'] == 'test': credentials = storage.get() if not credentials or credentials.invalid: flow = flow_from_clientsecrets(KEY_FILE_LOCATION, SCOPES, redirect_uri='http://localhost:8080/') auth_uri = flow.step1_get_authorize_url() print(auth_uri) code = input('Enter the auth code: ') credentials = flow.step2_exchange(code) storage.put(credentials) else: # with open(CREDENTIALS_FILE_LOCATION) as credentials_json: credentials_dict = json.loads(os.environ['CREDENTIALS']) credentials = OAuth2Credentials( refresh_token = credentials_dict["refresh_token"], token_uri = credentials_dict["token_uri"], client_id = credentials_dict["client_id"], client_secret = credentials_dict["client_secret"], access_token = credentials_dict["access_token"], token_expiry = credentials_dict["token_expiry"], user_agent = credentials_dict["user_agent"], ) if credentials is None: raise Exception('Credentials is None') adsense = build('adsense', 'v1.4', credentials=credentials) print(adsense) return adsense
def __init__(self): with open("oauth_credentials.json", "r") as oauth_credentials_file: oauth_credentials = json.loads(oauth_credentials_file.read()) credentials = OAuth2Credentials(**oauth_credentials) http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) self.service = service
def GetCredentials(self): """Fetches a credentials objects from the provider's token endpoint.""" access_token = self.GetAccessToken() credentials = OAuth2Credentials( access_token.token, self.client_id, self.client_secret, self.refresh_token, access_token.expiry, self.token_uri, None) return credentials
def client_with_credentials(app): """This fixture provides a Flask app test client that has a session pre-configured with use credentials.""" credentials = OAuth2Credentials('access_token', 'client_id', 'client_secret', 'refresh_token', '3600', None, 'Test', id_token={ 'sub': '123', 'email': '*****@*****.**' }, scopes=('email', 'profile')) @contextlib.contextmanager def inner(): with app.test_client() as client: with client.session_transaction() as session: session['profile'] = {'id': 'abc', 'displayName': 'Test User'} session['google_oauth2_credentials'] = credentials.to_json() yield client return inner
def test_json_credentials_storage(self): access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) m = mox.Mox() m.StubOutWithMock(keyring, 'get_password') m.StubOutWithMock(keyring, 'set_password') keyring.get_password('my_unit_test', 'me').AndReturn(None) keyring.set_password('my_unit_test', 'me', credentials.to_json()) keyring.get_password('my_unit_test', 'me').AndReturn(credentials.to_json()) m.ReplayAll() s = Storage('my_unit_test', 'me') self.assertEquals(None, s.get()) s.put(credentials) restored = s.get() self.assertEqual('foo', restored.access_token) self.assertEqual('some_client_id', restored.client_id) m.UnsetStubs() m.VerifyAll()
def _LoadAuthCredentials(self): """Load existing authentication credentials from auth.pkl. Returns: dict Dictionary object with populated authentication credentials. Raises: ValidationError: if authentication data is missing. """ auth = {} if os.path.exists(self.__class__.auth_pkl): fh = open(self.__class__.auth_pkl, 'r') try: auth = pickle.load(fh) finally: fh.close() if not auth: msg = 'Authentication data is missing.' raise ValidationError(msg) if _OAUTH_2_AUTH_KEYS.issubset(set(auth.keys())): from oauth2client.client import OAuth2Credentials auth['oauth2credentials'] = OAuth2Credentials( None, auth['clientId'], auth['clientSecret'], auth['refreshToken'], datetime.datetime(1980, 1, 1, 12), _GOOGLE_OAUTH2_ENDPOINT, 'Google Ads* Python Client Library') for auth_key in _OAUTH_2_AUTH_KEYS: del auth[auth_key] return auth
def youtube_credentials(access_token,refresh_token,token_expiry): client=YOUTUBE_INFO # credentials = AccessTokenCredentials(access_token,'tunesmash-agent/1.0') credentials = OAuth2Credentials(client_id=client['id'],client_secret=client['secret'],refresh_token=refresh_token,token_uri='https://www.googleapis.com/oauth2/v4/token',user_agent='ts-ipython',access_token=access_token,token_expiry=token_expiry) http = httplib2.Http() credentials.refresh(http) return credentials
def testExpiredDfaToken(self): """Tests regenerating the DFA token once it has expired. Uses a credential passed in to the constructor. Starts with an expired DFA token and has the library regenerate it. Since this library is tightly integrated with SOAPpy, this test mocks out the HTTP level rather than the SOAPpy proxy level. """ oauth2_credential = OAuth2Credentials(ACCESS_TOKEN, CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, None, OAUTH_URI, USER_AGENT) headers = { 'userAgent': USER_AGENT, 'Username': USER_NAME, 'oauth2credentials': oauth2_credential, 'AuthToken': EXPIRED_TOKEN, 'appName': USER_AGENT } config = {'compress': False} client = DfaClient(headers=headers, config=config) placement_service = self._CreatePlacementService(client) placement_service._config['compress'] = False page = self._MakeSoapRequest_ExpiredToken(placement_service) self.assertEquals(EXPECTED_RESULT, page)
def test_unicode_header_checks(self): access_token = u'foo' client_id = u'some_client_id' client_secret = u'cOuDdkfjxxnv+' refresh_token = u'1/0/a.df219fjls0' token_expiry = str(datetime.datetime.utcnow()) token_uri = str(GOOGLE_TOKEN_URI) revoke_uri = str(GOOGLE_REVOKE_URI) user_agent = u'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) # First, test that we correctly encode basic objects, making sure # to include a bytes object. Note that oauth2client will normalize # everything to bytes, no matter what python version we're in. http = credentials.authorize(HttpMock(headers={'status': '200'})) headers = {u'foo': 3, b'bar': True, 'baz': b'abc'} cleaned_headers = {b'foo': b'3', b'bar': b'True', b'baz': b'abc'} http.request(u'http://example.com', method=u'GET', headers=headers) for k, v in cleaned_headers.items(): self.assertTrue(k in http.headers) self.assertEqual(v, http.headers[k]) # Next, test that we do fail on unicode. unicode_str = six.unichr(40960) + 'abcd' self.assertRaises( NonAsciiHeaderError, http.request, u'http://example.com', method=u'GET', headers={u'foo': unicode_str})
def testWithPassedInCredential(self): """Tests the entire workflow of making a request against DFA. Uses a credential passed in to the constructor. Starts with no DFA token and has the library generate one. Since this library is tightly integrated with SOAPpy, this test mocks out the HTTP level rather than the SOAPpy proxy level. """ oauth2_credential = OAuth2Credentials(ACCESS_TOKEN, CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, None, OAUTH_URI, USER_AGENT) headers = { 'userAgent': USER_AGENT, 'Username': USER_NAME, 'oauth2credentials': oauth2_credential, 'appName': USER_AGENT } config = {'compress': False} client = DfaClient(headers=headers, config=config) placement_service = self._CreatePlacementService(client) page = self._MakeSoapRequest_NoDfaToken(placement_service) self.assertEquals(EXPECTED_RESULT, page)
def test_simple(self, step2_exchange): access_token = 'b' * 40 refresh_token = 'c' * 40 step2_exchange.return_value = OAuth2Credentials( access_token, current_app.config['GOOGLE_CLIENT_ID'], current_app.config['GOOGLE_CLIENT_SECRET'], refresh_token, datetime(2013, 9, 19, 22, 15, 22), GOOGLE_TOKEN_URI, 'foo/1.0', revoke_uri=GOOGLE_REVOKE_URI, id_token={ 'hd': 'example.com', 'email': '*****@*****.**', }, ) resp = self.client.get('/auth/complete/?code=abc') step2_exchange.assert_called_once_with('abc') assert resp.status_code == 302 assert resp.headers[ 'Location'] == 'http://localhost/?finished_login=success' user = User.query.filter(User.email == '*****@*****.**', ).first() assert user
def __init__(self): """初期化. OAuth認証もここで行います.""" refresh_params = { "client_id": CLIENT_ID, "refresh_token": REFRESH_TOKEN, "client_secret": CLIENT_SECRET, "grant_type": "refresh_token" } rs = requests.post('https://accounts.google.com/o/oauth2/token', refresh_params).json() expiry = datetime.datetime.now() + datetime.timedelta( seconds=rs['expires_in']) cred_params = { 'access_token': rs['access_token'], 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'refresh_token': REFRESH_TOKEN, 'token_expiry': expiry, 'token_uri': 'https://accounts.google.com/o/oauth2/token', 'user_agent': '' } self.credentials = OAuth2Credentials(**cred_params)
def test_pickle_and_json_interop(self): # Write a file with a pickled OAuth2Credentials. access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) f = open(FILENAME, 'w') pickle.dump(credentials, f) f.close() # Storage should be not be able to read that object, as the capability to # read and write credentials as pickled objects has been removed. s = Storage(FILENAME) read_credentials = s.get() self.assertEquals(None, read_credentials) # Now write it back out and confirm it has been rewritten as JSON s.put(credentials) f = file(FILENAME) data = simplejson.load(f) f.close() self.assertEquals(data['access_token'], 'foo') self.assertEquals(data['_class'], 'OAuth2Credentials') self.assertEquals(data['_module'], OAuth2Credentials.__module__)
def get_credentials(self, code, state, **kwargs): 'use callback data to get an access token' if state != self.state: return False # CSRF attack?!? d = dict(code=code, client_id=self.keys['client_id'], client_secret=self.keys['client_secret'], redirect_uri=self.keys['redirect_uri'], grant_type='authorization_code') r = requests.post(self.token_uri, data=d) self.access_data = ad = r.json() try: token_expiry = datetime.utcnow() \ + timedelta(seconds=int(ad['expires_in'])) except KeyError: token_expiry = None if 'id_token' in ad: ad['id_token'] = _extract_id_token(ad['id_token']) c = OAuth2Credentials(ad['access_token'], d['client_id'], d['client_secret'], ad.get('refresh_token', None), token_expiry, self.token_uri, self.user_agent, id_token=ad.get('id_token', None)) self.credentials = c return c
def update_google_analytics(date, **kw): creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None) if not creds_data: log.critical('Failed to update global stats: ' 'GOOGLE_ANALYTICS_CREDENTIALS not set') return creds = OAuth2Credentials( *[creds_data[k] for k in ('access_token', 'client_id', 'client_secret', 'refresh_token', 'token_expiry', 'token_uri', 'user_agent')]) h = httplib2.Http() creds.authorize(h) service = build('analytics', 'v3', http=h) domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN profile_id = get_profile_id(service, domain) if profile_id is None: log.critical('Failed to update global stats: could not access a Google' ' Analytics profile for ' + domain) return datestr = date.strftime('%Y-%m-%d') try: data = service.data().ga().get(ids='ga:' + profile_id, start_date=datestr, end_date=datestr, metrics='ga:visits').execute() # Storing this under the webtrends stat name so it goes on the # same graph as the old webtrends data. p = ['webtrends_DailyVisitors', data['rows'][0][0], date] except Exception, e: log.critical( 'Fetching stats data for %s from Google Analytics failed: %s' % e) return
def build(self, filename="output.mp4", token_uri="https://accounts.google.com/o/oauth2/token"): """ To post the video we need :param filename: the filename of the 1 hour video :param token_uri: the url to exchange the token for an access token (if you don't know what it is, just don't change it) """ with open(self.client_secret, "r") as info: client_secrets = json.load(info) with open(self.token_json, "r") as info: token_secrets = json.load(info) credentials = OAuth2Credentials(token_secrets["access_token"], client_secrets["web"]["client_id"], client_secrets["web"]["client_secret"], token_secrets["refresh_token"], token_secrets["expires_in"], token_uri, "", scopes=token_secrets["scope"]) self.builder = build('youtube', 'v3', http=credentials.authorize(httplib2.Http())) body = self.body(**self.get_config()) self.inserter = self.builder.videos().insert( part=','.join(body.keys()), body=body, media_body=MediaFileUpload(filename, chunksize=1024**2 * 10, resumable=True))