python类FlowExchangeError()的实例源码

googledrive.py 文件源码 项目:paste2box 作者: rokups 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_login(self, login_parameters):
        try:
            title = login_parameters['Title']
            code = login_parameters['Code']

            if not title or not code:
                raise ValueError('Invalid parameters')

            if title in self.config['login']:
                raise ValueError('Login "{}" already exists.'.format(title))

            try:
                credentials = self._flow.step2_exchange(code, http=None)
            except client.FlowExchangeError as e:
                raise ValueError('Authentication has failed: {}'.format(str(e)))

            self.config['login'][title] = json.loads(credentials.to_json())
            return title
        finally:
            self._flow = None
reddit.py 文件源码 项目:helios-server-mixnet 作者: RunasSudo 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_user_info_after_auth(request):
  flow = get_flow(request.session['reddit-redirect-url'])
  del request.session['reddit-redirect-url']

  state = request.session['reddit-state']
  del request.session['reddit-state']

  # Verify that the state matches
  if str(request.GET['state']) != str(state):
    raise FlowExchangeError('State does not match! Expected %s got %s' % (state, request.GET['state']))

  code = request.GET['code']
  credentials = step2_exchange(flow, code) # Needs to be modified for reddit OAuth

  # get the nice name
  http = httplib2.Http(".cache")
  http = credentials.authorize(http)
  (resp_headers, content) = http.request("https://oauth.reddit.com/api/v1/me", "GET")

  response = json.loads(content)

  name = response['name']

  return {'type': 'reddit', 'user_id': name, 'name': name, 'info': {'name': name}, 'token':{}}
api.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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()
test_views.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_callback_handles_bad_flow_exchange(self, jsonpickle_mock):
        request = self.factory.get('oauth2/oauth2callback', data={
            "state": json.dumps(self.fake_state),
            "code": 123
        })

        self.session['google_oauth2_csrf_token'] = self.CSRF_TOKEN

        flow = client.OAuth2WebServerFlow(
            client_id='clientid',
            client_secret='clientsecret',
            scope=['email'],
            state=json.dumps(self.fake_state),
            redirect_uri=request.build_absolute_uri('oauth2/oauth2callback'))

        session_key = 'google_oauth2_flow_{0}'.format(self.CSRF_TOKEN)
        pickled_flow = object()
        self.session[session_key] = pickled_flow

        def local_throws(code):
            raise client.FlowExchangeError('test')

        flow.step2_exchange = local_throws
        jsonpickle_mock.decode.return_value = flow

        request.session = self.session
        response = views.oauth2_callback(request)
        self.assertIsInstance(response, http.HttpResponseBadRequest)
        jsonpickle_mock.decode.assert_called_once_with(pickled_flow)
test_client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_exchange_failure(self):
        http = http_mock.HttpMock(
            headers={'status': http_client.BAD_REQUEST},
            data=b'{"error":"invalid_request"}',
        )

        with self.assertRaises(client.FlowExchangeError):
            self.flow.step2_exchange(code='some random code', http=http)
test_client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_urlencoded_exchange_failure(self):
        http = http_mock.HttpMock(
            headers={'status': http_client.BAD_REQUEST},
            data=b'error=invalid_request',
        )

        with self.assertRaisesRegexp(client.FlowExchangeError,
                                     'invalid_request'):
            self.flow.step2_exchange(code='some random code', http=http)
test_client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_exchange_failure_with_json_error(self):
        # Some providers have 'error' attribute as a JSON object
        # in place of regular string.
        # This test makes sure no strange object-to-string coversion
        # exceptions are being raised instead of FlowExchangeError.
        payload = (b'{'
                   b'  "error": {'
                   b'    "message": "Error validating verification code.",'
                   b'    "type": "OAuthException"'
                   b'  }'
                   b'}')
        http = http_mock.HttpMock(data=payload)

        with self.assertRaises(client.FlowExchangeError):
            self.flow.step2_exchange(code='some random code', http=http)
test_client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_exchange_fails_if_no_code(self):
        payload = (b'{'
                   b'  "access_token":"SlAV32hkKG",'
                   b'  "refresh_token":"8xLOxBtZp8"'
                   b'}')
        http = http_mock.HttpMock(data=payload)

        code = {'error': 'thou shall not pass'}
        with self.assertRaisesRegexp(
                client.FlowExchangeError, 'shall not pass'):
            self.flow.step2_exchange(code=code, http=http)
test_client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_exchange_code_and_file_for_token_fail(self):
        http = http_mock.HttpMock(
            headers={'status': http_client.BAD_REQUEST},
            data=b'{"error":"invalid_request"}',
        )

        with self.assertRaises(client.FlowExchangeError):
            client.credentials_from_clientsecrets_and_code(
                datafile('client_secrets.json'), self.scope,
                self.code, http=http)
