61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
import secrets
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from motor.motor_asyncio import AsyncIOMotorDatabase
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import get_db
|
|
from app.mongo import get_mongo_db
|
|
from app.models.user import User
|
|
from app.utils.security import verify_token
|
|
|
|
security_scheme = HTTPBearer(auto_error=False)
|
|
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials | None = Depends(security_scheme),
|
|
db: Session = Depends(get_db),
|
|
) -> User:
|
|
if credentials is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Not authenticated",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
subject = verify_token(credentials.credentials, expected_type="access")
|
|
if subject is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or expired token",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
user = db.query(User).filter(User.email == subject).first()
|
|
if user is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account is inactive")
|
|
|
|
return user
|
|
|
|
|
|
def get_mongo_db_dep() -> AsyncIOMotorDatabase:
|
|
try:
|
|
return get_mongo_db()
|
|
except RuntimeError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="MongoDB is not available. Start it with: docker compose up mongo -d",
|
|
)
|
|
|
|
|
|
def generate_reset_token() -> str:
|
|
return secrets.token_urlsafe(32)
|
|
|
|
|
|
def reset_token_expiry(hours: int = 1) -> datetime:
|
|
return datetime.now(UTC) + timedelta(hours=hours)
|