From aa3aa0f1b5a801cfab3318955905bd8c545f5738 Mon Sep 17 00:00:00 2001 From: Nils Wisiol Date: Sun, 27 Nov 2022 16:41:11 +0100 Subject: [PATCH] chore(api): move login token creation to model --- api/desecapi/models/tokens.py | 13 +++++++++++++ api/desecapi/views/users.py | 16 ++++------------ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/api/desecapi/models/tokens.py b/api/desecapi/models/tokens.py index a3b859039..814f13609 100644 --- a/api/desecapi/models/tokens.py +++ b/api/desecapi/models/tokens.py @@ -17,6 +17,8 @@ from django_prometheus.models import ExportModelOperationsMixin from netfields import CidrAddressField, NetManager +from .users import User + class Token(ExportModelOperationsMixin("Token"), rest_framework.authtoken.models.Token): @staticmethod @@ -100,6 +102,17 @@ def delete(self): self.tokendomainpolicy_set.filter(domain__isnull=True).delete() return super().delete() + @classmethod + def create_login_token(cls, user: User): + token = cls.objects.create( + user=user, + perm_manage_tokens=True, + max_age=timedelta(days=7), + max_unused_period=timedelta(hours=1), + mfa=False, + ) + return token + @pgtrigger.register( # Ensure that token_user is consistent with token diff --git a/api/desecapi/views/users.py b/api/desecapi/views/users.py index 8c3e73fa2..4257c4c13 100644 --- a/api/desecapi/views/users.py +++ b/api/desecapi/views/users.py @@ -1,5 +1,3 @@ -from datetime import timedelta - from django.conf import settings from django.contrib.auth import user_logged_in from rest_framework import generics, mixins, status @@ -99,16 +97,10 @@ class AccountLoginView(generics.GenericAPIView): def post(self, request, *args, **kwargs): user = self.request.user - token = Token.objects.create( - user=user, - perm_manage_tokens=True, - max_age=timedelta(days=7), - max_unused_period=timedelta(hours=1), - mfa=False, - ) - user_logged_in.send(sender=user.__class__, request=self.request, user=user) - - data = self.get_serializer(token, include_plain=True).data + data = self.get_serializer( + Token.create_login_token(user), include_plain=True + ).data + user_logged_in.send(sender=user.__class__, request=request, user=user) return Response(data)