Python oauth2client.client.SignedJwtAssertionCredentials() Examples

The following are 13 code examples of oauth2client.client.SignedJwtAssertionCredentials(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oauth2client.client , or try the search function .
Example #1
Source File: credentials_utils.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def _GetSignedJwtAssertionCredentials(user_email):
  """Retrieve an OAuth2 credentials object impersonating user_email.

  This object is then used to authorize an http connection that will be
  used to connect with Google services such as the Admin SDK.
  Also includes an access_token that is used to connect to IMAP.

  The first parameter, service_account_name,is the Email address
  created for the Service account from the API Console.  The sub parameter
  is the Authenticated user to impersonate.

  Args:
    user_email: String of the user email account to impersonate.

  Returns:
    oauth2client credentials object.
  """
  return client.SignedJwtAssertionCredentials(
      service_account_name=service_account.SERVICE_ACCOUNT_NAME,
      private_key=_SERVICE_ACCOUNT_KEY,
      scope=service_account.SERVICE_SCOPES,
      sub=user_email) 
Example #2
Source File: utils.py    From twitter-for-bigquery with Apache License 2.0 6 votes vote down vote up
def get_bq():
        
        if Utils.BQ_CLIENT:
            
            return Utils.BQ_CLIENT
        
        BQ_CREDENTIALS = None
        
        # If runing on Google stack, authenticate natively
        if Utils.isGae():
            
            from oauth2client import appengine
            BQ_CREDENTIALS = appengine.AppAssertionCredentials(scope='https://www.googleapis.com/auth/bigquery')

        else:
            
            from oauth2client.client import SignedJwtAssertionCredentials
            KEY = Utils.read_file(config.KEY_FILE)
            BQ_CREDENTIALS = SignedJwtAssertionCredentials(config.SERVICE_ACCOUNT, KEY, 'https://www.googleapis.com/auth/bigquery')
    
        BQ_HTTP = BQ_CREDENTIALS.authorize(httplib2.Http())
        Utils.BQ_CLIENT = build('bigquery', 'v2', http=BQ_HTTP)
        
        return  Utils.BQ_CLIENT 
Example #3
Source File: test_google.py    From sneaky-creeper with MIT License 6 votes vote down vote up
def setUp(self):

        configPath = os.path.join(basePath, 'config', 'google-config.json')
        try:
            with open(configPath, 'rb') as f:
                s = json.loads(f.read())
        except:
            raise SkipTest("Could not access Google configuration file.")

        self.params = s['google']

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = SignedJwtAssertionCredentials(self.params['client_email'], self.params['private_key'], scope)       
        gc = gspread.authorize(credentials)
        
        self.client = gc.open(self.params['google_sheet']).sheet1
        self.randText = ''.join([random.choice(string.letters) for i in range(10)])

        self.channel = googleSpread.GoogleSpread()
        self.channel.params['sending'] = self.params
        self.channel.params['receiving'] = self.params 
Example #4
Source File: googleSpread.py    From sneaky-creeper with MIT License 6 votes vote down vote up
def send(self, data):
        CLIENT_EMAIL = self.param('sending', 'client_email')
        PRIVATE_KEY = self.param('sending', 'private_key')
        GOOGLE_SPREAD = self.param('sending', 'google_sheet')

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = SignedJwtAssertionCredentials(CLIENT_EMAIL, PRIVATE_KEY, scope)
        gc = gspread.authorize(credentials)
        sheet = gc.open(GOOGLE_SPREAD).sheet1

        WRITE_COL = self.param('sending', 'column')
        row = 1
        while sheet.acell(WRITE_COL+str(row)).value:
            row += 1
        cell = WRITE_COL + str(row)

        sheet.update_acell(cell, data)
        return 
Example #5
Source File: googleSpread.py    From sneaky-creeper with MIT License 6 votes vote down vote up
def receive(self):
        CLIENT_EMAIL = self.param('receiving', 'client_email')
        PRIVATE_KEY = self.param('receiving', 'private_key')
        GOOGLE_SPREAD = self.param('receiving', 'google_sheet')

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = SignedJwtAssertionCredentials(CLIENT_EMAIL, PRIVATE_KEY, scope)
        gc = gspread.authorize(credentials)
        sheet = gc.open(GOOGLE_SPREAD).sheet1

        READ_COL = self.param('receiving', 'column')

        cells = []
        row = 1

        while sheet.acell(READ_COL+str(row)).value:
            cells.append(sheet.acell(READ_COL+str(row)).value)
            row += 1

        return cells 
Example #6
Source File: auth.py    From edx2bigquery with GNU General Public License v2.0 5 votes vote down vote up
def get_service_acct_creds(key_file, verbose=False):
  '''Generate service account credentials using the given key file.
    key_file: path to file containing private key.
  '''
  ### backcompatability for .p12 keyfiles
  if key_file.endswith('.p12') or key_file.endswith('.pem'):
    from edx2bigquery_config import auth_service_acct as SERVICE_ACCT
    if verbose:
      print "using key file"
      print "service_acct=%s, key_file=%s" % (SERVICE_ACCT, KEY_FILE)
    try:
      creds = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCT,
        key_file,
        scopes=BIGQUERY_SCOPE)
    except Exception as err:			# fallback to old google SignedJwtAssertionCredentials call
      with open (key_file, 'rb') as f:
        key = f.read();
        creds = SignedJwtAssertionCredentials(
          SERVICE_ACCT, 
          key,
          BIGQUERY_SCOPE)
    return creds
  ###
  creds = ServiceAccountCredentials.from_json_keyfile_name(
    key_file,
    BIGQUERY_SCOPE)
  return creds 
