Example #1
0
def youtube_setup(course_id, force_load=False):
    global api_youtube
    global api_youtube_analytics

    youtube_scopes = ["https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly"]
    youtube_servicename = "youtube"
    youtube_version = "v3"
    youtube_analytics_servicename = "youtubeAnalytics"
    youtube_analytics_version = "v1"

    flow = OAuth2WebServerFlow(client_id=settings.YOUTUBE_CLIENT_ID,
                           client_secret=settings.YOUTUBE_CLIENT_SECRET,
                           scope=" ".join(youtube_scopes))

    storage = Storage("cache/youtube_"+course_id+"_oauth2.json")
    youtube_credentials = storage.get()

    print "AAA"
    print youtube_credentials
    print "BBB"

    if youtube_credentials is None or youtube_credentials.invalid:
        if not force_load:
            return False
        youtube_credentials = run_flow(flow, storage)
        # youtube_credentials = run(flow, storage)

    http = youtube_credentials.authorize(httplib2.Http())
    api_youtube = build(youtube_servicename, youtube_version, http=http)
    api_youtube_analytics = build(youtube_analytics_servicename, youtube_analytics_version, http=http)
    return True
    def handle(self, *args, **options):
        print("=" * 50)
        print(" Login to Google Calendar API")
        print("=" * 50)
        flow = flow_from_clientsecrets(
            settings.GOOGLE_CALENDAR_CLIENT_SECRETS,
            scope='https://www.googleapis.com/auth/calendar',
            redirect_uri='urn:ietf:wg:oauth:2.0:oob')

        auth_uri = flow.step1_get_authorize_url()

        print("Open the following URL to authorize the API")
        print()
        print(auth_uri)
        print()
        code = input("Please fill the code: ")

        if not code:
            print("Canceled")
            exit(1)

        credentials = flow.step2_exchange(code)

        storage = Storage(settings.GOOGLE_CALENDAR_CREDENTIALS)
        storage.put(credentials)

        print("Credentials are saved in '{}'".format(
            settings.GOOGLE_CALENDAR_CREDENTIALS))
    def setup(self, client_secrets):
        storage = Storage("credentials.dat")
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            flow = flow_from_clientsecrets(
                client_secrets,
                scope="https://www.googleapis.com/auth/genomics",
                message="You need to copy a client_secrets.json file into this directory, "
                "or pass in the --client_secrets_filename option to specify where "
                "one exists. See the README for more help.",
            )

            # There's probably a better way to generate the 'flags' object.  Doing it this way for now.
            parser = argparse.ArgumentParser(
                description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]
            )
            parser.add_argument(
                "--client_secrets_filename",
                default=client_secrets,
                help="The filename of a client_secrets.json file from a "
                'Google "Client ID for native application" that '
                "has the Genomics API enabled.",
            )
            flags = parser.parse_args()

            credentials = run_flow(flow, storage, flags)
            # Create a genomics API service
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build("genomics", "v1beta2", http=http)
        return service
Example #4
0
def get_bigquery_jobs_service (authdir, args):
    """`args` should be a list of command-line arguments *not* containing the
    traditional `argv[0]` value.

    """
    import httplib2
    from oauth2client.file import Storage
    from oauth2client.client import flow_from_clientsecrets
    from oauth2client.tools import argparser, run_flow
    from googleapiclient.discovery import build

    storage = Storage (os.path.join (authdir, BQ_CREDENTIALS_FILE))
    credentials = storage.get ()
    projid = read_secret_line (os.path.join (authdir, BQ_PROJECT_FILE))

    if credentials is None or credentials.invalid:
        flow = flow_from_clientsecrets (os.path.join (authdir, BQ_SECRETS_FILE),
                                        scope='https://www.googleapis.com/auth/bigquery')
        parser = argparse.ArgumentParser (description='bigquery auth', parents=[argparser])
        flags = parser.parse_args (args)
        credentials = run_flow (flow, storage, flags)

    http = httplib2.Http ()
    http = credentials.authorize (http)
    bq = build ('bigquery', 'v2', http=http)

    # Hackity hack to not have to drag a projectId around.
    jobs = bq.jobs ()
    jobs.my_project_id = projid
    return jobs
Example #5
0
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'pill_cal.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
Example #6
0
	def _connect(self, scope="https://www.googleapis.com/auth/drive",
					redirect_url="urn:ietf:wg:oauth:2.0:oob", saved_credentials="drive_cred.txt"):
		""" Start connection for Google drive

		:param scope: Service to access
		:param redirect_url: URI handled by application
		:param storage: Store authorization credentials to avoid auth every time
		"""
		flow = OAuth2WebServerFlow(
				self._key, self._secret,
				scope, redirect_url)

		storage = Storage(saved_credentials)
		credentials = storage.get()

		if credentials is None:
			auth_url = flow.step1_get_authorize_url()
			print '1. Go to: ' + auth_url
			print '2. Click "Allow" (you might have to log in first)'
			print '3. Copy the authorization code.'
			code = raw_input("Enter the authorization code here: ").strip()
			credentials = flow.step2_exchange(code)
		else:
			print 'Previous authorization will be used!'

		http = httplib2.Http()
		http = credentials.authorize(http)
		print "Authorization successful!"

		self._client = build("drive", "v2", http=http)

		storage.put(credentials)
    def __enter__(self):
        # Ensure that we have not re-entered
        if self.temp_path != None or self.service != None:
            raise Exception('Cannot use multiple nested with blocks on same Youtube object!')

        flow = flow_from_clientsecrets(
            self.client_secrets_path,
            scope=YOUTUBE_UPLOAD_SCOPE,
            message=MISSING_CLIENT_SECRETS_MESSAGE)

        temp_file = NamedTemporaryFile(delete=False)
        self.temp_path = temp_file.name
        temp_file.close()

        storage = Storage(self.temp_path)
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            credentials = run_flow(
                flow, storage, argparser.parse_args(list())
            )

        self.service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
            http=credentials.authorize(httplib2.Http()))

        return self
