Ejemplo n.º 1
0
    def start(self, service_name, scope='https://www.googleapis.com/auth/drive'):
        """
        Reads config file and initializes the GSuite API client with proper authentication
        :param service_name: Name of service to start, one of gsuite.SERVICES
        :param scope: API scope to authorize.  Defaults to read/manage files in Google Drive.  
        :return: Google API client for making requests. 
        """

        log.info('Creating the client service')
        tokens, client_secrets = KIOutils.get_abs_config_path()
        flow = oa_client.flow_from_clientsecrets(client_secrets,
                                                 scope=scope,
                                                 message=oa_tools.message_if_missing(client_secrets))
        storage = oa_file.Storage(tokens)
        credentials = storage.get()

        # run_flow requires a wrapped oa_tools.argparse object to handle command line arguments
        flags = argparse.ArgumentParser(parents=[oa_tools.argparser])
        if credentials is None:  # or credentials.invalid:
            if self.has_client_secrets(client_secrets):
                credentials = oa_tools.run_flow(flow, storage, flags)
            else:
                raise NotImplementedError(oa_tools.message_if_missing(client_secrets))

        # noinspection PyBroadException
        try:
            http = credentials.authorize(httplib2.Http())
            client = googleapiclient.discovery.build(serviceName=service_name, version="v2", http=http,
                                                     cache_discovery=False)
        except Exception as e:
            log.error('Failed to create service', exc_info=True)
            raise sys.exit(1)
        else:
            log.info('Created and authorized the client service')
            return client
Ejemplo n.º 2
0
def authorize(config, flags):
    """Authorization for the Content API Samples.

  This function uses common idioms found across all the included
  samples, i.e., that service account credentials are located in a
  file called 'client-service.json' and that OAuth2 client credentials
  are located in a file called 'client-oauth2.json', both in the same
  directory as the sample configuration file.  Only one of these files
  needs to exist for authentication, and the service account will be
  chosen first if both exist.

  Args:
      config: dictionary, Python representation of config JSON.
      flags: the parsed commandline flags.

  Returns:
      An oauth2lib.Credential object suitable for using to authenticate
      to the Content API.
  """
    try:
        credentials = client.GoogleCredentials.get_application_default()
        print('Using application default credentials.')
        return credentials.create_scoped(_constants.API_SCOPE)
    except client.ApplicationDefaultCredentialsError:
        pass  # Can safely ignore this error, since it just means none were found.
    if os.path.isfile(_constants.SERVICE_ACCOUNT_FILE):
        print('Using service account credentials from %s.' %
              _constants.SERVICE_ACCOUNT_FILE)
        return ServiceAccountCredentials.from_json_keyfile_name(
            _constants.SERVICE_ACCOUNT_FILE, scopes=_constants.API_SCOPE)
    elif os.path.isfile(_constants.CLIENT_SECRETS_FILE):
        print('Using OAuth2 client secrets from %s.' %
              _constants.CLIENT_SECRETS_FILE)
        message = tools.message_if_missing(_constants.CLIENT_SECRETS_FILE)
        storage = token_storage.Storage(config)
        credentials = storage.get()
        if credentials is not None and not credentials.invalid:
            return credentials
        message = tools.message_if_missing(_constants.CLIENT_SECRETS_FILE)
        flow = client.flow_from_clientsecrets(
            _constants.CLIENT_SECRETS_FILE,
            scope=_constants.API_SCOPE,
            message=message,
            login_hint=config['emailAddress'])
        return tools.run_flow(flow, storage, flags)
    print('No OAuth2 authentication files found. Checked:', file=sys.stderr)
    print('- Google Application Default Credentials', file=sys.stderr)
    print('- %s' % _constants.SERVICE_ACCOUNT_FILE, file=sys.stderr)
    print('- %s' % _constants.CLIENT_SECRETS_FILE, file=sys.stderr)
    print('Please read the accompanying documentation.', file=sys.stderr)
    sys.exit(1)
    return None
Ejemplo n.º 3
0
def getGoogleService(secretFile,scope,apiName,apiVersion):
	secretFileType = 'user'
	searchSecretFile = open(secretFile, "r")
	for line in searchSecretFile.readlines():
		if '"type": "service_account"' in line: secretFileType = 'service'
		searchSecretFile.close()
	try:
		
		if secretFileType == 'service':
			auth = ServiceAccountGoogleAuth(secretFile, scope=scope)
			serviceSetup = BaseGoogleService(api_name=apiName, api_version=apiVersion, google_auth=auth)
			auth.authorize()
			return serviceSetup.getService()
		else:
			parser = argparse.ArgumentParser(
				formatter_class=argparse.RawDescriptionHelpFormatter,
				parents=[tools.argparser])
			flags = parser.parse_args([])
			flow = client.flow_from_clientsecrets(
				secretFile, scope=scope,
				message=tools.message_if_missing(secretFile,))
			storage = file.Storage(apiName + '.dat')
			credentials = storage.get()
			if credentials is None or credentials.invalid:
				tools.run_flow(flow, storage, flags)
			auth = ClientSecretGoogleAuth(secretFile,apiName + '.dat',scope=scope)
			serviceSetup = BaseGoogleService(api_name=apiName, api_version=apiVersion, google_auth=auth)
			auth.authorize()
			return serviceSetup.getService()
		
	except HttpError as err:
		raise err
    def initCredentialsAndService(self, name, version, scope = None, discovery_filename = None):
        if scope is None:
            scope = 'https://www.googleapis.com/auth/' + name

        client_secrets = os.path.join(self._directory, 'client_secrets.json')

        flow = client.flow_from_clientsecrets(client_secrets,
            scope=scope,
            message=tools.message_if_missing(client_secrets))

        storage = file.Storage(name + '.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            flags = Expando()
            flags.nonoauth_local_webserver = True
            credentials = tools.run_flow(flow, storage, flags)

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

        if discovery_filename is None:
            service = discovery.build(name, version, http=http)
        else:
            with open(discovery_filename) as discovery_file:
                service = discovery.build_from_document(
                    discovery_file.read(),
                    base='https://www.googleapis.com/',
                    http=http)

        return (credentials, service)
Ejemplo n.º 5
0
def init(argv, name, version, doc, filename, scope=None, parents=[]):
  """A common initialization routine for samples.

  Many of the sample applications do the same initialization, which has now
  been consolidated into this function. This function uses common idioms found
  in almost all the samples, i.e. for an API with name 'apiname', the
  credentials are stored in a file named apiname.dat, and the
  client_secrets.json file is stored in the same directory as the application
  main file.

  Args:
    argv: list of string, the command-line parameters of the application.
    name: string, name of the API.
    version: string, version of the API.
    doc: string, description of the application. Usually set to __doc__.
    file: string, filename of the application. Usually set to __file__.
    parents: list of argparse.ArgumentParser, additional command-line flags.
    scope: string, The OAuth scope used.

  Returns:
    A tuple of (service, flags), where service is the service object and flags
    is the parsed command-line flags.
  """
  if scope is None:
    scope = 'https://www.googleapis.com/auth/' + name

  # Parser command-line arguments.
  parent_parsers = [tools.argparser]
  parent_parsers.extend(parents)
  parser = argparse.ArgumentParser(
      description=doc,
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=parent_parsers)
  flags = parser.parse_args(argv[1:])

  # Name of a file containing the OAuth 2.0 information for this
  # application, including client_id and client_secret, which are found
  # on the API Access tab on the Google APIs
  # Console <http://code.google.com/apis/console>.
  client_secrets = os.path.join(os.path.dirname(filename),
                                'client_secrets.json')

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(client_secrets,
      scope=scope,
      message=tools.message_if_missing(client_secrets))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http = httplib2.Http())

  # Construct a service object via the discovery service.
  service = discovery.build(name, version, http=http)
  return (service, flags)
