當前位置: 首頁>>代碼示例>>Python>>正文


Python client.FlowExchangeError方法代碼示例

本文整理匯總了Python中oauth2client.client.FlowExchangeError方法的典型用法代碼示例。如果您正苦於以下問題:Python client.FlowExchangeError方法的具體用法?Python client.FlowExchangeError怎麽用?Python client.FlowExchangeError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在oauth2client.client的用法示例。


在下文中一共展示了client.FlowExchangeError方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: post

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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() 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:28,代碼來源:api.py

示例2: get

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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', '/')) 
開發者ID:trotto,項目名稱:go-links,代碼行數:32,代碼來源:handlers.py

示例3: login

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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.")) 
開發者ID:cfangmeier,項目名稱:tuijam,代碼行數:38,代碼來源:app.py

示例4: test_run_flow_no_webserver_exchange_error

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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) 
開發者ID:haynieresearch,項目名稱:jarvis,代碼行數:13,代碼來源:test_tools.py

示例5: _request_new_credentials

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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)) 
開發者ID:google,項目名稱:loaner,代碼行數:50,代碼來源:auth.py

示例6: oauth2_callback

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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) 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:57,代碼來源:views.py

示例7: callback_view

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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) 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:51,代碼來源:flask_util.py

示例8: oauth2_callback

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:62,代碼來源:views.py

示例9: callback_view

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:51,代碼來源:flask_util.py

示例10: get

# 需要導入模塊: from oauth2client import client [as 別名]
# 或者: from oauth2client.client import FlowExchangeError [as 別名]
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)))) 
開發者ID:trotto,項目名稱:go-links,代碼行數:53,代碼來源:handlers.py


注:本文中的oauth2client.client.FlowExchangeError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。