Spaces:
Sleeping
Sleeping
update
Browse files- common/auth.py +1 -2
- routes/auth.py +26 -24
common/auth.py
CHANGED
@@ -17,12 +17,11 @@ USERS = [
|
|
17 |
{"username": "user", "password": "user123"},
|
18 |
]
|
19 |
|
20 |
-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
21 |
|
22 |
class LoginRequest(BaseModel):
|
23 |
username: str
|
24 |
password: str
|
25 |
-
grant_type: str
|
26 |
|
27 |
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
28 |
to_encode = data.copy()
|
|
|
17 |
{"username": "user", "password": "user123"},
|
18 |
]
|
19 |
|
20 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login/token")
|
21 |
|
22 |
class LoginRequest(BaseModel):
|
23 |
username: str
|
24 |
password: str
|
|
|
25 |
|
26 |
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
27 |
to_encode = data.copy()
|
routes/auth.py
CHANGED
@@ -1,32 +1,34 @@
|
|
1 |
from typing import Optional
|
2 |
-
from fastapi import APIRouter, Form, HTTPException
|
3 |
from datetime import timedelta
|
4 |
import common.auth as auth
|
5 |
|
6 |
router = APIRouter(prefix="/auth", tags=["Auth"])
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
# Если данные пришли через Form Data
|
14 |
-
if username is not None and password is not None:
|
15 |
-
final_username = username
|
16 |
-
final_password = password
|
17 |
-
# Если данные пришли через JSON
|
18 |
-
elif request is not None:
|
19 |
-
final_username = request.username
|
20 |
-
final_password = request.password
|
21 |
-
else:
|
22 |
-
raise HTTPException(status_code=400, detail="Не указаны логин и пароль")
|
23 |
-
|
24 |
-
user = next((u for u in auth.USERS if u["username"] == final_username), None)
|
25 |
-
if not user or user["password"] != final_password:
|
26 |
raise HTTPException(status_code=401, detail="Неверный логин или пароль")
|
27 |
-
|
|
|
|
|
|
|
28 |
access_token_expires = timedelta(minutes=auth.ACCESS_TOKEN_EXPIRE_MINUTES)
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from typing import Optional
|
2 |
+
from fastapi import APIRouter, Body, Form, HTTPException
|
3 |
from datetime import timedelta
|
4 |
import common.auth as auth
|
5 |
|
6 |
router = APIRouter(prefix="/auth", tags=["Auth"])
|
7 |
|
8 |
+
def authenticate_user(username: str, password: str):
|
9 |
+
"""Проверяет, существует ли пользователь и правильный ли пароль."""
|
10 |
+
user = next((u for u in auth.USERS if u["username"] == username), None)
|
11 |
+
if not user or user["password"] != password:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
raise HTTPException(status_code=401, detail="Неверный логин или пароль")
|
13 |
+
return user
|
14 |
+
|
15 |
+
def generate_access_token(username: str):
|
16 |
+
"""Генерирует токен для аутентифицированного пользователя."""
|
17 |
access_token_expires = timedelta(minutes=auth.ACCESS_TOKEN_EXPIRE_MINUTES)
|
18 |
+
return auth.create_access_token(data={"sub": username}, expires_delta=access_token_expires)
|
19 |
+
|
20 |
+
async def login_common(username: str, password: str):
|
21 |
+
"""Общий метод аутентификации."""
|
22 |
+
user = authenticate_user(username, password)
|
23 |
+
access_token = generate_access_token(user["username"])
|
24 |
+
return {"access_token": access_token, "token_type": "bearer"}
|
25 |
+
|
26 |
+
@router.post("/login", summary="Авторизация через JSON")
|
27 |
+
async def login_json(request: auth.LoginRequest = Body(...)):
|
28 |
+
"""Принимает JSON-запросы."""
|
29 |
+
return await login_common(request.username, request.password)
|
30 |
+
|
31 |
+
@router.post("/login/token", summary="Авторизация через Form-Data")
|
32 |
+
async def login_form(username: str = Form(...), password: str = Form(...)):
|
33 |
+
"""Принимает Form-Data (x-www-form-urlencoded)."""
|
34 |
+
return await login_common(username, password)
|