Example #8
0
def main(argv):
    # create the orchestration object
    gce_cluster = GceCondor(None, PROJECT_ID)

    # create the top-level parser
    parser = argparse.ArgumentParser(parents=[argparser])
    subparsers = parser.add_subparsers()

    # create the parser for the "start_cluster" command
    parser_start = subparsers.add_parser('start', help="start a condor cluster")
    parser_start.add_argument('node_count', type=int, default=1, help="the number of nodes, including master")
    parser_start.add_argument('-i', '--image', action="store_true", help="create instance from predefined image")
    parser_start.set_defaults(func=gce_cluster.start)

    # create the parser for the "terminate" command
    parser_terminate = subparsers.add_parser('terminate', help="shutdown cluster, ie terminate all instances in project")
    parser_terminate.set_defaults(func=gce_cluster.terminate)

    args = parser.parse_args(argv)

    # Perform OAuth 2.0 authorization.
    flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=GCE_SCOPE)
    storage = Storage(OAUTH2_STORAGE)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, args)
    http = httplib2.Http()
    auth_http = credentials.authorize(http)

    # update the orchestration object with the authorized Http object
    gce_cluster.set_auth_http(auth_http)

    # perform the command
    args.func(args)
def revJSON(file_ID, file_Name):
	print "pulling credentials"
	myCreds = Storage('my_credentials.json')
	credentials = myCreds.get()

	print "authorizing HTTP request"
	http = httplib2.Http()
	http = credentials.authorize(http)

	print "building API resource"
	drive_service = build('drive', 'v2', http=http)

	data_file = time.strftime("Challenges/" + file_Name + ".json")

	try:
		directory = os.path.dirname(data_file)
		os.makedirs(directory)
	except:
		print "directory already exists"

	for revNum in xrange(1,300):

		print "calling API"
		stringRev = str(revNum)
		try:
			revisions = drive_service.revisions().get(fileId=file_ID, revisionId=stringRev).execute()

			rev =  open(data_file, "a+")
			jRevs = json.dump(revisions, rev)
			rev.write("\n")
			rev.close()

			print "Saved Revision %d" % revNum
		except:
			print "Revision %d doesn't exist" % revNum
Example #10
0
def OAuth2Login(client_secrets, credential_store, email):
    scope='https://picasaweb.google.com/data/'
    user_agent='picasawebuploader'

    storage = Storage(credential_store)
    credentials = storage.get()
    
    if credentials is None or credentials.invalid:
        flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
        uri = flow.step1_get_authorize_url()
        webbrowser.open(uri)
        code = raw_input('Enter the authentication code: ').strip()
        credentials = flow.step2_exchange(code)
    if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
        http = httplib2.Http()
        http = credentials.authorize(http)
        credentials.refresh(http)

    storage.put(credentials)

    gd_client = gdata.photos.service.PhotosService(source=user_agent,
                                                   email=email,
                                                   additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})

    return gd_client
Example #11
0
def authenService():
    CLIENT_SECRETS_FILE = "client_secrets.json"
    #display following message if file not found
    MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

   %s

with information from the Developers Console
https://console.developers.google.com/

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

    YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
    YOUTUBE_API_SERVICE_NAME = "youtube"
    YOUTUBE_API_VERSION = "v3"

    flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,message=MISSING_CLIENT_SECRETS_MESSAGE,scope=YOUTUBE_READ_WRITE_SCOPE)

    storage = Storage("%s-oauth2.json" % sys.argv[0])
    credentials = storage.get()

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

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,http=credentials.authorize(httplib2.Http()))
    return youtube
def get_credentials(calendar_name):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    credentials_file = settings.CALENDAR_CREDENTIALS[calendar_name]["credentials_file"]
    client_secret_file = settings.CALENDAR_CREDENTIALS[calendar_name]["client_secret_file"]

    project_dir = os.path.dirname(os.path.realpath(__file__))
    credential_dir = project_dir
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, credentials_file)

    store = Storage(credential_path)
    credentials = store.get()

    if not credentials or credentials.invalid:
        client_secret_file_path = os.path.join(project_dir, client_secret_file)
        flow = client.flow_from_clientsecrets(client_secret_file_path, SCOPES)
        flow.user_agent = APPLICATION_NAME

        flags = tools.argparser.parse_args(args=[])
        credentials = tools.run_flow(flow, store, flags)

        logger.info('[google_calendar_backend] Storing GCal acccess credentials to ' + credential_path)

    return credentials
  def test_pickle_and_json_interop(self):
    # Write a file with a pickled OAuth2Credentials.
    access_token = 'foo'
    client_id = 'some_client_id'
    client_secret = 'cOuDdkfjxxnv+'
    refresh_token = '1/0/a.df219fjls0'
    token_expiry = datetime.datetime.utcnow()
    token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
    user_agent = 'refresh_checker/1.0'

    credentials = OAuth2Credentials(
        access_token, client_id, client_secret,
        refresh_token, token_expiry, token_uri,
        user_agent)

    f = open(FILENAME, 'w')
    pickle.dump(credentials, f)
    f.close()

    # Storage should be not be able to read that object, as the capability to
    # read and write credentials as pickled objects has been removed.
    s = Storage(FILENAME)
    read_credentials = s.get()
    self.assertEquals(None, read_credentials)

    # Now write it back out and confirm it has been rewritten as JSON
    s.put(credentials)
    f = file(FILENAME)
    data = simplejson.load(f)
    f.close()

    self.assertEquals(data['access_token'], 'foo')
    self.assertEquals(data['_class'], 'OAuth2Credentials')
    self.assertEquals(data['_module'], OAuth2Credentials.__module__)
Example #14
0
def GetGoogleClient(filename):
  logging.debug("Creating Google client")
  credentials = Storage(filename).get()
  http = credentials.authorize(httplib2.Http())
  client = build('fitness', 'v1', http=http)
  logging.debug("Google client created")
  return client