Ejemplo n.º 6
0
    def _initialize_api_http(self):
        ''' Initializes an analytics instance for API access '''
        if self._SCOPES is None:
            raise Exception("Scope Error, please read the gAPI docs")
        credential_dir = self._CLIENT_SECRET_DIR
        credential_path = os.path.join(credential_dir,
                                       self.__class__.__name__ + '.dat')

        secret = os.path.join(credential_dir, self._CLIENT_SECRET_FILE)

        # In case of no authentication; set it up
        storage = file.Storage(credential_path)
        credentials = storage.get()
        if not credentials or credentials.invalid or self._refresh:
            logging.info("Invalid credentials in {}".format(
                os.path.dirname(credential_path)))
            flow = client.flow_from_clientsecrets(
                secret,
                scope=self._SCOPES,
                message=tools.message_if_missing(secret))
            if self.APPLICATION_NAME:
                flow.user_agent = self._APPLICATION_NAME
            credentials = tools.run_flow(flow, storage)

        return credentials.authorize(http=httplib2.Http())
Ejemplo n.º 7
0
def build_fit_service():
    filename = "json/"
    scope = [
        "https://www.googleapis.com/auth/fitness.activity.read",
        "https://www.googleapis.com/auth/fitness.activity.write",
        "https://www.googleapis.com/auth/fitness.location.read",
        "https://www.googleapis.com/auth/fitness.location.write",
    ]
    # Name of a file containing the OAuth 2.0 information for this
    # application, including client_id and client_secret, which are found
    # on the API Access tab on the Google APIs
    # Console <http://code.google.com/apis/console>.
    client_secrets = os.path.join(os.path.dirname(filename),
                                  "client_secrets.json")

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets,
        scope=scope,
        message=tools.message_if_missing(client_secrets))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage(
        os.path.join(os.path.dirname(filename), "token.json"))
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        # maybe add argv to support --noauth_local_webserver
        credentials = tools.run_flow(flow, storage)
    http = credentials.authorize(http=build_http())

    fit_service = build(serviceName='fitness', version='v1', http=http)
    return fit_service
def local_authenticate(flags):
    """Authenticate to the service using 3-legged OAuth flow for local testing"""
    # CLIENT_SECRET is name of a file containing the OAuth 2.0 information for
    # this application, including client_id and client_secret. You can see the
    # Client ID and Client secret on the APIs page in the Cloud Console:
    # <https://cloud.google.com/console#/project/287816926224/apiui>
    CLIENT_SECRET = os.path.join(os.path.dirname(__file__),
                                 'client_secrets.json')

    # Set up a Flow object to be used for authentication.
    # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
    # NEED. For more information on using scopes please see
    # <https://developers.google.com/+/best-practices>.
    FLOW = client.flow_from_clientsecrets(
        CLIENT_SECRET,
        scope=['https://www.googleapis.com/auth/androidbuild.internal'],
        message=tools.message_if_missing(CLIENT_SECRET))

    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    storage = file.Storage('credentials.json')
    credentials = storage.get()
    if not credentials or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)
    return credentials
