コード例 #1
0
def main():
    '''
    main function
    '''

    with open(settings.SERVICE_ACCOUNT_JSON) as json_file:

        json_data = json.load(json_file)
        #print json_data
        credentials = SignedJwtAssertionCredentials(
            json_data['client_email'],
            json_data['private_key'],
            scope=
            'https://www.googleapis.com/auth/admin.reports.audit.readonly',
            access_type='offline',
            approval_prompt='force',
            sub=email)

    storage = Storage(settings.STORAGE_FILE)

    storage.put(credentials)
    #credentials = storage.get()
    credentials.get_access_token()

    if test:
        print credentials.__dict__
        #print credentials.access_token

    http = httplib2.Http()
    auth = credentials.authorize(http)
    # refresh does not seem to work
    credentials.refresh(http)
    print credentials.__dict__
コード例 #2
0
def _auth(service_account, private_key, scopes, **kwargs):
    credentials = SignedJwtAssertionCredentials(service_account,
                                                bytes(private_key, "utf-8"),
                                                scopes,
                                                **kwargs)
    credentials.refresh(httplib2.Http())
    return credentials.authorize(httplib2.Http())
コード例 #3
0
 def __credentials(self):
     credentials = SignedJwtAssertionCredentials(
         self.__login,
         self.__key,
         scope='https://www.googleapis.com/auth/devstorage.read_write')
     credentials.refresh(httplib2.Http())
     return credentials.access_token
コード例 #4
0
def main():
    """
    main function
    """

    with open(settings.SERVICE_ACCOUNT_JSON) as json_file:

        json_data = json.load(json_file)
        #print json_data
        credentials = SignedJwtAssertionCredentials(
            json_data['client_email'],
            json_data['private_key'],
            scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/',
            access_type="offline",
            approval_prompt = "force",
            sub=email
        )

    storage = Storage(settings.STORAGE_FILE)

    storage.put(credentials)
    #credentials = storage.get()
    credentials.get_access_token()

    if test:
        print credentials.__dict__
        #print credentials.access_token

    http = httplib2.Http()
    auth = credentials.authorize(http)
    # refresh does not seem to work
    credentials.refresh(http)
    print credentials.__dict__
コード例 #5
0
def get_credentials(sub=None):
  '''
  Signed JWT Credentials allow for frictionless authentication
  using a private key as opposed to a three-legged oauth flow.
  '''

  # fetch the credentials object from memcache.
  credentials = memcache.get("rapid-reseller#credentials#%s" % sub)

  if credentials is None or credentials.invalid:
    logging.info("Couldn't find cached token, refreshing")

    http = httplib2.Http()

    # read private key.
    f = file(settings.OAUTH2_PRIVATEKEY)
    key = f.read()
    f.close()

    # establish the credentials.
    credentials = SignedJwtAssertionCredentials(
      service_account_name=settings.OAUTH2_SERVICE_ACCOUNT_EMAIL,
      private_key=key,
      scope=" ".join(settings.OAUTH2_SCOPES),
      sub=sub)

    # force the generation of an access token
    credentials.refresh(http)

    # cache the token for 59 minutes.
    memcache.set("rapid-reseller#credentials#%s" % sub,
                 value=credentials,
                 time=(60 * 59))

  return credentials
コード例 #6
0
ファイル: client.py プロジェクト: Labgoo/PyBigQuery
    def get_http_for_request(self):
        if self.use_jwt_credentials_auth:  # Local debugging using pem file
            scope = 'https://www.googleapis.com/auth/bigquery'
            from oauth2client.client import SignedJwtAssertionCredentials
            credentials = SignedJwtAssertionCredentials(self.jwt_account_name, self.jwt_key_func(), scope=scope)
            logging.info("Using Standard jwt authentication")
            return credentials.authorize(httplib2.Http())

        elif self.is_in_appengine():  # App engine
            from google.appengine.api import memcache
            scope = 'https://www.googleapis.com/auth/bigquery'
            credentials = AppAssertionCredentials(scope=scope)
            logging.info("Using Standard appengine authentication")
            return credentials.authorize(httplib2.Http(memcache))

        elif self.oauth_credentails_file:  # Local oauth token
            http = httplib2.Http()
            storage = Storage(self.oauth_credentails_file)
            credentials = storage.get()
            if not credentials:
                raise EnvironmentError('No credential file present')
            http = credentials.authorize(http)
            credentials.refresh(http)
            logging.info("Using Standard OAuth authentication")
            return http

        elif self.is_in_gce_machine():  # GCE authorization
            http = httplib2.Http()
            credentials = gce.AppAssertionCredentials('')
            http = credentials.authorize(http)
            credentials.refresh(http)
            logging.info("Using GCE authentication")
            return http

        raise BigQueryAuthorizationError()
