即使在 Django rest 框架身份验证中登录后也会出现身份验证错误?

时间:2021-06-28 07:31:24

标签: python django django-rest-framework

我的models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class User_model(AbstractUser):
    user_type = models.CharField(max_length=2, choices=(("MN", "Mentor"), ("NM", "NormalUser")))

我的serializers.py

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.models import User
from .models import User_model


class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User_model
    fields = ('username',)


class UserSerializerWithToken(serializers.ModelSerializer):

    token = serializers.SerializerMethodField()
    password = serializers.CharField(write_only=True)

    def get_token(self, obj):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(obj)
        token = jwt_encode_handler(payload)
        return token

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    class Meta:
        model = User_model
        fields = ('token', 'username', 'password')

views.py

from django.shortcuts import render
# Create your views here.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from rest_framework import permissions, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserSerializer, UserSerializerWithToken
from rest_framework import mixins
from rest_framework.generics import GenericAPIView

@api_view(['GET'])
def current_user(request):
    """
    Determine the current user by their token, and return their data
    """
    
    serializer = UserSerializer(request.user)
    return Response(serializer.data)

class UserList(mixins.CreateModelMixin, GenericAPIView):
    """
    Create a new user. It's called 'UserList' because normally we'd have a get
    method here too, for retrieving a list of all User objects.
    """

    permission_classes = (permissions.AllowAny,)
    serializer_class = UserSerializerWithToken

    def post(self, request, format=None):
        serializer = UserSerializerWithToken(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


'''To be constructed'''

class Logout(APIView):
    def get(self, request, format=None):
        # simply delete the token to force a login
        print(request.user)
        # request.user.auth_token.delete()
        return Response(status=status.HTTP_200_OK)

我的 urls.py

"""liveClass URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework_jwt.views import obtain_jwt_token
from . import views

urlpatterns = [
   
   path('login/', obtain_jwt_token),
   path('current_user/', views.current_user),
   path('register/', views.UserList.as_view()),
   path('logout/', views.Logout.as_view())
]

我尝试通过自定义 User_model 在我的应用程序中更改用于身份验证的默认用户模型,因为我想在登录时将用户分为两种类型的用户,但是当我更改它时,我可以将用户注册和登录为它能够生成令牌,但是当我尝试访问其他应用程序的任何受保护端点时,它给了我“未提供身份验证详细信息”,以前当我使用默认用户模型进行身份验证时它工作正常,因此请帮助解决这个问题以及我如何对这种类型的用户进行身份验证

0 个答案:

没有答案