feat(frontend/management command): Add a command to craft tokens

This commit is contained in:
sinavir 2024-10-12 17:37:55 +02:00
parent 005dc42433
commit dfbaf2fd65
5 changed files with 47 additions and 26 deletions

View file

View file

@ -0,0 +1,22 @@
import pprint
from django.core.management.base import BaseCommand
from frontend.utils import craft_token
class Command(BaseCommand):
help = "Craft a token for the backend"
def add_arguments(self, parser):
parser.add_argument(
"--is_cof",
action="store_true",
)
parser.add_argument("user", type=str)
parser.add_argument("exp_time", type=int)
def handle(self, *args, **options):
token = craft_token(options["user"], options["is_cof"], options["exp_time"])
self.stdout.write(f"Token:\n{pprint.pformat(token)}")

View file

@ -0,0 +1,21 @@
from datetime import datetime, timedelta, timezone
import jwt
from django.conf import settings
def craft_token(username, is_cof, hours=9):
claims = {
"exp": datetime.now(tz=timezone.utc) + timedelta(hours=hours),
"sub": "ragb",
"user": username,
"is_cof": is_cof,
"scope": "modify",
}
return {
"token": jwt.encode(
claims,
settings.JWT_SECRET,
),
"claims": claims,
}

View file

@ -1,6 +1,3 @@
from datetime import datetime, timedelta, timezone
import jwt
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ViewDoesNotExist
@ -8,6 +5,8 @@ from django.http import Http404, JsonResponse
from django.views import View
from django.views.generic.base import TemplateView
from .utils import craft_token
def get_context_from_proj(kind, chans):
print(kind, chans)
@ -40,20 +39,7 @@ def get_context_from_proj(kind, chans):
class TokenView(LoginRequiredMixin, View):
def get(self, request, *arg, **kwargs):
return JsonResponse(
{
"token": jwt.encode(
{
"exp": datetime.now(tz=timezone.utc) + timedelta(hours=9),
"sub": "ragb",
"user": self.request.user.username,
"is_cof": self.requests.user.groups.filter(name="cof").exists(),
"scope": "modify",
},
settings.JWT_SECRET,
)
}
)
return JsonResponse(craft_token(self.request.user.username, self.request.user.groups.filter(name="cof").exists()))
class LightView(TemplateView):
@ -64,15 +50,7 @@ class LightView(TemplateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
context["jwt"] = jwt.encode(
{
"exp": datetime.now(tz=timezone.utc) + timedelta(hours=9),
"sub": "ragb",
"user": self.request.user.username,
"scope": "modify",
},
settings.JWT_SECRET,
)
context["jwt"] = craft_token(self.request.user.username, self.request.user.groups.filter(name="cof").exists())["token"]
context["websocket_endpoint"] = settings.WEBSOCKET_ENDPOINT
light = self.kwargs["light"]
if light not in settings.LIGHTS["lights"]: