Решение по TD-STYLE-ANALYZERS: LF — инструменты проекта (Python/Node) пишут LF, CRLF-.sh не работают на Linux CI (sh scripts/ci.sh), большинство файлов уже были LF. Добавлен .gitattributes (* text=auto eol=lf, бинарные исключения), .editorconfig переведён на lf, 1029 файлов конвертированы, git add --renormalize. Из индекса убраны закравшиеся archive/**/__pycache__/*.pyc.
66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
"""Вход в дашборд и сессии (п.4.1 ТЗ)."""
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
|
from pydantic import BaseModel
|
|
|
|
from ..auth import (
|
|
change_password,
|
|
create_session,
|
|
current_login,
|
|
destroy_session,
|
|
ensure_creds,
|
|
set_session_cookie,
|
|
verify_password,
|
|
)
|
|
from ..config import COOKIE_NAME
|
|
|
|
router = APIRouter(prefix="/api", tags=["auth"])
|
|
|
|
|
|
class LoginBody(BaseModel):
|
|
login: str
|
|
password: str
|
|
|
|
|
|
class PasswordBody(BaseModel):
|
|
oldPassword: str
|
|
newPassword: str
|
|
|
|
|
|
@router.post("/auth/login")
|
|
def login(body: LoginBody, response: Response) -> dict:
|
|
ensure_creds()
|
|
login_name = body.login.strip()
|
|
if not verify_password(login_name, body.password):
|
|
raise HTTPException(401, "Неверный логин или пароль")
|
|
token = create_session(login_name)
|
|
set_session_cookie(response, token)
|
|
return {"ok": True, "login": login_name}
|
|
|
|
|
|
@router.post("/auth/logout")
|
|
def logout(request: Request, response: Response) -> dict:
|
|
token = request.cookies.get(COOKIE_NAME)
|
|
destroy_session(token)
|
|
response.delete_cookie(COOKIE_NAME)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/auth/me")
|
|
def me(login: str = Depends(current_login)) -> dict:
|
|
return {"login": login, "ok": True}
|
|
|
|
|
|
@router.post("/auth/change-password")
|
|
def change(body: PasswordBody, request: Request, response: Response, login: str = Depends(current_login)) -> dict:
|
|
token = request.cookies.get(COOKIE_NAME)
|
|
ok = change_password(login, body.oldPassword, body.newPassword)
|
|
if not ok:
|
|
raise HTTPException(400, "Текущий пароль неверен")
|
|
# старые сессии удалены внутри change_password; выдаём свежую
|
|
fresh = create_session(login)
|
|
destroy_session(token)
|
|
set_session_cookie(response, fresh)
|
|
return {"ok": True}
|