From 638676c2499954041331884d992ae680b730d395 Mon Sep 17 00:00:00 2001
From: Tim Neumann <neumantm@fius.informatik.uni-stuttgart.de>
Date: Sun, 6 Aug 2023 17:16:03 +0200
Subject: [PATCH] fix(check_token): Fix timestamp check and add bad signature
 check

---
 backend/main.py | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)

diff --git a/backend/main.py b/backend/main.py
index e659b45..76b6434 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -5,6 +5,7 @@ from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile, status
 from fastapi.middleware.cors import CORSMiddleware
 from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
 from itsdangerous.serializer import Serializer
+from itsdangerous import BadSignature
 from slowapi import Limiter, _rate_limit_exceeded_handler
 from slowapi.errors import RateLimitExceeded
 from slowapi.util import get_remote_address
@@ -48,12 +49,19 @@ def get_db():
 
 
 def check_token(token: str):
-    if datetime.fromtimestamp(oauth2_tokener.loads(token)) < datetime.now():
-        raise HTTPException(
-            status_code=status.HTTP_401_UNAUTHORIZED,
-            detail="Invalid authentication credentials",
-            headers={"WWW-Authenticate": "Bearer"},
-        )
+    try:
+        timestamp = oauth2_tokener.loads(token)
+        if datetime.fromtimestamp(timestamp) > datetime.now():
+            return  # success
+    except BadSignature:
+        pass
+
+    raise HTTPException(
+        status_code=status.HTTP_401_UNAUTHORIZED,
+        detail="Invalid authentication credentials",
+        headers={"WWW-Authenticate": "Bearer"},
+    )
+
 
 
 # Routes
-- 
GitLab