Example #15
0
    def _get_service(self):
        """Create and return the Google Calendar service object, using the
        credentials file generated through the command::

            python manage.py --authorize

        The service object is used to make API requests to Google Calendar, but
        will raise IOError if the credentials file is not generated

        :raises: IOError, NotImplementedError

        :returns: The Google Calendar service.
        """
        storage = Storage(
            e.eventum.app.config['EVENTUM_INSTALLED_APP_CREDENTIALS_PATH'])
        credentials = storage.get()

        if credentials is None:
            raise IOError

        if credentials.invalid is True:
            raise NotImplementedError

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

        return build('calendar', 'v3', http=http)
def get_email_service(config):
    """Return an authorized Gmail API service instance."""
    google_client_secret_path = config.get_google_client_secret_path()
    print("google_client_secret_path: {0}".format(google_client_secret_path))
    # The "scope" scope allows--
    #   "Create, read, update, and delete drafts. Send messages and drafts."
    # Check https://developers.google.com/gmail/api/auth/scopes for all
    # available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'
    # Start the OAuth flow to retrieve credentials
    flow = flow_from_clientsecrets(google_client_secret_path, scope=OAUTH_SCOPE)

    http = httplib2.Http()
    # Get default flags.
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args([])
    print("debug: flags: {0!r}".format(flags))
    # Location of the credentials storage file
    storage_path = config.get_gmail_storage_path()
    storage = Storage(storage_path)
    # Try to retrieve credentials from storage or run the flow to generate them
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags=flags, http=http)

    # Authorize the httplib2.Http object with our credentials
    http = credentials.authorize(http)

    # Build the Gmail service from discovery
    gmail_service = build('gmail', 'v1', http=http)

    return gmail_service
Example #17
0
    def __init__(self, config_fields):
        """
        Initialize the Google Drive handler using configuration dictionary fields.

        Args:
            config_fields (dict): String dictionary from the configuration segment

        Configuration Fields:
            access_token (str): Repository access token
        OAuth Interactive Configuration Fields:
            client_id (str): Client Id to use for OAuth validation
            client_secret (str): Client secret to use for OAuth validation
            cred_file (str): Full filepath to store credentials used for access.
        """
        flow = OAuth2WebServerFlow(config_fields["client_id"],
                                   config_fields["client_secret"],
                                   self.SCOPES)
        try:
            storage = Storage(config_fields["cred_file"])
        except:
            storage = Storage(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                           "gdc.dat"))
        credentials = storage.get()

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

        # Create an httplib2.Http object to handle our HTTP requests, and authorize it
        # using the credentials.authorize() function.
        http = httplib2.Http()
        http = credentials.authorize(http)
        self.client = discovery.build('drive', 'v3', http=http)
    def oauth2_login(self):
        """
        :return:
        """
        user_agent = "picasawebuploader"

        storage = Storage(self.credential_storage + self.user + ".dat")
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            print "Failed to get credential in cache. Going to get new"
            credentials = self.get_credentials()

        if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
            http = httplib2.Http()
            http = credentials.authorize(http)
            credentials.refresh(http)

        storage.put(credentials)

        gd_client = gdata.photos.service.PhotosService(
            source=user_agent,
            email=self.user + "@gmail.com",
            additional_headers={"Authorization": "Bearer %s" % credentials.access_token},
        )

        return gd_client
def main():

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

    flow = flow_from_clientsecrets(client_secrets_path,
                                   scope='https://www.googleapis.com/auth/bigquery')

    storage = Storage('bigquery_credentials.dat')
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        # Run oauth2 flow with default arguments.
        credentials = tools.run_flow(flow, storage, tools.argparser.parse_args([]))

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


    # todo: make a dataset and table?
    service = build('bigquery', 'v2', http=http)
    projectId = '907668440978'
    datasetId = 'isb_cgc'
    targetTableId = 'fmdata_egfr'
    sourceCSV = ['gs://fmdata/allDataMerge.EGFR.blankNA.csv']
    loadTable(service, projectId, datasetId, targetTableId, sourceCSV, schema_fm)
Example #20
0
def authorized_http(client_id, client_secret, apps, file=None):
    """
    Start an authorized HTTP session.

    Try fetching valid user credentials from storage. If nothing has been
    stored, or if the stored credentials are invalid, complete the OAuth2 flow
    to obtain new credentials.
    """
    if not os.path.exists(CREDENTIAL_DIR):
        os.makedirs(CREDENTIAL_DIR)

    credential_path = file or CREDENTIAL_PATH
    storage = Storage(credential_path)
    credentials = storage.get()

    scopes = set([
        "https://www.googleapis.com/auth/{0}.readonly".format(app)
        for app in apps
        ])

    if (not credentials or credentials.invalid
            or not scopes <= credentials.scopes):
        flow = OAuth2WebServerFlow(
            client_id=client_id,
            client_secret=client_secret,
            scope=scopes,
            redirect_uri=REDIRECT_URI)
        flow.user_agent = USER_AGENT

        # Do not parse did command-line options by OAuth client
        flags = tools.argparser.parse_args(args=[])
        credentials = tools.run_flow(flow, storage, flags)

    return credentials.authorize(httplib2.Http())
