File size: 1,386 Bytes
fd3c8b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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"}