コード例 #7
0
    def get_auth_token(self):
        scope = ['https://spreadsheets.google.com/feeds']
        credentials = SignedJwtAssertionCredentials(
            self.auth_key['client_email'], self.auth_key['private_key'], scope)

        credentials.refresh(httplib2.Http())
        return credentials.token_response["access_token"]
コード例 #8
0
def main():
    """
    main function
    """

    with open(settings.SERVICE_ACCOUNT_JSON) as json_file:

        json_data = json.load(json_file)
        #print json_data
        credentials = SignedJwtAssertionCredentials(
            json_data['client_email'],
            json_data['private_key'],
            scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/',
            access_type="offline",
            approval_prompt="force",
            sub=email)

    storage = Storage(settings.STORAGE_FILE)

    storage.put(credentials)
    #credentials = storage.get()
    credentials.get_access_token()

    if test:
        print credentials.__dict__
        #print credentials.access_token

    http = httplib2.Http()
    auth = credentials.authorize(http)
    # refresh does not seem to work
    credentials.refresh(http)
    print credentials.__dict__
コード例 #9
0
ファイル: oauth2_client.py プロジェクト: jkff/gsutil
 def FetchAccessToken(self):
   credentials = SignedJwtAssertionCredentials(self.client_id,
       self.private_key, scope=GSUTIL_DEFAULT_SCOPE, 
       private_key_password=self.password)
   http = self.CreateHttpRequest()
   credentials.refresh(http)
   return AccessToken(credentials.access_token, 
       credentials.token_expiry, datetime_strategy=self.datetime_strategy)
コード例 #10
0
 def _get_creds(self):
     if not module_enabled:
         raise Exception('GCS module is disabled')
     credentials = SignedJwtAssertionCredentials(
         CloudBufferTokenGCS.client_email, CloudBufferTokenGCS.private_key,
         CloudBufferTokenGCS.scope)
     credentials.refresh(Http())
     return credentials.access_token
コード例 #11
0
ファイル: oauth.py プロジェクト: zeapo/lumRest
 def getCredentials(email, scopes, client_secret, client_id):
     key = file(client_secret, 'rb')
     privateKey = key.read()
     key.close()
     credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email)
     http = httplib2.Http()
     http = credentials.authorize(http)
     credentials.refresh(http)
     return credentials, http
コード例 #12
0
ファイル: api.py プロジェクト: bobbyjoe/layercake
def connect():
	storage = Storage('creds.dat')
	credentials = storage.get()
	if credentials is None or credentials.invalid:
		credentials = SignedJwtAssertionCredentials(config.EMAIL_ADDRESS, key, scope=config.SCOPES)
		storage.put(credentials)
	else:
		http = httplib2.Http()
		credentials.refresh(http)
	return credentials
コード例 #13
0
ファイル: gmailbackup.py プロジェクト: jkrauska/google-backup
    def impersonate_user(self, scope='https://mail.google.com/'):
        self.logger.debug("Impersonating user")
        f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
        key = f.read()
        f.close()

        credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
            scope=scope, sub=self.user_email)
        http = httplib2.Http(".cache")
        http = credentials.authorize(http)
        credentials.refresh(http)
        return credentials
コード例 #14
0
    def _impersonate_user(self, scope):
        assert scope

        self.logger.debug("Impersonating user %s", self.user_email)
        with open(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb') as f:
            key = f.read()

        credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, scope=scope, sub=self.user_email)
        http = httplib2.Http(".cache")
        http = credentials.authorize(http)
        credentials.refresh(http)
        return (http, credentials)
コード例 #15
0
def get_spreadsheet(auth_key=getattr(settings, "GAUTH_CREDENTIALS", None),
                    spreadsheet=getattr(settings, "SPREADSHEET_ID", None)):
    """
    Helper to authenticate on google drive and obtain spreadsheet object.
    """
    credentials = SignedJwtAssertionCredentials(
        auth_key['client_email'], auth_key['private_key'],
        ['https://spreadsheets.google.com/feeds'])

    credentials.refresh(httplib2.Http())

    gc = gspread.authorize(credentials)
    return gc.open_by_key(spreadsheet)
