Ejemplo n.º 1
0
    def readPickledCache(cls, cache):
        creds = pickle.loads(cache)
        from google_auth_httplib2 import Request

        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
Ejemplo n.º 2
0
    def load_user_account_credentials(self):
        """
        Loads user account credentials from a local file.

        .. versionadded 0.2.0

        Parameters
        ----------
        None

        Returns
        -------
        - GoogleCredentials,
            If the credentials can loaded. The retrieved credentials should
            also have access to the project (self.project_id) on BigQuery.
        - OR None,
            If credentials can not be loaded from a file. Or, the retrieved
            credentials do not have access to the project (self.project_id)
            on BigQuery.
        """
        import httplib2
        from google_auth_httplib2 import Request
        from google.oauth2.credentials import Credentials

        # Use the default credentials location under ~/.config and the
        # equivalent directory on windows if the user has not specified a
        # credentials path.
        if not self.credentials_path:
            self.credentials_path = self.get_default_credentials_path()

            # Previously, pandas-gbq saved user account credentials in the
            # current working directory. If the bigquery_credentials.dat file
            # exists in the current working directory, move the credentials to
            # the new default location.
            if os.path.isfile('bigquery_credentials.dat'):
                os.rename('bigquery_credentials.dat', self.credentials_path)

        try:
            with open(self.credentials_path) as credentials_file:
                credentials_json = json.load(credentials_file)
        except (IOError, ValueError):
            return None

        credentials = Credentials(
            token=credentials_json.get('access_token'),
            refresh_token=credentials_json.get('refresh_token'),
            id_token=credentials_json.get('id_token'),
            token_uri=credentials_json.get('token_uri'),
            client_id=credentials_json.get('client_id'),
            client_secret=credentials_json.get('client_secret'),
            scopes=credentials_json.get('scopes'))

        # Refresh the token before trying to use it.
        http = httplib2.Http()
        request = Request(http)
        credentials.refresh(request)

        return _try_credentials(self.project_id, credentials)
Ejemplo n.º 3
0
def get_access_token_for_scopes(subject, scopes):
  logging.debug("Getting access token for scopes %s, user %s", scopes, subject)
  credentials = service_account.Credentials.from_service_account_file(
      KEY_FILE, scopes=scopes)
  delegated_credentials = credentials.with_subject(subject)
  request = Request(Http())
  delegated_credentials.refresh(request)
  logging.debug("Successfully obtained access token")
  return delegated_credentials.token
Ejemplo n.º 4
0
def gmail(update, context):
    # type: (Update, CallbackContext) -> [None, Resource]

    logger = logging.getLogger()
    gmail_settings = context.user_data.get('gmail', {})

    credentials = gmail_settings.get('credentials', None)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            logger.debug(f'updating existing credentials')
            credentials.refresh(Request())
        else:
            logger.debug(f'requesting credentials')
            oauth_secret_filename = settings['access']['google_api']['oauth20_secret_file']
            flow = Flow.from_client_secrets_file(
                oauth_secret_filename,
                scopes=['https://www.googleapis.com/auth/gmail.modify'],
                redirect_uri='urn:ietf:wg:oauth:2.0:oob',
                state=gmail_settings.get('oauth2_state', 'None')
            )

            if 'auth_code' in gmail_settings:
                auth_code = gmail_settings.pop('auth_code')
                flow.fetch_token(code=auth_code)
                credentials = flow.credentials
                gmail_settings['credentials'] = credentials
            else:
                auth_url, gmail_settings['oauth2_state'] = flow.authorization_url(prompt='consent')
                context.user_data.setdefault('awaiting_data', []).append(
                    ('gmail/auth_code',
                     'Please send me the auth code that you get from the link')
                )
                if update.effective_chat.type != 'private':
                    message = markdown_escape('Authentication required!'
                                              ' Please, go to the in a'
                                              ' [PRIVATE](https://t.me/a_work_assistant_bot) chat'
                                              ' to pass authentication process',
                                              r'!')
                    update.message.reply_markdown_v2(message)
                private_message = markdown_escape('To continue, you have to '
                                                  'sign in to your Google account '
                                                  'and allow requested access for that bot.\n'
                                                  'As a result, you''ll receive confirmation code '
                                                  'which you have to send to me in that chat.'
                                                  , r'.')
                private_reply_markup = InlineKeyboardMarkup([
                    [InlineKeyboardButton('Sign in to Google', url=auth_url, callback_data='awaiting_data')]
                ])
                update.effective_user.send_message(private_message,
                                                   parse_mode=ParseMode.MARKDOWN_V2,
                                                   reply_markup=private_reply_markup)
                return None
    gmail_api = build('gmail', 'v1', credentials=credentials)
    return gmail_api