Example #21
0
def build(*args, **kwargs):
    ip = get_ipython()
    if 'google_credential_path' in kwargs:
        credential_path = kwargs['google_credential_path']
        del kwargs['google_credential_path']
    elif 'Googleapihelper' in ip.config and 'credential_path' in ip.config.Googleapihelper:
        credential_path = ip.config.Googleapihelper['credential_path']
    else:
        logger.info('Credential store path not specified, trying default: '+
                DEFAULT_CREDENTIALS_PATH)
        credential_path = DEFAULT_CREDENTIALS_PATH

    if 'google_secrets_path' in kwargs:
        secrets_path = kwargs['google_secrets_path']
        del kwargs['google_secrets_path']
    elif 'Googleapihelper' in ip.config and 'secrets_path' in ip.config.Googleapihelper:
        secrets_path = ip.config.Googleapihelper['secrets_path']
    else:
        logger.info('Secrets path not specified, trying default: '+
                DEFAULT_SECRETS_PATH)
        secrets_path = DEFAULT_SECRETS_PATH

    if 'redirect_uri' in kwargs:
        redirect_uri = kwargs['redirect_uri']
        del kwargs['redirect_uri']
    elif 'Googleapihelper' in ip.config and 'redirect_uri' in ip.config.Googleapihelper:
        redirect_uri = ip.config.Googleapihelper['redirect_uri']
    else:
        logger.info('Redirect uri not specified, trying default: '+
            DEFAULT_REDIRECT_URI)
        redirect_uri = DEFAULT_REDIRECT_URI

    if 'scope' in kwargs:
        scope = kwargs['scope']
        del kwargs['scope']
    elif 'Googleapihelper' in ip.config and 'scope' in ip.config.Googleapihelper:
        scope = ip.config.Googleapihelper['scope']
    else:
        logger.error('No scope specified in options or ipython config. '+
            'Store scope in ipython profile or specify on command line.')
        return None

    storage = Storage(credential_path)
    credentials = storage.get()

    if credentials is None:
        flow = flow_from_clientsecrets(secrets_path, scope=scope,
                    redirect_uri=redirect_uri)
        flags, kwargs = extract_flags_from_kwargs(kwargs)
        tools.run_flow(flow, storage, flags)
        credentials = storage.get()

    if credentials is None:
        logger.error("Unable to retrieve google oauth credentials")
        return None

    http = httplib2.Http()
    http = credentials.authorize(http)
    kwargs['http'] = http
    return discovery.build(*args, **kwargs)
Example #22
0
    def __init__(self, job_description, saga_url, pilot_compute_description):
        
        self.job_description = job_description
        self.saga_url = saga_url
        self.pilot_compute_description = pilot_compute_description
        self.image_url = GCE_IMAGE_URL
        if self.pilot_compute_description.has_key("vm_id"):
            self.image_url = self.pilot_compute_description["vm_id"]
            
        self.machine_type = "https://www.googleapis.com/compute/v1beta12/projects/bigjob-pilot/machine-types/n1-standard-1"
        if self.pilot_compute_description.has_key("vm_type"):
            self.machine_type = self.pilot_compute_description["vm_type"]
        
        self.location = "https://www.googleapis.com/compute/v1beta12/projects/bigjob-pilot/zones/us-east1-a"
        if self.pilot_compute_description.has_key("vm_location"):
            self.location = self.pilot_compute_description["vm_location"]
       
            
        self.id="bigjob-" + str(uuid.uuid1())
        self.network_ip=None
        
        # Do OAUTH authentication
        storage = Storage('gce.dat')
        self.credentials = storage.get()
        if self.credentials is None or self.credentials.invalid == True:
            flow = OAuth2WebServerFlow(
                                       client_id=OAUTH2_CLIENT_ID,
                                       client_secret=OAUTH2_CLIENT_SECRET,
                                       scope='https://www.googleapis.com/auth/compute',
                                       user_agent='bigjob-client/1.0')

            self.credentials = run(flow, storage)
Example #23
0
def get_authenticated_service(oauth_file):

  args = namedtuple('flags', [
            'noauth_local_webserver',
            'logging_level'
            ] )

  args.noauth_local_webserver = True
  args.logging_level='ERROR'

  # how and where tokens are stored
  storage = Storage(oauth_file)

  # http://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.multistore_file-module.html

  credentials = storage.get()

  if credentials is None or credentials.invalid:

      flow = flow_from_clientsecrets( CLIENT_SECRETS_FILE,
              scope=YOUTUBE_READ_WRITE_SCOPE,)

      # do the "allow access" step, save token.
      credentials = run_flow(flow, storage, args)

  return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    http=credentials.authorize(httplib2.Http()))
Example #24
0
  def Authenticate(self):
    f = Auth(KEYS_FILE)

    # OAuth 2.0 Authentication
    flow = OAuth2WebServerFlow(
      client_id=f.GetClientId(),
      client_secret=f.GetClientSecret(),
      scope='https://www.googleapis.com/auth/tasks',
      user_agent='Tasky/v1')

    # If 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(os.path.join(TASKY_DIR, 'tasks.dat'))
    credentials = storage.get()

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

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

    # The main Tasks API object.
    self.service = build(
      serviceName='tasks', version='v1', http=http,
      developerKey=f.GetApiKey())
Example #25
0
    def __build_service(self):
        """ Creates the service object and based on the credentials stored in
        config.py """

        flow = OAuth2WebServerFlow(
            client_id=config.client_id,
            client_secret=config.client_secret,
            scope='https://www.googleapis.com/auth/calendar',
            user_agent=config.user_agent)    

        storage = Storage(self.credentials_filename)
        credentials = storage.get()
        if credentials is None or credentials.invalid == True:
            credentials = run(flow, storage)

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

        service = build(
            serviceName="calendar",
            version="v3",
            http=http,
            developerKey=config.developer_key)

        return service
Example #26
0
 def refreshCredentials(self):
     storage = Storage('credentials.dat')
     credentials = storage.get()
     # Create an httplib2.Http object and authorize it with our credentials
     http = httplib2.Http()        
     credentials.refresh(http)
     return credentials
def main():

  storage = Storage('bigquery_credentials.dat')
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    # Run oauth2 flow with default arguments.
    credentials = tools.run_flow(FLOW, storage, tools.argparser.parse_args([]))

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

  bigquery_service = build('bigquery', 'v2', http=http)

  try:
    query_request = bigquery_service.jobs()
    query_data = {'query':'SELECT TOP( title, 10) as title, COUNT(*) as revision_count FROM [publicdata:samples.wikipedia] WHERE wp_namespace = 0;'}

    query_response = query_request.query(projectId=PROJECT_NUMBER,
                                         body=query_data).execute()
    print 'Query Results:'
    for row in query_response['rows']:
      result_row = []
      for field in row['f']:
        result_row.append(field['v'])
      print ('\t').join(result_row)

  except HttpError as err:
    print 'Error:', pprint.pprint(err.content)

  except AccessTokenRefreshError:
    print ("Credentials have been revoked or expired, please re-run"
           "the application to re-authorize")
