5

I created a Django app in which I want to be able to authenticate users by checking not only the username and password, but also a specific field in a related model. The custom request body I want to POST to the endpoint is:

payload = { 'username': user, 'password': password, 'app_id': uuid4}

I am using djangorestframework-simplejwt module to get the access token.

models.py

class Application(models.Model):

    app_name  = models.CharField(max_length=300)
    app_id    = models.UUIDField(default=uuid.uuid4, editable=False)

    def __str__(self):
        return self.app_name

class ProfileApp(models.Model):

    user       = models.OneToOneField(User, on_delete=models.CASCADE)
    app        = models.ForeignKey(Application, on_delete=models.CASCADE)
    expires_on = models.DateTimeField(default=datetime.now() + timedelta(days=15))

    def __str__(self):
        return self.app.app_name + " | "  + self.user.username

Is it possible to override the TokenObtainPairView from rest_framework_simplejwt to only authenticate an user if the expires_on date is still not expired? Or is there an architecture problem by doing it like this?

4

1 回答 1

9

您可以通过创建一个继承自 的自定义序列化程序TokenObtainPairSerializer并扩展该validate方法以检查自定义字段值来做到这一点。如果您小心不要覆盖父类的必要功能,则不存在体系结构问题。

这是一个例子:

import datetime as dt
import json
from rest_framework import exceptions
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView



class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        try:
            request = self.context["request"]
        except KeyError:
            pass
        else:
            request_data = json.loads(request.body)
            username = request_data.get("username")
            app_id = request_data.get("app_id")

            profile_has_expired = False
            try:
                profile = ProfileApp.objects.get(user__username=username, app__app_id=app_id)
            except ProfileApp.DoesNotExist:
                profile_has_expired = True
            else:
                profile_has_expired = dt.date.today() > profile.expires_on
            finally:
                if profile_has_expired:
                    error_message = "This profile has expired"
                    error_name = "expired_profile"
                    raise exceptions.AuthenticationFailed(error_message, error_name)
        finally:
            return super().validate(attrs)


class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

然后MyTokenObtainPairViewTokenObtainPairView您的 urls 文件中使用。

此外,由于UserProfileApp共享一个一对一的字段,看起来您完全可以不使用"app_id" 键/字段。

原始源文件:https ://github.com/davesque/django-rest-framework-simplejwt/blob/04376b0305e8e2fda257b08e507ccf511359d04a/rest_framework_simplejwt/serializers.py

于 2019-07-10T23:54:31.197 回答