コード例 #16
0
    def impersonate_user(self, scope='https://mail.google.com/'):
        self.logger.debug("Impersonating user")
        f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
        key = f.read()
        f.close()

        credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL,
                                                    key,
                                                    scope=scope,
                                                    sub=self.user_email)
        http = httplib2.Http(".cache")
        http = credentials.authorize(http)
        credentials.refresh(http)
        return credentials
コード例 #17
0
ファイル: oauth2_client.py プロジェクト: lotten/gsutil
  def FetchAccessToken(self, refresh_token):
    credentials = SignedJwtAssertionCredentials(self.client_id,
        self.private_key, scope=GSUTIL_DEFAULT_SCOPE, 
        private_key_password=self.password)
    ca_certs = os.path.join(
        os.path.dirname(os.path.abspath(cacerts.__file__ )), "cacerts.txt")
    
    http = httplib2.Http(
        ca_certs=ca_certs,
        disable_ssl_certificate_validation
            = self.disable_ssl_certificate_validation)
    credentials.authorize(http)
    credentials.refresh(http)

    return AccessToken(http.request.credentials.access_token, 
        credentials.token_expiry, datetime_strategy=self.datetime_strategy)
コード例 #18
0
  def get_access_token(self):
       storage = Storage(CREDENTIALS_STORAGE)
       credentials = storage.get()
       http = httplib2.Http()

       if credentials is None or credentials.invalid:
         with open(PRIVATE_KEY_PATH, 'rb') as f:
            private_key = json.loads(f.read()).get("private_key")
         credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL,
                                                    private_key,
                                                    scope='https://www.googleapis.com/auth/sqlservice.admin')
         storage.put(credentials)
       else:
         credentials.refresh(http)

       return credentials
def oauthSheets():
	####--logging.info("Authenticating using OAuth for Google Sheets")
	f = file('%s/%s' % (SITE_ROOT,'data/key/sheets.p12'), 'rb')
	key = f.read()
	f.close()
	http = httplib2.Http()
	storage = Storage(SITE_ROOT + '/data/sheets.dat')
	credentials = storage.get()
	if credentials is None or credentials.invalid:
		credentials = SignedJwtAssertionCredentials(google_api_user, key, scope='https://spreadsheets.google.com/feeds/',sub=google_user)
		storage.put(credentials)
	else:
		credentials.refresh(http)
	http = httplib2.Http()
	http = credentials.authorize(http)
	gc = gspread.authorize(credentials)
	return gc
コード例 #20
0
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)
コード例 #21
0
    def get_access_token(self):
        storage = Storage(CREDENTIALS_STORAGE)
        credentials = storage.get()
        http = httplib2.Http()

        if credentials is None or credentials.invalid:
            with open(PRIVATE_KEY_PATH, 'rb') as f:
                private_key = json.loads(f.read()).get("private_key")
            credentials = SignedJwtAssertionCredentials(
                SERVICE_ACCOUNT_EMAIL,
                private_key,
                scope='https://www.googleapis.com/auth/sqlservice.admin')
            storage.put(credentials)
        else:
            credentials.refresh(http)

        return credentials
コード例 #22
0
ファイル: main.py プロジェクト: IanGSY/billing-export-python
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)
コード例 #23
0
def get_google_drive_service():
    storage = Storage(app.config['GOOGLE_CREDENTIALS_PATH'])
    credentials = storage.get()
    http = httplib2.Http()

    if credentials is None or credentials.invalid:
        email = app.config['GOOGLE_SERVICE_EMAIL']
        key = app.config['GOOGLE_PRIVATE_KEY']
        scope = app.config['GOOGLE_SERVICE_SCOPE']
        credentials = SignedJwtAssertionCredentials(email, key, scope=scope)
        storage.put(credentials)
    else:
        credentials.refresh(http)

    name = app.config['GOOGLE_SERVICE_NAME']
    version = app.config['GOOGLE_SERVICE_API_VERSION']
    http = credentials.authorize(http)
    return build(serviceName=name, version=version, http=http)
