Skip to content

Commit

Permalink
chore(api): move login token creation to model
Browse files Browse the repository at this point in the history
  • Loading branch information
nils-wisiol committed Nov 27, 2022
1 parent b7a0845 commit aa3aa0f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
13 changes: 13 additions & 0 deletions api/desecapi/models/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
16 changes: 4 additions & 12 deletions api/desecapi/views/users.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)


Expand Down

0 comments on commit aa3aa0f

Please sign in to comment.