Ejemplo n.º 9
0
    def connect(self, argv):
        parser = argparse.ArgumentParser(
            description=__doc__,
            formatter_class=argparse.RawDescriptionHelpFormatter,
            parents=[tools.argparser])

        flags = parser.parse_args(argv[1:])

        CLIENT_SECRETS = os.path.join(os.path.dirname(__file__),
                                      'client_secrets.json')
        FLOW = client.flow_from_clientsecrets(
            CLIENT_SECRETS,
            scope=[
                'https://www.googleapis.com/auth/calendar',
                'https://www.googleapis.com/auth/calendar.readonly',
            ],
            message=tools.message_if_missing(CLIENT_SECRETS))
        storage = file.Storage('credentials.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(FLOW, storage, flags)

        # Create an httplib2.Http object to handle our HTTP requests and authorize it
        # with our good Credentials.
        http = httplib2.Http()
        http = credentials.authorize(http)

        # Construct the service object for the interacting with the Calendar API.
        self.service = discovery.build('calendar', 'v3', http=http)
Ejemplo n.º 10
0
def get_service(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """

  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))
  #storage = file.Storage(api_name + '.dat')
  storage = file.Storage(re.sub('json$', 'dat', PARAMS['json']))
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  return build(api_name, api_version, http=http)
Ejemplo n.º 11
0
def initialize_analyticsreporting():
  """Инициализирует объект службы analyticsreporting.
  Возвращает Analytics – авторизованный объект службы Analytics Reporting.
  """
  # Синтаксический анализ аргументов командной строки.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Настройка объекта Flow, который будет использоваться при необходимости аутентификации.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(CLIENT_SECRETS_PATH))

  # Подготовьте учетные данные и авторизуйте с их помощью объект HTTP.
  # Если учетные данные недействительны или не существуют, воспользуйтесь оригинальной
  # процедурой клиента. Применение объекта Storage гарантирует, что в случае успеха правильные
  # учетные данные будут записаны обратно в файл.
  storage = file.Storage('analyticsreporting.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Создание объекта службы.
  analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)

  return analytics
Ejemplo n.º 12
0
def authorize_creds(creds: str = CLIENT_SECRETS_PATH,
                    authorized_creds_file: str = AUTHORIZED_CREDS_FILE):
    #creds should be CLIENT_SECRETS_PATH unless the user submits other credentials

    # Create a parser to be able to open browser for Authorization
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    flow = client.flow_from_clientsecrets(
        creds,
        scope=SCOPES,  #used to be CLIENT_SECRETS_PATH instead of creds
        message=tools.message_if_missing(
            creds))  #this used to be CLIENT_SECRETS_PATH

    # Prepare credentials and authorize HTTP
    # If they exist, get them from the storage object
    # credentials will get written back to a file.
    storage = file.Storage(authorized_creds_file)
    credentials = storage.get()

    # If authenticated credentials don't exist, open Browser to authenticate
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)

    http = credentials.authorize(http=httplib2.Http())
    webmasters_service = build('webmasters', 'v3', http=http)
    return webmasters_service
Ejemplo n.º 13
0
Archivo: cal.py Proyecto: pjot/calendar
    def __init__(self, parent):
        self.calendar_id = None
        self.parent = parent
        arg_parser = argparse.ArgumentParser(
            description=__doc__,
            formatter_class=argparse.RawDescriptionHelpFormatter,
            parents=[tools.argparser]
        )
        flags = arg_parser.parse_args([])
        self.CLIENT_SECRETS = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'client_secrets.json'
        )
        self.FLOW = client.flow_from_clientsecrets(
            self.CLIENT_SECRETS,
            scope=[
                'https://www.googleapis.com/auth/calendar',
                'https://www.googleapis.com/auth/calendar.readonly',
            ],
            message=tools.message_if_missing(self.CLIENT_SECRETS)
        )

        data_file = os.path.join(self.parent.CONFIG_DIR, 'google-calendar.dat')
        storage = file.Storage(data_file)
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(self.FLOW, storage, flags)

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

        self.service = discovery.build('calendar', 'v3', http=http)
def google_service(argv, name, version, doc, filename, parents, discovery_filename=None):
    # Define the auth scopes to request.
    scope = ['https://www.googleapis.com/auth/webmasters.readonly']  # Read and Analyze Data

    parent_parsers = [tools.argparser]
    parent_parsers.extend(parents)
    parser = argparse.ArgumentParser(description=doc,
                                     formatter_class=argparse.RawDescriptionHelpFormatter,
                                     parents=parent_parsers)

    flags = parser.parse_args(argv[1:])
    client_secrets = os.path.join(os.path.dirname(filename), 'client_secrets.json')
    flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=tools.message_if_missing(client_secrets))

    storage = file.Storage(name + '.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)

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

    if discovery_filename is None:
        # Construct a service object via the discovery service.
        service = discovery.build(name, version, http=http)
    else:
        # Construct a service object using a local discovery document file.
        with open(discovery_filename) as discovery_file:
            service = discovery.build_from_document(discovery_file.read(),
                                                    base='https://www.googleapis.com/',
                                                    http=http)

    return service, flags
Ejemplo n.º 15
0
def initialize_analyticsreporting():
  """Initializes the analyticsreporting service object.

  Returns:
    analytics an authorized analyticsreporting service object.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(CLIENT_SECRETS_PATH))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage('analyticsreporting.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)

  return analytics
Ejemplo n.º 16
0
def get_auth_token():
    scope = 'https://www.googleapis.com/auth/contacts.readonly'
    user_agent = __name__
    client_secrets = os.path.join(os.path.dirname(__file__),
                                  CLIENT_SECRETS_JSON)
    filename = os.path.splitext(__file__)[0] + '.dat'

    flow = client.flow_from_clientsecrets(
        client_secrets,
        scope=scope,
        message=tools.message_if_missing(client_secrets))

    storage = file.Storage(filename)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        if args.non_interactive:
            sys.stderr.write(
                'ERROR: Invalid or missing Oauth2 credentials. To reset auth flow manually, run without --non_interactive\n'
            )
            sys.exit(1)
        else:
            credentials = tools.run_flow(flow, storage, args)

    j = json.loads(open(filename).read())

    return gdata.gauth.OAuth2Token(j['client_id'],
                                   j['client_secret'],
                                   scope,
                                   user_agent,
                                   access_token=j['access_token'],
                                   refresh_token=j['refresh_token'])
Ejemplo n.º 17
0
    def __init__(self, json_keyfile, dat_keyfile):
        """
        Read service key file and initialize the API client
        """
        self.parser = argparse.ArgumentParser(
            formatter_class=argparse.RawDescriptionHelpFormatter,
            parents=[tools.argparser])
        self.flags = self.parser.parse_args([])
        self.flow = client.flow_from_clientsecrets(
            json_keyfile,
            scope=SCOPES,
            message=tools.message_if_missing(json_keyfile))
        self.storage = file.Storage(dat_keyfile)
        self.credentials = self.storage.get()
        if self.credentials is None or self.credentials.invalid:
            self.credentials = tools.run_flow(self.flow, self.storage,
                                              self.flags)
        self.http = self.credentials.authorize(http=httplib2.Http())
        self.client = build('analytics',
                            'v4',
                            http=self.http,
                            discoveryServiceUrl=DISCOVERY_URI)

        self.set_view_id(None)
        self.set_dateranges(None, None)

        logger.debug("gaapi4py client initiated")
Ejemplo n.º 18
0
def get_service():
    """Get a service that communicates to a Google API."""
    api_name = 'analytics'
    api_version = 'v3'
    scope = ['https://www.googleapis.com/auth/analytics.readonly']
    client_secrets_path = 'client_secrets.json'

    # Parse command-line arguments.
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets_path,
        scope=scope,
        message=tools.message_if_missing(client_secrets_path)
    )

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage(api_name + '.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

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

    return service
Ejemplo n.º 19
0
    def __call__(self):
        SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
        DISCOVERY_URI = (
            'https://analyticsreporting.googleapis.com/$discovery/rest')
        CLIENT_SECRETS_PATH = '/home/henry/MarieClaire/zeocluster/src/MarieClaire.content/src/MarieClaire/content/browser/static/client_secrets.json'

        parser = argparse.ArgumentParser(
            formatter_class=argparse.RawDescriptionHelpFormatter,
            parents=[tools.argparser])
        flags = parser.parse_args([])

        flow = client.flow_from_clientsecrets(
            CLIENT_SECRETS_PATH,
            scope=SCOPES,
            message=tools.message_if_missing(CLIENT_SECRETS_PATH))

        storage = file.Storage('analyticsreporting.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(flow, storage, flags)
        http = credentials.authorize(http=httplib2.Http())

        # Build the service object.
        analytics = build('analytics',
                          'v4',
                          http=http,
                          discoveryServiceUrl=DISCOVERY_URI)

        self.get_report(analytics)
Ejemplo n.º 20
0
def get_service():
    """Get a service that communicates to a Google API."""
    api_name = 'analytics'
    api_version = 'v3'
    scope = ['https://www.googleapis.com/auth/analytics.readonly']
    client_secrets_path = 'client_secrets.json'

    # Parse command-line arguments.
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets_path,
        scope=scope,
        message=tools.message_if_missing(client_secrets_path)
    )

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage(api_name + '.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

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

    return service
def GetService_bigquery():
    scope = 'https://www.googleapis.com/auth/bigquery'
    client_secrets_path = 'client_secrets.json'
    api_name = 'bigquery'
    api_version = 'v2'
# Parse command-line arguments.
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets_path, scope=scope,
        message=tools.message_if_missing(client_secrets_path))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    TOKEN_FILE_NAME = 'credentials.dat'
    storage = file.Storage(TOKEN_FILE_NAME)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

    # Build the service object.
    service = build(api_name, api_version, http=http)
    print service
    return service
Ejemplo n.º 22
0
def init(argv, name, version, doc, filename, scope=None, parents=[]):
  """A common initialization routine for samples.

  Many of the sample applications do the same initialization, which has now
  been consolidated into this function. This function uses common idioms found
  in almost all the samples, i.e. for an API with name 'apiname', the
  credentials are stored in a file named apiname.dat, and the
  client_secrets.json file is stored in the same directory as the application
  main file.

  Args:
    argv: list of string, the command-line parameters of the application.
    name: string, name of the API.
    version: string, version of the API.
    doc: string, description of the application. Usually set to __doc__.
    file: string, filename of the application. Usually set to __file__.
    parents: list of argparse.ArgumentParser, additional command-line flags.
    scope: string, The OAuth scope used.

  Returns:
    A tuple of (service, flags), where service is the service object and flags
    is the parsed command-line flags.
  """
  if scope is None:
    scope = 'https://www.googleapis.com/auth/' + name

  # Parser command-line arguments.
  parent_parsers = [tools.argparser]
  parent_parsers.extend(parents)
  parser = argparse.ArgumentParser(
      description=doc,
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=parent_parsers)
  flags = parser.parse_args(argv[1:])

  # Name of a file containing the OAuth 2.0 information for this
  # application, including client_id and client_secret, which are found
  # on the API Access tab on the Google APIs
  # Console <http://code.google.com/apis/console>.
  client_secrets = os.path.join(os.path.dirname(filename),
                                'client_secrets.json')

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(client_secrets,
      scope=scope,
      message=tools.message_if_missing(client_secrets))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http = httplib2.Http())

  # Construct a service object via the discovery service.
  service = discovery.build(name, version, http=http)
  return (service, flags)
def load_user_credentials(client_secrets, storage, flags):
    """Attempts to load user credentials from the provided client secrets file.

    Args:
      client_secrets: path to the file containing client secrets.
      storage: the data store to use for caching credential information.
      flags: command-line flags.

    Returns:
      A credential object initialized with user account credentials.
    """
    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets,
        scope=API_SCOPES,
        message=tools.message_if_missing(client_secrets))

    # Retrieve credentials from storage.
    # If the credentials don't exist or are invalid run through the installed
    # client flow. The storage object will ensure that if successful the good
    # credentials will get written back to file.
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)

    return credentials
