refactor: extract all routes to app/api/v1/endpoints/ with proper structure
This commit is contained in:
65
app/api/v1/endpoints/auth.py
Normal file
65
app/api/v1/endpoints/auth.py
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
LogBoard+ - Аутентификация API
|
||||
Автор: Сергей Антропов
|
||||
Сайт: https://devops.org.ru
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Response
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
|
||||
from app.core.auth import (
|
||||
authenticate_user,
|
||||
create_access_token,
|
||||
verify_token,
|
||||
get_current_user,
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
)
|
||||
from app.models.auth import UserLogin, Token
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Инициализация безопасности
|
||||
security = HTTPBearer()
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login(user_data: UserLogin, response: Response):
|
||||
"""API для входа в систему"""
|
||||
if authenticate_user(user_data.username, user_data.password):
|
||||
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user_data.username}, expires_delta=access_token_expires
|
||||
)
|
||||
|
||||
# Устанавливаем cookie с токеном
|
||||
response.set_cookie(
|
||||
key="access_token",
|
||||
value=access_token,
|
||||
httponly=True,
|
||||
secure=False, # Установите True для HTTPS
|
||||
samesite="lax",
|
||||
max_age=ACCESS_TOKEN_EXPIRE_MINUTES * 60
|
||||
)
|
||||
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Неверное имя пользователя или пароль. Проверьте учетные данные и попробуйте снова.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(response: Response):
|
||||
"""API для выхода из системы"""
|
||||
response.delete_cookie(key="access_token")
|
||||
return {"message": "Успешный выход из системы"}
|
||||
|
||||
@router.get("/me")
|
||||
async def get_current_user_info(current_user: str = Depends(get_current_user)):
|
||||
"""Получить информацию о текущем пользователе"""
|
||||
return {"username": current_user}
|
||||
Reference in New Issue
Block a user