-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
executable file
·70 lines (53 loc) · 2.02 KB
/
auth.py
File metadata and controls
executable file
·70 lines (53 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
from datetime import datetime
from typing import Optional
from zoneinfo import ZoneInfo
from dotenv import find_dotenv, load_dotenv
from fastapi import HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from pydantic import BaseModel
from logging_config import setup_logging
logger = setup_logging()
load_dotenv(find_dotenv('cfg/.env', raise_error_if_not_found=True))
# These should be kept secret and stored securely (e.g., in environment variables)
JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
JWT_ALGORITHM = os.getenv('JWT_ALGORITHM')
tz_info = ZoneInfo(os.getenv('TIMEZONE'))
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class TokenData(BaseModel):
email: Optional[str] = None
role: Optional[str] = None
exp: Optional[float] = None
def verify_token(token: str):
credentials_exception = HTTPException(
status_code=401,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
email: str = payload.get("sub")
role: str = payload.get("role")
exp: int = payload.get("exp")
logger.debug(f"{email}, {role}, {exp}")
if email is None:
raise credentials_exception
token_data = TokenData(email=email, role=role, exp=exp)
return token_data
except JWTError as e:
logger.error(e)
raise credentials_exception
def authenticate(token: str):
if token.startswith("Bearer "):
token = token.split(" ")[1]
token_data = verify_token(token)
if not token_data:
logger.error("No token data")
raise HTTPException(status_code=401, detail="Not authenticated")
# Check if the token has expired
if datetime.now(tz_info).timestamp() > token_data.exp:
logger.error("Token has expired")
raise HTTPException(status_code=401, detail="Token has expired")
logger.info("Login successful")
return token_data