Python oauth2client.client.flow_from_clientsecrets() Examples

The following are 30 code examples of oauth2client.client.flow_from_clientsecrets(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oauth2client.client , or try the search function .
Example #1
Source File: 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 #2
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 #3
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 #4
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 #5
Source File: auth.py    From drive-cli with MIT License 6 votes vote down vote up
def login(remote):
    token = os.path.join(dirpath, 'token.json')
    store = file.Storage(token)
    creds = store.get()
    if not creds or creds.invalid:
        client_id = os.path.join(dirpath, 'oauth.json')
        flow = client.flow_from_clientsecrets(client_id, SCOPES)
        flags = tools.argparser.parse_args(args=[])
        if remote:
            flags.noauth_local_webserver = True
        creds = tools.run_flow(flow, store, flags)
        click.secho(
            "********************** welcome to **********************", bold=True, fg='red')
        result = pyfiglet.figlet_format("Drive - CLI", font="slant")
        click.secho(result, fg='yellow')
        click.secho(
            "********************************************************", bold=True, fg='red') 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: auth.py    From Computable with MIT License 6 votes vote down vote up
def get_flow(secret, scope, redirect):
    """
    Retrieve an authentication flow object based on the given
    configuration in the secret file name, the authentication scope,
    and a redirect URN
    """
    key = (secret, scope, redirect)
    flow = FLOWS.get(key, None)
    if flow is None:
        msg = MISSING_CLIENT_MSG % secret
        if not os.path.exists(secret):
            raise AuthenticationConfigError(msg)
        flow = oauth.flow_from_clientsecrets(secret, scope,
                                             redirect_uri=redirect,
                                             message=msg)
        FLOWS[key] = flow
    return flow 
Example #13
Source File: gmail_refresh.py    From alfred-gmail with MIT License 6 votes vote down vote up
def refresh_cache(labels=None):
    labels = labels if labels is not None else config.SYSTEM_LABELS.keys()
    flow = flow_from_clientsecrets(
        config.CLIENT_SECRET_FILE, scope=config.OAUTH_SCOPE)
    http = httplib2.Http()

    try:
        credentials = OAuth2Credentials.from_json(
            WF.get_password('gmail_credentials'))
        if credentials is None or credentials.invalid:
            credentials = run_flow(flow, PseudoStorage(), http=http)
            WF.save_password('gmail_credentials', credentials.to_json())
            WF.logger.debug('Credentials securely updated')

        http = credentials.authorize(http)
        gmail_service = build('gmail', 'v1', http=http)

        for label in labels:
            WF.cache_data('gmail_%s' %
                          label.lower(), get_list(http, gmail_service, label))
            sleep(2)
        if not WF.cached_data_fresh('gmail_labels', max_age=300):
            WF.cache_data('gmail_labels', get_labels(gmail_service))

    except PasswordNotFound:
        WF.logger.debug('Credentials not found')
        credentials = run_flow(flow, PseudoStorage(), http=http)
        WF.save_password('gmail_credentials', credentials.to_json())
        WF.logger.debug('New Credentials securely saved')

    except httplib2.ServerNotFoundError:
        WF.logger.debug('ServerNotFoundError') 
Example #14
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 #15
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 #16
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 #17
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 #18
Source File: handlers.py    From go-links with Apache License 2.0 6 votes vote down vote up
def get_google_login_url(self, oauth_redirect_uri=None, redirect_to_after_oauth=None):
    if not oauth_redirect_uri:
      oauth_redirect_uri = '%s%s' % (
        'http://localhost:9095' if self.request.host.startswith('localhost')
        else authentication.get_host_for_request(self.request),
        '/_/auth/oauth2_callback')

    if not redirect_to_after_oauth:
      redirect_to_after_oauth = 'http://localhost:5007' if self.request.host.startswith('localhost') else '/'

    self.session['redirect_to_after_oauth'] = str(redirect_to_after_oauth)

    # http://oauth2client.readthedocs.io/en/latest/source/oauth2client.client.html
    flow = flow_from_clientsecrets(get_path_to_oauth_secrets(),
                                   scope='https://www.googleapis.com/auth/userinfo.email',
                                   redirect_uri=oauth_redirect_uri)

    self.session['pickled_oauth_flow'] = pickle.dumps(flow)
    self.session['oauth_state'] = utils.generate_secret(32)
    try:
      return str(flow.step1_get_authorize_url(state=self.session['oauth_state']))
    except TypeError:
      # TODO: Fix breakage only appearing in tests.
      return str(flow.step1_get_authorize_url()) 
Example #19
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 #20
Source File: main.py    From DriveInvoicing with Apache License 2.0 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.
    """
    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,
                                   'drive_invoicing.json')

    store = oauth2client.file.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)
        print('Storing credentials to ' + credential_path)
    return credentials 
Example #21
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 #22
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 #23
Source File: authorise.py    From RPi-InfoScreen-Kivy with GNU General Public License v3.0 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,
                                   'calendar-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(SECRET, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials 
Example #24
Source File: target_gsheet.py    From target-gsheet with GNU Affero General Public License v3.0 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-singer-target.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 #25
Source File: add_events.py    From gyft 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,
                                   'calendar-python-quickstart.json')

    store = file.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

### days to number 
Example #26
Source File: archive_deployment_packages.py    From Lecture-Series-Python 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,
                                   'drive-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
        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 #27
Source File: GoogleDriveDownloader.py    From VideoSuperResolution with MIT License 5 votes vote down vote up
def require_authorize(store, credentials, scope):
  _argv = sys.argv.copy()
  sys.argv = _argv[:1]
  if '--noauth_local_webserver' in _argv:
    sys.argv.append('--noauth_local_webserver')
  flow = client.flow_from_clientsecrets(credentials, scope)
  creds = tools.run_flow(flow, store)
  sys.argv = _argv
  return creds 
Example #28
Source File: handlers.py    From go-links with Apache License 2.0 5 votes vote down vote up
def get(self):
    if self.session.get('pickled_oauth_flow'):
      flow = pickle.loads(self.session['pickled_oauth_flow'])
    else:
      flow = flow_from_clientsecrets(get_path_to_oauth_secrets(),
                                     scope='https://www.googleapis.com/auth/userinfo.email',
                                     redirect_uri='https://trot.to/_/auth/oauth2_callback')

    if not self.session.get('oauth_state') or self.session.get('oauth_state') != self.request.get('state'):
      self.redirect('/_/auth/login')
      return

    try:
      credentials = flow.step2_exchange(self.request.get('code'))
    except (FlowExchangeError, ValueError):
      # user declined to auth; move on
      self.redirect(self.session.get('redirect_to_after_oauth', '/'))
      return

    self.session['credentials'] = pickle.dumps(credentials)

    self.session['user_email'] = authentication.get_user_email(credentials)

    user = get_or_create_user(self.session['user_email'], get_organization_id_for_email(self.session['user_email']))
    if not user.accepted_terms_at:
      # all login methods now have UI for consenting to terms
      user.accepted_terms_at = datetime.datetime.utcnow()
      user.put()

    self.redirect(self.session.get('redirect_to_after_oauth', '/')) 
Example #29
Source File: get_portfolio.py    From crypto_predictor 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-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
        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 #30
Source File: quickstart.py    From pyrobotlab with Apache License 2.0 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,
                                   'calendar-python-quickstart.json')

    store = oauth2client.file.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