Example #28
0
 def gdrive_login(self):
     """ Logins to the gdrive using the your credentials - no input needed"""
     # Authenticate and get a service object
     attempt_1=0
     while attempt_1 < 4:
         try:
         
             # Send in client secret and client ID to the authetication server. Need to set this up in google developer console to get the client secrets and ID
             # Then need to also activate google analytics in the allowed applications
             flow = OAuth2WebServerFlow(
                 self.client_id,
                 self.client_secret,
                 'https://www.googleapis.com/auth/drive')
             
             # Stores the credentials in credentials.dat (i think)
             storage = Storage('credentials_gdrive.dat')
             credentials = storage.get()
             if credentials is None or credentials.invalid:
                 credentials = run(flow, storage)
             
             # Use the credentials to get authentication?
             # Finally if this is the first time, your browser should pop to ask for login and permission allowing app
             http = httplib2.Http()
             http = credentials.authorize(http)
             self.service_gd = build('drive', 'v2', http=http)
             attempt_1=100
 
         except Exception as e_connection:
             attempt_1+=1            
             self.logger.info('Exception is: '+str(e_connection))
             self.logger.info('Attempt number '+str(attempt_1))     
             time.sleep(7)
             pass
             print ('Exception is: '+str(e_connection)+'\n'+'Attempt number '+str(attempt_1))
def get_biqquery_service(CLIENT_SECRET='client_secret_big_query.json'):

    FLOW = flow_from_clientsecrets(CLIENT_SECRET, scope='https://www.googleapis.com/auth/bigquery')
    flags = tools.argparser.parse_args(args=['--noauth_local_webserver'])

    storage = Storage('bigquery_credentials.dat')
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run_flow(FLOW, storage, flags)

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

    bigquery_service = build('bigquery', 'v2', http=http)

    try:
        # try retrieve some data
        datasets = bigquery_service.datasets()
        # listReply = datasets.list(projectId=PROJECT_NUMBER).execute()
        # if it runs OK, return the service
        return bigquery_service

    except HttpError as err:
        print 'Error in listDatasets:', pprint.pprint(err.content)

    except AccessTokenRefreshError:
        print ("Credentials have been revoked or expired, please re-run \
                the application to re-authorize")
def GetCredentials(flags, scope_list):
  """Retrieve saved credentials or create and save credentials using flow.

  Args:
    flags: argparse parsed flags object.
    scope_list: List of strings reflecting desired API access (scope)
                e.g.: ['https://www.googleapis.com/auth/directory.user'].

  Returns:
    An oauth2client Credentials() object.
  """
  client_file_storage = Storage(
      FILE_MANAGER.BuildFullPathToFileName(_CURRENT_ACCESS_FILE_NAME))
  credentials = client_file_storage.get()
  if credentials is None or credentials.invalid:
    client_secrets_path = FILE_MANAGER.BuildFullPathToFileName(
        _CLIENT_SECRETS_FILE_NAME, work_dir=False)
    missing_secrets_msg = _MISSING_CLIENT_SECRETS_MSG % client_secrets_path
    flow_manager = flow_from_clientsecrets(client_secrets_path,
                                           scope=scope_list,
                                           message=missing_secrets_msg)
    credentials = run_flow(flow_manager, client_file_storage, flags)
  if not credentials:
    log_utils.LogError('Unable to retrieve valid credentials.')
    sys.exit(-1)
  return credentials
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'todoist_gcal_sync.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        log.info('Storing credentials to ' + credential_path)
    return credentials
Example #32
0
    def _load_credentials(self, credentials_file_path):
        if credentials_file_path == GCE_CREDENTIALS:
            return gce.AppAssertionCredentials(self._SCOPES)
        if credentials_file_path == APPENGINE_CREDENTIALS:  # pragma: no cover
            # This import doesn't work outside appengine, so delay it until it's used.
            from oauth2client import appengine
            return appengine.AppAssertionCredentials(self._SCOPES)

        with open(credentials_file_path, 'r') as credentials_file:
            credentials_json = json.load(credentials_file)
        if credentials_json.get('type', None):
            credentials = GoogleCredentials.from_stream(credentials_file_path)
            credentials = credentials.create_scoped(self._SCOPES)
            return credentials
        return Storage(credentials_file_path).get()
Example #33
0
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow in completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'gmail-python-stats.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
        credentials = tools.run_flow(flow, store, flags)
        print('Storing credentials to ' + credential_path)
    return credentials
Example #34
0
    def get_credentials(self):
        """Gets valid user credentials from storage.
    
        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.
    
        Returns:
            Credentials, the obtained credential.
        """
#        home_dir = os.path.expanduser('~')
#        credential_dir = os.path.join(home_dir, '.credentials')
#        if not os.path.exists(credential_dir):
#            os.makedirs(credential_dir)
#        credential_path = os.path.join(credential_dir,
#                                       __file__ + '.json')
        credential_path = self.oauth
        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(self.secrets, SCOPES)
            flow.user_agent = APPLICATION_NAME
            credentials = tools.run_flow(flow, store, self.flags)
  
        return credentials
Example #35
0
def tryFetchingCredentials():
    global credentials

    try:
        credentials = flow.step2_exchange(device_flow_info=deviceFlowInfo)
    except FlowExchangeError as e:
        if e.message != 'authorization_pending':
            raise ValueError('Unknown FlowExchange error: %s' % e.message)

        return False

    if credentials.invalid:
        credentials = None
        return False

    credentialsFile = File.fromNameAndDir(CREDENTIALS_FILE, YOUTUBE_DATA_DIR)

    storage = Storage(
        credentialsFile.fullpathTranslated())  #store on hard drive
    storage.put(credentials)

    return True


