Python oauth2client.client.FlowExchangeError() Examples

The following are 14 code examples of oauth2client.client.FlowExchangeError(). 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: api.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def post(self):
        """
        Exchange client supplied oauth code for credentials.
        This does not require idtoken auth. User id is obtained form the
        oauth flow instead.
        """
        code = validation.auth_code_schema(self.json).get('code')
        try:
            credentials = auth.credentials_from_code(code)
        except FlowExchangeError:
            raise HTTPBadRequest('invalid code')
            # reject if we did not get a refresh token and id_token
        if not credentials.refresh_token:
            logging.warning('got no refresh token')
            raise HTTPForbidden('not initial code')
        id_token = credentials.id_token
        if id_token is None:
            raise HTTPForbidden('got no id token')
        try:
            email = id_token['email']
            user_id = id_token['sub']
        except KeyError:
            raise HTTPForbidden('no valid id')
        account = models.Account(email=email, id=user_id,
                                 credentials=credentials)
        account.put() 
Example #2
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 #3
Source File: app.py    From tuijam with MIT License 5 votes vote down vote up
def login(self):
        self.g_api = gmusicapi.Mobileclient(debug_logging=False)
        self.load_config()

        if not isfile(CRED_FILE):
            from oauth2client.client import FlowExchangeError

            print(_("No local credentials file found."))
            print(_("TUIJam will now open a browser window so you can provide"))
            print(_("permission for TUIJam to access your Google Play Music account."))
            input(_("Press enter to continue."))
            try:
                self.g_api.perform_oauth(CRED_FILE, open_browser=True)
            except FlowExchangeError:
                raise RuntimeError(_("Oauth authentication Failed."))

        self.g_api.oauth_login(self.g_api.FROM_MAC_ADDRESS, CRED_FILE,
                               locale=locale.getdefaultlocale()[0])

        if self.lastfm_sk is not None:
            try:
                self.lastfm = LastFMAPI(self.lastfm_sk)
            except Exception:
                print(_("Could not retrieve Last.fm keys."))
                print(_("Scrobbling will not be available."))
            # TODO handle if sk is invalid

        from apiclient.discovery import build

        try:
            developer_key, = lookup_keys("GOOGLE_DEVELOPER_KEY")
            self.youtube = build("youtube", "v3", developerKey=developer_key)
        except Exception:
            self.youtube = None
            print(_("Could not retrieve YouTube key."))
            print(_("YouTube will not be available.")) 
Example #4
Source File: test_tools.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_run_flow_no_webserver_exchange_error(
            self, input_mock, logging_mock):
        input_mock.return_value = 'auth_code'
        self.flow.step2_exchange.side_effect = client.FlowExchangeError()

        # Error while exchanging.
        with self.assertRaises(SystemExit):
            tools.run_flow(self.flow, self.storage, flags=self.flags)

        self.flow.step2_exchange.assert_called_once_with(
            'auth_code', http=None) 
Example #5
Source File: auth.py    From loaner with Apache License 2.0 4 votes vote down vote up
def _request_new_credentials(self, scopes):
    """Create the user credentials without a local webserver.

    Args:
      scopes: List[str], a list of the required scopes for this credential.

    Returns:
      An instance of credentials.Credentials for the authenticated user.

    Raises:
      InvalidCredentials: when we are unable to get valid credentials for the
          user.
    """
    redirect = 'urn:ietf:wg:oauth:2.0:oob'
    creds_flags = argparse.ArgumentParser(
        parents=[tools.argparser]).parse_args(['--noauth_local_webserver'])
    if _run_local_web_server_for_auth():
      redirect = 'http://localhost:8080/oauth2callback'
      creds_flags = argparse.ArgumentParser(
          parents=[tools.argparser]).parse_args([
              '--auth_host_port=8080',
              '--auth_host_name=localhost',
          ])
    flow = oauth2_client.OAuth2WebServerFlow(
        client_id=self._config.client_id,
        client_secret=self._config.client_secret,
        scope=scopes,
        redirect_uri=redirect)
    try:
      old_credentials = tools.run_flow(
          flow, client_file.Storage(self._config.local_credentials_file_path),
          creds_flags)
    except oauth2_client.FlowExchangeError as err:
      raise InvalidCredentials(
          'Unable to get valid credentials: {}.'.format(err))

    if _remove_creds() and os.path.isfile(
        self._config.local_credentials_file_path):
      os.remove(self._config.local_credentials_file_path)

    return credentials.Credentials(
        token=old_credentials.access_token,
        refresh_token=old_credentials.refresh_token,
        id_token=old_credentials.id_token,
        token_uri=old_credentials.token_uri,
        client_id=old_credentials.client_id,
        client_secret=old_credentials.client_secret,
        scopes=list(old_credentials.scopes)) 
