muryshev's picture
update
fd3c8b9
raw
history blame
1.39 kB
from typing import Optional
from fastapi import APIRouter, Form, HTTPException
from datetime import timedelta
import common.auth as auth
router = APIRouter(prefix="/auth", tags=["Auth"])
@router.post("/login")
async def login(username: Optional[str] = Form(default=None),
password: Optional[str] = Form(default=None),
request: Optional[auth.LoginRequest] = None):
# Если данные пришли через Form Data
if username is not None and password is not None:
final_username = username
final_password = password
# Если данные пришли через JSON
elif request is not None:
final_username = request.username
final_password = request.password
else:
raise HTTPException(status_code=400, detail="Не указаны логин и пароль")
user = next((u for u in auth.USERS if u["username"] == final_username), None)
if not user or user["password"] != final_password:
raise HTTPException(status_code=401, detail="Неверный логин или пароль")
access_token_expires = timedelta(minutes=auth.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = auth.create_access_token(
data={"sub": user["username"]}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}