gpt4 book ai didi

python - 获取用户角色并将其添加到 jwt 负载中

转载 作者:行者123 更新时间:2023-11-28 17:09:18 35 4
gpt4 key购买 nike

我有如下所示的用户登录序列化程序 我想在用户通过身份验证时将用户角色添加到我的 JWT 负载中 如何访问用户信息,例如我的验证函数中的“is_stuff”字段?用户对象包含 <QuerySet [<User: admin>]>

class UserLoginSerializer(ModelSerializer):
token = CharField(allow_blank=True, read_only=True)
username = CharField(required=False, allow_blank=True)
email = EmailField(label='email address', required=False, allow_blank=True)

class Meta:
model = User
fields = [
'username',
'email',
'password',
'token',
'is_staff',
]
extra_kwargs = {
"password": {
"write_only": True
}
}

def validate(self, data):
user_obj = None
email = data.get('email', None)
username = data.get('username', None)
password = data.get('password')
if not email and not username:
raise ValidationError("email or username is required!")
if '@' in username:
email = username
user = User.objects.filter(
Q(email=email) |
Q(username=username)
).distinct()


# user = user.exclude(email__isnull=True).exclude(email__iexact='')
if user.exists() and user.count() == 1:
user_obj = user.first()
else:
raise ValidationError("this username/email is not valid")
if user_obj:
if not user_obj.check_password(password):
raise ValidationError("password is incorrect")


payload = jwt_payload_handler(user_obj)
payload["role"] = ???
data['token'] = jwt_encode_handler(payload)
return data

View :

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

def post(self, request, *args, **kwargs):
data = request.data
serializer = UserLoginSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)

return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

最佳答案

如果您正在使用 rest_framework_jwt 只需定义:

JWT_AUTH = {
...
'JWT_PAYLOAD_HANDLER': 'project.jwt.jwt_payload_handler',
...
}

而且你可以在这个文件中定义你自己的函数(或者你怎么调用它)project.jwt

from django.conf import settings
from rest_framework_jwt import utils

def jwt_payload_handler(user):
payload = utils.jwt_payload_handler(user)
payload['is_staff'] = user.is_staff
payload['is_superuser'] = user.is_superuser
....
return payload

关于python - 获取用户角色并将其添加到 jwt 负载中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48803029/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com