Example #6
Source File: views.py    From aqua-monitor with GNU Lesser General Public License v3.0 4 votes vote down vote up
def oauth2_callback(request):
    """ View that handles the user's return from OAuth2 provider.

    This view verifies the CSRF state and OAuth authorization code, and on
    success stores the credentials obtained in the storage provider,
    and redirects to the return_url specified in the authorize view and
    stored in the session.

    :param request: Django request
    :return: A redirect response back to the return_url
    """
    if 'error' in request.GET:
        reason = request.GET.get(
            'error_description', request.GET.get('error', ''))
        return http.HttpResponseBadRequest(
            'Authorization failed %s' % reason)

    try:
        encoded_state = request.GET['state']
        code = request.GET['code']
    except KeyError:
        return http.HttpResponseBadRequest(
            "Request missing state or authorization code")

    try:
        server_csrf = request.session[_CSRF_KEY]
    except KeyError:
        return http.HttpResponseBadRequest("No existing session for this flow.")

    try:
        state = json.loads(encoded_state)
        client_csrf = state['csrf_token']
        return_url = state['return_url']
    except (ValueError, KeyError):
        return http.HttpResponseBadRequest('Invalid state parameter.')

    if client_csrf != server_csrf:
        return http.HttpResponseBadRequest('Invalid CSRF token.')

    flow = _get_flow_for_token(client_csrf, request)

    if not flow:
        return http.HttpResponseBadRequest("Missing Oauth2 flow.")

    try:
        credentials = flow.step2_exchange(code)
    except client.FlowExchangeError as exchange_error:
        return http.HttpResponseBadRequest(
            "An error has occurred: {0}".format(exchange_error))

    storage.get_storage(request).put(credentials)

    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,
                                   request=request, credentials=credentials)
    return shortcuts.redirect(return_url) 
Example #7
Source File: flask_util.py    From aqua-monitor with GNU Lesser General Public License v3.0 4 votes vote down vote up
def callback_view(self):
        """Flask view that handles the user's return from OAuth2 provider.

        On return, exchanges the authorization code for credentials and stores
        the credentials.
        """
        if 'error' in request.args:
            reason = request.args.get(
                'error_description', request.args.get('error', ''))
            return ('Authorization failed: {0}'.format(reason),
                    httplib.BAD_REQUEST)

        try:
            encoded_state = request.args['state']
            server_csrf = session[_CSRF_KEY]
            code = request.args['code']
        except KeyError:
            return 'Invalid request', httplib.BAD_REQUEST

        try:
            state = json.loads(encoded_state)
            client_csrf = state['csrf_token']
            return_url = state['return_url']
        except (ValueError, KeyError):
            return 'Invalid request state', httplib.BAD_REQUEST

        if client_csrf != server_csrf:
            return 'Invalid request state', httplib.BAD_REQUEST

        flow = _get_flow_for_token(server_csrf)

        if flow is None:
            return 'Invalid request state', httplib.BAD_REQUEST

        # Exchange the auth code for credentials.
        try:
            credentials = flow.step2_exchange(code)
        except FlowExchangeError as exchange_error:
            current_app.logger.exception(exchange_error)
            content = 'An error occurred: {0}'.format(exchange_error)
            return content, httplib.BAD_REQUEST

        # Save the credentials to the storage.
        self.storage.put(credentials)

        if self.authorize_callback:
            self.authorize_callback(credentials)

        return redirect(return_url) 
