|
| 1 | +from datetime import datetime, timedelta |
| 2 | +from typing import Union |
| 3 | + |
| 4 | +from passlib.context import CryptContext |
| 5 | +from fastapi import Depends, HTTPException |
| 6 | +from fastapi.security import OAuth2PasswordBearer |
| 7 | +import jwt |
| 8 | +from jwt.exceptions import InvalidSignatureError |
| 9 | +from sqlalchemy.orm import Session |
| 10 | +from starlette.requests import Request |
| 11 | +from starlette.responses import RedirectResponse |
| 12 | +from starlette.status import HTTP_401_UNAUTHORIZED |
| 13 | +from . import schema |
| 14 | + |
| 15 | +from app.config import JWT_ALGORITHM, JWT_KEY, JWT_MIN_EXP |
| 16 | +from app.database.models import User |
| 17 | + |
| 18 | + |
| 19 | +pwd_context = CryptContext(schemes=["bcrypt"]) |
| 20 | +oauth_schema = OAuth2PasswordBearer(tokenUrl="/login") |
| 21 | + |
| 22 | + |
| 23 | +def get_hashed_password(password: str) -> str: |
| 24 | + """Hashing user password""" |
| 25 | + return pwd_context.hash(password) |
| 26 | + |
| 27 | + |
| 28 | +def verify_password(plain_password: str, hashed_password: str) -> bool: |
| 29 | + """Verifying password and hashed password are equal""" |
| 30 | + return pwd_context.verify(plain_password, hashed_password) |
| 31 | + |
| 32 | + |
| 33 | +async def authenticate_user( |
| 34 | + db: Session, new_user: schema.LoginUser, |
| 35 | +) -> Union[schema.LoginUser, bool]: |
| 36 | + """Verifying user is in database and password is correct""" |
| 37 | + db_user = await User.get_by_username(db=db, username=new_user.username) |
| 38 | + if db_user and verify_password(new_user.password, db_user.password): |
| 39 | + return schema.LoginUser( |
| 40 | + user_id=db_user.id, is_manager=db_user.is_manager, |
| 41 | + username=new_user.username, password=db_user.password) |
| 42 | + return False |
| 43 | + |
| 44 | + |
| 45 | +def create_jwt_token( |
| 46 | + user: schema.LoginUser, jwt_min_exp: int = JWT_MIN_EXP, |
| 47 | + jwt_key: str = JWT_KEY) -> str: |
| 48 | + """Creating jwt-token out of user unique data""" |
| 49 | + expiration = datetime.utcnow() + timedelta(minutes=jwt_min_exp) |
| 50 | + jwt_payload = { |
| 51 | + "sub": user.username, |
| 52 | + "user_id": user.user_id, |
| 53 | + "is_manager": user.is_manager, |
| 54 | + "exp": expiration} |
| 55 | + jwt_token = jwt.encode( |
| 56 | + jwt_payload, jwt_key, algorithm=JWT_ALGORITHM) |
| 57 | + return jwt_token |
| 58 | + |
| 59 | + |
| 60 | +async def check_jwt_token( |
| 61 | + db: Session, |
| 62 | + token: str = Depends(oauth_schema), path: bool = None, |
| 63 | + manager: bool = False) -> User: |
| 64 | + """ |
| 65 | + Check whether JWT token is correct. |
| 66 | + Returns jwt payloads if correct. |
| 67 | + Raises HTTPException if fails to decode. |
| 68 | + """ |
| 69 | + try: |
| 70 | + jwt_payload = jwt.decode( |
| 71 | + token, JWT_KEY, algorithms=JWT_ALGORITHM) |
| 72 | + if not manager: |
| 73 | + return True |
| 74 | + if jwt_payload.get("is_manager"): |
| 75 | + return True |
| 76 | + raise HTTPException( |
| 77 | + status_code=HTTP_401_UNAUTHORIZED, |
| 78 | + headers=path, |
| 79 | + detail="You don't have a permition to enter this page") |
| 80 | + except InvalidSignatureError: |
| 81 | + raise HTTPException( |
| 82 | + status_code=HTTP_401_UNAUTHORIZED, |
| 83 | + headers=path, |
| 84 | + detail="Your token is incorrect. Please log in again") |
| 85 | + except jwt.ExpiredSignatureError: |
| 86 | + raise HTTPException( |
| 87 | + status_code=HTTP_401_UNAUTHORIZED, |
| 88 | + headers=path, |
| 89 | + detail="Your token has expired. Please log in again") |
| 90 | + except jwt.DecodeError: |
| 91 | + raise HTTPException( |
| 92 | + status_code=HTTP_401_UNAUTHORIZED, |
| 93 | + headers=path, |
| 94 | + detail="Your token is incorrect. Please log in again") |
| 95 | + |
| 96 | + |
| 97 | +async def get_authorization_cookie(request: Request) -> str: |
| 98 | + """ |
| 99 | + Extracts jwt from HTTPONLY cookie, if exists. |
| 100 | + Raises HTTPException if not. |
| 101 | + """ |
| 102 | + if 'Authorization' in request.cookies: |
| 103 | + return request.cookies['Authorization'] |
| 104 | + raise HTTPException( |
| 105 | + status_code=HTTP_401_UNAUTHORIZED, |
| 106 | + headers=request.url.path, |
| 107 | + detail="Please log in to enter this page") |
| 108 | + |
| 109 | + |
| 110 | +async def auth_exception_handler( |
| 111 | + request: Request, |
| 112 | + exc: HTTP_401_UNAUTHORIZED) -> RedirectResponse: |
| 113 | + """ |
| 114 | + Whenever HTTP_401_UNAUTHORIZED is raised, |
| 115 | + redirecting to login route, with original requested url, |
| 116 | + and details for why original request failed. |
| 117 | + """ |
| 118 | + paramas = f"?next={exc.headers}&message={exc.detail}" |
| 119 | + url = f"/login{paramas}" |
| 120 | + response = RedirectResponse(url=url) |
| 121 | + response.delete_cookie('Authorization') |
| 122 | + return response |
0 commit comments