コード例 #24
0
def get_service():
    storage = Storage(CREDENTIALS_STORAGE)
    credentials = storage.get()
    http = httplib2.Http()

    if credentials is None or credentials.invalid:
        with open(PRIVATE_KEY_PATH, 'rb') as f:
            private_key = f.read()
        credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL,
                                                    private_key,
                                                    scope=SERVICE_SCOPE)
        storage.put(credentials)
    else:
        credentials.refresh(http)

    http = credentials.authorize(http)
    return build(serviceName=SERVICE_NAME,
                 version=SERVICE_API_VERSION,
                 http=http)
コード例 #25
0
ファイル: apilib.py プロジェクト: omnibond/IdmScriptingGoogle
def get_service(name, version, scopes, admin_email, client_email, key_file,
                storage_file, **kwargs):
    """
	Helper for initializing a Google API Client service.
	
	:param name: the API name
	:param version:
	:param storage_file:
	:param scopes:
	:param admin_email:
	:param client_email:
	:param key_file:
	"""
    # name = service_kwargs['name']
    # version = service_kwargs['version']
    # storage_file = service_kwargs['storage_file']

    http = httplib2.Http(timeout=10)
    storage = Storage(storage_file)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        # scopes = service_kwargs['scopes']
        # admin_email = service_kwargs['admin_email']
        # client_email = service_kwargs['client_email']
        # key_file = service_kwargs['key_file']

        with open(key_file) as f:
            private_key = f.read()

        credentials = SignedJwtAssertionCredentials(client_email,
                                                    private_key,
                                                    scopes,
                                                    sub=admin_email)

        storage.put(credentials)
    else:
        credentials.refresh(http)

    http = credentials.authorize(http)
    service = build(name, version, http=http)

    return service
コード例 #26
0
ファイル: apilib.py プロジェクト: omnibond/IdmScriptingGoogle
def get_service(name, version, scopes, admin_email,
		client_email, key_file, storage_file, **kwargs):
	"""
	Helper for initializing a Google API Client service.
	
	:param name: the API name
	:param version:
	:param storage_file:
	:param scopes:
	:param admin_email:
	:param client_email:
	:param key_file:
	"""
	# name = service_kwargs['name']
	# version = service_kwargs['version']
	# storage_file = service_kwargs['storage_file']
	
	http = httplib2.Http(timeout=10)
	storage = Storage(storage_file)
	credentials = storage.get()
	
	if credentials is None or credentials.invalid:
		# scopes = service_kwargs['scopes']
		# admin_email = service_kwargs['admin_email']
		# client_email = service_kwargs['client_email']
		# key_file = service_kwargs['key_file']
		
		with open(key_file) as f:
			private_key = f.read()
		
		credentials = SignedJwtAssertionCredentials(
			client_email, private_key, scopes, sub=admin_email)
		
		storage.put(credentials)
	else:
		credentials.refresh(http)
	
	http = credentials.authorize(http)
	service = build(name, version, http=http)
	
	return service
	
def oauthSheets():
    ####--logging.info("Authenticating using OAuth for Google Sheets")
    f = file('%s/%s' % (SITE_ROOT, 'data/key/sheets.p12'), 'rb')
    key = f.read()
    f.close()
    http = httplib2.Http()
    storage = Storage(SITE_ROOT + '/data/sheets.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = SignedJwtAssertionCredentials(
            google_api_user,
            key,
            scope='https://spreadsheets.google.com/feeds/',
            sub=google_user)
        storage.put(credentials)
    else:
        credentials.refresh(http)
    http = httplib2.Http()
    http = credentials.authorize(http)
    gc = gspread.authorize(credentials)
    return gc
コード例 #28
0
    def get_service(self):
        if self.service:
            return self.service

        else:
            http = httplib2.Http()
            storage = Storage(settings.GCALSYNC_CREDENTIALS)
            credentials = storage.get()

            if credentials is None or credentials.invalid == True:
                    f = file(settings.GCALSYNC_CREDENTIALS_KEY, 'rb')
                    key = f.read()
                    f.close()
                    credentials = SignedJwtAssertionCredentials(settings.GCALSYNC_CREDENTIALS_EMAIL, key , scope="https://www.googleapis.com/auth/calendar")
                    storage.put(credentials)
            else:
                credentials.refresh(http)

            http = credentials.authorize(http)

            self.service = build("calendar", "v3", http=http)
            return self.service
