Files
saura_shakti_website/backend/app/routes/auth.py
T
Shubhankar45 53dbfa976b -
2026-11-13 12:14:55 +00:00

100 lines
3.9 KiB
Python

from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import func, select
from app.core.config import settings
from app.core.deps import CurrentAdmin, DbSession, SuperAdmin
from app.core.security import DUMMY_HASH, create_access_token, hash_password, verify_password
from app.middleware.rate_limit import RateLimiter
from app.models import Admin, AdminRole
from app.schemas.auth import (
AdminCreate,
AdminOut,
AdminUpdate,
ChangePasswordRequest,
LoginRequest,
TokenResponse,
)
from app.schemas.common import MessageResponse
router = APIRouter(prefix="/auth", tags=["Authentication"])
users_router = APIRouter(prefix="/admin/users", tags=["Admin users"])
login_limiter = RateLimiter("login", settings.LOGIN_RATE_LIMIT_PER_MINUTE)
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(login_limiter)])
async def login(body: LoginRequest, db: DbSession):
admin = await db.scalar(select(Admin).where(func.lower(Admin.email) == body.email.lower()))
# Always run a hash verification so response time doesn't reveal valid emails.
valid = verify_password(body.password, admin.hashed_password if admin else DUMMY_HASH)
if not admin or not valid:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Incorrect email or password")
if not admin.is_active:
raise HTTPException(status.HTTP_403_FORBIDDEN, "This account is disabled")
admin.last_login_at = datetime.now(UTC)
await db.commit()
await db.refresh(admin)
token, expires_in = create_access_token(str(admin.id), admin.role.value)
return TokenResponse(access_token=token, expires_in=expires_in, admin=AdminOut.model_validate(admin))
@router.get("/me", response_model=AdminOut)
async def me(admin: CurrentAdmin):
return admin
@router.post("/change-password", response_model=MessageResponse)
async def change_password(body: ChangePasswordRequest, admin: CurrentAdmin, db: DbSession):
if not verify_password(body.current_password, admin.hashed_password):
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Current password is incorrect")
admin.hashed_password = hash_password(body.new_password)
await db.commit()
return MessageResponse(message="Password updated")
# ------------------------------------------------------------------ admin accounts (super admin)
@users_router.get("", response_model=list[AdminOut])
async def list_admins(_: SuperAdmin, db: DbSession):
return (await db.scalars(select(Admin).order_by(Admin.id))).all()
@users_router.post("", response_model=AdminOut, status_code=status.HTTP_201_CREATED)
async def create_admin(body: AdminCreate, _: SuperAdmin, db: DbSession):
email = body.email.lower()
if await db.scalar(select(Admin.id).where(func.lower(Admin.email) == email)):
raise HTTPException(status.HTTP_409_CONFLICT, "An admin with this email already exists")
admin = Admin(
email=email,
full_name=body.full_name,
hashed_password=hash_password(body.password),
role=body.role,
)
db.add(admin)
await db.commit()
await db.refresh(admin)
return admin
@users_router.patch("/{admin_id}", response_model=AdminOut)
async def update_admin(admin_id: int, body: AdminUpdate, current: SuperAdmin, db: DbSession):
admin = await db.get(Admin, admin_id)
if not admin:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Admin not found")
data = body.model_dump(exclude_unset=True)
if admin.id == current.id and (
data.get("is_active") is False or data.get("role", AdminRole.SUPER_ADMIN) != AdminRole.SUPER_ADMIN
):
raise HTTPException(status.HTTP_400_BAD_REQUEST, "You cannot demote or disable your own account")
if (password := data.pop("password", None)) is not None:
admin.hashed_password = hash_password(password)
for key, value in data.items():
setattr(admin, key, value)
await db.commit()
await db.refresh(admin)
return admin