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


Python exceptions.AuthException方法代碼示例

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


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

示例1: test_post_facebook_provider_code_validation_fails

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def test_post_facebook_provider_code_validation_fails(self):
        data = {"code": "XYZ", "state": "ABC"}

        mock.patch(
            "social_core.backends.facebook.FacebookOAuth2.auth_complete",
            side_effect=AuthException(backend=None),
        ).start()
        mock.patch(
            "social_core.backends.oauth.OAuthAuth.get_session_state",
            return_value=data["state"],
        ).start()

        request = self.factory.post()
        request.GET = {k: v for k, v in six.iteritems(data)}
        response = self.view(request, provider="facebook")
        self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) 
開發者ID:sunscrapers,項目名稱:djoser,代碼行數:18,代碼來源:test_provider_auth.py

示例2: validate

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def validate(self, attrs):
        request = self.context["request"]
        if "state" in request.GET:
            self._validate_state(request.GET["state"])

        strategy = load_strategy(request)
        redirect_uri = strategy.session_get("redirect_uri")

        backend_name = self.context["view"].kwargs["provider"]
        backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri)

        try:
            user = backend.auth_complete()
        except exceptions.AuthException as e:
            raise serializers.ValidationError(str(e))
        return {"user": user} 
開發者ID:sunscrapers,項目名稱:djoser,代碼行數:18,代碼來源:serializers.py

示例3: check_edx_verified_email

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def check_edx_verified_email(backend, response, details, *args, **kwargs):  # pylint: disable=unused-argument
    """Get account information to check if email was verified for account on edX"""
    if backend.name != EdxOrgOAuth2.name:
        return {}

    username = details.get('username')
    access_token = response.get('access_token')
    if not access_token:
        # this should never happen for the edx oauth provider, but just in case...
        raise AuthException('Missing access token for the edX user {0}'.format(username))

    user_profile_edx = backend.get_json(
        urljoin(backend.EDXORG_BASE_URL, '/api/user/v1/accounts/{0}'.format(username)),
        headers={
            "Authorization": "Bearer {}".format(access_token),
        }
    )

    if not user_profile_edx.get('is_active'):
        return redirect('verify-email')

    return {'edx_profile': user_profile_edx} 
開發者ID:mitodl,項目名稱:micromasters,代碼行數:24,代碼來源:pipeline_api.py

示例4: test_initialize_engine_object_ObjectDoesNotExist

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def test_initialize_engine_object_ObjectDoesNotExist(self):
        input_engine = 'tethys_dataset_services.engines.HydroShareDatasetEngine'
        input_end_point = 'http://localhost/api/3/action'

        mock_user = mock.MagicMock()
        mock_request = mock.MagicMock(user=mock_user, path='path')

        mock_social = mock.MagicMock()

        mock_user.social_auth.get.side_effect = [ObjectDoesNotExist, mock_social]

        mock_social.extra_data['access_token'].return_value = None

        self.assertRaises(AuthException, initialize_engine_object, engine=input_engine, endpoint=input_end_point,
                          request=mock_request)

        mock_user.social_auth.get.assert_called_once_with(provider='hydroshare') 
開發者ID:tethysplatform,項目名稱:tethys,代碼行數:19,代碼來源:test_utilities.py

示例5: post

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def post(self, request, *args, **kwargs):
        input_data = self.get_serializer_in_data()
        provider_name = self.get_provider_name(input_data)
        if not provider_name:
            return self.respond_error("Provider is not specified")
        self.set_input_data(request, input_data)
        decorate_request(request, provider_name)
        serializer_in = self.get_serializer_in(data=input_data)
        if self.oauth_v1() and request.backend.OAUTH_TOKEN_PARAMETER_NAME not in input_data:
            # oauth1 first stage (1st is get request_token, 2nd is get access_token)
            manual_redirect_uri = self.request.auth_data.pop('redirect_uri', None)
            manual_redirect_uri = self.get_redirect_uri(manual_redirect_uri)
            if manual_redirect_uri:
                self.request.backend.redirect_uri = manual_redirect_uri
            request_token = parse_qs(request.backend.set_unauthorized_token())
            return Response(request_token)
        serializer_in.is_valid(raise_exception=True)
        try:
            user = self.get_object()
        except (AuthException, HTTPError) as e:
            return self.respond_error(e)
        if isinstance(user, HttpResponse):
            # error happened and pipeline returned HttpResponse instead of user
            return user
        resp_data = self.get_serializer(instance=user)
        self.do_login(request.backend, user)
        return Response(resp_data.data) 
開發者ID:st4lk,項目名稱:django-rest-social-auth,代碼行數:29,代碼來源:views.py

示例6: respond_error

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def respond_error(self, error):
        if isinstance(error, Exception):
            if not isinstance(error, AuthException) or LOG_AUTH_EXCEPTIONS:
                self.log_exception(error)
        else:
            logger.error(error)
        return Response(status=status.HTTP_400_BAD_REQUEST) 
