Spaces:
Sleeping
Sleeping
Download auth/service.py from Coeinterns/bank-statement-api: direct link, hf CLI and curl.
- Browser
- Download file 5.83 kB
-
https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/auth/service.py
- Command line
-
hf download hf://spaces/Coeinterns/bank-statement-api/auth/service.py
-
curl -L -o service.py https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/auth/service.py
5.83 kB
| """ | |
| auth/service.py β Auth business logic: password hashing, JWT creation/verification, | |
| user lookup dependency, and user creation. | |
| """ | |
| import os | |
| import uuid | |
| from datetime import datetime, timedelta | |
| from typing import Optional | |
| from fastapi import Depends, HTTPException, status, Query | |
| from fastapi.security import OAuth2PasswordBearer | |
| from jose import JWTError, jwt | |
| import bcrypt | |
| from sqlalchemy.orm import Session | |
| from auth.database import get_db | |
| from auth.models import User, UserSession | |
| # ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "CHANGE-ME-IN-PRODUCTION-min-32-chars-please") | |
| JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256") | |
| JWT_ACCESS_TOKEN_EXPIRE_MINUTES = int( | |
| os.getenv("JWT_ACCESS_TOKEN_EXPIRE_MINUTES", "480") | |
| ) | |
| # ββ Password hashing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def hash_password(plain: str) -> str: | |
| """Return bcrypt hash of the plain-text password.""" | |
| salt = bcrypt.gensalt() | |
| hashed_bytes = bcrypt.hashpw(plain.encode('utf-8'), salt) | |
| return hashed_bytes.decode('utf-8') | |
| def verify_password(plain: str, hashed: str) -> bool: | |
| """Return True if plain matches the stored hash.""" | |
| try: | |
| return bcrypt.checkpw(plain.encode('utf-8'), hashed.encode('utf-8')) | |
| except Exception: | |
| return False | |
| # ββ JWT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login", auto_error=False) | |
| def create_access_token(data: dict) -> str: | |
| """ | |
| Create a signed JWT. | |
| Always adds: | |
| - jti : unique token ID (used for per-token revocation) | |
| - exp : expiry timestamp | |
| """ | |
| to_encode = data.copy() | |
| jti = str(uuid.uuid4()) | |
| expire = datetime.utcnow() + timedelta(minutes=JWT_ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"jti": jti, "exp": expire}) | |
| return jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM) | |
| def decode_token(token: str) -> dict: | |
| """ | |
| Decode and validate a JWT. | |
| Raises HTTP 401 if the token is invalid, expired, or malformed. | |
| """ | |
| try: | |
| payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM]) | |
| return payload | |
| except JWTError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # ββ FastAPI dependency βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def get_current_user( | |
| token: Optional[str] = Depends(oauth2_scheme), | |
| token_query: Optional[str] = Query(None, alias="token"), | |
| db: Session = Depends(get_db), | |
| ) -> User: | |
| """ | |
| FastAPI dependency that: | |
| 1. Decodes the JWT (either from Authorization header or 'token' query param) | |
| 2. Looks up the session by jti β raises 401 if not found or revoked | |
| 3. Looks up the user β raises 401 if not found or inactive | |
| 4. Returns the User ORM object | |
| """ | |
| credentials_exc = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| actual_token = token or token_query | |
| if not actual_token: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Not authenticated", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| payload = decode_token(actual_token) | |
| jti: Optional[str] = payload.get("jti") | |
| username: Optional[str] = payload.get("sub") | |
| if jti is None or username is None: | |
| raise credentials_exc | |
| # Check session validity | |
| session = db.query(UserSession).filter(UserSession.token_jti == jti).first() | |
| if session is None or session.is_revoked: | |
| raise credentials_exc | |
| # Check user validity | |
| user = db.query(User).filter(User.username == username).first() | |
| if user is None or not user.is_active: | |
| raise credentials_exc | |
| return user | |
| # ββ User creation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def create_user( | |
| db: Session, | |
| username: str, | |
| password: str, | |
| email: Optional[str] = None, | |
| full_name: Optional[str] = None, | |
| role: str = "tester", | |
| ) -> User: | |
| """ | |
| Create and persist a new user. | |
| Raises HTTP 400 if the username already exists. | |
| """ | |
| existing = db.query(User).filter(User.username == username).first() | |
| if existing: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail=f"Username '{username}' already exists", | |
| ) | |
| user = User( | |
| id=str(uuid.uuid4()), | |
| username=username, | |
| email=email, | |
| hashed_password=hash_password(password), | |
| full_name=full_name, | |
| role=role, | |
| is_active=True, | |
| created_at=datetime.utcnow(), | |
| ) | |
| db.add(user) | |
| db.commit() | |
| db.refresh(user) | |
| return user | |