#READ_ONLY_SCOPE    = 'https://www.googleapis.com/auth/youtube.readonly'
#REDIERCT_URI        = 'urn:ietf:wg:oauth:2.0:oob'

#directLink = flow.step1_get_authorize_url()

#from oauth2client.client import OAuth2WebServerFlow
#CLIENT_ID = '1074802623980-dpf5kf1o0e14hkjb9al8st51r2fqk71l.apps.googleusercontent.com'
#CLIENT_SECRET = 'xCvTxLTqi0TbkWijXxYBS8_7'
#     flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
#                            client_secret=CLIENT_SECRET,
#                            scope=READ_WRITE_SCOPE,
#                            redirect_uri=REDIERCT_URI)
    def _get_credentials():
        """
        Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.
        @return: The obtained credentials.
        """
        # Make sure the credentials directory exists. If not, create it and store the credentials in there.
        home_dir = os.path.expanduser('~')
        credential_dir = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir, "google_sheets.json")

        # Try loading credentials from file
        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            # Perform authentication
            flow = client.flow_from_clientsecrets(CREDENTIALS_FILE_PATH,
                                                  SCOPES)
            flow.user_agent = APPLICATION_NAME
            credentials = tools.run_flow(flow, store)

        return credentials
Example #37
0
    def step2_exchange(now):
        """Keep trying to validate the user_code until it expires."""
        if now >= dt.as_local(dev_flow.user_code_expiry):
            hass.components.persistent_notification.create(
                'Authentication code expired, please restart '
                'Home-Assistant and try again',
                title=NOTIFICATION_TITLE,
                notification_id=NOTIFICATION_ID)
            listener()

        try:
            credentials = oauth.step2_exchange(device_flow_info=dev_flow)
        except FlowExchangeError:
            # not ready yet, call again
            return

        storage = Storage(hass.config.path(TOKEN_FILE))
        storage.put(credentials)
        do_setup(hass, config)
        listener()
        hass.components.persistent_notification.create(
            'We are all setup now. Check {} for calendars that have '
            'been found'.format(YAML_DEVICES),
            title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
Example #38
0
    def createAuthorizedHTTP(self):
        storage = Storage('credentials.dat')
        credentials = storage.get()

        print "===> Credentials: ", credentials.to_json()

        # Create an httplib2.Http object and authorize it with our credentials
        http = httplib2.Http()

        if credentials is None:
            #TODO: print exception or authorize user
            print "Credentials does not exist!"
        if credentials.invalid:
            print "Refresh credentials(createAuthorizedHTTP)..."
            print "Credentials (Before refresh):"
            print credentials.to_json()
            credentials.refresh(http)
            print "Credentials (After refresh):"
            print credentials.to_json()

        # authorize http with credentials
        http = credentials.authorize(http)

        return http
    def _get_authenticated_service(self):
        flow = flow_from_clientsecrets(self.client_secrets_file_path,
                                       scope=self.scopes,
                                       message="missing secrets message here!")

        storage = Storage(self.credentials_file_path)
        credentials = storage.get()

        class Args(object):
            pass

        args = Args()

        args.auth_host_name = 'localhost'
        args.auth_host_port = [8080, 8090]
        args.logging_level = 'ERROR'
        args.noauth_local_webserver = False

        if credentials is None or credentials.invalid:
            credentials = run_flow(flow, storage, args)

        return build(self.api_service,
                     self.api_version,
                     http=credentials.authorize(httplib2.Http()))
Example #40
0
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(
        credential_dir, 'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
Example #41
0
    def auth(self, force=False):
        if self.service != None or force:
            return self.service

        FLOW = OAuth2WebServerFlow(
            client_id=self.client_id,
            client_secret=self.client_secret,
            scope='https://www.googleapis.com/auth/calendar',
            user_agent='DIMVA2015/1.0')

        storage = Storage(self.creds_file)
        credentials = storage.get()

        if credentials is None or credentials.invalid == True:
            credentials = run(FLOW, storage)

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

        service = build(serviceName='calendar',
                        version='v3',
                        http=http,
                        developerKey=self.api_key)

        return service
Example #42
0
def getAuthorizedHttp():

    config = ConfigParser.ConfigParser()
    config.read([os.path.dirname(__file__) + '/config.ini'])

    # Copy your app credentials from the console
    CLIENT_ID = config.get('gdrive', 'CLIENT_ID')
    CLIENT_SECRET = config.get('gdrive', 'CLIENT_SECRET')

    # OAuth 2.0 scope that will be authorized.
    # Check https://developers.google.com/drive/scopes for all available scopes.
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

    # Redirect URI for installed apps
    REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

    # Init auth storage
    storage = Storage(os.path.dirname(__file__) + '/client_secrets.json')
    credentials = storage.get()

    # Check credentials existance
    if not credentials:
        # Perform OAuth2.0 authorization flow.
        flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE,
                                   REDIRECT_URI)
        authorize_url = flow.step1_get_authorize_url()
        print 'Go to the following link in your browser: ' + authorize_url
        code = raw_input('Enter verification code: ').strip()
        credentials = flow.step2_exchange(code)
        # Store allowed credentials
        storage.put(credentials)

    # Create an authorized Drive API client.
    http = httplib2.Http()
    credentials.authorize(http)
    return http
Example #43
0
def create_credentials(name):
    config = get_config(name)
    if 'client_id' not in config \
            or 'client_secret' not in config:
        print('Error: client_id, client_secret is not set.\n\n'
              'Please create a client ID here and update '
              'config.py:\n\nhttps://code.google.com/apis/console/#:access')
        sys.exit(1)

    FLOW = OAuth2WebServerFlow(
        client_id=config['client_id'],
        client_secret=config['client_secret'],
        scope='https://www.googleapis.com/auth/{}.readonly'.format(name))

    run_flags = tools.argparser.parse_args(args=[])

    credentials_file = os.path.join(app.instance_path, 'jobs',
                                    '.{}.json'.format(name))
    storage = Storage(credentials_file)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, run_flags)
    else:
        print('Google API credentials already exist: %s' % (credentials_file,))
    def access_to_youtube(self):
        CLIENT_SECRETS_FILE = "client_id.json"
        MISSING_CLIENT_SECRETS_MESSAGE = 'WARNING: Please configure OAuth 2.0'

        # This OAuth 2.0 access scope allows for full read/write access to the
        # authenticated user's account.
        YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
        YOUTUBE_API_SERVICE_NAME = "youtube"
        YOUTUBE_API_VERSION = "v3"

        flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
                                       message=MISSING_CLIENT_SECRETS_MESSAGE,
                                       scope=YOUTUBE_READ_WRITE_SCOPE)

        storage = Storage("oauth2.json")
        credentials = storage.get()

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

        self.youtube = build(YOUTUBE_API_SERVICE_NAME,
                             YOUTUBE_API_VERSION,
                             http=credentials.authorize(httplib2.Http()))
