Exemplo n.º 1
0
    def _make_flow(self, return_url=None, **kwargs):
        """Creates a Web Server Flow"""
        # Generate a CSRF token to prevent malicious requests.
        csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest()

        session['google_oauth2_csrf_token'] = csrf_token

        state = json.dumps({
            'csrf_token': csrf_token,
            'return_url': return_url
        })

        kw = self.flow_kwargs.copy()
        kw.update(kwargs)

        extra_scopes = util.scopes_to_string(kw.pop('scopes', ''))
        scopes = ' '.join([util.scopes_to_string(self.scopes), extra_scopes])

        return OAuth2WebServerFlow(
            client_id=self.client_id,
            client_secret=self.client_secret,
            scope=scopes,
            state=state,
            redirect_uri=url_for('oauth2.callback', _external=True),
            **kw)
Exemplo n.º 2
0
    def __init__(
        self,
        service_account_id,
        service_account_email,
        private_key_id,
        private_key_pkcs8_text,
        scopes,
        user_agent=None,
        token_uri=GOOGLE_TOKEN_URI,
        revoke_uri=GOOGLE_REVOKE_URI,
        **kwargs
    ):

        super(_ServiceAccountCredentials, self).__init__(
            None, user_agent=user_agent, token_uri=token_uri, revoke_uri=revoke_uri
        )

        self._service_account_id = service_account_id
        self._service_account_email = service_account_email
        self._private_key_id = private_key_id
        self._private_key = _get_private_key(private_key_pkcs8_text)
        self._private_key_pkcs8_text = private_key_pkcs8_text
        self._scopes = util.scopes_to_string(scopes)
        self._user_agent = user_agent
        self._token_uri = token_uri
        self._revoke_uri = revoke_uri
        self._kwargs = kwargs
Exemplo n.º 3
0
    def oidc_callback(self):
        """
        Exchange the auth code for actual credentials,
        then redirect to the originally requested page.
        """
        # retrieve session and callback variables
        try:
            session_csrf_token = session.pop('oidc_csrf_token')

            state = json.loads(request.args['state'])
            csrf_token = state['csrf_token']
            destination = state['destination']

            code = request.args['code']
        except (KeyError, ValueError):
            logger.debug("Can't retrieve CSRF token, state, or code",
                         exc_info=True)
            return self.oidc_error()

        # check callback CSRF token passed to IdP
        # against session CSRF token held by user
        if csrf_token != session_csrf_token:
            logger.debug("CSRF token mismatch")
            return self.oidc_error()

        # make a request to IdP to exchange the auth code for OAuth credentials
        flow = self.flow_for_request()
        if 'scope' in request.args:
            scopes = set(util.string_to_scopes(request.args['scope']))
            scopes |= set(util.string_to_scopes(flow.scope))
            flow.scope = util.scopes_to_string(scopes)
        credentials = flow.step2_exchange(code, http=self.http)
        id_token = credentials.id_token
        if not self.is_id_token_valid(id_token):
            logger.debug("Invalid ID token")
            # None will allow all domains otherwise limit down to the specific domain.
            if self.google_apps_domain is not None:
                if not isinstance(self.google_apps_domain, list):
                    self.google_apps_domain = [self.google_apps_domain]
                if id_token.get('hd') not in self.google_apps_domain:
                    return self.oidc_error(
                        "You must log in with an account from one of the following domains: {0}"
                        .format(', '.join(self.google_apps_domain)),
                        self.WRONG_GOOGLE_APPS_DOMAIN)
            return self.oidc_error()

        # store credentials by subject
        # when Google is the IdP, the subject is their G+ account number
        self.credentials_store[id_token['sub']] = credentials

        # set a persistent signed cookie containing the ID token
        # and redirect to the final destination
        # TODO: validate redirect destination
        response = self.redirect_to(destination)
        self.set_cookie_id_token(id_token)
        return response
Exemplo n.º 4
0
def getOauthFlow():
  config = ufo.get_user_config()
  # TODO give user an option to input their own and go through a different flow
  # to handle it
  return client.OAuth2WebServerFlow(
      client_id=ufo.app.config.get('SHARED_OAUTH_CLIENT_ID'),
      client_secret=ufo.app.config.get('SHARED_OAUTH_CLIENT_SECRET'),
      scope=util.scopes_to_string(OAUTH_SCOPES),
      redirect_uri='urn:ietf:wg:oauth:2.0:oob',
  )
