Không cần phải viết một xác thực tùy chỉnh phụ trợ hoặc tùy chỉnh phương pháp đăng nhập.
Trình chỉnh sửa tùy chỉnh kế thừa JSONWebTokenSerializer, đổi tên phương thức 'username_field' và ghi đè xác thực().
Điều này hoạt động hoàn hảo cho trường 'username_or_email' và 'mật khẩu' nơi người dùng có thể nhập tên người dùng hoặc email của mình và nhận JSONWebToken cho thông tin đăng nhập chính xác.
class CustomJWTSerializer(JSONWebTokenSerializer):
username_field = 'username_or_email'
def validate(self, attrs):
password = attrs.get("password")
user_obj = User.objects.filter(email=attrs.get("username_or_email")).first() or User.objects.filter(username=attrs.get("username_or_email")).first()
if user_obj is not None:
credentials = {
'username':user_obj.username,
'password': password
}
if all(credentials.values()):
user = authenticate(**credentials)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
payload = jwt_payload_handler(user)
return {
'token': jwt_encode_handler(payload),
'user': user
}
else:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg)
else:
msg = _('Must include "{username_field}" and "password".')
msg = msg.format(username_field=self.username_field)
raise serializers.ValidationError(msg)
else:
msg = _('Account with this email/username does not exists')
raise serializers.ValidationError(msg)
Trong urls.py:
url(r'{Your url name}$', ObtainJSONWebToken.as_view(serializer_class=CustomJWTSerializer)),
Nguồn
2017-09-13 07:55:21
độc đáo làm @ Shikhar-thapliyal –
@OhadtheLad nhờ :) –