Python oauth2client.file.Storage() Examples

The following are 30 code examples of oauth2client.file.Storage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oauth2client.file , or try the search function .
Example #1
Source File: fb2cal.py    From fb2cal with GNU General Public License v3.0 6 votes vote down vote up
def google_drive_api_authenticate():
    """ Authenticate with Google Drive Api """

    # Confirm credentials.json exists
    if not os.path.isfile('credentials.json'):
        logger.error(f'credentials.json file does not exist')
        raise SystemExit

    SCOPES = 'https://www.googleapis.com/auth/drive.file'
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('drive', 'v3', http=creds.authorize(Http()), cache_discovery=False)
    return service 
Example #2
Source File: bigquery.py    From deezer-bigquery with MIT License 6 votes vote down vote up
def build_service(secret, credentials):
    """
    Build reference to a BigQuery service / API.
    
    Parameters
    ----------
    secret : string
        Path to the secret files
    credentials : string
        Path to the credentials files

    Returns
    -------
    out : object
        The service reference
    """
    flow = flow_from_clientsecrets(secret, scope="https://www.googleapis.com/auth/bigquery")
    storage = Storage(credentials)
    credentials = storage.get()

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

    http = credentials.authorize(httplib2.Http())
    return build("bigquery", "v2", http=http) 
