Spaces:
Sleeping
Sleeping
Download routers/auth.py from Coeinterns/bank-statement-api: direct link, hf CLI and curl.
- Browser
- Download file 6.48 kB
-
https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/routers/auth.py
- Command line
-
hf download hf://spaces/Coeinterns/bank-statement-api/routers/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/routers/auth.py
6.48 kB
| import os | |
| import logging | |
| from datetime import datetime | |
| from typing import List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, Request, Header | |
| from auth.models import User, AuditLog, UserSession | |
| from auth.service import ( | |
| verify_password, create_access_token, get_current_user, | |
| create_user, JWT_ACCESS_TOKEN_EXPIRE_MINUTES | |
| ) | |
| from auth.schemas import ( | |
| TokenResponse, LoginRequest, UserProfile, SeedUserEntry | |
| ) | |
| logger = logging.getLogger("befree.auth") | |
| router = APIRouter(prefix="/api/v1/auth", tags=["auth"]) | |
| async def login(payload: LoginRequest, request: Request): | |
| """Authenticate a user and return a JWT token.""" | |
| from sqlalchemy.orm import Session as SASession | |
| from auth.database import SessionLocal as _SessionLocal | |
| _db: SASession = _SessionLocal() | |
| try: | |
| user = _db.query(User).filter(User.username == payload.username).first() | |
| if user is None or not verify_password(payload.password, user.hashed_password): | |
| try: | |
| log = AuditLog( | |
| user_id=user.id if user else None, | |
| username=payload.username, | |
| action="login_failed", | |
| resource_type="session", | |
| http_method="POST", | |
| endpoint="/api/v1/auth/login", | |
| response_status=401, | |
| ip_address=request.client.host if request.client else None, | |
| user_agent=request.headers.get("user-agent"), | |
| occurred_at=datetime.utcnow(), | |
| duration_ms=0, | |
| ) | |
| _db.add(log) | |
| _db.commit() | |
| except Exception: | |
| pass | |
| raise HTTPException(status_code=401, detail="Invalid username or password") | |
| user.last_login_at = datetime.utcnow() | |
| token = create_access_token({"sub": user.username}) | |
| from jose import jwt as _jose_jwt | |
| payload_data = _jose_jwt.decode( | |
| token, | |
| os.getenv("JWT_SECRET_KEY", ""), | |
| algorithms=[os.getenv("JWT_ALGORITHM", "HS256")], | |
| ) | |
| jti = payload_data.get("jti") | |
| exp = datetime.utcfromtimestamp(payload_data["exp"]) | |
| session = UserSession( | |
| user_id=user.id, | |
| token_jti=jti, | |
| expires_at=exp, | |
| ip_address=request.client.host if request.client else None, | |
| user_agent=request.headers.get("user-agent"), | |
| ) | |
| _db.add(session) | |
| log = AuditLog( | |
| user_id=user.id, | |
| username=user.username, | |
| action="login_success", | |
| resource_type="session", | |
| http_method="POST", | |
| endpoint="/api/v1/auth/login", | |
| response_status=200, | |
| ip_address=request.client.host if request.client else None, | |
| user_agent=request.headers.get("user-agent"), | |
| occurred_at=datetime.utcnow(), | |
| duration_ms=0, | |
| ) | |
| log.user_id = user.id # Make sure it's linked | |
| _db.add(log) | |
| _db.commit() | |
| return TokenResponse( | |
| access_token=token, | |
| user_id=user.id, | |
| username=user.username, | |
| full_name=user.full_name, | |
| role=user.role, | |
| expires_in=JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 60, | |
| ) | |
| finally: | |
| _db.close() | |
| async def logout( | |
| request: Request, | |
| current_user: User = Depends(get_current_user), | |
| ): | |
| """Revoke the current session token.""" | |
| from auth.database import SessionLocal as _SL | |
| from auth.service import decode_token as _dt | |
| _db = _SL() | |
| try: | |
| auth_header = request.headers.get("Authorization", "") | |
| token = auth_header.split(" ", 1)[1] if auth_header.startswith("Bearer ") else "" | |
| payload_data = _dt(token) | |
| jti = payload_data.get("jti") | |
| if jti: | |
| sess = _db.query(UserSession).filter(UserSession.token_jti == jti).first() | |
| if sess: | |
| sess.is_revoked = True | |
| log = AuditLog( | |
| user_id=current_user.id, | |
| username=current_user.username, | |
| action="logout", | |
| resource_type="session", | |
| http_method="POST", | |
| endpoint="/api/v1/auth/logout", | |
| response_status=200, | |
| ip_address=request.client.host if request.client else None, | |
| user_agent=request.headers.get("user-agent"), | |
| occurred_at=datetime.utcnow(), | |
| duration_ms=0, | |
| ) | |
| _db.add(log) | |
| _db.commit() | |
| finally: | |
| _db.close() | |
| return {"message": "Logged out successfully"} | |
| async def get_me(current_user: User = Depends(get_current_user)): | |
| """Return the profile of the currently authenticated user.""" | |
| return UserProfile( | |
| id=current_user.id, | |
| username=current_user.username, | |
| email=current_user.email, | |
| full_name=current_user.full_name, | |
| role=current_user.role, | |
| is_active=current_user.is_active, | |
| created_at=current_user.created_at.isoformat(), | |
| last_login_at=current_user.last_login_at.isoformat() if current_user.last_login_at else None, | |
| ) | |
| async def seed_users( | |
| request: Request, | |
| users: List[SeedUserEntry], | |
| x_seed_secret: Optional[str] = Header(None), | |
| ): | |
| """One-time endpoint to create initial employee accounts.""" | |
| logger.warning("seed-users endpoint called — disable after initial setup") | |
| seed_secret = os.getenv("SEED_SECRET", "") | |
| if not seed_secret or x_seed_secret != seed_secret: | |
| raise HTTPException(status_code=403, detail="Invalid or missing X-Seed-Secret header") | |
| from auth.database import SessionLocal as _SL | |
| _db = _SL() | |
| created, skipped = [], [] | |
| try: | |
| for entry in users: | |
| try: | |
| user = create_user( | |
| _db, | |
| username=entry.username, | |
| password=entry.password, | |
| email=entry.email, | |
| full_name=entry.full_name, | |
| role=entry.role, | |
| ) | |
| created.append(user.username) | |
| except HTTPException: | |
| skipped.append(entry.username) | |
| return {"created": created, "skipped": skipped} | |
| finally: | |
| _db.close() | |