Ejemplo n.º 24
0
def oauthorize(client_secrets, session_file):
    """Takes a path to a client_secrets.json and a session.dat file,
    performs an OAuth auth-flow and returns a service object."""
    # If the credentials don't exist or are invalid run through the native
    # client flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    storage = oauth_file.Storage(session_file)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        # Prevent obnoxious browser window launching if our session is expired
        faux_parser = argparse.ArgumentParser(parents=[tools.argparser])
        flow_flags = faux_parser.parse_args("--noauth_local_webserver".split())
        scope = [
            'https://www.googleapis.com/auth/admin.reports.audit.readonly',
            'https://www.googleapis.com/auth/admin.reports.usage.readonly'
        ]
        err_msg = tools.message_if_missing(client_secrets)
        flow = client.flow_from_clientsecrets(client_secrets, scope=scope,
                                              message=err_msg)
        credentials = tools.run_flow(flow, storage, flow_flags)

    # Create an httplib2.Http object to handle our HTTP requests and do auth
    http = httplib2.Http()
    http = credentials.authorize(http)

    return discovery.build('admin', 'reports_v1', http=http)
Ejemplo n.º 25
0
   def do_authorize(self, cr, uid, ids, context=None):
     
       account = self.browse(cr, uid, ids[0])
       
       FLOW = client.flow_from_clientsecrets(account.secrets_path,
                                             scope=[
                                                    'https://www.googleapis.com/auth/calendar',
                                                    'https://www.googleapis.com/auth/calendar.readonly',
                                                    'https://www.google.com/m8/feeds',
                                                    ],
                                             message=tools.message_if_missing(account.secrets_path))
               
       storage = file.Storage(account.credential_path)        
       credentials = storage.get()
       if credentials is None or credentials.invalid:
           parser = argparse.ArgumentParser(
                                            description=__doc__,
                                            formatter_class=argparse.RawDescriptionHelpFormatter,
                                            parents=[tools.argparser])
           if not account.use_local_browser:
               flags = parser.parse_args(['--noauth_local_webserver'])
           else:
               flags = parser.parse_args([])
           credentials = tools.run_flow(FLOW, storage, flags) 
 
       raise osv.except_osv(_('Done.'), _('Please verify if your credential file is created or updated.'))
Ejemplo n.º 26
0
  def get_service(self):
    if not self.service:
      # If the credentials don't exist or are invalid run through the native client
      # flow. The Storage object will ensure that if successful the good
      # credentials will get written back to the file.
      storage = file.Storage(os.path.join(os.path.dirname(__file__), 'credentials.dat'))
      credentials = storage.get()
      if credentials is None or credentials.invalid:
        # Set up a Flow object to be used for authentication.
        # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
        # NEED. For more information on using scopes please see
        # <https://developers.google.com/+/best-practices>.
        FLOW = client.flow_from_clientsecrets(self.CLIENT_SECRETS,
          scope=[
              'https://www.googleapis.com/auth/calendar.readonly',
            ],
          message=tools.message_if_missing(self.CLIENT_SECRETS))

        credentials = tools.run_flow(FLOW, storage, self.flags)


      # Create an httplib2.Http object to handle our HTTP requests and authorize it
      # with our good Credentials.
      http = httplib2.Http()
      http = credentials.authorize(http)
      # Construct the service object for the interacting with the Calendar API.
      self.service = discovery.build('calendar', 'v3', http=http)

    return self.service
Ejemplo n.º 27
0
def GetService(api_name, api_version, scope, client_secrets_path):

    # Parser command-line arguments.
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets_path,
        scope=scope,
        message=tools.message_if_missing(client_secrets_path))

    storage = file.Storage(api_name + '.dat')
    credentials = storage.get()
    try:
        already_has_scopes = all([credentials.has_scopes(s) for s in scope])
    except AttributeError:
        # No prior credentials
        already_has_scopes = False

    if credentials is None or credentials.invalid or not already_has_scopes:
        credentials = tools.run_flow(flow, storage, flags)

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

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

    return service
Ejemplo n.º 28
0
def oauthorize(client_secrets, session_file):
    """Takes a path to a client_secrets.json and a session.dat file,
    performs an OAuth auth-flow and returns a service object."""
    # If the credentials don't exist or are invalid run through the native
    # client flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    storage = oauth_file.Storage(session_file)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        # Prevent obnoxious browser window launching if our session is expired
        faux_parser = argparse.ArgumentParser(parents=[tools.argparser])
        flow_flags = faux_parser.parse_args("--noauth_local_webserver".split())
        scope = [
            'https://www.googleapis.com/auth/admin.reports.audit.readonly',
            'https://www.googleapis.com/auth/admin.reports.usage.readonly'
        ]
        err_msg = tools.message_if_missing(client_secrets)
        flow = client.flow_from_clientsecrets(client_secrets,
                                              scope=scope,
                                              message=err_msg)
        credentials = tools.run_flow(flow, storage, flow_flags)

    # Create an httplib2.Http object to handle our HTTP requests and do auth
    http = httplib2.Http()
    http = credentials.authorize(http)

    return discovery.build('admin', 'reports_v1', http=http)
