from datetime import datetime, timedelta from typing import Annotated, Union 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 .db import database from . import orm_models, pydantic_schemas SECRET_KEY = "651a52941cf5de14d48ef5d7af115709" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 1440 pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token") def get_db(): db = database try: yield db finally: db.close() def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password): return pwd_context.hash(password) def get_user_by_nickname(db: Annotated[Session, Depends(get_db)], nickname: str): user_with_required_id = db.query(orm_models.User).filter(orm_models.User.nickname == nickname).first() if user_with_required_id: return user_with_required_id return None def get_user_by_id(db: Annotated[Session, Depends(get_db)], user_id: int): user_with_required_id = db.query(orm_models.User).filter(orm_models.User.id == user_id).first() if user_with_required_id: return user_with_required_id return None def authenticate_user(db: Annotated[Session, Depends(get_db)], nickname: str, password: str): user = get_user_by_nickname(db=db, nickname=nickname) if not user: return False if not verify_password(password, user.hashed_password): return False return user def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt async def get_current_user(db: Annotated[Session, Depends(get_db)], token: Annotated[str, Depends(oauth2_scheme)]): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id: int = payload.get("user_id") if user_id is None: raise credentials_exception token_data = pydantic_schemas.TokenData(user_id=user_id) except JWTError: raise credentials_exception user = get_user_by_id(db, user_id=token_data.user_id) if user is None: raise credentials_exception return pydantic_schemas.User(id=user.id, nickname=user.nickname, name=user.name, surname=user.surname, disabled=user.disabled, items=user.announcements, reg_date=user.reg_date, points=user.points) async def get_current_active_user( current_user: Annotated[pydantic_schemas.User, Depends(get_current_user)] ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user