Exemplo n.º 5
0
    def __init__(self, scope, **kwargs):
        """Constructor for AppAssertionCredentials

    Args:
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
    """
        self.scope = util.scopes_to_string(scope)

        super(AppAssertionCredentials, self).__init__("ignored")  # assertion_type is ignore in this subclass.
Exemplo n.º 6
0
    def __init__(self, scope, **kwargs):
        """Constructor for AppAssertionCredentials

    Args:
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
    """
        self.scope = util.scopes_to_string(scope)

        # Assertion type is no longer used, but still in the parent class signature.
        super(AppAssertionCredentials, self).__init__(None)
Exemplo n.º 7
0
  def __init__(self, scope, **kwargs):
    """Constructor for AppAssertionCredentials

    Args:
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
    """
    self.scope = util.scopes_to_string(scope)

    # Assertion type is no longer used, but still in the parent class signature.
    super(AppAssertionCredentials, self).__init__(None)
Exemplo n.º 8
0
    def __init__(self, scope, **kwargs):
        """Constructor for AppAssertionCredentials

    Args:
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
    """
        self.scope = util.scopes_to_string(scope)

        super(AppAssertionCredentials, self).__init__(
            'ignored'  # assertion_type is ignore in this subclass.
        )
Exemplo n.º 9
0
    def __init__(self,
                 client_id,
                 client_secret,
                 scope,
                 auth_uri=GOOGLE_AUTH_URI,
                 token_uri=GOOGLE_TOKEN_URI,
                 revoke_uri=GOOGLE_REVOKE_URI,
                 user_agent=None,
                 message=None,
                 callback_path='/oauth2callback',
                 token_response_param=None,
                 **kwargs):
        """Constructor for OAuth2Decorator

    Args:
      client_id: string, client identifier.
      client_secret: string client secret.
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      auth_uri: string, URI for authorization endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      token_uri: string, URI for token endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      revoke_uri: string, URI for revoke endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      user_agent: string, User agent of your application, default to None.
      message: Message to display if there are problems with the OAuth 2.0
        configuration. The message may contain HTML and will be presented on the
        web interface for any method that uses the decorator.
      callback_path: string, The absolute path to use as the callback URI. Note
        that this must match up with the URI given when registering the
        application in the APIs Console.
      token_response_param: string. If provided, the full JSON response
        to the access token request will be encoded and included in this query
        parameter in the callback URI. This is useful with providers (e.g.
        wordpress.com) that include extra fields that the client may want.
      **kwargs: dict, Keyword arguments are be passed along as kwargs to the
        OAuth2WebServerFlow constructor.
    """
        self.flow = None
        self.credentials = None
        self._client_id = client_id
        self._client_secret = client_secret
        self._scope = util.scopes_to_string(scope)
        self._auth_uri = auth_uri
        self._token_uri = token_uri
        self._revoke_uri = revoke_uri
        self._user_agent = user_agent
        self._kwargs = kwargs
        self._message = message
        self._in_error = False
        self._callback_path = callback_path
        self._token_response_param = token_response_param
Exemplo n.º 10
0
    def __init__(self,
                 client_id,
                 client_secret,
                 scope,
                 redirect_uri=None,
                 user_agent=None,
                 auth_uri=GOOGLE_AUTH_URI,
                 token_uri=GOOGLE_TOKEN_URI,
                 revoke_uri=GOOGLE_REVOKE_URI,
                 login_hint=None,
                 **kwargs):
        """Constructor for OAuth2WebServerFlow.

    The kwargs argument is used to set extra query parameters on the
    auth_uri. For example, the access_type and approval_prompt
    query parameters can be set via kwargs.

    Args:
      client_id: string, client identifier.
      client_secret: string client secret.
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
        a non-web-based application, or a URI that handles the callback from
        the authorization server.
      user_agent: string, HTTP User-Agent to provide for this application.
      auth_uri: string, URI for authorization endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      token_uri: string, URI for token endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      revoke_uri: string, URI for revoke endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      login_hint: string, Either an email address or domain. Passing this hint
        will either pre-fill the email box on the sign-in form or select the
        proper multi-login session, thereby simplifying the login flow.
      **kwargs: dict, The keyword arguments are all optional and required
                        parameters for the OAuth calls.
    """
        self.client_id = client_id
        self.client_secret = client_secret
        self.scope = util.scopes_to_string(scope)
        self.redirect_uri = redirect_uri
        self.login_hint = login_hint
        self.user_agent = user_agent
        self.auth_uri = auth_uri
        self.token_uri = token_uri
        self.revoke_uri = revoke_uri
        self.params = {
            'access_type': 'offline',
            'response_type': 'code',
        }
        self.params.update(kwargs)