Example #7
Source File: main.py    From billing-export-python with Apache License 2.0 5 votes vote down vote up
def UseRemoteGCS():
    """Use remote GCS via a signed certificate."""
    logging.debug('Using remote gcs.')
    try:
        from oauth2client.client import SignedJwtAssertionCredentials
    except ImportError:
        logging.error('For local testing with remote GCS, install pycrypto.')
        return
    http_object = httplib2.Http(timeout=60)
    service_account = config.service_account
    private_key_pem_file = config.private_key_pem_file
    scope = 'https://www.googleapis.com/auth/devstorage.full_control'
    private_key = file(private_key_pem_file, 'rb').read()
    certificate = SignedJwtAssertionCredentials(service_account,
                                                private_key,
                                                scope)
    certificate.refresh(http_object)
    gcs_common.set_access_token(certificate.access_token)


# Do convolutions to speak to remote cloud storage even when on a local
# devserver. If you want to communicate to remote GCS, rather then use local
# GCS stubs, set this value in config.py to true. It requires setting:
# config.service_account and config.private_key_pem_file from a project service
# account.
# 
Example #8
Source File: os_utilities.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _get_oauth2_client(service_account_json_file, scopes):
  with open(service_account_json_file) as f:
    service_account_json = json.load(f)
  return client.SignedJwtAssertionCredentials(
      service_account_json['client_email'], service_account_json['private_key'],
      scopes)


### Android. 
Example #9
Source File: googledata.py    From danforth-east with MIT License 5 votes vote down vote up
def __init__(self):
        try:
            urlfetch.set_default_fetch_deadline(_TIMEOUT)
        except:
            # urlfetch.set_default_fetch_deadline may not exist
            pass

        self._http = httplib2.Http(timeout=_TIMEOUT)

        with open(config.SERVICE_ACCOUNT_PEM_FILE_PATH, 'rb') as keyfile:
            key = keyfile.read()

        credentials = SignedJwtAssertionCredentials(
            config.SERVICE_ACCOUNT_EMAIL,
            key,
            scope=config.SCOPE)

        self._http = credentials.authorize(self._http)

        self._headers = {'Content-type': 'application/atom+xml',}

        self._drive_service = None


    #
    # Worksheets operations
    # 
