【问题标题】:django social auth with django rest frameworkdjango 社交身份验证与 django rest 框架
【发布时间】:2023-04-07 08:05:01
【问题描述】:

我无法将我的社交用户与 django 相关联。我创建了一个 CreateAPIView,它从用户那里获取 token_access、token_access_secret 和提供者。但一切似乎都正常。但 do_auth 方法并没有完全创建
我的用户社交帐户。

views.py
class SocialSignUp(CreateAPIView):
# permission_classes = ()
queryset = User.objects.all()
serializer_class = SocialUserRegistrationSerializer
# social_serializer = SocialUserRegistrationSerializer
ee = None

def create(self, request, *args, **kwargs):

    prov = request.DATA['provider']
    redirect = request.path
    if request.user.is_authenticated():
        authed_user = request.user
    else:
        authed_user = AnonymousUser()

    backend = get_backend(name=prov, request=request, redirect=redirect)
    serializer = self.serializer_class(data=request.QUERY_PARAMS)
    if isinstance(backend, BaseOAuth):
        print 'BaseOAUTH 1'
        # Twitter, for example, uses OAuth1 and requires that you also pass
        # an `oauth_token_secret` with your authentication request
        token = {
            'oauth_token': request.DATA['access_token'],
            'oauth_token_secret': request.DATA['access_token_secret'],
        }

    elif isinstance(backend, BaseOAuth2):
        # We're using oauth's implicit grant type (usually used for web and mobile
        # applications), so all we have to pass here is an access_token
        print 'BaseOAUTH 2'
        token = request.DATA['access_token']
    print backend.user_data(request.DATA['access_token'])
    print backend.get_scope()
    try:
        # if `authed_user` is None, python-social-auth will make a new user,
        # else this social account will be associated with the user you pass in
        user = backend.do_auth(access_token=token, )
        print user
    except AuthAlreadyAssociated:
        # You can't associate a social account with more than user
        return Response({"errors": "That social media account is already in use"},
                        status=status.HTTP_400_BAD_REQUEST)

    if user and user.is_active:
        # if the access token was set to an empty string, then save the access token
        # from the request
        auth_created = user.social_auth.get(provider=prov)
        if not auth_created.extra_data['access_token']:
            # Facebook for example will return the access_token in its response to you.
            # This access_token is then saved for your future use. However, others
            # e.g., Instagram do not respond with the access_token that you just
            # provided. We save it here so it can be used to make subsequent calls.
            auth_created.extra_data['access_token'] = token
            auth_created.save()

        # Set instance since we are not calling `serializer.save()`
        serializer.instance = user
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED,
                        headers=headers)
    else:
        return Response({"errors": "Error with social authentication"},
                        status=status.HTTP_400_BAD_REQUEST)

我的序列化程序类

class SocialUserRegistrationSerializer(serializers.Serializer):
     """
     Serializer to receive social auth for python-social-auth
     """
     access_token = serializers.CharField()
     access_token_secret = serializers.CharField(required=False)
     provider = serializers.CharField()

另一个实现:

def create(self, request, *args, **kwargs):


    prov = request.DATA['provider']
    redirect = request.path
    backend = get_backend(name=prov, request=request, redirect=redirect)
    request.social_auth_backend = backend
    access_token = request.DATA['access_token']

    if hasattr(request, 'user'):
        if request.user.is_authenticated():
            user = request.user
        else:
            user = None
    user = None

    try:
        if prov == "google-oauth2":
            test_response = googleapis_profile(GOOGLEAPIS_PROFILE, access_token)

            # gender = test_response.get('gender')
            # email = test_response.get('email')
            # full_name = test_response.get('familly_name') + test_response.get('given_name')

            if test_response is None:
                return Response({'success': False, 'detail': "bad access_token"}, status=status.HTTP_400_BAD_REQUEST)


            user = backend.do_auth(access_token, user=user)

            print user
            my_user = user
            user_serializer = SocialUserRegistrationSerializer(user)
            return Response({'success': True, 'detail': user_serializer.data})
    except Exception as e:
            return Response({'success': False, 'detail': e}, status = status.HTTP_400_BAD_REQUEST)

我不知道如何使 do_auth 工作,它总是将用户返回为 None

谢谢。

【问题讨论】:

    标签: django django-rest-framework python-social-auth django-socialauth


    【解决方案1】:

    django-social-auth 已被弃用,取而代之的是 python-social-auth。我认为您会很好地切换并尝试使用为该项目提供的大量文档。

    【讨论】:

    • 是的,我知道,但问题是我不得不升级整个项目。我使用的是 Django 1.5,还有很多第三方。
    • 啊,这总是很有趣。我相信您已经很清楚这一点,但 Django 1.5(和 1.6,也是)被认为不受支持并且可能不安全。抱歉,在您的情况下我无法提供更多帮助:)
    • 检查我的编辑,我添加了另一个实现,但我仍然坚持。
    • 您是否有理由不能使用库中已包含的 create_user 管道步骤?
    猜你喜欢
    • 2013-06-29
    • 2017-09-26
    • 2017-11-02
    • 2021-05-09
    • 2019-03-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多