|
| 1 | +from datetime import datetime, timedelta |
| 2 | +from typing import Annotated |
| 3 | +from database import query_get |
| 4 | +from fastapi import Depends, HTTPException, status |
| 5 | +from fastapi.security import OAuth2PasswordBearer |
| 6 | +from jose import JWTError, jwt |
| 7 | +from passlib.context import CryptContext |
| 8 | +from pydantic import BaseModel |
| 9 | +import os |
| 10 | + |
| 11 | +OAUTH2_SCHEME = OAuth2PasswordBearer(tokenUrl="token") |
| 12 | + |
| 13 | +CREDENTIALS_EXCEPTION = HTTPException( |
| 14 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 15 | + detail="Could not validate credentials", |
| 16 | + headers={"WWW-Authenticate": "Bearer"}, |
| 17 | +) |
| 18 | +USER_NOT_FOUND_EXCEPTION = HTTPException( |
| 19 | + status_code=status.HTTP_404_NOT_FOUND, |
| 20 | + detail="User not found", |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +class TokenData(BaseModel): |
| 25 | + user_email: str | None = None |
| 26 | + |
| 27 | + |
| 28 | +class AuthUser(BaseModel): |
| 29 | + id: int |
| 30 | + first_name: str |
| 31 | + last_name: str |
| 32 | + user_email: str |
| 33 | + |
| 34 | + |
| 35 | +class AuthProvider: |
| 36 | + ALGORITHM = "HS256" |
| 37 | + TOKEN_EXPIRE_MINS = 30 |
| 38 | + REFRESH_TOKEN_EXPIRE_HOURS = 10 |
| 39 | + PWD_CONTEXT = CryptContext(schemes=["bcrypt"], deprecated="auto") |
| 40 | + |
| 41 | + def __init__(self) -> None: |
| 42 | + self.SECRET_KEY = os.getenv("APP_SECRET_STRING") |
| 43 | + if not self.SECRET_KEY: |
| 44 | + raise EnvironmentError("APP_SECRET_STRING environment variable not found") |
| 45 | + |
| 46 | + def verify_password(self, plain_password, hashed_password) -> bool: |
| 47 | + return self.PWD_CONTEXT.verify(plain_password, hashed_password) |
| 48 | + |
| 49 | + def get_password_hash(self, password) -> str: |
| 50 | + return self.PWD_CONTEXT.hash(password) |
| 51 | + |
| 52 | + def authenticate_user(self, user_email: str, password: str) -> AuthUser: |
| 53 | + user = self.get_user_by_email(user_email) |
| 54 | + if not user: |
| 55 | + raise USER_NOT_FOUND_EXCEPTION |
| 56 | + if not self.verify_password(password, user["password_hash"]): |
| 57 | + raise CREDENTIALS_EXCEPTION |
| 58 | + return user |
| 59 | + |
| 60 | + def create_access_token( |
| 61 | + self, data: dict, expires_delta: timedelta | None = None |
| 62 | + ) -> str: |
| 63 | + to_encode = data.copy() |
| 64 | + if expires_delta: |
| 65 | + expire = datetime.utcnow() + expires_delta |
| 66 | + else: |
| 67 | + expire = datetime.utcnow() + timedelta(minutes=self.TOKEN_EXPIRE_MINS) |
| 68 | + to_encode.update({"exp": expire}) |
| 69 | + encoded_jwt = jwt.encode(to_encode, self.SECRET_KEY, algorithm=self.ALGORITHM) |
| 70 | + return encoded_jwt |
| 71 | + |
| 72 | + def encode_token(self, user_email) -> str: |
| 73 | + payload = { |
| 74 | + "exp": datetime.utcnow() |
| 75 | + + timedelta(days=0, minutes=self.TOKEN_EXPIRE_MINS), |
| 76 | + "iat": datetime.utcnow(), |
| 77 | + "scope": "access_token", |
| 78 | + "sub": user_email, |
| 79 | + } |
| 80 | + return jwt.encode(payload, self.SECRET_KEY, algorithm=self.ALGORITHM) |
| 81 | + |
| 82 | + def refresh_token(self, refresh_token) -> str: |
| 83 | + try: |
| 84 | + payload = jwt.decode( |
| 85 | + refresh_token, self.SECRET_KEY, algorithms=self.ALGORITHM |
| 86 | + ) |
| 87 | + if payload["scope"] == "refresh_token": |
| 88 | + user_email = payload["sub"] |
| 89 | + new_token = self.encode_token(user_email) |
| 90 | + return new_token |
| 91 | + raise CREDENTIALS_EXCEPTION |
| 92 | + except jwt.ExpiredSignatureError: |
| 93 | + raise CREDENTIALS_EXCEPTION |
| 94 | + except jwt.InvalidTokenError: |
| 95 | + raise CREDENTIALS_EXCEPTION |
| 96 | + |
| 97 | + def encode_refresh_token(self, user_email) -> str: |
| 98 | + payload = { |
| 99 | + "exp": datetime.utcnow() |
| 100 | + + timedelta(days=0, hours=self.REFRESH_TOKEN_EXPIRE_HOURS), |
| 101 | + "iat": datetime.utcnow(), |
| 102 | + "scope": "refresh_token", |
| 103 | + "sub": user_email, |
| 104 | + } |
| 105 | + return jwt.encode(payload, self.SECRET_KEY, algorithm=self.ALGORITHM) |
| 106 | + |
| 107 | + async def get_current_user( |
| 108 | + self, token: Annotated[str, Depends(OAUTH2_SCHEME)] |
| 109 | + ) -> AuthUser: |
| 110 | + user = None |
| 111 | + try: |
| 112 | + payload = jwt.decode(token, self.SECRET_KEY, algorithms=[self.ALGORITHM]) |
| 113 | + user_email: str = payload.get("sub") |
| 114 | + if user_email is None: |
| 115 | + raise CREDENTIALS_EXCEPTION |
| 116 | + token_data = TokenData(user_email=user_email) |
| 117 | + except JWTError: |
| 118 | + raise CREDENTIALS_EXCEPTION |
| 119 | + user = self.get_user_by_email(token_data.user_email) |
| 120 | + if user is None: |
| 121 | + raise CREDENTIALS_EXCEPTION |
| 122 | + return user |
| 123 | + |
| 124 | + def get_user_by_email(self, user_email: str) -> AuthUser: |
| 125 | + user = query_get( |
| 126 | + """ |
| 127 | + SELECT |
| 128 | + user.id, |
| 129 | + user.first_name, |
| 130 | + user.last_name, |
| 131 | + user.email, |
| 132 | + user.password_hash |
| 133 | + FROM user |
| 134 | + WHERE email = %s |
| 135 | + """, |
| 136 | + [user_email], |
| 137 | + ) |
| 138 | + if len(user) == 0: |
| 139 | + raise USER_NOT_FOUND_EXCEPTION |
| 140 | + return user[0] |
0 commit comments