Example #8
Source File: views.py    From alfred-gmail with MIT License 4 votes vote down vote up
def oauth2_callback(request):
    """ View that handles the user's return from OAuth2 provider.

    This view verifies the CSRF state and OAuth authorization code, and on
    success stores the credentials obtained in the storage provider,
    and redirects to the return_url specified in the authorize view and
    stored in the session.

    Args:
        request: Django request.

    Returns:
         A redirect response back to the return_url.
    """
    if 'error' in request.GET:
        reason = request.GET.get(
            'error_description', request.GET.get('error', ''))
        return http.HttpResponseBadRequest(
            'Authorization failed {0}'.format(reason))

    try:
        encoded_state = request.GET['state']
        code = request.GET['code']
    except KeyError:
        return http.HttpResponseBadRequest(
            'Request missing state or authorization code')

    try:
        server_csrf = request.session[_CSRF_KEY]
    except KeyError:
        return http.HttpResponseBadRequest(
            'No existing session for this flow.')

    try:
        state = json.loads(encoded_state)
        client_csrf = state['csrf_token']
        return_url = state['return_url']
    except (ValueError, KeyError):
        return http.HttpResponseBadRequest('Invalid state parameter.')

    if client_csrf != server_csrf:
        return http.HttpResponseBadRequest('Invalid CSRF token.')

    flow = _get_flow_for_token(client_csrf, request)

    if not flow:
        return http.HttpResponseBadRequest('Missing Oauth2 flow.')

    try:
        credentials = flow.step2_exchange(code)
    except client.FlowExchangeError as exchange_error:
        return http.HttpResponseBadRequest(
            'An error has occurred: {0}'.format(exchange_error))

    get_storage(request).put(credentials)

    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,
                                   request=request, credentials=credentials)

    return shortcuts.redirect(return_url) 
Example #9
Source File: flask_util.py    From alfred-gmail with MIT License 4 votes vote down vote up
def callback_view(self):
        """Flask view that handles the user's return from OAuth2 provider.

        On return, exchanges the authorization code for credentials and stores
        the credentials.
        """
        if 'error' in request.args:
            reason = request.args.get(
                'error_description', request.args.get('error', ''))
            return ('Authorization failed: {0}'.format(reason),
                    httplib.BAD_REQUEST)

        try:
            encoded_state = request.args['state']
            server_csrf = session[_CSRF_KEY]
            code = request.args['code']
        except KeyError:
            return 'Invalid request', httplib.BAD_REQUEST

        try:
            state = json.loads(encoded_state)
            client_csrf = state['csrf_token']
            return_url = state['return_url']
        except (ValueError, KeyError):
            return 'Invalid request state', httplib.BAD_REQUEST

        if client_csrf != server_csrf:
            return 'Invalid request state', httplib.BAD_REQUEST

        flow = _get_flow_for_token(server_csrf)

        if flow is None:
            return 'Invalid request state', httplib.BAD_REQUEST

        # Exchange the auth code for credentials.
        try:
            credentials = flow.step2_exchange(code)
        except client.FlowExchangeError as exchange_error:
            current_app.logger.exception(exchange_error)
            content = 'An error occurred: {0}'.format(exchange_error)
            return content, httplib.BAD_REQUEST

        # Save the credentials to the storage.
        self.storage.put(credentials)

        if self.authorize_callback:
            self.authorize_callback(credentials)

        return redirect(return_url) 
