56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
# backend/app/routes/auth.py
|
|
from datetime import timedelta
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
|
|
from ..schemas import Token
|
|
from ..core.auth import create_access_token, get_authenticated_user
|
|
from ..core.config import (
|
|
ACCESS_TOKEN_EXPIRE_MINUTES,
|
|
ADMIN_HASH,
|
|
ADMIN_USER,
|
|
REF_HASH,
|
|
REF_USER,
|
|
verify_password,
|
|
)
|
|
|
|
router = APIRouter(prefix="/auth", tags=["Auth"])
|
|
|
|
|
|
@router.post("/token", response_model=Token)
|
|
async def login_for_access_token(
|
|
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
|
|
):
|
|
role = None
|
|
|
|
if form_data.username == ADMIN_USER and verify_password(
|
|
form_data.password, ADMIN_HASH
|
|
):
|
|
role = "admin"
|
|
elif form_data.username == REF_USER and verify_password(
|
|
form_data.password, REF_HASH
|
|
):
|
|
role = "ref"
|
|
|
|
if not role:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect username or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
access_token = create_access_token(
|
|
data={"sub": form_data.username, "role": role},
|
|
expires_delta=access_token_expires,
|
|
)
|
|
|
|
return {"access_token": access_token, "token_type": "bearer", "role": role}
|
|
|
|
|
|
@router.get("/check")
|
|
async def check_auth(user: dict = Depends(get_authenticated_user)):
|
|
return {"role": user.get("role"), "user": user.get("sub")}
|