Ejemplo n.º 29
0
def initialize_api(project, version='v4'):
    google_client_secret_path, google_credentials_path = credential_path(
        project)
    scopes = ['https://www.googleapis.com/auth/analytics.readonly']
    discovery_uri = 'https://analyticsreporting.googleapis.com/$discovery/rest'
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        google_client_secret_path,
        scope=scopes,
        message=tools.message_if_missing(google_client_secret_path))

    path_storage = google_credentials_path + "/analytics.json"
    storage = file.Storage(path_storage)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

    # Build the service object.
    if version == 'v3':
        account = build('analytics', version, http=http)
    else:
        account = build('analytics',
                        version,
                        http=http,
                        discoveryServiceUrl=discovery_uri)

    return account
Ejemplo n.º 30
0
def authorize_creds(creds):
    # Variable parameter that controls the set of resources that the access token permits.
    SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly'] 
 
    # Path to client_secrets.json file
    CLIENT_SECRETS_PATH = creds
 
    # Create a parser to be able to open browser for Authorization
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])
 
    flow = client.flow_from_clientsecrets(
        CLIENT_SECRETS_PATH, scope = SCOPES,
        message = tools.message_if_missing(CLIENT_SECRETS_PATH))
 
    # Prepare credentials and authorize HTTP
    # If they exist, get them from the storage object
    # credentials will get written back to a file.
    storage = file.Storage('authorizedcreds.dat')
    credentials = storage.get()
 
    # If authenticated credentials don't exist, open Browser to authenticate
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())
    webmasters_service = build('webmasters', 'v3', http=http)
    return webmasters_service
def setup(flags):
    """Handles authentication and loading of the API.

    Args:
      flags: command-line flags obtained by calling ''get_arguments()''.

    Returns:
      An initialized service object.
    """
    # Name of a file containing the OAuth 2.0 information for this
    # application, including client_id and client_secret, which are found
    # on the Credentials tab on the Google Developers Console.
    client_secrets = os.path.join(os.path.dirname(__file__), 'client_secrets.json')

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets,
        scope=API_SCOPES,
        message=tools.message_if_missing(client_secrets))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the installed
    # client flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = oauthFile.Storage(CREDENTIAL_STORE_FILE)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

    # Construct and return a service object via the discovery service.
    return discovery.build(API_NAME, API_VERSION, http=http)
Ejemplo n.º 32
0
    def get_service(self):
        if not self.service:
            # If the credentials don't exist or are invalid run through the native client
            # flow. The Storage object will ensure that if successful the good
            # credentials will get written back to the file.
            storage = file.Storage(
                os.path.join(os.path.dirname(__file__), 'credentials.dat'))
            credentials = storage.get()
            if credentials is None or credentials.invalid:
                # Set up a Flow object to be used for authentication.
                # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
                # NEED. For more information on using scopes please see
                # <https://developers.google.com/+/best-practices>.
                FLOW = client.flow_from_clientsecrets(
                    self.CLIENT_SECRETS,
                    scope=[
                        'https://www.googleapis.com/auth/calendar.readonly',
                    ],
                    message=tools.message_if_missing(self.CLIENT_SECRETS))

                credentials = tools.run_flow(FLOW, storage, self.flags)

            # Create an httplib2.Http object to handle our HTTP requests and authorize it
            # with our good Credentials.
            http = httplib2.Http()
            http = credentials.authorize(http)
            # Construct the service object for the interacting with the Calendar API.
            self.service = discovery.build('calendar', 'v3', http=http)

        return self.service
Ejemplo n.º 33
0
    def __init__(self, reset_credentials, blogid, secret_filename):
        self._blogid = blogid
        flow = client.flow_from_clientsecrets(
            secret_filename,
            scope="https://www.googleapis.com/auth/blogger",
            message=tools.message_if_missing(secret_filename))

        user = getpass.getuser()
        storage = keyring_storage.Storage('blogspot-tool-storage', user)
        if not reset_credentials:
            credentials = storage.get()
        else:
            credentials = None

        http = httplib2.Http()
        if credentials is None or credentials.invalid:
            flow.redirect_uri = client.OOB_CALLBACK_URN
            authorize_url = flow.step1_get_authorize_url()
            print('Please open', authorize_url)
            code = raw_input('Enter verification code: ').strip()

            try:
                credentials = flow.step2_exchange(code, http=http)
            except client.FlowExchangeError as e:
                raise RemoteError('Authentication has failed: %s' % e)

            storage.put(credentials)
            credentials.set_store(storage)


        http = credentials.authorize(http=http)

        # Construct a service object via the discovery service.
        service = discovery.build('blogger', 'v3', http=http)
        self._client = service
Ejemplo n.º 34
0
    def get(name, version, doc, filename, discovery_filename, scope):
        # Name of a file containing the OAuth 2.0 information details
        client_secrets = os.path.join(os.path.dirname(filename),
                                      'client_secrets_adsense.json')

        # Set up a Flow object to be used if we need to authenticate.
        flow = client.flow_from_clientsecrets(
            client_secrets,
            scope=scope,
            message=tools.message_if_missing(client_secrets))

        # Prepare credentials, and authorize HTTP object with them.
        # If the credentials don't exist or are invalid run through the native client
        # flow. The Storage object will ensure that if successful the good
        # credentials will get written back to a file.
        storage = file.Storage(name + '.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            flags = None
            credentials = tools.run_flow(flow, storage, flags)

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

        if discovery_filename is None:
            # Construct a service object via the discovery service.
            service = discovery.build(name, version, http=http)
        else:
            # Construct a service object using a local discovery document file.
            with open(discovery_filename) as discovery_file:
                service = discovery.build_from_document(
                    discovery_file.read(),
                    base='https://www.googleapis.com/',
                    http=http)
        return service
Ejemplo n.º 35
0
    def __init__(
            self,
            scopes='https://www.googleapis.com/auth/analytics.readonly',
            discovery_uri=(
                'https://analyticsreporting.googleapis.com/$discovery/rest'),
            #Dirección de credenciales
            credentials_dir='Ganalytics_token.json',
            client_secret_dir='GoogleAPIsCredentials.json'):
        # Por el proyecto, asume las credenciales en ../data/config/
        # Ver variables de entorno.
        self.scopes = scopes
        self.discovery_uri = discovery_uri
        self.credentials_dir = credentials_dir
        self.client_secret_dir = client_secret_dir
        self.store = file.Storage(credentials_dir)
        self.creds = self.store.get()
        if not self.creds or self.creds.invalid:
            parser = argparse.ArgumentParser(
                formatter_class=argparse.RawDescriptionHelpFormatter,
                parents=[tools.argparser])
            flags = parser.parse_args([])
            flow = client.flow_from_clientsecrets(
                self.client_secret_dir,
                scope=self.scopes,
                message=tools.message_if_missing(self.client_secret_dir))

            self.creds = tools.run_flow(flow, self.store, flags)
Ejemplo n.º 36
0
def auth(api_name, api_version, scope, client_secrets_path):

    secret_folder = client_secrets_path.rsplit('/', 1)[0] + '/'

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object tobe used if we need to authenticate
    flow = client.flow_from_clientsecrets(
        client_secrets_path,
        scope=scope,
        message=tools.message_if_missing(client_secrets_path))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid, run through the native client
    # flow. The Storage object will ensure that if successful, the good
    # credentials will be written back to a file.
    storage = file.Storage(secret_folder + api_name + '.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

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

    return service
Ejemplo n.º 37
0
def InitAuthFlow():
  # N.B.: Most of this code is lifted from googleapiclient.sample_tools.
  name = 'calendar'
  version = 'v3'
  scope = 'https://www.googleapis.com/auth/calendar.readonly'

  client_secrets = os.path.join(
      os.path.dirname(__file__), 'client_secrets.json')

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets, scope=scope,
      message=tools.message_if_missing(client_secrets),
      redirect_uri='urn:ietf:wg:oauth:2.0:oob')

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native
  # client flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = f.Storage(name + '.dat')
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    auth_uri = flow.step1_get_authorize_url()
    print 'Open the following URI in a browser: %s' % auth_uri
    auth_code = raw_input('Enter the auth code: ')
    credentials = flow.step2_exchange(auth_code)

  storage.put(credentials)
  credentials.set_store(storage)
  http = credentials.authorize(http=httplib2.Http())

  # Construct a service object via the discovery service.
  service = discovery.build(name, version, http=http)
  return service
def setup(flags):
    """Handles authentication and loading of the API.

  Args:
    flags: command-line flags obtained by calling ''get_arguments()''.

  Returns:
    An initialized service object.
  """
    # Name of a file containing the OAuth 2.0 information for this
    # application, including client_id and client_secret, which are found
    # on the Credentials tab on the Google Developers Console.
    client_secrets = os.path.join(os.path.dirname(__file__), "client_secrets.json")

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets, scope=API_SCOPES, message=tools.message_if_missing(client_secrets)
    )

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the installed
    # client flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = oauthFile.Storage(CREDENTIAL_STORE_FILE)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

    # Construct and return a service object via the discovery service.
    return discovery.build(API_NAME, API_VERSION, http=http)