Example #10
Source File: handlers.py    From go-links with Apache License 2.0 4 votes vote down vote up
def get(self):
    if self.request.get('r'):  # outgoing request
      self.session['request_data_to_replay'] = str(self.request.get('r'))

      self.render_login_selector_page(self.request.path_url)
      return

    try:
      original_request_data = json.loads(base64.urlsafe_b64decode(self.session['request_data_to_replay']))
    except (KeyError, ValueError):
      self.redirect('/')
      return

    if self.request.get('code'):
      flow = pickle.loads(self.session['pickled_oauth_flow'])

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

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

      self.session['user_email'] = authentication.get_user_email(credentials)
      self.user_email = self.session['user_email']
      self.user_org = get_organization_id_for_email(self.user_email)
    else:
      # assume this was a login via email, which would have been processed in the base handler
      pass

    object_data = json.loads(original_request_data['body'])

    new_link = None

    try:
      new_link = helpers.create_short_link(self.user_org,
                                           self.user_email,
                                           object_data['shortpath'],
                                           object_data['destination'])
      response_data = {
        'shortpath': new_link.shortpath,
        'destination': new_link.destination_url
      }
    except helpers.LinkCreationException as e:
      response_data = {
        'error': str(e)
      }

    self.redirect(str(original_request_data['origin'] + '?r=' + base64.urlsafe_b64encode(json.dumps(response_data)))) 
Example #11
Source File: views.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
def oauth2_callback(request):
    """ View that handles the user's return from OAuth2 provider.

    This view verifies the CSRF state and OAuth authorization code, and on
    success stores the credentials obtained in the storage provider,
    and redirects to the return_url specified in the authorize view and
    stored in the session.

    Args:
        request: Django request.

    Returns:
         A redirect response back to the return_url.
    """
    if 'error' in request.GET:
        reason = request.GET.get(
            'error_description', request.GET.get('error', ''))
        return http.HttpResponseBadRequest(
            'Authorization failed {0}'.format(reason))

    try:
        encoded_state = request.GET['state']
        code = request.GET['code']
    except KeyError:
        return http.HttpResponseBadRequest(
            'Request missing state or authorization code')

    try:
        server_csrf = request.session[_CSRF_KEY]
    except KeyError:
        return http.HttpResponseBadRequest(
            'No existing session for this flow.')

    try:
        state = json.loads(encoded_state)
        client_csrf = state['csrf_token']
        return_url = state['return_url']
    except (ValueError, KeyError):
        return http.HttpResponseBadRequest('Invalid state parameter.')

    if client_csrf != server_csrf:
        return http.HttpResponseBadRequest('Invalid CSRF token.')

    flow = _get_flow_for_token(client_csrf, request)

    if not flow:
        return http.HttpResponseBadRequest('Missing Oauth2 flow.')

    try:
        credentials = flow.step2_exchange(code)
    except client.FlowExchangeError as exchange_error:
        return http.HttpResponseBadRequest(
            'An error has occurred: {0}'.format(exchange_error))

    get_storage(request).put(credentials)

    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,
                                   request=request, credentials=credentials)

    return shortcuts.redirect(return_url) 
Example #12
Source File: flask_util.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
def callback_view(self):
        """Flask view that handles the user's return from OAuth2 provider.

        On return, exchanges the authorization code for credentials and stores
        the credentials.
        """
        if 'error' in request.args:
            reason = request.args.get(
                'error_description', request.args.get('error', ''))
            return ('Authorization failed: {0}'.format(reason),
                    httplib.BAD_REQUEST)

        try:
            encoded_state = request.args['state']
            server_csrf = session[_CSRF_KEY]
            code = request.args['code']
        except KeyError:
            return 'Invalid request', httplib.BAD_REQUEST

        try:
            state = json.loads(encoded_state)
            client_csrf = state['csrf_token']
            return_url = state['return_url']
        except (ValueError, KeyError):
            return 'Invalid request state', httplib.BAD_REQUEST

        if client_csrf != server_csrf:
            return 'Invalid request state', httplib.BAD_REQUEST

        flow = _get_flow_for_token(server_csrf)

        if flow is None:
            return 'Invalid request state', httplib.BAD_REQUEST

        # Exchange the auth code for credentials.
        try:
            credentials = flow.step2_exchange(code)
        except client.FlowExchangeError as exchange_error:
            current_app.logger.exception(exchange_error)
            content = 'An error occurred: {0}'.format(exchange_error)
            return content, httplib.BAD_REQUEST

        # Save the credentials to the storage.
        self.storage.put(credentials)

        if self.authorize_callback:
            self.authorize_callback(credentials)

        return redirect(return_url) 