Example #45
0
    def get_people_service(self):
        # Set up a Flow object to be used if we need to authenticate. This
        # sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
        # the information it needs to authenticate. Note that it is called
        # the Web Server Flow, but it can also handle the flow for
        # installed applications.
        #
        # Go to the Google API Console, open your application's
        # credentials page, and copy the client ID and client secret.
        # Then paste them into the following code.
        FLOW = OAuth2WebServerFlow(
            client_id=self.CLIENT_ID,
            client_secret=self.CLIENT_SECRET,
            scope='https://www.googleapis.com/auth/contacts.readonly',
            user_agent='addresslabel/%s' %
            self.app.VERSION if self.app is not None else "1.0.0")

        # If the Credentials don't exist or are invalid, run through the
        # installed application flow. The Storage object will ensure that,
        # if successful, the good Credentials will get written back to a
        # file.
        storage = Storage('info.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid == True:
            credentials = run_flow(FLOW, storage)

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

        # Build a service object for interacting with the API. To get an API key for
        # your application, visit the Google API Console
        # and look at your application's credentials page.
        people_service = build(serviceName='people', version='v1', http=http)
        return people_service
Example #46
0
    def get_credentials(self): # pragma: no cover
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """
        if not os.path.exists(self.cred):
            os.makedirs(self.cred)
        cred_file = os.path.join(self.cred, 'calendar-token.json')

        store = Storage(cred_file)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
            flow.user_agent = APPLICATION_NAME
            if self.flags:
                credentials = tools.run_flow(flow, store, self.flags)
            else: # Needed only for compatibility with Python 2.6
                credentials = tools.run(flow, store)
            print('Storing credentials to ' + cred_file)
        return credentials
Example #47
0
def get_credentials():
    """Gets valid user credentials from storage.
    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.
    Returns:
        Credentials, the obtained credential.
    """
    cur_dir = os.path.curdir
    credential_dir = os.path.join(cur_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'GCal-Cleanup.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
Example #48
0
    def getCredentials(self):
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """
        home_dir = os.getcwd()
        credential_path = os.path.join(home_dir,
                                       'credential.json')

        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
            flow.user_agent = APPLICATION_NAME
            flags.noauth_local_webserver = True
            credentials = tools.run_flow(flow, store, flags)
            logging.info('Storing credentials to ' + credential_path)

        http = credentials.authorize(httplib2.Http())
        self.service = discovery.build('drive', 'v2', http=http)
Example #49
0
    def _credentials_procedure(self):
        home_dir = os.path.expanduser('~')
        credential_dir = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(
            credential_dir, 'wrh_uploader_%i.json' % int(self._file_id))

        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            try:
                import argparse

                flags = argparse.ArgumentParser(
                    parents=[tools.argparser]).parse_args()
            except ImportError:
                flags = None
            flow = client.flow_from_clientsecrets(self._secret, self.SCOPES)
            flow.user_agent = self.APPLICATION_NAME
            flags.noauth_local_webserver = True
            credentials = tools.run_flow(flow, store, flags)
            log('Storing credentials to ' + credential_path)
        return credentials
def goog_cred(name):
	flow = client.flow_from_clientsecrets(
		'client_secret.json',
		scope='https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/gmail.readonly',
		redirect_uri='urn:ietf:wg:oauth:2.0:oob')

	auth_uri = flow.step1_get_authorize_url()
	
	webbrowser.open(auth_uri)

	auth_code = input('Login and enter code here: ')
	file = str(name) + '_goog.txt'
	
	try:
		credentials = flow.step2_exchange(auth_code)
		storage = Storage(file)
		storage.put(credentials)
		return 1
		
	except oauth2client.client.FlowExchangeError:
		fob = open(file, 'w')
		fob.write("None")
		fob.close()
		return 0
Example #51
0
def get_credentials():

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

	client_secret_file = cwd+"/"+credential_name
        if not os.path.exists(client_secret_file):
                print "ERROR.  The Google Sheet secret file "+client_secret_file+" does not exist. Not ablwe to get sourcetype <-> index mapping"
                exit()

    	home_dir = os.path.expanduser('~')
    	credential_dir = os.path.join(home_dir, '.credentials')
    	if not os.path.exists(credential_dir):
        	os.makedirs(credential_dir)
    	credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-break-main.json')

    	store = Storage(credential_path)
    	credentials = store.get()
    	if not credentials or credentials.invalid:
        	flow = client.flow_from_clientsecrets(client_secret_file, scopes)
        	flow.user_agent = application_name
            	credentials = tools.run_flow(flow, store, flags)
		#credentials = tools.run_flow(flow, store)
    	return credentials
def authenticate() -> httplib2.Http:
    """
    returns an Http instance that already contains the user credentials and is
    ready to make requests to alter user data.

    On the first time, this function will open the browser so that the user can
    grant it access to his data
    """
    with open(APP_KEYS_FILE) as f:
        app_keys = json.load(f)
    storage = Storage(USER_OAUTH_DATA_FILE)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(
            OAuth2WebServerFlow(
                client_id=app_keys['APP_CLIENT_ID'],
                client_secret=app_keys['APP_CLIENT_SECRET'],
                scope=['https://www.googleapis.com/auth/reminders'],
                user_agent='google reminders cli tool'),
            storage,
            tools.argparser.parse_args([])
        )
    auth_http = credentials.authorize(httplib2.Http())
    return auth_http
Example #53
0
    def _get_credentials(self):
        """Get OAuth credentials

        :return: OAuth credentials
        :rtype: :class:`oauth2client.client.Credentials`
        """
        credential_dir = join(self.var_dir, 'cached_oauth_credentials')
        if not exists(credential_dir):
            makedirs(credential_dir)
        credential_path = join(credential_dir, 'googleapis.json')

        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(self.config['creds'],
                                                  self.config['scope'])
            flow.user_agent = 'Iris Gmail Integration'
            credentials = tools.run_flow(
                flow, store,
                tools.argparser.parse_args(args=['--noauth_local_webserver']))
            logger.info('Storing credentials to %s', credential_path)
        else:
            credentials.refresh(self.http)
        return credentials
Example #54
0
    def _get_google_credentials(self):
        """Gets valid user credentials from storage.
    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.
    Returns:
        Credentials, the obtained credential.
    """
        home_dir = os.path.expanduser('~')
        credential_dir = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir, 'garage-server.json')

        store = Storage(credential_path)
        credentials = store.get()
        '''
    No interactive context in this module, so just fail
    '''
        if not credentials or credentials.invalid:
            logger = logging.getLogger(__name__)
            logger.error("Invalid Google Credentials")
            credentials = None

        return credentials