Example #10
Source File: baton_tags.py    From django-baton with MIT License 5 votes vote down vote up
def analytics(context, next=None):

    analytics_settings = get_config('ANALYTICS')

    if not analytics_settings['CREDENTIALS']:
        raise ImproperlyConfigured('Analytics service account json path missing') # noqa

    if not analytics_settings['VIEW_ID']:
        raise ImproperlyConfigured('Analytics view id missing')

    # The scope for the OAuth2 request.
    SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'

    # The location of the key file with the key data.
    KEY_FILEPATH = analytics_settings['CREDENTIALS']

    # Load the key file's private data.
    with open(KEY_FILEPATH) as key_file:
        _key_data = json.load(key_file)

    # Construct a credentials objects from the key data and OAuth2 scope.
    _credentials = SignedJwtAssertionCredentials(
        _key_data['client_email'], _key_data['private_key'], SCOPE)

    return {
        'token': _credentials.get_access_token().access_token,
        'view_id': analytics_settings['VIEW_ID']
    } 
Example #11
Source File: google.py    From Raspberry_Pi_Weather_Station with GNU General Public License v2.0 5 votes vote down vote up
def login_open_sheet(oauth_key_file, spreadsheet):
	"""Connect to Google Docs spreadsheet and return the first worksheet."""
	try:
		json_key = json.load(open(oauth_key_file))
		credentials = SignedJwtAssertionCredentials(json_key['client_email'],
													json_key['private_key'],
													['https://spreadsheets.google.com/feeds'])
		gc = gspread.authorize(credentials)
		worksheet = gc.open(spreadsheet).sheet1
		return worksheet
	except Exception as ex:
		print 'Unable to login and get spreadsheet.  Check OAuth credentials, spreadsheet name, and make sure spreadsheet is shared to the client_email address in the OAuth .json file!'
		print 'Google sheet login failed with error:', ex
		sys.exit(1) 
Example #12
Source File: google_spreadsheet.py    From Raspberry_Pi_Weather_Station with GNU General Public License v2.0 5 votes vote down vote up
def login_open_sheet(oauth_key_file, spreadsheet):
	"""Connect to Google Docs spreadsheet and return the first worksheet."""
	try:
		json_key = json.load(open(oauth_key_file))
		credentials = SignedJwtAssertionCredentials(json_key['client_email'], 
													json_key['private_key'], 
													['https://spreadsheets.google.com/feeds'])
		gc = gspread.authorize(credentials)
		worksheet = gc.open(spreadsheet).sheet1
		return worksheet
	except Exception as ex:
		print 'Unable to login and get spreadsheet.  Check OAuth credentials, spreadsheet name, and make sure spreadsheet is shared to the client_email address in the OAuth .json file!'
		print 'Google sheet login failed with error:', ex
		sys.exit(1) 
Example #13
Source File: utils.py    From df2gspread with GNU General Public License v3.0 4 votes vote down vote up
def create_service_credentials(private_key_file=None, client_email=None,
                               client_secret_file=CLIENT_SECRET_FILE):
    """Create credentials from service account information.

    See Also:
        https://developers.google.com/api-client-library/python/auth/service-accounts

    Args:
        client_secret_file (str): path to json file with just the client_email when
            providing the `private_key_file` separately, or this file can have both the
            `client_email` and `private_key` contained in it. Defaults to .gdrive_private
        client_email (str): service email account
        private_key_file (str): path to the p12 private key, defaults to same name of file
            used for regular authentication

    Returns:
        `~oauth2client.client.OAuth2Credentials`: google credentials object

    """
    if private_key_file is not None:
        with open(os.path.expanduser(private_key_file)) as f:
            private_key = f.read()
    else:
        private_key = None

    if client_email is None:
        with open(os.path.expanduser(client_secret_file)) as client_file:
            client_data = json.load(client_file)

            if 'installed' in client_data:

                # handle regular json format where key is separate
                client_email = client_data['installed']['client_id']
                if private_key is None:
                    raise RuntimeError('You must have the private key file \
                                       with the regular json file. Try creating a new \
                                       public/private key pair and downloading as json.')
            else:
                # handle newer case where json file has everything in it
                client_email = client_data['client_email']
                private_key = client_data['private_key']

    if client_email is None or private_key is None:
        raise RuntimeError(
            'Client email and/or private key not provided by inputs.')

    credentials = client.SignedJwtAssertionCredentials(
        client_email, private_key, SCOPES)

    return credentials