diff --git a/backend/auth.py b/backend/auth.py index e5f209c..e4f9c82 100644 --- a/backend/auth.py +++ b/backend/auth.py @@ -2,6 +2,7 @@ from database import execute, fetch_one import bcrypt from jose import jwt, JWTError from datetime import datetime, timedelta +from fastapi import Header, HTTPException SECRET_KEY = "" ALGORITHM = "HS256" @@ -56,4 +57,35 @@ def verify_user(username, password): ): return user["id"] - return None \ No newline at end of file + return None + + +def get_current_user(authorization: str = Header(None)): + + if authorization is None: + raise HTTPException( + status_code=401, + detail="Missing token" + ) + + try: + scheme, token = authorization.split(" ") + + if scheme.lower() != "bearer": + raise Exception() + + payload = jwt.decode( + token, + SECRET_KEY, + algorithms=[ALGORITHM] + ) + + user_id = payload["user_id"] + + return user_id + + except JWTError: + raise HTTPException( + status_code=401, + detail="Invalid token" + ) \ No newline at end of file