django 使用rest_framework_simplejwt沿着标记返回用户对象

uelo1irk  于 2023-01-14  发布在  Go
关注(0)|答案(3)|浏览(128)

我使用django_rest_passwordreset在Django rest框架上进行身份验证。
我按照他们的官方文档和登录教程,注册工作很好.
Login返回访问和刷新令牌,我想做的是在访问和刷新令牌的旁边返回用户对象。
我有一个定制的模型

# auth/models.py
# Inherited from user
class MUser(AbstractUser, models.Model):
    email = models.EmailField(unique=True)
    role = models.CharField(max_length=40, default="student")

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'role']

串行器

# auth/serializers.py
class TokenObtainPairSerializer(TokenObtainSerializer):
    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)

        if api_settings.UPDATE_LAST_LOGIN:
            update_last_login(None, self.user)

        return data

我的看法

# auth/views.py
class TokenObtainPairView(TokenViewBase):
    """
    Takes a set of user credentials and returns access and refresh JSON web
    token pair to prove the authentication of those credentials.
    """
    serializer_class = serializers.TokenObtainPairSerializer

总之,成功登录后,我将收到

{
   access: xxx,
   refresh: xxx,
   
   # I want to add this 
   user: {username, first_name, last_name, email, ...}
}
06odsfpq

06odsfpq1#

我想这可能会帮到你:

def validate(self, attrs):
    data = super().validate(attrs)

    refresh = self.get_token(self.user)

    data['refresh'] = str(refresh)
    data['access'] = str(refresh.access_token)

    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    my_user = User.objects.filter(pk=self.user.id).first()
    if my_user:
        # use user serelizor or parse required fields
        data['user'] = my_user
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

    if api_settings.UPDATE_LAST_LOGIN:
        update_last_login(None, self.user)

    return data
guicsvcw

guicsvcw2#

经过尝试和错误,这就是对我起作用的

def validate(self, attrs):
        data = super(CustomTokenObtainPairSerializer, self).validate(attrs)
        data['user'] = {
            'id': self.user.id,
            "first_name": self.user.first_name,
            "last_name": self.user.last_name,
            "email": self.user.email,
            "role": self.user.role,
            "telephone": str(self.user.telephone)
        }

        return data
ou6hu8tu

ou6hu8tu3#

这可能会有帮助。
serializers.py

from rest_framework import serializers
from .models import MUser

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class UserTokenSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserBase
        fields = [ "email", "role" ]

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)
        data["user"] =  UserTokenSerializer(self.user).data
    
        return data

views.py

from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import MyTokenObtainPairSerializer

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

相关问题