def get_service(api_name, api_version, scope, client_secrets_path):
    """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets_path,
        scope=scope,
        message=tools.message_if_missing(client_secrets_path))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage(api_name + '.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage)
    http = credentials.authorize(http=httplib2.Http())

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

    return service
def load_user_credentials(client_secrets, storage, flags):
  """Attempts to load user credentials from the provided client secrets file.

  Args:
    client_secrets: path to the file containing client secrets.
    storage: the data store to use for caching credential information.
    flags: command-line flags.

  Returns:
    A credential object initialized with user account credentials.
  """
  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets,
      scope=API_SCOPES,
      message=tools.message_if_missing(client_secrets))

  # Retrieve credentials from storage.
  # If the credentials don't exist or are invalid run through the installed
  # client flow. The storage object will ensure that if successful the good
  # credentials will get written back to file.
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)

  return credentials
Ejemplo n.º 41
0
def get_web_server_flow(scope=None):
    return client.OAuth2WebServerFlow(
        client_id=WEB_CLIENT_ID,
        client_secret=WEB_CLIENT_SECRET,
        # hd=HD,
        scope=APP_SCOPE,
        # access_type=ACCESS_TYPE,
        # approval_prompt=APPROVAL_PROMPT,
        redirect_uri=REDIRECT_URI,
        message=tools.message_if_missing(WEB_CLIENT_SECRET),
    )
    def create(self, scope):
        from oauth2client import file, client, tools

        flow = client.flow_from_clientsecrets(self.client_secrets_path,
                                              scope=scope,
                                              message=tools.message_if_missing(self.client_secrets_path))

        storage = file.Storage(self.credentials_storage_path)
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(flow, storage, self.flags)

        return credentials
Ejemplo n.º 43
0
    def __init__(self, extra_parser=None):
        self.parser = parser if not extra_parser else extra_parser

        # Parse the command-line flags.
        flags = self.parser.parse_args()
        self.flags = flags

        config_defaults = {}
        config_defaults['here'] = os.path.dirname(os.path.abspath(flags.config))
        config = SafeConfigParser(config_defaults)
        config.readfp(open(flags.config))

        if flags.section != 'DEFAULT' and not config.has_section(flags.section):
            parser.error("Specified section doesn't exist in configuration.")

        try:
            # CLIENT_SECRETS is name of a file containing the OAuth 2.0 information for this
            # application, including client_id and client_secret. You can see the Client ID
            # and Client secret on the APIs page in the Cloud Console:
            # <https://cloud.google.com/console>
            self.CLIENT_SECRETS = config.get(flags.section, 'secrets')
            self.CLIENT_CREDENTIALS = config.get(flags.section, 'credentials')
            self.INTERVAL = int(config.get(flags.section, 'interval'))
            self.GEOIPDB = config.get(flags.section, 'geoip_db')
            self.email = {}
        except NoOptionError as e:
            parser.error('Unable to get required parameter from config: {}'.format(e))

        # Get the rest of the parameters into a settings dictionary that can be
        # retrieved from this object

        self.settings = dict(config.items(flags.section))

        # Set up a Flow object to be used for authentication.
        # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
        # NEED. For more information on using scopes please see
        # <https://developers.google.com/+/best-practices>.
        self.FLOW = client.flow_from_clientsecrets(self.CLIENT_SECRETS,
                scope=[
                    'https://www.googleapis.com/auth/admin.reports.audit.readonly',
                    'https://www.googleapis.com/auth/admin.reports.usage.readonly',
                    ],
                message=tools.message_if_missing(self.CLIENT_SECRETS)
                )

        # If the credentials don't exist or are invalid run through the native client
        # flow. The Storage object will ensure that if successful the good
        # credentials will get written back to the file.
        self.storage = file.Storage(self.CLIENT_CREDENTIALS)
        self.credentials = self.storage.get()
    def get_flow(self,verbose=0):
        "returns a configured google api flow object"
        secrets=os.path.join(os.path.dirname(__file__), "client_secrets.json")
        if not os.path.isfile(secrets):
            if verbose:
                print("Could not find file: \"%s\""%secrets)
            return 0

        flow = client.flow_from_clientsecrets(secrets,
                                              scope=[
                                                  'https://www.googleapis.com/auth/calendar',
                                                  'https://www.googleapis.com/auth/calendar.readonly',
                                              ],
                                              message=tools.message_if_missing(secrets))
        return flow
Ejemplo n.º 45
0
def main(argv):
   
    # Define variable constants for the application
    CLIENT_SECRETS = 'client_secrets.json'
    SCOPE = ['https://www.googleapis.com/auth/tagmanager.readonly']

    # Parse command-line arguments
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args()
    
    # Set up a Flow object tobe used if we need to authenticate
    flow = client.flow_from_clientsecrets(
        CLIENT_SECRETS,
        scope=SCOPE,
        message=tools.message_if_missing(CLIENT_SECRETS))
    
    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid, run through the native client
    # flow. The Storage object will ensure that if successful, the good
    # credentials will be written back to a file.
    storage = file.Storage('tagmanager.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())
    
    # Build the service object
    service = build('tagmanager', 'v1', http=http)
    
    # Get all accounts the user has access to
    accounts = service.accounts().list().execute()

    # If the user has access to accounts, open accounts.txt and
    # write the account and container names the user can access
    if len(accounts):
        with open('accounts.txt', 'w') as f:
            for a in accounts['accounts']:
                f.write('Account: ' + 
                        unicode(a['name']).encode('utf-8') + 
                        '\n')
                # Get all the containers under each account
                containers = service.accounts().containers().list(
                    accountId=a['accountId']).execute()
                if len(containers):
                    for c in containers['containers']:
                        f.write('Container: ' + 
                                unicode(c['name']).encode('utf-8') + 
                                '\n')
def initialize_service(token_file_path, client_secrets_file_path):
    flow = client.flow_from_clientsecrets(client_secrets_file_path,
                                          scope=[
                                          'https://www.googleapis.com/auth/analytics',
                                          'https://www.googleapis.com/auth/analytics.readonly',
                                          ],
                                          message=tools.message_if_missing(client_secrets_file_path))

    storage = file.Storage(token_file_path)
    credentials = storage.get()
    flags = parser.parse_args([])
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = httplib2.Http()
    http = credentials.authorize(http)
    return discovery.build('analytics', 'v3', http=http)
Ejemplo n.º 47
0
def checkAccount(username):
    # Parser for command-line arguments.
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])

    # CLIENT_SECRETS is name of a file containing the OAuth 2.0 information for
    # this application, including client_id and client_secret. You can see the
    # Client ID and Client secret on the APIs page in the Cloud Console:
    # <https://cloud.google.com/console#/project/39017739811/apiui>
    CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), \
                                  'client_secrets.json')

    # Set up a Flow object to be used for authentication.
    # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
    # NEED. For more information on using scopes please see
    # <https://developers.google.com/+/best-practices>.
    FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS,
      scope=[
          'https://www.googleapis.com/auth/calendar'
        ],
        message=tools.message_if_missing(CLIENT_SECRETS))

    argv=sys.argv
    
    # Parse the command-line flags.
    flags = parser.parse_args(argv[1:])

    # If the credentials don't exist or are invalid run through the native
    # client flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.

    fileName='%s.dat'%username
    storage = file.Storage(fileName)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)

    # Create an httplib2.Http object to handle our HTTP requests and authorize
    # it with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = discovery.build('calendar', 'v3', http=http)

    return service
Ejemplo n.º 48
0
def reinit_storage(argv):
	parser = argparse.ArgumentParser(
		description=__doc__,
		formatter_class=argparse.RawDescriptionHelpFormatter,
		parents=[tools.argparser])
	
	CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
	FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS,
	  scope=[
		  'https://www.googleapis.com/auth/devstorage.full_control',
		  'https://www.googleapis.com/auth/devstorage.read_only',
		  'https://www.googleapis.com/auth/devstorage.read_write',
		],
		message=tools.message_if_missing(CLIENT_SECRETS))
	storage = file.Storage(os.path.join(os.path.dirname(__file__), 'sample.dat'))
	flags = parser.parse_args(argv[1:])
	credentials = tools.run_flow(FLOW, storage, flags)
Ejemplo n.º 49
0
 def _create_flow(self, secrets):
     '''
     Create an authentication flow based on the secrets file
     
     Parameters
     ----------
     secrets : str
         File name for client secrets
         
     Notes
     -----
     See google documentation for format of secrets file
     '''
     flow = client.flow_from_clientsecrets(secrets, scope=self._scope, \
                 message=tools.message_if_missing(secrets))
     
     return flow
Ejemplo n.º 50
0
def auth(token_file_path, client_secrets_file_path, parameters):
    if not os.path.exists(client_secrets_file_path):
        print client_secrets_file_path, u'is not exists.'
        exit(1)
    print client_secrets_file_path
    flow = client.flow_from_clientsecrets(client_secrets_file_path,
                                          scope=[
                                          'https://www.googleapis.com/auth/analytics',
                                          'https://www.googleapis.com/auth/analytics.readonly',
                                          ],
                                          message=tools.message_if_missing(client_secrets_file_path))

    storage = file.Storage(token_file_path)
    credentials = storage.get()
    flags = parser.parse_args(parameters)
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
Ejemplo n.º 51
0
def init_cal_service():
    """Creates googleapis service for calendar
        Modified from the Google apiclient.sample_tools code which is
        licensed under the Apache License, Version 2.0,
        available at:
        http://www.apache.org/licenses/LICENSE-2.0

        Changes were made to remove unneeded arguments and add offline
        access to the flow
    """

    name = 'calendar'
    version = 'v3'
    scope='https://www.googleapis.com/auth/calendar.readonly'

    # Create the flags
    parent_parsers = [tools.argparser]
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=parent_parsers)
    flags = parser.parse_args(['--noauth_local_webserver'])

    client_secrets = os.path.join(os.path.dirname(__file__),
                                  'client_secrets.json')

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(client_secrets,
        scope=scope,
        message=tools.message_if_missing(client_secrets))
    flow.params['access_type'] = 'offline'

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage(name + '.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
      credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http = httplib2.Http())

    # Construct a service object via the discovery service.
    service = discovery.build(name, version, http=http)
    return service
Ejemplo n.º 52
0
	def setup(self):
	
		# CLIENT_SECRETS is name of a file containing the OAuth 2.0 information for this
		# application, including client_id and client_secret. You can see the Client ID
		# and Client secret on the APIs page in the Cloud Console:
		# <https://cloud.google.com/console#/project/102389784529/apiui>
		# CLIENT_SECRETS = os.path.join(os.path.basename(__file__), 'client_secrets.json')
		CLIENT_SECRETS = 'client_secrets.json'
		FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS,
		  scope=[
		      'https://www.googleapis.com/auth/calendar',
		      'https://www.googleapis.com/auth/calendar.readonly',
		    ],
		    message=tools.message_if_missing(CLIENT_SECRETS))
		

		# If the Credentials don't exist or are invalid, run through the native client
		# flow. The Storage object will ensure that if successful the good
		# Credentials will get written back to a file.
		storage = Storage('calendar.dat')
		self.credentials = storage.get()
		try:
			api_keys_file = open('google_secrets.json')
			api_keys = json.load(api_keys_file)
		except Exception as e:
			print "The following error occurred. Do you have an api_secrets.json file? %s" % e
			sys.exit()

		try:
			self.GOOGLE_CALENDAR_DEVELOPER_KEY = api_keys['GOOGLE_CALENDAR_DEVELOPER_KEY']
		except Exception as e:
			print 'The following error occurred. We could not process your Google Calendar API key. It should be of format' + \
 					'{ "GOOGLE_CALENDAR_API_KEY": "YOUR API KEY HERE"} \n %s' % e
			sys.exit()

		try:
			self.GOOGLE_CALENDAR_ID = api_keys['GOOGLE_CALENDAR_ID']
		except Exception as e:
			print "The following error occurred: %s" % e
		api_keys_file.close()
		if self.credentials is None or self.credentials.invalid == True:
		  self.credentials = tools.run(FLOW, storage)
Ejemplo n.º 53
0
def GetTasks():
    # CLIENT_SECRETS is name of a file containing the OAuth 2.0 information for this
    # application, including client_id and client_secret. You can see the Client ID
    # and Client secret on the APIs page in the Cloud Console:
    # <https://cloud.google.com/console#/project/440632827315/apiui>
    CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')

    # Set up a Flow object to be used for authentication.
    # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
    # NEED. For more information on using scopes please see
    # <https://developers.google.com/+/best-practices>.
    FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS, scope=['https://www.googleapis.com/auth/tasks',
                                                                 'https://www.googleapis.com/auth/tasks.readonly', ],
                                          message=tools.message_if_missing(CLIENT_SECRETS))
    # Parse the command-line
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
                                     parents=[tools.argparser])
    flags = parser.parse_args([])
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    storage = file.Storage(os.path.join(os.path.dirname(__file__), 'tasks.dat'))
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)
    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)
    # Construct the service object for the interacting with the Tasks API.
    service = discovery.build('tasks', 'v1', http=http)

    try:
        tasklists = service.tasklists().list().execute()
        mytasklistID = tasklists['items']
        mytasklistID = mytasklistID[0]
        mytasklistID = mytasklistID['id']
        tasks = service.tasks().list(tasklist=mytasklistID).execute()
        return tasks
    except client.AccessTokenRefreshError:
        print("The credentials have been revoked or expired.")
        return None
Ejemplo n.º 54
0
def api_con( scope, store, name, version):
	#Identify client secret file
	client_secrets = os.path.join( os.path.dirname(sys.argv[0]), 'client_secret.json')
		
	#Establish flow for API connection
	flow = client.flow_from_clientsecrets( client_secrets, scope, message=tools.message_if_missing(client_secrets))
		
	#Establishes storage file
	storage = authFile.Storage(store)
		
	#Checks for credentials and builds new credentials if none are found
	credentials = storage.get()
	if credentials is None or credentials.invalid:
		flags = tools.argparser.parse_args(args=[])
		credentials = tools.run_flow( flow, storage, flags)
		
	http = credentials.authorize(http = httplib2.Http())
		
	#Generates and runs a service object
	return discovery.build( name, version, http=http)
def get_auth_token():
    scope = 'https://www.googleapis.com/auth/contacts.readonly'
    user_agent = __name__
    client_secrets = os.path.join(os.path.dirname(__file__), CLIENT_SECRETS_JSON)
    filename = os.path.splitext(__file__)[0] + '.dat'

    flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=tools.message_if_missing(client_secrets))
    
    storage = file.Storage(filename)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        if args.non_interactive:
            sys.stderr.write('ERROR: Invalid or missing Oauth2 credentials. To reset auth flow manually, run without --non_interactive\n')
            sys.exit(1)
        else:
            credentials = tools.run_flow(flow, storage, args)

    j = json.loads(open(filename).read())

    return gdata.gauth.OAuth2Token(j['client_id'], j['client_secret'], scope, user_agent, access_token = j['access_token'], refresh_token = j['refresh_token'])
Ejemplo n.º 56
0
    def gen_credentials(self):
        """Generate credentials with Google OAuth2.0 server,
            or use authentication tokens
        """
        result = True

##        print("(gen_credentials) -- Path:",self.configpaths['CLIENT_SECRETS'])
        CLIENT_SECRETS = self.configpaths['CLIENT_SECRETS']

        # CLIENT_SECRETS is name of a file containing the OAuth 2.0 information for this
        # application, including client_id and client_secret. You can see the Client ID
        # and Client secret on the APIs page in the Cloud Console:
        # <https://cloud.google.com/console#/project/561458633478/apiui>
        if CLIENT_SECRETS is None:
            print('(gen_credentials) -- Failed to find client_secrets file.')
            result = False

        # If the credentials don't exist or are invalid run through the native client
        # flow. The Storage object will ensure that if successful the good
        # credentials will get written back to the file.
        try:
            storage = file.Storage(self.configpaths['AUTH']) ## Read, or write to config path if necessary
            self.config['CREDENTIALS'] = storage.get()
            if self.config['CREDENTIALS'] is None or self.config['CREDENTIALS'].invalid:
                print('(gen_credentials) -- Re-authenticating and re-writing credentials.')

                # Set up a Flow object to be used for authentication.
                # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
                # NEED. For more information on using scopes please see
                # <https://developers.google.com/+/best-practices>.
                FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS,
                  scope=[
                      'https://www.googleapis.com/auth/calendar',
                      'https://www.googleapis.com/auth/calendar.readonly',
                    ],
                    message=tools.message_if_missing(CLIENT_SECRETS))
                self.config['CREDENTIALS'] = tools.run_flow(FLOW, storage, flags)
        except:
            result = False

        return result
Ejemplo n.º 57
0
    def __init__(self, secrets_filename, args, credentials_filename='calendar.dat'):
        self._parser = argparse.ArgumentParser(
            description=__doc__,
            formatter_class=argparse.RawDescriptionHelpFormatter,
            parents=[tools.argparser]
        )
        self._secrets_filename = os.path.join(os.path.dirname(__file__), secrets_filename)
        self._flow = client.flow_from_clientsecrets(
            self._secrets_filename,
            scope=['https://www.googleapis.com/auth/calendar.readonly'],
            message=tools.message_if_missing(self._secrets_filename)
        )
        self._service = None

        flags = self._parser.parse_args(args[1:])
        storage = file.Storage(credentials_filename)
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(self._flow, storage, flags)

        self.authorize(credentials)
Ejemplo n.º 58
0
def get_service(name, version, filename, scope):
    """指定された Google API に接続する

    name: APIの名前
    version: APIのバージョン(通常 v3)
    file: ファイルの場所を指定する、通常 __file__ を使用する
    scope: OAuth のスコープを指定する

    serviceオブジェクトを返す
    """

    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()

    # Name of a file containing the OAuth 2.0 information for this
    # application, including client_id and client_secret, which are found
    # on the API Access tab on the Google APIs
    # Console <http://code.google.com/apis/console>.
    client_secrets = os.path.join(os.path.dirname(filename),
                                  'client_secrets.json')

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets,
        scope=scope,
        message=tools.message_if_missing(client_secrets))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native
    # client flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storagefile = os.path.join(os.path.dirname(filename),
                               name + '.dat')
    storage = file.Storage(storagefile)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http = httplib2.Http())

    service = discovery.build(name, version, http=http)
    return service
def get_service(api_name, api_version, scope, client_secrets_path):
    """Get a service that communicates to a Google API.
    
    Args:
      api_name: string The name of the api to connect to.
      api_version: string The api version to connect to.
      scope: A list of strings representing the auth scopes to authorize for the
        connection.
      client_secrets_path: string A path to a valid client secrets file.
    
    Returns:
      A service that is connected to the specified API.
    """
    # Parse command-line arguments.
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])
    
    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets_path, scope=scope,
        message=tools.message_if_missing(client_secrets_path))
    
    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage(api_name + '.dat')
    credentials = storage.get()
    http=httplib2.Http(ca_certs='cacerts.txt')
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags, http)
    http = credentials.authorize(http)
    
    # Build the service object.
    service = build(api_name, api_version, http=http)
    
    return service