コード例 #29
0
ファイル: gaclient.py プロジェクト: iselu/tornado-analytics
    def get_service(self, api_name, api_version, scope, key_file_location,
                    service_account_email):
        """Get a service that communicates to a Google API.

        Args:
          api_name: The name of the api to connect to.
          api_version: The api version to connect to.
          scope: A list auth scopes to authorize for the application.
          key_file_location: The path to a valid service account p12 key file.
          service_account_email: The service account email address.

        Returns:
          A service that is connected to the specified API.
        """
        # reusing saved credentials
        storage = Storage("ta_saved_credentials.dat")
        http = httplib2.Http()

        credentials = storage.get()
        if credentials is None or credentials.invalid:
            print("credentials not found, authorizing")
            f = open(key_file_location, 'rb')
            key = f.read()
            f.close()
            credentials = SignedJwtAssertionCredentials(service_account_email,
                                                        key,
                                                        scope=scope)
            storage.put(credentials)
        else:
            print("credentials found")
            credentials.refresh(http)

        http = credentials.authorize(httplib2.Http())

        # Build the service object.
        service = build(api_name, api_version, http=http)

        return service
コード例 #30
0
ファイル: gaclient.py プロジェクト: iselu/tornado-analytics
    def get_service(self, api_name, api_version, scope, key_file_location,
                    service_account_email):
        """Get a service that communicates to a Google API.

        Args:
          api_name: The name of the api to connect to.
          api_version: The api version to connect to.
          scope: A list auth scopes to authorize for the application.
          key_file_location: The path to a valid service account p12 key file.
          service_account_email: The service account email address.

        Returns:
          A service that is connected to the specified API.
        """
        # reusing saved credentials
        storage = Storage("ta_saved_credentials.dat")
        http = httplib2.Http()

        credentials = storage.get()
        if credentials is None or credentials.invalid:
            print("credentials not found, authorizing")
            f = open(key_file_location, 'rb')
            key = f.read()
            f.close()
            credentials = SignedJwtAssertionCredentials(service_account_email, key, scope=scope)
            storage.put(credentials)
        else:
            print("credentials found")
            credentials.refresh(http)

        http = credentials.authorize(httplib2.Http())

        # Build the service object.
        service = build(api_name, api_version, http=http)

        return service
コード例 #31
0
ファイル: cli.py プロジェクト: keithmoss/Hodor
    def get_authenticated_service(self, scope, version):
      self.vlog('Authenticating...')

      credential_storage = CredentialStorage(self.CREDENTIALS_STORE)
      credentials = credential_storage.get()
      http = httplib2.Http()

      if credentials is None or credentials.invalid:
        # Service Account
        if self.auth_type == 'service-account':
          with open(self.CREDENTIALS_SERVICE_ACC) as f:
            config = json.load(f)

          credentials = SignedJwtAssertionCredentials(
            service_account_name=config['client_email'],
            private_key=config['private_key'],
            scope=self.RW_SCOPE
          )
        else:
        # Web Flow
          if os.path.isfile(self.CREDENTIALS_NATIVE_APP):
            with open(self.CREDENTIALS_NATIVE_APP) as f:
              config = json.load(f)
          else:
            # This is OK according to Google
            # http://stackoverflow.com/questions/7274554/why-google-native-oauth2-flow-require-client-secret
            config = {
              "installed": {
                "client_id": "75839337166-pc5il9vgrgseopqberqi9pcr4clglcng.apps.googleusercontent.com",
                "client_secret": "OdkKJCeg_ocgu9XO9JjbGSlv"
              }
            }

          flow = OAuth2WebServerFlow(
            client_id=config['installed']['client_id'],
            client_secret=config['installed']['client_secret'],
            scope=scope,
            user_agent='Landgate-Hodor')
          credentials = run_oauth2(flow, credential_storage)

      if credentials is None or credentials.invalid:
        raise Exception("Unable to obtain valid credentials.")
      elif credentials.access_token_expired is True:
        self.vlog("Refreshing access token!")
        credentials.refresh(http)

      self.vlog('Constructing Google Maps Engine %s service...' % (version))
      http = credentials.authorize(http)

      resource = discovery_build('mapsengine', version, http=http)
      self.vlog("Access Token: %s" % credentials.access_token)

      # Fix for the default TCP send buffer being so riciculosuly low on Windows (8192)
      # These lines of code represent two days of work by multiple people.
      if 'https:www.googleapis.com' not in resource._http.connections:
        raise Exception("Unable to locate an open connection to googleapis.com")

      connection = resource._http.connections.get(resource._http.connections.keys()[0]) # https:www.googleapis.com
      self.vlog("Changing TCP send buffer from %s to %s" % (connection.sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF), 5242880))
      connection.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 5242880)

      return resource