Exemplo n.º 11
0
  def __init__(self, client_id, client_secret, scope,
               auth_uri=GOOGLE_AUTH_URI,
               token_uri=GOOGLE_TOKEN_URI,
               revoke_uri=GOOGLE_REVOKE_URI,
               user_agent=None,
               message=None,
               callback_path='/oauth2callback',
               token_response_param=None,
               **kwargs):

    """Constructor for OAuth2Decorator

    Args:
      client_id: string, client identifier.
      client_secret: string client secret.
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      auth_uri: string, URI for authorization endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      token_uri: string, URI for token endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      revoke_uri: string, URI for revoke endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      user_agent: string, User agent of your application, default to None.
      message: Message to display if there are problems with the OAuth 2.0
        configuration. The message may contain HTML and will be presented on the
        web interface for any method that uses the decorator.
      callback_path: string, The absolute path to use as the callback URI. Note
        that this must match up with the URI given when registering the
        application in the APIs Console.
      token_response_param: string. If provided, the full JSON response
        to the access token request will be encoded and included in this query
        parameter in the callback URI. This is useful with providers (e.g.
        wordpress.com) that include extra fields that the client may want.
      **kwargs: dict, Keyword arguments are be passed along as kwargs to the
        OAuth2WebServerFlow constructor.
    """
    self.flow = None
    self.credentials = None
    self._client_id = client_id
    self._client_secret = client_secret
    self._scope = util.scopes_to_string(scope)
    self._auth_uri = auth_uri
    self._token_uri = token_uri
    self._revoke_uri = revoke_uri
    self._user_agent = user_agent
    self._kwargs = kwargs
    self._message = message
    self._in_error = False
    self._callback_path = callback_path
    self._token_response_param = token_response_param
    def test_multistore_file_backwards_compatibility(self):
        credentials = self.create_test_credentials()
        scopes = ["scope1", "scope2"]

        # store the credentials using the legacy key method
        store = multistore_file.get_credential_storage(FILENAME, "client_id", "user_agent", scopes)
        store.put(credentials)

        # retrieve the credentials using a custom key that matches the legacy key
        key = {"clientId": "client_id", "userAgent": "user_agent", "scope": util.scopes_to_string(scopes)}
        store = multistore_file.get_credential_storage_custom_key(FILENAME, key)
        stored_credentials = store.get()

        self.assertEqual(credentials.access_token, stored_credentials.access_token)
Exemplo n.º 13
0
  def __init__(self, client_id, client_secret, scope,
               redirect_uri=None,
               user_agent=None,
               auth_uri=GOOGLE_AUTH_URI,
               token_uri=GOOGLE_TOKEN_URI,
               revoke_uri=GOOGLE_REVOKE_URI,
               login_hint=None,
               **kwargs):
    """Constructor for OAuth2WebServerFlow.

    The kwargs argument is used to set extra query parameters on the
    auth_uri. For example, the access_type and approval_prompt
    query parameters can be set via kwargs.

    Args:
      client_id: string, client identifier.
      client_secret: string client secret.
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
        a non-web-based application, or a URI that handles the callback from
        the authorization server.
      user_agent: string, HTTP User-Agent to provide for this application.
      auth_uri: string, URI for authorization endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      token_uri: string, URI for token endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      revoke_uri: string, URI for revoke endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      login_hint: string, Either an email address or domain. Passing this hint
        will either pre-fill the email box on the sign-in form or select the
        proper multi-login session, thereby simplifying the login flow.
      **kwargs: dict, The keyword arguments are all optional and required
                        parameters for the OAuth calls.
    """
    self.client_id = client_id
    self.client_secret = client_secret
    self.scope = util.scopes_to_string(scope)
    self.redirect_uri = redirect_uri
    self.login_hint = login_hint
    self.user_agent = user_agent
    self.auth_uri = auth_uri
    self.token_uri = token_uri
    self.revoke_uri = revoke_uri
    self.params = {
        'access_type': 'offline',
        'response_type': 'code',
    }
    self.params.update(kwargs)