Example #55
0
def get_credentials():
    """
    Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    #home_dir = os.path.expanduser('~')

    credential_dir = os.path.join(Filepath, '.credentials')

    CLIENT_SECRET_FILE = './OAuth/client_secret.json'

    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    if not os.path.exists(CLIENT_SECRET_FILE):
        print('**Not find Client_Secret_FIle**')
    else:
        SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
            if flags:
                credentials = tools.run_flow(flow, store, flags)
            else:
                credentials = tools.run_flow(flow, store)
            print('Storing credentials to ' + credential_path)

    return credentials
Example #56
0
    def get_credentials(self):
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """

        credential_path = self._token_filename
        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(self._client_secrets,
                                                  self._scope)
            flow.user_agent = APPLICATION_NAME

            if args:
                credentials = tools.run_flow(flow, store, args)
            else:  # Needed only for compatibility with Python 2.6
                credentials = tools.run(flow, store)
            print('Storing credentials to ' + credential_path)
        return credentials
Example #57
0
    def login(self, src_path):
        """
        Login to Google API using data provided in config.

        :param src_path: path to calendar credentials
        :type src_path: str
        """
        # The client_id and client_secret can be found in Google Developers Console
        flow = OAuth2WebServerFlow(
            client_id=self.config['client_id'],
            client_secret=self.config['client_secret'],
            scope='https://www.googleapis.com/auth/calendar',
            user_agent=self.user_agent)
        # To disable the local server feature, uncomment the following line:
        # import gflags
        # FLAGS = gflags.FLAGS
        # FLAGS.auth_local_webserver = 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 a file.
        storage = Storage(src_path + '/calendar.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid is True:
            credentials = tools.run(flow, storage)

        # Create an httplib2.Http object to handle our HTTP requests and authorize it
        # with our good Credentials.
        http = httplib2.Http()
        http = credentials.authorize(http)
        # Build a service object for interacting with the API. Visit
        # the Google Developers Console
        # to get a developerKey for your own application.
        self.service = build(serviceName='calendar',
                             version='v3',
                             http=http,
                             developerKey='notsosecret')
Example #58
0
def _load_user_credentials(scope,
                           app_cred,
                           user_cred_file=default_user_cred_file,
                           log=None):
    # Get user consent
    client_id = app_cred['installed']['client_id']
    client_secret = app_cred['installed']['client_secret']
    flow = OAuth2WebServerFlow(client_id, client_secret, scope)
    flow.user_agent = user_agent

    storage = Storage(user_cred_file)
    user_cred = storage.get()

    # If no credentials are able to be loaded, fire up a web
    # browser to get a user login, etc.  Then save those
    # credentials in the file listed above so that next time we
    # run, those credentials are available.
    if user_cred is None or user_cred.invalid:
        user_cred = tools.run_flow(flow, storage, tools.argparser.parse_args())

    if log:
        log.debug('Loaded user credentials from {0}'.format(user_cred_file))

    return user_cred
Example #59
0
    def gmailauth(self, setType):
    
        scope = ("https://www.googleapis.com/auth/%s" % (setType))

        # create flow object 
        flow = OAuth2WebServerFlow(self.client_id, self.client_secret, scope)

        # create / refresh credentials
        storage = Storage(".%s_credentials.dat" % (setType))
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(flow, storage, tools.argparser.parse_args())

        # create / authorize http object to handle HTTP requests
        http = httplib2.Http()
        http = credentials.authorize(http)

        # create object to make API calls
        if "admin" in setType:
            service = build("admin", "directory_v1", http=http)
        elif "gmail" in setType:
            service = build("gmail", "v1", http=http)

        return service
Example #60
0
def get_authenticated_service():
    """Get youtube credentials identified. """
    try:
        youtube_uploader = settings.YOUTUBE_UPLOADER
    except Exception as e:
        raise ValueError(e)

    scope = youtube_uploader['scope']
    credentials_path = youtube_uploader['credentials_path']
    client_info = youtube_uploader['client_info']
    credentials_file = youtube_uploader['credentials_file']

    my_flow_from_clientsecrets(client_info, scope)
    module_dir = os.path.abspath(credentials_path)
    file_path = os.path.join(module_dir, credentials_file)
    storage = Storage(file_path)
    credentials = storage.get()

    try:
        builded = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                        http=credentials.authorize(httplib2.Http()))
        return builded
    except Exception as e:
        print(("error", e))