test_tools.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
oauth.py 文件源码 项目:GoogleBot 作者: MarcoBuster 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def save(usr, code):
    try:
        credentials = flow.step2_exchange(code)
    except FlowExchangeError:
        return False

    os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials')

    file_name = '{id}.json'.format(id=usr.id)
    open(file_name, 'a').close()
    storage = Storage(file_name)
    storage.put(credentials)
    return True
test_views.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_callback_handles_bad_flow_exchange(self, jsonpickle_mock):
        request = self.factory.get('oauth2/oauth2callback', data={
            "state": json.dumps(self.fake_state),
            "code": 123
        })

        self.session['google_oauth2_csrf_token'] = self.CSRF_TOKEN

        flow = client.OAuth2WebServerFlow(
            client_id='clientid',
            client_secret='clientsecret',
            scope=['email'],
            state=json.dumps(self.fake_state),
            redirect_uri=request.build_absolute_uri('oauth2/oauth2callback'))

        session_key = 'google_oauth2_flow_{0}'.format(self.CSRF_TOKEN)
        pickled_flow = object()
        self.session[session_key] = pickled_flow

        def local_throws(code):
            raise client.FlowExchangeError('test')

        flow.step2_exchange = local_throws
        jsonpickle_mock.decode.return_value = flow

        request.session = self.session
        response = views.oauth2_callback(request)
        self.assertIsInstance(response, http.HttpResponseBadRequest)
        jsonpickle_mock.decode.assert_called_once_with(pickled_flow)
test_client.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_exchange_failure(self):
        http = http_mock.HttpMock(
            headers={'status': http_client.BAD_REQUEST},
            data=b'{"error":"invalid_request"}',
        )

        with self.assertRaises(client.FlowExchangeError):
            self.flow.step2_exchange(code='some random code', http=http)
test_client.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 50 收藏 0 点赞 0 评论 0
def test_urlencoded_exchange_failure(self):
        http = http_mock.HttpMock(
            headers={'status': http_client.BAD_REQUEST},
            data=b'error=invalid_request',
        )

        with self.assertRaisesRegexp(client.FlowExchangeError,
                                     'invalid_request'):
            self.flow.step2_exchange(code='some random code', http=http)
test_client.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_exchange_failure_with_json_error(self):
        # Some providers have 'error' attribute as a JSON object
        # in place of regular string.
        # This test makes sure no strange object-to-string coversion
        # exceptions are being raised instead of FlowExchangeError.
        payload = (b'{'
                   b'  "error": {'
                   b'    "message": "Error validating verification code.",'
                   b'    "type": "OAuthException"'
                   b'  }'
                   b'}')
        http = http_mock.HttpMock(data=payload)

        with self.assertRaises(client.FlowExchangeError):
            self.flow.step2_exchange(code='some random code', http=http)
test_client.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_exchange_fails_if_no_code(self):
        payload = (b'{'
                   b'  "access_token":"SlAV32hkKG",'
                   b'  "refresh_token":"8xLOxBtZp8"'
                   b'}')
        http = http_mock.HttpMock(data=payload)

        code = {'error': 'thou shall not pass'}
        with self.assertRaisesRegexp(
                client.FlowExchangeError, 'shall not pass'):
            self.flow.step2_exchange(code=code, http=http)
test_client.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_exchange_code_and_file_for_token_fail(self):
        http = http_mock.HttpMock(
            headers={'status': http_client.BAD_REQUEST},
            data=b'{"error":"invalid_request"}',
        )

        with self.assertRaises(client.FlowExchangeError):
            client.credentials_from_clientsecrets_and_code(
                datafile('client_secrets.json'), self.scope,
                self.code, http=http)
test_tools.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
gsheets.py 文件源码 项目:Tobo-Cogs 作者: Tobotimus 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def authsheets(self, ctx):
        """Authorize GSheets to use the Google Sheets API."""
        flow = client.OAuth2WebServerFlow(**FLOW_KWARGS)
        authorize_url = flow.step1_get_authorize_url()
        info_message = ("Use the link below to authorize the cog to communicate with Google Sheets, "
                        "then copy the code you recieve and paste it here.")
        warn_message = ("**NOTE**: It is not recommended to authorize the cog using "
                        "your personal Google Account; it is best to create a new Google Account, "
                        "and share any Sheets you would like to access with that google account.")
        embed = discord.Embed(title="Authorize GSheets", url=authorize_url, description=warn_message)
        try:
            await self.bot.say(info_message, embed=embed)
        except discord.errors.Forbidden:
            await self.bot.say("\n\n".join(info_message, authorize_url, warn_message))
        resp = await self.bot.wait_for_message(author=ctx.message.author)
        credentials = None
        if resp:
            try:
                code = resp.content
                http = httplib2.Http()
                credentials = flow.step2_exchange(code, http=http)
            except client.FlowExchangeError as e:
                await self.bot.say("Authentication has failed: {}".format(e.args[0]))
                return
        self.gc = GSheetsClient(credentials)
        store = Storage(CREDENTIAL_PATH)
        store.put(credentials)
        credentials.set_store(store)
        await self.bot.say("Authentication successful.")