Exemplo n.º 14
0
  def __init__(self, scope, **kwargs):
    """Constructor for AppAssertionCredentials

    Args:
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
    """
    self.scope = util.scopes_to_string(scope)
    self.kwargs = kwargs

    # Assertion type is no longer used, but still in the parent class signature.
    super(AppAssertionCredentials, self).__init__(
        None, user_agent=(
            'Legacy oauth2client.gce.AppAssertionCrendentials (not current '
            'oauth2client.contrib.gce.AppAssertionCredentials)'))
Exemplo n.º 15
0
    def __init__(self, scope, **kwargs):
        """Constructor for AppAssertionCredentials

    Args:
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      kwargs: optional keyword args, including:
        service_account_id: service account id of the application. If None or
          unspecified, the default service account for the app is used.
    """
        self.scope = util.scopes_to_string(scope)
        self.service_account_id = kwargs.get('service_account_id', None)

        # Assertion type is no longer used, but still in the parent class signature.
        super(AppAssertionCredentials, self).__init__(None)
Exemplo n.º 16
0
  def __init__(self, scope, **kwargs):
    """Constructor for AppAssertionCredentials

    Args:
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      kwargs: optional keyword args, including:
        service_account_id: service account id of the application. If None or
          unspecified, the default service account for the app is used.
    """
    self.scope = util.scopes_to_string(scope)
    self.service_account_id = kwargs.get('service_account_id', None)

    # Assertion type is no longer used, but still in the parent class signature.
    super(AppAssertionCredentials, self).__init__(None)
Exemplo n.º 17
0
 def test_iterables(self):
     cases = [
         ('', ''),
         ('', ()),
         ('', []),
         ('', ('',)),
         ('', ['', ]),
         ('a', ('a',)),
         ('b', ['b', ]),
         ('a b', ['a', 'b']),
         ('a b', ('a', 'b')),
         ('a b', 'a b'),
         ('a b', (s for s in ['a', 'b'])),
     ]
     for expected, case in cases:
         self.assertEqual(expected, util.scopes_to_string(case))
Exemplo n.º 18
0
def get_credential_storage(filename, client_id, user_agent, scope, warn_on_readonly=True):
    """Get a Storage instance for a credential.

  Args:
    filename: The JSON file storing a set of credentials
    client_id: The client_id for the credential
    user_agent: The user agent for the credential
    scope: string or iterable of strings, Scope(s) being requested
    warn_on_readonly: if True, log a warning if the store is readonly

  Returns:
    An object derived from client.Storage for getting/setting the
    credential.
  """
    # Recreate the legacy key with these specific parameters
    key = {"clientId": client_id, "userAgent": user_agent, "scope": util.scopes_to_string(scope)}
    return get_credential_storage_custom_key(filename, key, warn_on_readonly=warn_on_readonly)
Exemplo n.º 19
0
  def __init__(self, service_account_id, service_account_email, private_key_id,
      private_key_pkcs8_text, scopes, user_agent=None,
      token_uri=GOOGLE_TOKEN_URI, revoke_uri=GOOGLE_REVOKE_URI, **kwargs):

    super(_ServiceAccountCredentials, self).__init__(
        None, user_agent=user_agent, token_uri=token_uri, revoke_uri=revoke_uri)
    
    self._service_account_id = service_account_id
    self._service_account_email = service_account_email
    self._private_key_id = private_key_id
    self._private_key = _get_private_key(private_key_pkcs8_text)
    self._private_key_pkcs8_text = private_key_pkcs8_text
    self._scopes = util.scopes_to_string(scopes)
    self._user_agent = user_agent
    self._token_uri = token_uri
    self._revoke_uri = revoke_uri
    self._kwargs = kwargs
    def __init__(self,
                 service_account_email,
                 signer,
                 scopes='',
                 private_key_id=None,
                 client_id=None,
                 user_agent=None,
                 **kwargs):

        super(ServiceAccountCredentials, self).__init__(
            None, user_agent=user_agent)

        self._service_account_email = service_account_email
        self._signer = signer
        self._scopes = util.scopes_to_string(scopes)
        self._private_key_id = private_key_id
        self.client_id = client_id
        self._user_agent = user_agent
        self._kwargs = kwargs
