diff --git a/auth.py b/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..c2015855e918f959c792bba120348aec82e0d3f4 --- /dev/null +++ b/auth.py @@ -0,0 +1,57 @@ +# auth.py +# pip install fastapi uvicorn jose[cryptography] passlib[bcrypt] +from datetime import datetime, timedelta +from typing import Optional + +from fastapi import HTTPException, Depends, status +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm +from jose import JWTError, jwt +from passlib.context import CryptContext + +from db import get_user_by_username + +# Configuration +SECRET_KEY = "your_secret_key" +ALGORITHM = "HS256" +ACCESS_TOKEN_EXPIRE_MINUTES = 30 + +# OAuth2PasswordBearer defines the token URL +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + +# Password hashing context +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +# Helper Functions +def verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + +def get_password_hash(password: str) -> str: + return pwd_context.hash(password) + +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): + to_encode = data.copy() + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) + to_encode.update({"exp": expire}) + return jwt.encode(to_encode, SECRET_KEY, ALGORITHM) + +def authenticate_user(username: str, password: str): + user = get_user_by_username(username) + if not user or not verify_password(password, user["password"]): + return None + return user + +def get_current_user(token: str = Depends(oauth2_scheme)): + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username = payload.get("sub") + if not username: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") + user = get_user_by_username(username) + if not user: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found") + except JWTError: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") + return user