From 9593b1f885bb0c835f888d1195fc3af9fcabc25c Mon Sep 17 00:00:00 2001 From: Guilherme Kruger Date: Mon, 16 Oct 2023 13:17:00 +0200 Subject: [PATCH] Refresh token is now sent to FE --- backend/api/auth_token.py | 12 +++- backend/api/middleware.py | 106 ---------------------------- backend/shift_3_womenpp/settings.py | 2 - 3 files changed, 9 insertions(+), 111 deletions(-) delete mode 100644 backend/api/middleware.py diff --git a/backend/api/auth_token.py b/backend/api/auth_token.py index 81437a8..a281c77 100644 --- a/backend/api/auth_token.py +++ b/backend/api/auth_token.py @@ -94,9 +94,14 @@ def format_token(token: json) -> json: supabase_user_id = token["user"]["id"] - id = SupabaseIdToUserIds.objects.get( + user = SupabaseIdToUserIds.objects.filter( supabase_authenticaiton_uuid=supabase_user_id - ).user_id + ).first() + + if user: + id = user.user_id + else: + id = "No id found in connection table, this is probably an old user." new_token = { "access_token": token["access_token"], @@ -104,8 +109,9 @@ def format_token(token: json) -> json: "expires_in": token["expires_in"], "expires_at": token["expires_at"], "role": token["user"]["role"], - "last_sign_in_a": token["token_type"], + "last_sign_in_at": token["user"]["last_sign_in_at"], "id": id, + "refresh_token": token["refresh_token"], } return new_token diff --git a/backend/api/middleware.py b/backend/api/middleware.py deleted file mode 100644 index ce8ad44..0000000 --- a/backend/api/middleware.py +++ /dev/null @@ -1,106 +0,0 @@ -import json -import os -import logging - -from dotenv import load_dotenv - -from api.auth_models import RefreshTokens -from api.auth_token import authenticate_access_token -from api.services import gotrue_auth_request -from rest_framework import status - -load_dotenv() - - -JWT_SECRET_KEY = os.environ["JWT_SECRET_KEY"] - -logging.basicConfig( - level=int(os.environ["LOGGING_LEVEL"]), - handlers=[logging.FileHandler("logs/middleware.log"), logging.StreamHandler()], -) - - -class RefreshTokenMiddleware: - def __init__(self, get_response): - self.get_response = get_response - - def __call__(self, request): - if "Authorization" in request.headers: - decoded_token = authenticate_access_token(request.headers["Authorization"]) - logging.debug("Updated request token", decoded_token) - if not "error" in decoded_token.keys(): - request.META["Authorization"] = decoded_token - - response = self.get_response(request) - - return response - - -def authenticate_access_token(token: str) -> json: - """Authenticates the token using the JWT key - - Args: - token (str): the JWT token - - Returns: - json: returns a JSON with the token in case it is valid, otherwise returns a JSON with error - """ - if token[0:6] in ["Bearer", "bearer"]: - token = token[7:] - - try: - jwt.decode( - token, - JWT_SECRET_KEY, - algorithms=["HS256"], - audience=["authenticated", "service_role"], - ) - except jwt.exceptions.ExpiredSignatureError as err: - # If jwt.decode reaches ExpiredSignatureError means the signature is valid but has expired - return refresh_expired_token(token) - except Exception as error: - return error - - return token - - -def refresh_expired_token(token: str) -> json: - """Refreshes the access token if it has expired - - Should only be called if the token signature is already verified. - - Args: - token (str): the expired and but valid JWT token - """ - decoded_jwt = jwt.decode( - token, algorithms=["HS256"], options={"verify_signature": False} - ) - - access_token = decoded_jwt["session_id"] - try: - refresh_token = RefreshTokens.objects.get( - session_id=access_token, revoked=False - ).token - - except RefreshTokens.DoesNotExist: - refresh_token = { - "error": "Not authorized", - "error_description": "Bearer token does not have a valid refresh token.", - "status_code": status.HTTP_401_UNAUTHORIZED, - } - - try: - request_new_token = requests.Request( - "POST", - "https://127.0.0.1/api/login/", - ) - - request_new_token = request_new_token.prepare() - request_new_token.data = {"refresh_token": refresh_token} - request_new_token.path = "https://127.0.0.1/api/login/" - - new_token, _ = gotrue_auth_request(request_new_token) - except Exception as e: - return {"error": "Failed refresh token request", "error_detail": e} - - return new_token diff --git a/backend/shift_3_womenpp/settings.py b/backend/shift_3_womenpp/settings.py index f9d5d0f..4ad45d7 100644 --- a/backend/shift_3_womenpp/settings.py +++ b/backend/shift_3_womenpp/settings.py @@ -65,8 +65,6 @@ "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "corsheaders.middleware.CorsMiddleware", - # Internal middleware - "api.middleware.RefreshTokenMiddleware", ] ROOT_URLCONF = "shift_3_womenpp.urls"