コード例 #32
0
ファイル: cli.py プロジェクト: ruo91/Hodor
    def get_authenticated_service(self, scope):
        self.vlog('Authenticating...')

        # Service Account
        if self.auth_type == 'service-account':
            with open(self.CREDENTIALS_SERVICE_ACC) as f:
                config = json.load(f)

            credentials = SignedJwtAssertionCredentials(
                service_account_name=config['client_email'],
                private_key=config['private_key'],
                scope=self.RW_SCOPE)

            if credentials is None or credentials.invalid:
                raise Exception('Credentials invalid.')
        else:
            # Web Flow
            if os.path.isfile(self.CREDENTIALS_NATIVE_APP):
                with open(self.CREDENTIALS_NATIVE_APP) as f:
                    config = json.load(f)
            else:
                # This is OK according to Google
                # http://stackoverflow.com/questions/7274554/why-google-native-oauth2-flow-require-client-secret
                config = {
                    "client_id":
                    "75839337166-pc5il9vgrgseopqberqi9pcr4clglcng.apps.googleusercontent.com",
                    "client_secret": "OdkKJCeg_ocgu9XO9JjbGSlv"
                }

            flow = OAuth2WebServerFlow(client_id=config['client_id'],
                                       client_secret=config['client_secret'],
                                       scope=scope,
                                       user_agent='Landgate-Hodor/1.0')

            credential_storage = CredentialStorage(self.CREDENTIALS_STORE)
            credentials = credential_storage.get()

            if credentials is None or credentials.invalid:
                credentials = run_oauth2(flow, credential_storage)
            elif credentials.access_token_expired is True:
                self.log("Refreshing access token!")
                credentials.refresh(httplib2.Http())

        self.vlog('Constructing Google Maps Engine service...')
        http = credentials.authorize(httplib2.Http())
        resource = discovery_build('mapsengine', self.version, http=http)

        self.log("Access Token: %s" % credentials.access_token)
        self.access_token = credentials.access_token  # For handcrafted requests to exp2

        # Fix for the default TCP send buffer being so riciculosuly low on Windows (8192)
        # These lines of code represent two days of work by multiple people.
        if 'https:www.googleapis.com' not in resource._http.connections:
            raise Exception(
                "Unable to locate an open connection to googleapis.com")

        connection = resource._http.connections.get(
            resource._http.connections.keys()[0])  # https:www.googleapis.com
        self.vlog("Changing TCP send buffer from %s to %s" %
                  (connection.sock.getsockopt(socket.SOL_SOCKET,
                                              socket.SO_SNDBUF), 5242880))
        connection.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF,
                                   5242880)

        return resource
コード例 #33
0
ファイル: google.py プロジェクト: ericpauley/ama.io
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
from django.conf import settings
from apiclient import discovery
import os
import json
try:
    data = json.load(open(os.path.join(settings.PROJECT_PATH, 'google.json')))
except:
    data = None

if data is not None:
    credentials = SignedJwtAssertionCredentials(data['client_email'], data['private_key'], "https://www.googleapis.com/auth/analytics.readonly")
    http = httplib2.Http()
    credentials.refresh(http)
    http = credentials.authorize(http)

    service = discovery.build('analytics', 'v3', http=http)
else:
    service = {}