開發者ID:st4lk,項目名稱:django-rest-social-auth,代碼行數:9,代碼來源:views.py

示例7: associate_by_email_or_pause

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def associate_by_email_or_pause(strategy, details, user=None, backend=None,
                                is_new=False, *args, **kwargs):
    """
    Associate current auth with a user with the same email address in the DB.

    This pipeline entry is not 100% secure unless you know that the providers
    enabled enforce email verification on their side, otherwise a user can
    attempt to take over another user account by using the same (not validated)
    email address on some provider.  This pipeline entry is disabled by
    default.

    We redirect the user to a access denied page where they can resume the
    login in the case an admin grants them access.
    """
    if user:
        return None

    email = details.get('email')
    if email:
        # Try to associate accounts registered with the same email address,
        # only if it's a single object. AuthException is raised if multiple
        # objects are returned.
        users = list(strategy.storage.user.get_users_by_email(email))
        if len(users) == 0:
            # Redirect to an error page notifying user their email hasn't
            # been added by the admins. This page can be re-visited once the
            # user account has been added to the system.
            current_partial = kwargs.get('current_partial')
            return strategy.redirect(
                '/request-access?partial_token={0}&backend={1}'.format(
                    current_partial.token, backend.name
                ))
        elif len(users) > 1:
            raise AuthException(
                backend,
                'The given email address is associated with another account'
            )
        else:
            return {'user': users[0],
                    'is_new': False} 
開發者ID:propublica,項目名稱:django-collaborative,代碼行數:42,代碼來源:user.py

示例8: test_get_engine_hydroshare_error

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def test_get_engine_hydroshare_error(self, _):
        user = mock.MagicMock()
        user.social_auth.get.side_effect = ObjectDoesNotExist
        request = mock.MagicMock(user=user)
        ds = service_model.DatasetService(
            name='test_ds',
            engine='tethys_dataset_services.engines.HydroShareDatasetEngine',
        )
        self.assertRaises(AuthException, ds.get_engine, request=request) 
開發者ID:tethysplatform,項目名稱:tethys,代碼行數:11,代碼來源:test_DatasetService.py

示例9: get_engine

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def get_engine(self, request=None):
        """
        Retrieves dataset service engine
        """
        # Get Token for HydroShare interactions
        if self.engine == self.HYDROSHARE:
            # Constants
            HYDROSHARE_OAUTH_PROVIDER_NAME = 'hydroshare'
            user = request.user

            try:
                # social = user.social_auth.get(provider='google-oauth2')
                social = user.social_auth.get(provider=HYDROSHARE_OAUTH_PROVIDER_NAME)
                apikey = social.extra_data['access_token']  # noqa: F841
            except ObjectDoesNotExist:
                # User is not associated with that provider
                # Need to prompt for association
                raise AuthException("HydroShare authentication required. To automate the authentication prompt "
                                    "decorate your controller function with the @ensure_oauth('hydroshare') decorator.")

            return HydroShareDatasetEngine(endpoint=self.endpoint,
                                           username=self.username,
                                           password=self.password,
                                           apikey=self.apikey)

        return CkanDatasetEngine(endpoint=self.endpoint,
                                 username=self.username,
                                 password=self.password,
                                 apikey=self.apikey) 
開發者ID:tethysplatform,項目名稱:tethys,代碼行數:31,代碼來源:models.py

示例10: initialize_engine_object

# 需要導入模塊: from social_core import exceptions [as 別名]
# 或者: from social_core.exceptions import AuthException [as 別名]
def initialize_engine_object(engine, endpoint, apikey=None, username=None, password=None, request=None):
    """
    Initialize a DatasetEngine object from a string that points at the engine class.
    """
    # Constants
    HYDROSHARE_OAUTH_PROVIDER_NAME = 'hydroshare'

    # Derive import parts from engine string
    engine_split = engine.split('.')
    module_string = '.'.join(engine_split[:-1])
    engine_class_string = engine_split[-1]

    # Import
    module_ = __import__(module_string, fromlist=[str(engine_class_string)])
    EngineClass = getattr(module_, engine_class_string)

    # Get Token for HydroShare interactions
    if EngineClass is HydroShareDatasetEngine:
        user = request.user

        try:
            # social = user.social_auth.get(provider='google-oauth2')
            social = user.social_auth.get(provider=HYDROSHARE_OAUTH_PROVIDER_NAME)
            apikey = social.extra_data['access_token']
        except ObjectDoesNotExist:
            # User is not associated with that provider
            # Need to prompt for association
            raise AuthException("HydroShare authentication required. To automate the authentication prompt decorate "
                                "your controller function with the @ensure_oauth('hydroshare') decorator.")
        except AttributeError:
            # Anonymous User...
            raise
        except AuthAlreadyAssociated:
            raise

    # Create Engine Object
    engine_instance = EngineClass(
        endpoint=endpoint,
        apikey=apikey,
        username=username,
        password=password
    )
    return engine_instance 
開發者ID:tethysplatform,項目名稱:tethys,代碼行數:45,代碼來源:utilities.py


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