Repository navigation
Expand file tree
/
Copy pathauth.py
More file actions
46 lines (35 loc) · 1.48 KB
/
Copy pathauth.py
File metadata and controls
46 lines (35 loc) · 1.48 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
from datetime import datetime, timedelta, timezone
from jose import JWTError, jwt
import bcrypt
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from database import get_db
import models
import os
SECRET_KEY = os.getenv("SECRET_KEY", "change-me-to-a-long-random-secret")
ALGORITHM = "HS256"
EXPIRE_DAYS = 7
bearer_scheme = HTTPBearer()
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
def verify_password(plain: str, hashed: str) -> bool:
return bcrypt.checkpw(plain.encode(), hashed.encode())
def create_access_token(user_id: int) -> str:
expire = datetime.now(timezone.utc) + timedelta(days=EXPIRE_DAYS)
payload = {"sub": str(user_id), "exp": expire}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
db: Session = Depends(get_db),
) -> models.User:
token = credentials.credentials
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id = int(payload.get("sub"))
except (JWTError, TypeError, ValueError):
raise HTTPException(status_code=401, detail="Invalid or expired token")
user = db.query(models.User).filter(models.User.id == user_id).first()
if not user:
raise HTTPException(status_code=401, detail="User not found")
return user