使用DRF挂钩oauth2代码

时间:2016-10-01 07:48:17

标签: python django python-3.x oauth-2.0 django-rest-framework

我正在尝试构建一个具有用户登录和注册功能的应用程序。
我可以从django和DRF创建登录和注册,但无法使用DRF挂钩oAuth2以使其正常运行。
我不知道我应该在哪里使用它。

我应该在注册或登录时生成令牌吗?
如何使其正常运行?

这是我的代码

serializers.py

class UserSerializer(ModelSerializer):
    class Meta:
        model = User


class UserCreateSerializer(ModelSerializer):
    email = EmailField()
    username =  CharField()
    first_name = CharField(required=False)
    last_name = CharField(required=False)
    password = CharField()
    confirm_password = CharField()
    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'first_name',
            'last_name',
            'password',
            'confirm_password'
        ]
        extra_kwargs = {"password": {"write_only": True}}


    def create(self, validated_data):
        username = validated_data['username']
        first_name = validated_data['first_name']
        last_name = validated_data['last_name']
        email = validated_data['email']
        password = validated_data['password']
        confirm_password = validated_data['password']
        user_obj = User(
                username = username,
                first_name = first_name,
                last_name = last_name,
                email = email
            )
        user_obj.set_password(password)
        user_obj.save()
        return validated_data



class UserLoginSerializer(ModelSerializer):
    username = CharField()
    class Meta:
        model = User
        fields = [
            'username',
            # 'email',
            'password',
            # 'token',

        ]
        extra_kwargs = {"password":
                            {"write_only": True}
                            }
    def validate(self, data):
        return data

views.py

class UserCreateAPI(CreateAPIView):
    serializer_class = UserCreateSerializer
    queryset = User.objects.all()
    permission_classes = [AllowAny]

class UserLoginAPI(APIView):
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        print('data',data)
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            if new_data:
                try:
                    user = User.objects.get(username=data['username'])
                    print ('user',user)
                except ObjectDoesNotExist:
                    return HttpResponse("Can't find this user")
                login(request, user)
            return Response(new_data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

tools.py

def get_token_json(access_token):
    return JsonResponse({
        'access_token':access_token.token,
        'expires_in':datetime.now() + timedelta(days=365),
        'token_type':'Bearer',
        'refresh_token':access_token.refresh_token.token,
        'scope':access_token.scope
    })


def get_access_token(user):
    application = Application.objects.get(name="Foodie")
    try:
        old_access_token = AccessToken.objects.get(user=user, application=application)
        old_refresh_token = RefreshToken.objects.get(user=user, access_token=old_access_token)
    except ObjectDoesNotExist:
        return HttpResponse('Have not set any token')
    else:
        old_access_token.delete()
        old_refresh_token.delete()
    new_token = generate_token()
    refresh_token = generate_token()
    access_token=AccessToken.objects.create(user=user, application=app, expires=datetime.now() + timedelta(days=365),token=new_token)
    RefreshToken.objects.create(user=user, application=app, token=refresh_token, access_token=access_token)
    print('aceess',AccessToken)
    return get_token_json(access_token)

如何弥合DRF和oAuth2之间的差距,使登录和用户注册功能正常?

1 个答案:

答案 0 :(得分:0)

尝试使用python social auth。

social.apps.django_app.default添加到INSTALLED_APPS

social.backends.facebook.FacebookOAuth2添加到AUTHENTICATION_BACKENDS

url(r'^auth/', include('social.apps.django_app.urls', namespace='social'))添加到您的urls.py

但是,如果您的应用中有会话身份验证,这将有效。如果您只想使用基于令牌,则添加管道以创建令牌并发送它或查看https://github.com/PhilipGarnero/django-rest-framework-social-oauth2