Example #3
Source File: videouploader.py    From Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader with MIT License 6 votes vote down vote up
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.
    """
    credential_path = settings.creds_path + ".youtube-upload-credentials.json"
    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(settings.google_cred_upload, 'https://www.googleapis.com/auth/youtube.upload')
        flow.user_agent = 'youtube-upload'
        credentials = tools.run_flow(flow, store)
    return credentials 
Example #4
Source File: gmail.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #5
Source File: auth.py    From edx2bigquery with GNU General Public License v2.0 6 votes vote down vote up
def get_oauth2_creds():
  '''Generates user credentials.
  
  Will prompt the user to authorize the client when run the first time.
  Saves the credentials in ~/bigquery_credentials.dat.
  '''
  flow  = flow_from_clientsecrets('edx2bigquery-client-key.json',
                                  scope=BIGQUERY_SCOPE)
  storage = Storage(os.path.expanduser('~/bigquery_credentials.dat'))
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    flags = tools.argparser.parse_args([])
    credentials = tools.run_flow(flow, storage, flags)
  else:
    # Make sure we have an up-to-date copy of the creds.
    credentials.refresh(httplib2.Http())
  return credentials 
Example #6
Source File: google_api.py    From pyconjpbot with MIT License 6 votes vote down vote up
def get_credentials():
    """
    credentialsファイルを生成する
    """
    dirname = os.path.dirname(__file__)
    credential_path = os.path.join(dirname, CREDENTIAL_FILE)
    client_secret_file = os.path.join(dirname, CLIENT_SECRET_FILE)

    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)
        print('credentialsを{}に保存しました'.format(credential_path))
    return credentials 
Example #7
Source File: auth_google.py    From fitbit-googlefit with GNU General Public License v3.0 6 votes vote down vote up
def main():
    # Arguments parsing
    parser = argparse.ArgumentParser("Client ID and Secret are mandatory arguments")
    parser.add_argument("-i", "--id", required=True, help="Client id", metavar='<client-id>')
    parser.add_argument("-s", "--secret", required=True, help="Client secret", 
        metavar='<client-secret>')
    parser.add_argument("-c", "--console", default=False, 
        help="Authenticate only using console (for headless systems)", action="store_true")
    args = parser.parse_args()

    # Scopes of authorization
    activity = "https://www.googleapis.com/auth/fitness.activity.write"
    body = "https://www.googleapis.com/auth/fitness.body.write"
    location = "https://www.googleapis.com/auth/fitness.location.write"
    scopes = activity + " " + body + " " + location

    flow = OAuth2WebServerFlow(args.id, args.secret, scopes)
    storage = Storage('google.json')
    flags = ['--noauth_local_webserver'] if args.console else []
    run_flow(flow, storage, argparser.parse_args(flags)) 
Example #8
Source File: google_calendar.py    From ask-jira with MIT License 6 votes vote down vote up
def _get_credentials(conf):
    """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.
    """
    store = Storage(conf.CREDENTIAL_FILE)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(conf.CLIENT_SECRET_FILE, conf.SCOPES)
        flow.user_agent = conf.APPLICATION_NAME
        # avoid mess with argparse
        sys.argv = [sys.argv[0]]
        credentials = tools.run_flow(flow, store)
        print('Storing Google Calendar credentials to', conf.CREDENTIAL_FILE)
    return credentials 
Example #9
Source File: configure_oauth.py    From splunk-ref-pas-code with Apache License 2.0 6 votes vote down vote up
def handle_POST(self):
        redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
        oauth_scope = 'https://www.googleapis.com/auth/admin.reports.audit.readonly'

        try:
            client_id = self.args.get('client_id')
            client_secret = self.args.get('client_secret')
            auth_code = self.args.get('auth_code')

            storage = Storage(app_dir + os.path.sep + 'google_drive_creds')

            flow = OAuth2WebServerFlow(client_id, client_secret, oauth_scope, redirect_uri)
            credentials = flow.step2_exchange(auth_code)
            logger.debug("Obtained OAuth2 credentials!")
            storage.put(credentials)
        except Exception, e:
                logger.exception(e)
                self.response.write(e)

    # listen to all verbs 
Example #10
Source File: obtainGSToken.py    From ingress-fieldplan with GNU General Public License v3.0 6 votes vote down vote up
def main():
    description = (
            'Obtain a Google Spreadsheets authorization token using credentials.json.'
            'To obtain the credentials.json file, follow instructions on this page:'
            'https://developers.google.com/sheets/api/quickstart/python'
            'Save credentials.json in the same directory with this script.'
            )

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

    home = str(Path.home())
    cachedir = os.path.join(home, '.cache', 'ingress-fieldmap')
    Path(cachedir).mkdir(parents=True, exist_ok=True)
    tokenfile = os.path.join(cachedir, 'token.json')

    store = file.Storage(tokenfile)
    flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
    creds = tools.run_flow(flow, store, flags)

    if creds:
        print('Token saved in %s' % tokenfile) 
Example #11
Source File: api.py    From uds with GNU Affero General Public License v3.0 6 votes vote down vote up
def reauth(self):
        # Set up the Drive v3 API
        SCOPES = ["https://www.googleapis.com/auth/drive"]
        store = file.Storage('credentials.json')
        credentials = store.get()
        if not credentials or credentials.invalid:
            try:
                flow = client.flow_from_clientsecrets(GoogleAPI.CLIENT_SECRET, SCOPES)
                credentials = tools.run_flow(flow, store)
            except ConnectionRefusedError:
                print("{!s} Make sure you've saved your OAuth credentials as {!s}".format(
                      GoogleAPI.ERROR_OUTPUT, GoogleAPI.CLIENT_SECRET))
                sys.exit(
                    "If you've already done that, then run uds.py without any arguments first.")

        self.service = build('drive', 'v3', http=credentials.authorize(Http()))
        return self.service 
Example #12
Source File: gmail.py    From iris with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_credentials(self):
        """Get OAuth credentials

        :return: OAuth credentials
        :rtype: :class:`oauth2client.client.Credentials`
        """
        credential_dir = join(self.config['creds_cache_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 #13
Source File: gd_client_oauth.py    From GooglePhotosSync with GNU General Public License v2.0 6 votes vote down vote up
def OAuth2Login(client_secrets, credential_store, email):
    scope='https://picasaweb.google.com/data/'
    user_agent='myapp'

    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)
        storage.put(credentials)

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

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

    return gd_client 
Example #14
Source File: cleaner.py    From google-drive-trash-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def get_credentials(flags):
    """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.
    """
    store = Storage(flags.credfile)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.OAuth2WebServerFlow(**CLIENT_CREDENTIAL)
        credentials = tools.run_flow(flow, store, flags)
        print('credential file saved at\n\t' + flags.credfile)
    return credentials 
Example #15
Source File: gdrivenew.py    From BotHub with Apache License 2.0 6 votes vote down vote up
def create_token_file(token_file, event):
    # Run through the OAuth flow and retrieve credentials
    flow = OAuth2WebServerFlow(
        CLIENT_ID,
        CLIENT_SECRET,
        OAUTH_SCOPE,
        redirect_uri=REDIRECT_URI
    )
    authorize_url = flow.step1_get_authorize_url()
    async with event.client.conversation(Config.PRIVATE_GROUP_BOT_API_ID) as conv:
        await conv.send_message(f"Go to the following link in your browser: {authorize_url} and reply the code")
        response = conv.wait_event(events.NewMessage(
            outgoing=True,
            chats=Config.PRIVATE_GROUP_BOT_API_ID
        ))
        response = await response
        code = response.message.message.strip()
        credentials = flow.step2_exchange(code)
        storage = Storage(token_file)
        storage.put(credentials)
        return storage 
Example #16
Source File: glink.py    From BotHub with Apache License 2.0 6 votes vote down vote up
def create_token_file(token_file, event):
    # Run through the OAuth flow and retrieve credentials
    flow = OAuth2WebServerFlow(
        CLIENT_ID,
        CLIENT_SECRET,
        OAUTH_SCOPE,
        redirect_uri=REDIRECT_URI
    )
    authorize_url = flow.step1_get_authorize_url()
    async with event.client.conversation(Config.PRIVATE_GROUP_BOT_API_ID) as conv:
        await conv.send_message(f"Go to the following link in your browser: {authorize_url} and reply the code")
        response = conv.wait_event(events.NewMessage(
            outgoing=True,
            chats=Config.PRIVATE_GROUP_BOT_API_ID
        ))
        response = await response
        code = response.message.message.strip()
        credentials = flow.step2_exchange(code)
        storage = Storage(token_file)
        storage.put(credentials)
        return storage 
Example #17
Source File: googledrive_test.py    From VideoSuperResolution with MIT License 6 votes vote down vote up
def test_downloads(self):
    """Shows basic usage of the Drive v3 API.
       Prints the names and ids of the first 10 files the user has access to.
    """
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    store = file.Storage('/tmp/token.json')
    creds = store.get()
    if not creds or creds.invalid:
      flow = client.flow_from_clientsecrets('../Data/credentials.json', SCOPES)
      creds = tools.run_flow(flow, store)
    service = build('drive', 'v3', http=creds.authorize(Http()))
    file_id = '1H0PIXvJH4c40pk7ou6nAwoxuR4Qh_Sa2'
    request = service.files().get_media(fileId=file_id)
    request.execute() 
Example #18
Source File: __init__.py    From vexbot with GNU General Public License v3.0 6 votes vote down vote up
def _youtube_authentication(client_filepath, youtube_scope=_READ_ONLY):
    missing_client_message = "You need to populate the client_secrets.json!"
    flow = flow_from_clientsecrets(client_filepath,
                                   scope=youtube_scope,
                                   message=missing_client_message)

    dir = os.path.abspath(__file__)
    filepath = "{}-oauth2.json".format(dir)
    # TODO: Determine if removing file is needed
    # remove old oauth files to be safe
    if os.path.isfile(filepath):
        os.remove(filepath)

    storage = Storage(filepath)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        args = Namespace(auth_host_name='localhost',
                         auth_host_port=[8080, 8090],
                         noauth_local_webserver=False,
                         logging_level='ERROR')

        credentials = run_flow(flow, storage, args)
        return build(_YOUTUBE_API_SERVICE_NAME,
                     _YOUTUBE_API_VERSION,
                     http=credentials.authorize(httplib2.Http())) 
Example #19
Source File: googledrive.py    From packtpub-crawler with MIT License 6 votes vote down vote up
def __save_credentials(self, auth_token):
        flow = flow_from_clientsecrets(
            self.__config.get('googledrive', 'googledrive.client_secrets'),
            self.__config.get('googledrive', 'googledrive.oauth2_scope'),
            OOB_CALLBACK_URN)

        authorize_url = flow.step1_get_authorize_url()

        print '[-] open browser...'
        webbrowser.open(authorize_url)

        code = raw_input('[*] Please, enter verification code: ').strip()
        credentials = flow.step2_exchange(code)

        storage = Storage(auth_token)
        storage.put(credentials)
        log_info('[+] new credentials saved') 
Example #20
Source File: credentials.py    From platypush with MIT License 6 votes vote down vote up
def get_credentials(scope):
    credentials_file = get_credentials_filename(*sorted(scope.split(' ')))
    if not os.path.exists(credentials_file):
        raise RuntimeError(('Credentials file {} not found. Generate it through:\n' +
                           '\tpython -m platypush.plugins.google.credentials "{}" ' +
                           '<path to client_secret.json>\n' +
                           '\t\t[--auth_host_name AUTH_HOST_NAME]\n' +
                           '\t\t[--noauth_local_webserver]\n' +
                           '\t\t[--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]]\n' +
                           '\t\t[--logging_level [DEBUG,INFO,WARNING,ERROR,CRITICAL]]\n').
                           format(credentials_file, scope))

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

    if not credentials or credentials.invalid:
        credentials.refresh(httplib2.Http())

    return credentials 
Example #21
Source File: main.py    From Awesome-Scripts with MIT License 6 votes vote down vote up
def main():
    
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('gmail', 'v1', http=creds.authorize(Http()))

  
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name']) 
Example #22
Source File: tosheets.py    From tosheets with MIT License 5 votes vote down vote up
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-tosheets.json')

    store = Storage(credential_path)
    credentials = store.get()
    sys.argv = ['']
    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)
        print('Storing credentials to ' + credential_path)
    return credentials

# creates a new sheet with the chosen Name 
Example #23
Source File: __main__.py    From budget-cli with MIT License 5 votes vote down vote up
def getSheetService():
    os.chdir(APP_DIR)
    store = file.Storage('token.json')
    creds = store.get()
    return build('sheets', 'v4', http=creds.authorize(Http())).spreadsheets().values()

# reads configuration from file 
Example #24
Source File: gmail.py    From unfurl with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_credentials():
    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-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 #25
Source File: monitors.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create(self, scopes):
    with open(self.path, 'r') as fh:
      data = json.load(fh)
    if data.get('type', None):
      credentials = GoogleCredentials.from_stream(self.path)
      credentials = credentials.create_scoped(scopes)
      return credentials
    return Storage(self.path).get() 
Example #26
Source File: monitors.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create(self, scopes):
    with open(self.path, 'r') as fh:
      data = json.load(fh)
    if data.get('type', None):
      credentials = GoogleCredentials.from_stream(self.path)
      credentials = credentials.create_scoped(scopes)
      return credentials
    return Storage(self.path).get() 
Example #27
Source File: monitors.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create(self, scopes):
    with open(self.path, 'r') as fh:
      data = json.load(fh)
    if data.get('type', None):
      credentials = GoogleCredentials.from_stream(self.path)
      credentials = credentials.create_scoped(scopes)
      return credentials
    return Storage(self.path).get() 
Example #28
Source File: monitors.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create(self, scopes):
    with open(self.path, 'r') as fh:
      data = json.load(fh)
    if data.get('type', None):
      credentials = GoogleCredentials.from_stream(self.path)
      credentials = credentials.create_scoped(scopes)
      return credentials
    return Storage(self.path).get() 
Example #29
Source File: monitors.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create(self, scopes):
    with open(self.path, 'r') as fh:
      data = json.load(fh)
    if data.get('type', None):
      credentials = GoogleCredentials.from_stream(self.path)
      credentials = credentials.create_scoped(scopes)
      return credentials
    return Storage(self.path).get() 
Example #30
Source File: monitors.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create(self, scopes):
    with open(self.path, 'r') as fh:
      data = json.load(fh)
    if data.get('type', None):
      credentials = GoogleCredentials.from_stream(self.path)
      credentials = credentials.create_scoped(scopes)
      return credentials
    return Storage(self.path).get()