65 lines
2.8 KiB
Python
65 lines
2.8 KiB
Python
import hmac
|
|
import json
|
|
import os
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.http import JsonResponse
|
|
from django.urls import path
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
from django.views.decorators.debug import sensitive_variables
|
|
|
|
from config import urls as original_urls
|
|
from sarex.core.serializers.token import CustomTokenSerializer
|
|
|
|
|
|
@csrf_exempt
|
|
@sensitive_variables("credential", "supplied", "token")
|
|
def issue_access_token(request):
|
|
if request.method != "POST":
|
|
return JsonResponse({"detail": "Method not allowed"}, status=405)
|
|
credential = os.environ.get("JWT_SIGNER_CLIENT_TOKEN", "")
|
|
supplied = request.headers.get("Authorization", "")
|
|
if not credential or not hmac.compare_digest(supplied.encode(), ("Bearer " + credential).encode()):
|
|
return JsonResponse({"detail": "Unauthorized"}, status=401)
|
|
if len(request.body) > 1024:
|
|
return JsonResponse({"detail": "Invalid request"}, status=400)
|
|
try:
|
|
value = json.loads(request.body)
|
|
user_id = value["user_id"]
|
|
if isinstance(user_id, bool) or not isinstance(user_id, int) or not 0 < user_id <= 9223372036854775807:
|
|
raise ValueError()
|
|
except (ValueError, TypeError, KeyError):
|
|
return JsonResponse({"detail": "Invalid request"}, status=400)
|
|
user = get_user_model().objects.filter(pk=user_id, is_active=True).first()
|
|
if user is None:
|
|
return JsonResponse({"detail": "User not found"}, status=404)
|
|
token = str(CustomTokenSerializer.get_token(user).access_token)
|
|
return JsonResponse({"access": token}, headers={"Cache-Control": "no-store"})
|
|
|
|
|
|
@sensitive_variables("credential", "token")
|
|
def issue_legacy_access_token(request, pk):
|
|
credential = os.environ.get("JWT_SIGNER_CLIENT_TOKEN", "")
|
|
if not credential or not hmac.compare_digest(
|
|
request.headers.get("Authorization", "").encode(), ("Bearer " + credential).encode()
|
|
):
|
|
return JsonResponse({"detail": "Unauthorized"}, status=401)
|
|
if request.method != "GET":
|
|
return JsonResponse({"detail": "Method not allowed"}, status=405)
|
|
if not 0 < pk <= 9223372036854775807:
|
|
return JsonResponse({"detail": "Invalid request"}, status=400)
|
|
user = get_user_model().objects.filter(pk=pk, is_active=True).first()
|
|
if user is None:
|
|
return JsonResponse({"detail": "User not found"}, status=404)
|
|
token = str(CustomTokenSerializer.get_token(user).access_token)
|
|
return JsonResponse(token, safe=False, headers={"Cache-Control": "no-store"})
|
|
|
|
|
|
urlpatterns = [
|
|
path("internal/jwt/access-token/", issue_access_token),
|
|
path("internal/client/token/<int:pk>/", issue_legacy_access_token),
|
|
] + original_urls.urlpatterns
|
|
for name in ("handler400", "handler403", "handler404", "handler500"):
|
|
if hasattr(original_urls, name):
|
|
globals()[name] = getattr(original_urls, name)
|