|
| 1 | +from datetime import datetime, timedelta |
| 2 | +from typing import Annotated |
| 3 | +from jose import JWTError, jwt |
| 4 | +from fastapi import APIRouter, Depends, HTTPException, status |
| 5 | +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm |
| 6 | + |
| 7 | +from . import crud, schemas |
| 8 | +from . import models |
| 9 | +from .database import SessionLocal, engine |
| 10 | +from passlib.context import CryptContext |
| 11 | + |
| 12 | +# to get a string like this run: |
| 13 | +# openssl rand -hex 32 |
| 14 | +SECRET_KEY = "89afa0ea05e272f5a746f466be7c256d982d307903e8201ad8f6c11450e71d7f" |
| 15 | +ALGORITHM = "HS256" |
| 16 | +ACCESS_TOKEN_EXPIRE_MINUTES = 24 * 60 |
| 17 | +access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) |
| 18 | + |
| 19 | + |
| 20 | +models.Base.metadata.create_all(bind=engine) |
| 21 | + |
| 22 | +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") |
| 23 | + |
| 24 | +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") |
| 25 | + |
| 26 | + |
| 27 | +router = APIRouter() |
| 28 | + |
| 29 | + |
| 30 | +# Dependency |
| 31 | +""" |
| 32 | +def get_db(): |
| 33 | + db = SessionLocal() |
| 34 | + try: |
| 35 | + yield db |
| 36 | + finally: |
| 37 | + db.close() |
| 38 | +""" |
| 39 | + |
| 40 | +db = SessionLocal() |
| 41 | + |
| 42 | + |
| 43 | +def verify_password(plain_password, hashed_password): |
| 44 | + return pwd_context.verify(plain_password, hashed_password) |
| 45 | + |
| 46 | + |
| 47 | +def get_password_hash(password): |
| 48 | + return pwd_context.hash(password) |
| 49 | + |
| 50 | + |
| 51 | +def create_access_token(data: dict, expires_delta: timedelta | None = None): |
| 52 | + to_encode = data.copy() |
| 53 | + if expires_delta: |
| 54 | + expire = datetime.utcnow() + expires_delta |
| 55 | + else: |
| 56 | + expire = datetime.utcnow() + timedelta(minutes=15) |
| 57 | + to_encode.update({"exp": expire}) |
| 58 | + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) |
| 59 | + return encoded_jwt |
| 60 | + |
| 61 | + |
| 62 | +def authenticate_user(username: str, password: str): |
| 63 | + user = crud.get_user(db, username) |
| 64 | + if not user: |
| 65 | + return False |
| 66 | + if not verify_password(password, user.password): |
| 67 | + return False |
| 68 | + return user |
| 69 | + |
| 70 | + |
| 71 | +async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): |
| 72 | + credentials_exception = HTTPException( |
| 73 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 74 | + detail="Could not validate credentials", |
| 75 | + headers={"WWW-Authenticate": "Bearer"}, |
| 76 | + ) |
| 77 | + try: |
| 78 | + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) |
| 79 | + username = payload.get("sub") |
| 80 | + if username is None: |
| 81 | + raise credentials_exception |
| 82 | + token_data = schemas.TokenData(username=username) |
| 83 | + except JWTError: |
| 84 | + raise credentials_exception |
| 85 | + user = crud.get_user(db, token_data.username) |
| 86 | + if user is None: |
| 87 | + raise credentials_exception |
| 88 | + return user |
| 89 | + |
| 90 | + |
| 91 | +@router.post("/token") |
| 92 | +async def login_for_access_token( |
| 93 | + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], |
| 94 | +): |
| 95 | + user = authenticate_user(form_data.username, form_data.password) |
| 96 | + if not user: |
| 97 | + raise HTTPException( |
| 98 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 99 | + detail="Incorrect username or password", |
| 100 | + headers={"WWW-Authenticate": "Bearer"}, |
| 101 | + ) |
| 102 | + |
| 103 | + access_token = create_access_token( |
| 104 | + data={"sub": user.username}, expires_delta=access_token_expires |
| 105 | + ) |
| 106 | + return {"access_token": access_token, "token_type": "bearer"} |
| 107 | + |
| 108 | + |
| 109 | +@router.get("/users/me") |
| 110 | +async def read_users_me( |
| 111 | + current_user: Annotated[schemas.User, Depends(get_current_user)] |
| 112 | +): |
| 113 | + return current_user.username |
0 commit comments