Exemplo n.º 21
0
def main():

     # Manage database
    totalCount_db, pcUser_db, calendar_db, drive_db, gmail_db, plus_db, lastFm_db, twitter_db, facebook_db = connection()

    # Path to client_secret file
    CLIENT_SECRET_FILE = 'C:\client_secret.json'
    # Google scopes used
    OAUTH_SCOPES = ['https://www.googleapis.com/auth/calendar.readonly',
                    'https://www.googleapis.com/auth/drive.readonly',
                    'https://www.googleapis.com/auth/gmail.readonly',
                    'https://www.googleapis.com/auth/plus.login',
                    'https://www.googleapis.com/auth/plus.me'
    ]

    # Location of the credentials storage file
    STORAGE = Storage('credentials.storage')

    # Try to retrieve credentials from storage or run the flow to generate them
    credentials = STORAGE.get()

    # Start the OAuth flow to retrieve credentials
    flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope = scopes_to_string(OAUTH_SCOPES))
    http = httplib2.Http()

    if credentials is None or credentials.invalid:
        credentials = run(flow, STORAGE, http = http)

    # Authorize the httplib2.Http object with our credentials
    http = credentials.authorize(http)
    
    print credentials.access_token_expired
    print credentials.to_json()
    
    # Authenticate and construct services
    calendar_service = build('calendar', 'v3', http = http)
    drive_service = build('drive', 'v2', http = http)
    gmail_service = build('gmail', 'v1', http = http)
    plus_service = build('plus', 'v1', http = http)

    while(True):
        #try:
        gmail.extract_subjects(gmail_service, '')
Exemplo n.º 22
0
    def __init__(self,
                 client_id,
                 client_secret,
                 scope,
                 auth_uri='https://accounts.google.com/o/oauth2/auth',
                 token_uri='https://accounts.google.com/o/oauth2/token',
                 user_agent=None,
                 message=None,
                 callback_path='/oauth2callback',
                 **kwargs):
        """Constructor for OAuth2Decorator

    Args:
      client_id: string, client identifier.
      client_secret: string client secret.
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      auth_uri: string, URI for authorization endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      token_uri: string, URI for token endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      user_agent: string, User agent of your application, default to None.
      message: Message to display if there are problems with the OAuth 2.0
        configuration. The message may contain HTML and will be presented on the
        web interface for any method that uses the decorator.
      callback_path: string, The absolute path to use as the callback URI. Note
        that this must match up with the URI given when registering the
        application in the APIs Console.
      **kwargs: dict, Keyword arguments are be passed along as kwargs to the
        OAuth2WebServerFlow constructor.
    """
        self.flow = None
        self.credentials = None
        self._client_id = client_id
        self._client_secret = client_secret
        self._scope = util.scopes_to_string(scope)
        self._auth_uri = auth_uri
        self._token_uri = token_uri
        self._user_agent = user_agent
        self._kwargs = kwargs
        self._message = message
        self._in_error = False
        self._callback_path = callback_path
Exemplo n.º 23
0
    def __init__(self, scope='', **kwargs):
        """Constructor for AppAssertionCredentials

        Args:
            scope: string or iterable of strings, scope(s) of the credentials
                   being requested. Using this argument will have no effect on
                   the actual scopes for tokens requested. These scopes are
                   set at VM instance creation time and won't change.
        """
        if scope:
            warnings.warn(_SCOPES_WARNING)
        # This is just provided for backwards compatibility, but is not
        # used by this class.
        self.scope = util.scopes_to_string(scope)
        self.kwargs = kwargs

        # Assertion type is no longer used, but still in the
        # parent class signature.
        super(AppAssertionCredentials, self).__init__(None)
Exemplo n.º 24
0
    def __init__(self,
                 service_account_email,
                 signer,
                 scopes='',
                 private_key_id=None,
                 client_id=None,
                 user_agent=None,
                 **kwargs):

        super(ServiceAccountCredentials, self).__init__(None,
                                                        user_agent=user_agent)

        self._service_account_email = service_account_email
        self._signer = signer
        self._scopes = util.scopes_to_string(scopes)
        self._private_key_id = private_key_id
        self.client_id = client_id
        self._user_agent = user_agent
        self._kwargs = kwargs