コード例 #34
0
class CloudSpooler(object):

    CLOUDPRINT_URL = 'https://www.google.com/cloudprint'

    def __init__(self, client_email, private_key):
        self.client_email = client_email
        self.private_key = private_key
        scope = 'https://www.googleapis.com/auth/cloudprint'
        httplib2.debuglevel=0
        self.credentials = SignedJwtAssertionCredentials(client_email, private_key, scope=scope)

        self.http_auth = self.credentials.authorize(Http())

        logging.basicConfig(level=logging.DEBUG)
        self.logger = logging.getLogger('google_print')


    def refresh(self):
	self.credentials.refresh(self.http_auth)


    # ------------------------------------------START------> PRINTER FUNCTIONS

    def getPrinterStatus(self, idPrinter):
	self.refresh()
        printers = {}
        values = {}
        tokens_n = ['"id"', '"name"', '"proxy"']
        for t in tokens_n:
            values[t] = ''
        try:

            (resp_headers, response) = self.http_auth.request(
                '%s/printer?printerid=%s&extra_fields=connectionStatus' % (self.CLOUDPRINT_URL, idPrinter), method="GET")

            data = json.loads(response)
            return data['printers'][0]['connectionStatus']

        except:
            return "SERVICE NOT WOKING -- ERROR"

    def getPrinters(self, proxy=None):
        """Get a list of all printers, including name, id, and proxy.

        Args:
          proxy: name of proxy to filter by.
        Returns:
          dictionary, keys = printer id, values = printer name, and proxy.
        """
	self.refresh()

        printers = {}
        values = {}
        tokens_n = ['"id"', '"name"', '"proxy"']
        for t in tokens_n:
            values[t] = ''

        (resp_headers, content) = self.http_auth.request('%s/search' % self.CLOUDPRINT_URL, method="GET")

        data = json.loads(content)
        pprint(data)

        for printer in data['printers']:
            # pprint(printer)
            if printer["id"]:
                printers[printer["id"]] = {}
                printers[printer["id"]]['name'] = printer["name"]
                printers[printer["id"]]['proxy'] = printer["proxy"]
                printers[printer["id"]]['displayName'] = printer["displayName"]
                printers[printer["id"]]['description'] = printer["description"]
                printers[printer["id"]]['id'] = printer["id"]

        return printers

    def choosePrinter(self, proxy=None):
        """Ti permette di scegleire la stampante sulla quale stampare

        Args:
          proxy: name of proxy to filter by.
        Returns:
          object, keys = id, name, proxy,displayName,description
        """
	self.refresh()
        printers = {}
        values = {}
        tokens_n = ['"id"', '"name"', '"proxy"']
        for t in tokens_n:
            values[t] = ''

        (resp_headers, content) = self.http_auth.request('%s/search' % self.CLOUDPRINT_URL, method="GET")

        data = json.loads(content)

        numero = 0

        print "Stampanti disponibili\n\n"

        for printer in data['printers']:
            if printer["id"]:
                numero += 1
                printers[numero] = {}
                printers[numero]['id'] = printer["id"]
                printers[numero]['name'] = printer["name"]
                printers[numero]['proxy'] = printer["proxy"]
                printers[numero]['displayName'] = printer["displayName"]
                printers[numero]['description'] = printer["description"]

                print "%d : %s" % (numero, printer["name"])

        try:
            input = "\nScegli una stampante da utilizzare selezionando i numero a fianco della stampante e premere invio : "
            scelta = int(raw_input(input))
            # print "hai scelto %d"%(mode,)
            return printers[scelta]

        except ValueError:
            print "\n\n" + "*" * 40 + "ERRORE" + "*" * 40
            print "La tua scelta non è valida, devi scegliere un numero "
            print "*" * 86 + "\n\n"

            return None


            # ------------------------------------------END------> PRINTER FUNCTIONS
            # ------------------------------------------START------> SPOOLER FUNCTIONS

    def getJobs(self):
	self.refresh()
        try:
            (resp_headers, response) = self.http_auth.request('%s/jobs' % (self.CLOUDPRINT_URL,), method="GET")

            jobs = json.loads(response)
            ret_dict = {}
            for job in jobs['jobs']:
                ret_dict[job['id']] = job

            return ret_dict
        except:
            return None


    def submitPdf(self, printerid, jobsrc):
	self.refresh()
    
        b64file = self.base64Encode(jobsrc)
        content = self.readFile(b64file)
        hsid = True
    
        title = "%s" % jobsrc
    
        content_type = 'dataUrl'
    
        headers = [('printerid', printerid),
                   ('title', title),
                   ('content', content),
                   ('contentType', content_type)]
    
        files = [('capabilities', 'capabilities', '{"capabilities":[]}')]
        edata = self.encodeMultiPart(headers, files)
        headers=[('Content-Length', str(len(edata))),('Content-Type', 'multipart/form-data;boundary=%s' % BOUNDARY)]


        (resp_headers, response) = self.http_auth.request('%s/submit' % (self.CLOUDPRINT_URL,),method='POST', headers=headers,
                                                          body=edata)

        data = json.loads(response)
    
        ret_data = {"success": False, "job": None}
    
        if data['success']:
            ret_data['success'] = data['success']
            ret_data['job'] = data['job']
    
        return ret_data


    def submitJob(self, printerid, jobtype, jobsrc):
        """Submit a job to printerid with content of dataUrl.

        Args:
          printerid: string, the printer id to submit the job to.
          jobtype: string, must match the dictionary keys in content and content_type.
          jobsrc: string, points to source for job. Could be a pathname or id string.
        Returns:
          boolean: True = submitted, False = errors.
        """
	self.refresh()
        if jobtype == 'pdf':
            b64file = self.base64Encode(jobsrc)
            fdata = self.readFile(b64file)
            hsid = True
        elif jobtype in ['png', 'jpeg']:
            fdata = self.readFile(jobsrc)
        else:
            fdata = None

        # Make the title unique for each job, since the printer by default will name
        # the print job file the same as the title.

        title = '%s' % (jobsrc,)

        """The following dictionaries expect a certain kind of data in jobsrc, depending on jobtype:
          jobtype                jobsrc
          ================================================
          pdf                    pathname to the pdf file
          png                    pathname to the png file
          jpeg                   pathname to the jpeg file
          ================================================
          """
        content = {'pdf': fdata,
                   'jpeg': jobsrc,
                   'png': jobsrc,
                   }
        content_type = {'pdf': 'dataUrl',
                        'jpeg': 'image/jpeg',
                        'png': 'image/png',
                        }
        headers = [('printerid', printerid),
                   ('title', title),
                   ('content', content[jobtype]),
                   ('contentType', content_type[jobtype])]

        files = [('capabilities', 'capabilities', '{"capabilities":[]}')]
        edata = self.encodeMultiPart(headers, files)
        #print "#"*100
        #print edata
        #print "#"*100


        headers=[('Content-Length', str(len(edata))),('Content-Type', 'multipart/form-data;boundary=%s' % BOUNDARY)]


        (resp_headers, response) = self.http_auth.request('%s/submit' % (self.CLOUDPRINT_URL,),method='POST', headers=headers,
                                                          body=edata)
        #print "*"*100
        #print response
        #print resp_headers
        #print "*"*100

        status = self.validate(response)
        if not status:
            error_msg = self.getMessage(response)
            self.logger.error('Print job %s failed with %s', jobtype, error_msg)

        return status

    # ------------------------------------------END------> SPOOLER FUNCTIONS
    # ------------------------------------------START------> UTILITY FUNCTIONS

    def encodeMultiPart(self, fields, files, file_type='application/xml'):
        """Encodes list of parameters and files for HTTP multipart format.

        Args:
          fields: list of tuples containing name and value of parameters.
          files: list of tuples containing param name, filename, and file contents.
          file_type: string if file type different than application/xml.
        Returns:
          A string to be sent as data for the HTTP post request.
        """
        lines = []
        for (key, value) in fields:
            lines.append('--' + BOUNDARY)
            lines.append('Content-Disposition: form-data; name="%s"' % key)
            lines.append('')  # blank line
            lines.append(value)
        for (key, filename, value) in files:
            lines.append('--' + BOUNDARY)
            lines.append(
                'Content-Disposition: form-data; name="%s"; filename="%s"'
                % (key, filename))
            lines.append('Content-Type: %s' % file_type)
            lines.append('')  # blank line
            lines.append(value)
        lines.append('--' + BOUNDARY + '--')
        lines.append('')  # blank line
        return CRLF.join(lines)



    def getMessage(self, response):
        """Extract the API message from a Cloud Print API json response.

        Args:
          response: json response from API request.
        Returns:
          string: message content in json response.
        """
        lines = response.split('\n')
        for line in lines:
            if '"message":' in line:
                msg = line.split(':')
                return msg[1]

        return None


    def readFile(self, pathname):
        """Read contents of a file and return content.

        Args:
          pathname: string, (path)name of file.
        Returns:
          string: contents of file.
        """
        try:
            f = open(pathname, 'rb')
            try:
                s = f.read()
            except IOError, e:
                self.logger('Error reading %s\n%s', pathname, e)
            finally:
                f.close()
                return s
        except IOError, e:
            self.logger.error('Error opening %s\n%s', pathname, e)
            return None