64 lines
2.0 KiB
Python
64 lines
2.0 KiB
Python
import uuid
|
|||
|
|
from datetime import datetime, timedelta, timezone
|
||
|
|
|
||
|
|
from fastapi import Depends, HTTPException, status
|
||
|
|
from fastapi.security import OAuth2PasswordBearer
|
||
|
|
from jose import JWTError, jwt
|
||
|
|
from passlib.context import CryptContext
|
||
|
|
from sqlalchemy.orm import Session
|
||
|
|
|
||
|
|
from .config import settings
|
||
|
|
from .database import get_db
|
||
|
|
from .models import User
|
||
|
|
|
||
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login", auto_error=False)
|
||
|
|
|
||
|
|
|
||
|
|
def hash_password(password: str) -> str:
|
||
|
|
return pwd_context.hash(password)
|
||
|
|
|
||
|
|
|
||
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
||
|
|
return pwd_context.verify(plain, hashed)
|
||
|
|
|
||
|
|
|
||
|
|
def create_access_token(user_id: uuid.UUID) -> str:
|
||
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.jwt_expire_minutes)
|
||
|
|
payload = {"sub": str(user_id), "exp": expire}
|
||
|
|
return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
|
||
|
|
|
||
|
|
|
||
|
|
def _decode_user_id(token: str) -> uuid.UUID:
|
||
|
|
try:
|
||
|
|
payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
|
||
|
|
return uuid.UUID(payload["sub"])
|
||
|
|
except (JWTError, KeyError, ValueError):
|
||
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired token")
|
||
|
|
|
||
|
|
|
||
|
|
def get_current_user(
|
||
|
|
token: str | None = Depends(oauth2_scheme),
|
||
|
|
db: Session = Depends(get_db),
|
||
|
|
) -> User:
|
||
|
|
if not token:
|
||
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
||
|
|
user_id = _decode_user_id(token)
|
||
|
|
user = db.get(User, user_id)
|
||
|
|
if not user:
|
||
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
||
|
|
return user
|
||
|
|
|
||
|
|
|
||
|
|
def get_current_user_optional(
|
||
|
|
token: str | None = Depends(oauth2_scheme),
|
||
|
|
db: Session = Depends(get_db),
|
||
|
|
) -> User | None:
|
||
|
|
if not token:
|
||
|
|
return None
|
||
|
|
try:
|
||
|
|
user_id = _decode_user_id(token)
|
||
|
|
except HTTPException:
|
||
|
|
return None
|
||
|
|
return db.get(User, user_id)
|