Exemplo n.º 25
0
    def test_multistore_file_backwards_compatibility(self):
        credentials = self._create_test_credentials()
        scopes = ['scope1', 'scope2']

        # store the credentials using the legacy key method
        store = multistore_file.get_credential_storage(
            FILENAME, 'client_id', 'user_agent', scopes)
        store.put(credentials)

        # retrieve the credentials using a custom key that matches the
        # legacy key
        key = {'clientId': 'client_id', 'userAgent': 'user_agent',
               'scope': util.scopes_to_string(scopes)}
        store = multistore_file.get_credential_storage_custom_key(
            FILENAME, key)
        stored_credentials = store.get()

        self.assertEqual(credentials.access_token,
                         stored_credentials.access_token)
Exemplo n.º 26
0
    def __init__(self, scope='', **kwargs):
        """Constructor for AppAssertionCredentials

        Args:
            scope: string or iterable of strings, scope(s) of the credentials
                   being requested. Using this argument will have no effect on
                   the actual scopes for tokens requested. These scopes are
                   set at VM instance creation time and won't change.
        """
        if scope:
            warnings.warn(_SCOPES_WARNING)
        # This is just provided for backwards compatibility, but is not
        # used by this class.
        self.scope = util.scopes_to_string(scope)
        self.kwargs = kwargs

        # Assertion type is no longer used, but still in the
        # parent class signature.
        super(AppAssertionCredentials, self).__init__(None)