getoauthtoken.py 文件源码 项目:Deploy_XXNET_Server 作者: jzp820927 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def handle_noargs(self, **unused_options):
    """Perform an OAuth 2.0 oob flow.

    After the flow completes, instructions are provided to manually store the
    OAuth2 refresh_token in the project settings file.
    """
    flow = rdbms_googleapi.GetFlow()
    self.stdout.write('\nGo to the following link in your browser:\n%s\n\n' %
                      flow.step1_get_authorize_url('oob'))
    accepted = 'n'
    while accepted.lower() == 'n':
      accepted = raw_input('Have you authorized me? (y/n) ')
    code = raw_input('What is the verification code? ').strip()
    try:
      credential = flow.step2_exchange(code)
    except client.FlowExchangeError:
      raise base.CommandError('The authentication has failed.')
    self.stdout.write(
        '\nAdd your OAuth refresh token (%s) as an "OAUTH2_SECRET" parameter to'
        ' your database OPTIONS.  For example:\n' % credential.refresh_token)
    self.stdout.write("""
    DATABASES = {
        'default': {
            'ENGINE': 'google.storage.speckle.python.django.backend',
            'INSTANCE': 'examplecom:instance',
            'NAME': 'dbname',
            'OPTIONS': {
                'OAUTH2_SECRET': '%s',
            }
        }
    }\n""" % credential.refresh_token)
views.py 文件源码 项目:quupod 作者: alvinwan 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def login(home: str=None, login: str=None) -> str:
    """Login using Google authentication.

    :param home: URL for queue homepage
    :param login: URL for queue login page
    """
    try:
        flow = get_google_auth_flow(login)
        if 'code' not in request.args:
            return redirect(get_google_authorize_uri(flow))
        person = get_google_person(flow)
        user = User.query.filter_by(google_id=person['id']).first()
        if not user:
            user = User(
                name=person['displayName'],
                email=person['emails'][0]['value'],
                google_id=person['id'],
                image_url=person['image']['url']).save()
        flask_login.login_user(user)
        return redirect(home or url_for('public.home'))
    except client.FlowExchangeError:
        return redirect(login or url_for('public.login'))


######################
# SESSION UTILIITIES #
######################
__init__.py 文件源码 项目:oauth2l 作者: google 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _GetCredentialsVia3LO(client_info, credentials_filename=None):
    credential_store = _GetCredentialStore(credentials_filename,
                                           client_info['client_id'],
                                           client_info['scope'])
    credentials = credential_store.get()
    if credentials is None or credentials.invalid:
        for _ in range(10):
            # If authorization fails, we want to retry, rather
            # than let this cascade up and get caught elsewhere.
            # If users want out of the retry loop, they can ^C.
            try:
                flow = client.OAuth2WebServerFlow(**client_info)
                flags, _ = tools.argparser.parse_known_args(
                    ['--noauth_local_webserver'])
                credentials = tools.run_flow(
                    flow, credential_store, flags)
                break
            except (SystemExit, client.FlowExchangeError) as e:
                # Here SystemExit is "no credential at all", and the
                # FlowExchangeError is "invalid" -- usually because
                # you reused a token.
                pass
            except httplib2.HttpLib2Error as e:
                raise ValueError(
                    'Communication error creating credentials:'
                    '{}'.format(e))
        else:
            credentials = None
    return credentials
cli.py 文件源码 项目:adwordspy 作者: MihaZelnik 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def main(argv=sys.argv):
    """
        Retrieve and display the access and refresh token.
    """
    if len(argv) < 3:
        print('CLIENT_ID or CLIENT_SECRET is missing')
        return 0

    client_id = argv[1]
    client_secret = argv[2]
    flow = client.OAuth2WebServerFlow(
        client_id=client_id,
        client_secret=client_secret,
        scope=['https://www.googleapis.com/auth/adwords'],
        user_agent='Ads Python Client Library',
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')

    authorize_url = flow.step1_get_authorize_url()

    print('Log into the Google Account you use to access your AdWords account'
          'and go to the following URL: \n{}\n'.format(authorize_url))
    print('After approving the token enter the verification code (if specified).')
    code = input('Code: ').strip()

    try:
        credential = flow.step2_exchange(code)
    except client.FlowExchangeError as e:
        print('Authentication has failed: {}'.format(e))
        sys.exit(1)
    else:
        print('OAuth 2.0 authorization successful!\n\n'
              'Your access token is:\n {}\n\nYour refresh token is:\n {}'.format(
                credential.access_token, credential.refresh_token))
views.py 文件源码 项目:oscars2016 作者: 0x0ece 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
flask_util.py 文件源码 项目:oscars2016 作者: 0x0ece 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
flask_util.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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', ''))
            reason = markupsafe.escape(reason)
            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)
views.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
flask_util.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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', ''))
            reason = markupsafe.escape(reason)
            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)
views.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号