Example #13
Source File: flask_util.py    From data with GNU General Public License v3.0 4 votes vote down vote up
def callback_view(self):
        """Flask view that handles the user's return from OAuth2 provider.

        On return, exchanges the authorization code for credentials and stores
        the credentials.
        """
        if 'error' in request.args:
            reason = request.args.get(
                'error_description', request.args.get('error', ''))
            return ('Authorization failed: {0}'.format(reason),
                    httplib.BAD_REQUEST)

        try:
            encoded_state = request.args['state']
            server_csrf = session[_CSRF_KEY]
            code = request.args['code']
        except KeyError:
            return 'Invalid request', httplib.BAD_REQUEST

        try:
            state = json.loads(encoded_state)
            client_csrf = state['csrf_token']
            return_url = state['return_url']
        except (ValueError, KeyError):
            return 'Invalid request state', httplib.BAD_REQUEST

        if client_csrf != server_csrf:
            return 'Invalid request state', httplib.BAD_REQUEST

        flow = _get_flow_for_token(server_csrf)

        if flow is None:
            return 'Invalid request state', httplib.BAD_REQUEST

        # Exchange the auth code for credentials.
        try:
            credentials = flow.step2_exchange(code)
        except FlowExchangeError as exchange_error:
            current_app.logger.exception(exchange_error)
            content = 'An error occurred: {0}'.format(exchange_error)
            return content, httplib.BAD_REQUEST

        # Save the credentials to the storage.
        self.storage.put(credentials)

        if self.authorize_callback:
            self.authorize_callback(credentials)

        return redirect(return_url) 
Example #14
Source File: flask_util.py    From data with GNU General Public License v3.0 4 votes vote down vote up
def callback_view(self):
        """Flask view that handles the user's return from OAuth2 provider.

        On return, exchanges the authorization code for credentials and stores
        the credentials.
        """
        if 'error' in request.args:
            reason = request.args.get(
                'error_description', request.args.get('error', ''))
            return ('Authorization failed: {0}'.format(reason),
                    httplib.BAD_REQUEST)

        try:
            encoded_state = request.args['state']
            server_csrf = session[_CSRF_KEY]
            code = request.args['code']
        except KeyError:
            return 'Invalid request', httplib.BAD_REQUEST

        try:
            state = json.loads(encoded_state)
            client_csrf = state['csrf_token']
            return_url = state['return_url']
        except (ValueError, KeyError):
            return 'Invalid request state', httplib.BAD_REQUEST

        if client_csrf != server_csrf:
            return 'Invalid request state', httplib.BAD_REQUEST

        flow = _get_flow_for_token(server_csrf)

        if flow is None:
            return 'Invalid request state', httplib.BAD_REQUEST

        # Exchange the auth code for credentials.
        try:
            credentials = flow.step2_exchange(code)
        except FlowExchangeError as exchange_error:
            current_app.logger.exception(exchange_error)
            content = 'An error occurred: {0}'.format(exchange_error)
            return content, httplib.BAD_REQUEST

        # Save the credentials to the storage.
        self.storage.put(credentials)

        if self.authorize_callback:
            self.authorize_callback(credentials)

        return redirect(return_url)