Ejemplo n.º 5
0
 def __new__(cls, credentials: Credentials) -> GDriveFileProviderFactory:
     if not credentials.valid:
         if (credentials and credentials.expired
                 and credentials.refresh_token):
             try:
                 credentials.refresh(Request())
             except RefreshError as e:
                 logging.error(e, exc_info=True)
                 raise InvalidFileProviderFactoryError(
                     "Could not get a valid token.")
         else:
             raise InvalidFileProviderFactoryError(
                 "No refresh token available to get new token.")
     cls._credentials = credentials
     return cast(GDriveFileProviderFactory, super().__new__(cls))
Ejemplo n.º 6
0
    def load_user_account_credentials(self):
        """
        Loads user account credentials from a local file.

        .. versionadded 0.2.0

        Parameters
        ----------
        None

        Returns
        -------
        - GoogleCredentials,
            If the credentials can loaded. The retrieved credentials should
            also have access to the project (self.project_id) on BigQuery.
        - OR None,
            If credentials can not be loaded from a file. Or, the retrieved
            credentials do not have access to the project (self.project_id)
            on BigQuery.
        """
        import httplib2
        from google_auth_httplib2 import Request
        from google.oauth2.credentials import Credentials

        try:
            with open('bigquery_credentials.dat') as credentials_file:
                credentials_json = json.load(credentials_file)
        except (IOError, ValueError):
            return None

        credentials = Credentials(
            token=credentials_json.get('access_token'),
            refresh_token=credentials_json.get('refresh_token'),
            id_token=credentials_json.get('id_token'),
            token_uri=credentials_json.get('token_uri'),
            client_id=credentials_json.get('client_id'),
            client_secret=credentials_json.get('client_secret'),
            scopes=credentials_json.get('scopes'))

        # Refresh the token before trying to use it.
        http = httplib2.Http()
        request = Request(http)
        credentials.refresh(request)

        return _try_credentials(self.project_id, credentials)
Ejemplo n.º 7
0
def get_authenticated_service():
    credentials = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)
    #  Check if the credentials are invalid or do not exist
    if not credentials or not credentials.valid:
        # Check if the credentials have expired
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CLIENT_SECRETS_FILE, SCOPES)
            credentials = flow.run_console()

        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(credentials, token)

    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
Ejemplo n.º 8
0
    def get_service_account_credentials(self):
        import httplib2
        from google_auth_httplib2 import Request
        from google.oauth2.service_account import Credentials
        from os.path import isfile

        try:
            if isfile(self.private_key):
                with open(self.private_key) as f:
                    json_key = json.loads(f.read())
            else:
                # ugly hack: 'private_key' field has new lines inside,
                # they break json parser, but we need to preserve them
                json_key = json.loads(self.private_key.replace('\n', '   '))
                json_key['private_key'] = json_key['private_key'].replace(
                    '   ', '\n')

            if compat.PY3:
                json_key['private_key'] = bytes(json_key['private_key'],
                                                'UTF-8')

            credentials = Credentials.from_service_account_info(json_key)
            credentials = credentials.with_scopes([self.scope])

            # Refresh the token before trying to use it.
            http = httplib2.Http()
            request = Request(http)
            credentials.refresh(request)

            return credentials
        except (KeyError, ValueError, TypeError, AttributeError):
            raise InvalidPrivateKeyFormat(
                "Private key is missing or invalid. It should be service "
                "account private key JSON (file path or string contents) "
                "with at least two keys: 'client_email' and 'private_key'. "
                "Can be obtained from: https://console.developers.google."
                "com/permissions/serviceaccounts")
Ejemplo n.º 9
0
def _build_service():
    credentials = None

    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)

    # If there are no (valid) credentials available, let the user log in.
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            http = httplib2.Http()
            credentials.refresh(Request(http))
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            credentials = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(credentials, token)

    return build('drive', 'v3', credentials=credentials, cache_discovery=False)