当前位置: 首页>>代码示例>>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;未经允许,请勿转载。