|
| 1 | +from datetime import datetime, timedelta, timezone |
| 2 | +from typing import Annotated, Union |
| 3 | + |
| 4 | +import jwt |
| 5 | +from api.database.models.users import User |
| 6 | +from api.exceptions.http_exceptions import CredentialsException |
| 7 | +from api.schemas.auth import TokenData |
| 8 | +from fastapi import Depends |
| 9 | +from fastapi.security import OAuth2PasswordBearer |
| 10 | +from passlib.context import CryptContext |
| 11 | + |
| 12 | +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") |
| 13 | +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token") |
| 14 | + |
| 15 | + |
| 16 | +SECRET_KEY = "ef555b4c8637c33623fe8e91ba7256725e7e2a1bcc75fe84acb189bcaa6c8693" |
| 17 | +ALGORITHM = "HS256" |
| 18 | +ACCESS_TOKEN_EXPIRE_MINUTES = 30 |
| 19 | + |
| 20 | + |
| 21 | +class AuthService: |
| 22 | + @staticmethod |
| 23 | + def verify_password(plain_password, hashed_password): |
| 24 | + return pwd_context.verify(plain_password, hashed_password) |
| 25 | + |
| 26 | + @staticmethod |
| 27 | + def get_password_hash(password): |
| 28 | + return pwd_context.hash(password) |
| 29 | + |
| 30 | + @staticmethod |
| 31 | + async def authenticate_user(username: str, password: str): |
| 32 | + user: Union[User, None] = await User.get_by_email(username) |
| 33 | + if not user: |
| 34 | + return False |
| 35 | + if not AuthService.verify_password(password, user.password): |
| 36 | + return False |
| 37 | + return user |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def create_access_token( |
| 41 | + data: dict, expires_delta_in_minutes: Union[int, None] = None |
| 42 | + ): |
| 43 | + to_encode = data.copy() |
| 44 | + expires_at = datetime.now(timezone.utc) + timedelta( |
| 45 | + minutes=expires_delta_in_minutes or ACCESS_TOKEN_EXPIRE_MINUTES |
| 46 | + ) |
| 47 | + to_encode.update({"exp": expires_at}) |
| 48 | + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) |
| 49 | + return encoded_jwt, expires_at |
| 50 | + |
| 51 | + # @staticmethod |
| 52 | + async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): |
| 53 | + try: |
| 54 | + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) |
| 55 | + username: Union[str, None] = payload.get("sub") |
| 56 | + if username is None: |
| 57 | + raise CredentialsException() |
| 58 | + token_data = TokenData(email=username) |
| 59 | + except jwt.InvalidTokenError: |
| 60 | + raise CredentialsException() |
| 61 | + user: Union[User, None] = await User.get_by_email(token_data.email) |
| 62 | + if user is None: |
| 63 | + raise CredentialsException() |
| 64 | + return user |
| 65 | + |
| 66 | + @staticmethod |
| 67 | + async def get_current_active_user( |
| 68 | + current_user: Annotated[User, Depends(get_current_user)], |
| 69 | + ): |
| 70 | + if current_user.deleted_at: |
| 71 | + raise CredentialsException() |
| 72 | + return current_user |
0 commit comments