我正在开发一个身份验证应用程序,用户可以通过该应用程序登录
(email or mobile) and (password or otp)
使用的框架/库
Django Rest Framework and djangorestframework-simplejwt
我正在尝试在生成的 jwt 令牌中添加多个声明。
下面是我的 LoginView 和 LoginSerializer。
看法
class Login(TokenObtainPairView):
serializer_class = LoginSerializer
串行器
class LoginSerializer(TokenObtainPairSerializer):
mobile = serializers.CharField(allow_blank=True)
email = serializers.EmailField(allow_blank=True)
password = serializers.CharField(allow_blank=True)
otp = serializers.CharField(allow_blank=True)
@classmethod
def get_token(cls, user):
token = super().get_token(user)
token['name'] = user.first_name
return token
def validate(self, attrs):
mobile = attrs.get("mobile", None)
email = attrs.get("email", None)
password = attrs.get("password", None)
otp = attrs.get("otp", None)
user = authenticate(mobile=mobile, email=email, password=password, otp=otp)
if user is None and self.password:
raise serializers.ValidationError(
detail="Incorrect Username or Password.", code=HTTP_401_UNAUTHORIZED
)
if user.is_active:
refresh = self.get_token(user)
data = dict()
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
return data
if user.is_locked:
raise serializers.ValidationError(
detail="Account Locked. Contact Support.", code=HTTP_423_LOCKED
)
raise serializers.ValidationError(
detail="User Account is Deactivated.",
code=HTTP_401_UNAUTHORIZED
)
但是在请求中发送有效的电话号码和密码时,我收到电子邮件不能为空白错误。这是因为 TokenObtainPairSerializer 会检查 User.USERNAME_FIELD (在我的情况下是电子邮件。)
我该如何处理这种情况或让它发挥作用?