Exemplo n.º 27
0
    def __init__(self, http, service_account_email, scopes, project='-'):
        """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account actor role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

        super(DelegateServiceAccountCredentials, self).__init__(None)
        self._service_account_email = service_account_email
        self._scopes = util.scopes_to_string(scopes)
        self._http = http
        self._name = 'projects/%s/serviceAccounts/%s' % (project,
                                                         service_account_email)
Exemplo n.º 28
0
    def test_multistore_file_backwards_compatibility(self):
        credentials = self._create_test_credentials()
        scopes = ['scope1', 'scope2']

        # store the credentials using the legacy key method
        store = multistore_file.get_credential_storage(
            FILENAME, 'client_id', 'user_agent', scopes)
        store.put(credentials)

        # retrieve the credentials using a custom key that matches the
        # legacy key
        key = {'clientId': 'client_id', 'userAgent': 'user_agent',
               'scope': util.scopes_to_string(scopes)}
        store = multistore_file.get_credential_storage_custom_key(
            FILENAME, key)
        stored_credentials = store.get()

        self.assertEqual(credentials.access_token,
                         stored_credentials.access_token)
Exemplo n.º 29
0
    def __init__(self,
        service_account_name,
        private_key,
        scope,
        private_key_password='******',
        user_agent=None,
        token_uri=GOOGLE_TOKEN_URI,
        revoke_uri=GOOGLE_REVOKE_URI,
        **kwargs):
      """Constructor for SignedJwtAssertionCredentials.

      Args:
        service_account_name: string, id for account, usually an email address.
        private_key: string, private key in PKCS12 or PEM format.
        scope: string or iterable of strings, scope(s) of the credentials being
          requested.
        private_key_password: string, password for private_key, unused if
          private_key is in PEM format.
        user_agent: string, HTTP User-Agent to provide for this application.
        token_uri: string, URI for token endpoint. For convenience
          defaults to Google's endpoints but any OAuth 2.0 provider can be used.
        revoke_uri: string, URI for revoke endpoint.
        kwargs: kwargs, Additional parameters to add to the JWT token, for
          example [email protected]."""

      super(SignedJwtAssertionCredentials, self).__init__(
          None,
          user_agent=user_agent,
          token_uri=token_uri,
          revoke_uri=revoke_uri,
          )

      self.scope = util.scopes_to_string(scope)

      # Keep base64 encoded so it can be stored in JSON.
      if isinstance(private_key, str):
          private_key = private_key.encode('ascii')
      self.private_key = base64.b64encode(private_key)

      self.private_key_password = private_key_password
      self.service_account_name = service_account_name
      self.kwargs = kwargs
Exemplo n.º 30
0
def get_credential_storage(filename, client_id, user_agent, scope,
                           warn_on_readonly=True):
  """Get a Storage instance for a credential.

  Args:
    filename: The JSON file storing a set of credentials
    client_id: The client_id for the credential
    user_agent: The user agent for the credential
    scope: string or iterable of strings, Scope(s) being requested
    warn_on_readonly: if True, log a warning if the store is readonly

  Returns:
    An object derived from client.Storage for getting/setting the
    credential.
  """
  # Recreate the legacy key with these specific parameters
  key = {'clientId': client_id, 'userAgent': user_agent,
         'scope': util.scopes_to_string(scope)}
  return get_credential_storage_custom_key(
      filename, key, warn_on_readonly=warn_on_readonly)
Exemplo n.º 31
0
  def __init__(self, client_id, client_secret, scope,
               auth_uri='https://accounts.google.com/o/oauth2/auth',
               token_uri='https://accounts.google.com/o/oauth2/token',
               user_agent=None,
               message=None,
               callback_path='/oauth2callback',
               **kwargs):

    """Constructor for OAuth2Decorator

    Args:
      client_id: string, client identifier.
      client_secret: string client secret.
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      auth_uri: string, URI for authorization endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      token_uri: string, URI for token endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      user_agent: string, User agent of your application, default to None.
      message: Message to display if there are problems with the OAuth 2.0
        configuration. The message may contain HTML and will be presented on the
        web interface for any method that uses the decorator.
      callback_path: string, The absolute path to use as the callback URI. Note
        that this must match up with the URI given when registering the
        application in the APIs Console.
      **kwargs: dict, Keyword arguments are be passed along as kwargs to the
        OAuth2WebServerFlow constructor.
    """
    self.flow = None
    self.credentials = None
    self._client_id = client_id
    self._client_secret = client_secret
    self._scope = util.scopes_to_string(scope)
    self._auth_uri = auth_uri
    self._token_uri = token_uri
    self._user_agent = user_agent
    self._kwargs = kwargs
    self._message = message
    self._in_error = False
    self._callback_path = callback_path
Exemplo n.º 32
0
  def __init__(self, client_id, client_secret, scope,
               redirect_uri=None,
               user_agent=None,
               auth_uri='https://accounts.google.com/o/oauth2/auth',
               token_uri='https://accounts.google.com/o/oauth2/token',
               **kwargs):
    """Constructor for OAuth2WebServerFlow.

    The kwargs argument is used to set extra query parameters on the
    auth_uri. For example, the access_type and approval_prompt
    query parameters can be set via kwargs.

    Args:
      client_id: string, client identifier.
      client_secret: string client secret.
      scope: string or iterable of strings, scope(s) of the credentials being
        requested.
      redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
          a non-web-based application, or a URI that handles the callback from
          the authorization server.
      user_agent: string, HTTP User-Agent to provide for this application.
      auth_uri: string, URI for authorization endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      token_uri: string, URI for token endpoint. For convenience
        defaults to Google's endpoints but any OAuth 2.0 provider can be used.
      **kwargs: dict, The keyword arguments are all optional and required
                        parameters for the OAuth calls.
    """
    self.client_id = client_id
    self.client_secret = client_secret
    self.scope = util.scopes_to_string(scope)
    self.redirect_uri = redirect_uri
    self.user_agent = user_agent
    self.auth_uri = auth_uri
    self.token_uri = token_uri
    self.params = {
        'access_type': 'offline',
        'response_type': 'code',
        }
    self.params.update(kwargs)
Exemplo n.º 33
0
        def __init__(self,
                     service_account_name,
                     private_key,
                     scope,
                     private_key_password='******',
                     user_agent=None,
                     token_uri=GOOGLE_TOKEN_URI,
                     revoke_uri=GOOGLE_REVOKE_URI,
                     **kwargs):
            """Constructor for SignedJwtAssertionCredentials.

      Args:
        service_account_name: string, id for account, usually an email address.
        private_key: string, private key in PKCS12 or PEM format.
        scope: string or iterable of strings, scope(s) of the credentials being
          requested.
        private_key_password: string, password for private_key, unused if
          private_key is in PEM format.
        user_agent: string, HTTP User-Agent to provide for this application.
        token_uri: string, URI for token endpoint. For convenience
          defaults to Google's endpoints but any OAuth 2.0 provider can be used.
        revoke_uri: string, URI for revoke endpoint.
        kwargs: kwargs, Additional parameters to add to the JWT token, for
          example [email protected]."""

            super(SignedJwtAssertionCredentials, self).__init__(
                None,
                user_agent=user_agent,
                token_uri=token_uri,
                revoke_uri=revoke_uri,
            )

            self.scope = util.scopes_to_string(scope)

            # Keep base64 encoded so it can be stored in JSON.
            self.private_key = base64.b64encode(private_key)

            self.private_key_password = private_key_password
            self.service_account_name = service_account_name
            self.kwargs = kwargs
Exemplo n.º 34
0
    def __init__(self,
                 service_account_email,
                 signer,
                 scopes='',
                 private_key_id=None,
                 client_id=None,
                 user_agent=None,
                 token_uri=oauth2client.GOOGLE_TOKEN_URI,
                 revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
                 **kwargs):  # noqa

        super(ServiceAccountCredentials, self).__init__(
            None, user_agent=user_agent, token_uri=token_uri,
            revoke_uri=revoke_uri)

        self._service_account_email = service_account_email
        self._signer = signer
        self._scopes = util.scopes_to_string(scopes)
        self._private_key_id = private_key_id
        self.client_id = client_id
        self._user_agent = user_agent
        self._kwargs = kwargs
Exemplo n.º 35
0
    def __init__(self,
                 service_account_email,
                 signer,
                 scopes='',
                 private_key_id=None,
                 client_id=None,
                 user_agent=None,
                 token_uri=GOOGLE_TOKEN_URI,
                 revoke_uri=GOOGLE_REVOKE_URI,
                 **kwargs):

        super(ServiceAccountCredentials, self).__init__(
            None, user_agent=user_agent, token_uri=token_uri,
            revoke_uri=revoke_uri)

        self._service_account_email = service_account_email
        self._signer = signer
        self._scopes = util.scopes_to_string(scopes)
        self._private_key_id = private_key_id
        self.client_id = client_id
        self._user_agent = user_agent
        self._kwargs = kwargs
Exemplo n.º 36
0
    def __init__(self,
        service_account_name,
        private_key,
        scope,
        private_key_password='******',
        user_agent=None,
        token_uri='https://accounts.google.com/o/oauth2/token',
        **kwargs):
      """Constructor for SignedJwtAssertionCredentials.

      Args:
        service_account_name: string, id for account, usually an email address.
        private_key: string, private key in PKCS12 or PEM format.
        scope: string or iterable of strings, scope(s) of the credentials being
          requested.
        private_key_password: string, password for private_key, unused if
          private_key is in PEM format.
        user_agent: string, HTTP User-Agent to provide for this application.
        token_uri: string, URI for token endpoint. For convenience
          defaults to Google's endpoints but any OAuth 2.0 provider can be used.
        kwargs: kwargs, Additional parameters to add to the JWT token, for
          example [email protected]."""

      super(SignedJwtAssertionCredentials, self).__init__(
          'http://oauth.net/grant_type/jwt/1.0/bearer',
          user_agent=user_agent,
          token_uri=token_uri,
          )

      self.scope = util.scopes_to_string(scope)

      # Keep base64 encoded so it can be stored in JSON.
      self.private_key = base64.b64encode(private_key)

      self.private_key_password = private_key_password
      self.service_account_name = service_account_name
      self.kwargs = kwargs
def get_credential_storage(filename, client_id, user_agent, scope,
                           warn_on_readonly=True):
  """Get a Storage instance for a credential.

  Args:
    filename: The JSON file storing a set of credentials
    client_id: The client_id for the credential
    user_agent: The user agent for the credential
    scope: string or iterable of strings, Scope(s) being requested
    warn_on_readonly: if True, log a warning if the store is readonly

  Returns:
    An object derived from client.Storage for getting/setting the
    credential.
  """
  filename = os.path.expanduser(filename)
  _multistores_lock.acquire()
  try:
    multistore = _multistores.setdefault(
        filename, _MultiStore(filename, warn_on_readonly=warn_on_readonly))
  finally:
    _multistores_lock.release()
  scope = util.scopes_to_string(scope)
  return multistore._get_storage(client_id, user_agent, scope)