gonets/SRV/api/v1/auth.py

131 lines
5.1 KiB
Python
Raw Normal View History

2025-06-09 14:43:25 +05:00
# api/v1/auth.py
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.security import OAuth2PasswordBearer
from services.auth_service import AuthService
from models.auth import UserCreate, UserLogin, UserResponse, Token
from storage.json_storage import JsonStorage
import logging
import os
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
router = APIRouter()
auth_service = AuthService()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
@router.post("/register", response_model=UserResponse)
async def register(user: UserCreate):
"""Регистрирует нового пользователя"""
try:
db_user = auth_service.register(user)
logger.info(f"Пользователь {user.username} успешно зарегистрирован")
return db_user
except HTTPException as e:
raise e
except Exception as e:
logger.error(f"Ошибка в register: {type(e).__name__} - {str(e)}")
2025-06-20 11:22:54 +05:00
raise HTTPException(status_code=500,
detail="Не удалось зарегистрировать пользователя")
2025-06-09 14:43:25 +05:00
@router.post("/login", response_model=Token)
async def login(user: UserLogin, request: Request):
"""Авторизует пользователя и создаёт сессию"""
try:
client_id = request.client.host
logger.debug(f"Попытка авторизации для client_id {client_id}")
result = auth_service.login(user, client_id)
2025-06-20 11:22:54 +05:00
logger.info(
f"Успешная авторизация для client_id {client_id}, session_id: {result['session_id']}"
)
2025-06-09 14:43:25 +05:00
return result
except HTTPException as e:
raise e
except Exception as e:
logger.error(f"Ошибка в login: {type(e).__name__} - {str(e)}")
2025-06-20 11:22:54 +05:00
raise HTTPException(status_code=500,
detail="Не удалось авторизовать пользователя")
2025-06-09 14:43:25 +05:00
@router.get("/me")
async def get_current_user(request: Request):
"""Возвращает данные текущего пользователя и токен"""
try:
client_id = request.client.host
logger.debug(f"Запрос /me для client_id {client_id}")
result = auth_service.get_user_by_session(client_id)
return {
"user": result["user"],
"access_token": result["access_token"],
2025-06-20 11:22:54 +05:00
"token_type": "bearer",
2025-06-09 14:43:25 +05:00
}
except HTTPException as e:
raise e
except Exception as e:
2025-06-20 11:22:54 +05:00
logger.error(
f"Ошибка в get_current_user: {type(e).__name__} - {str(e)}")
raise HTTPException(status_code=500,
detail="Не удалось получить данные пользователя")
2025-06-09 14:43:25 +05:00
@router.get("/logout")
async def logout(request: Request):
"""Выход из системы, удаление сессии"""
try:
client_id = request.client.host
logger.debug(f"Запрос logout для client_id {client_id}")
return auth_service.logout(client_id)
except HTTPException as e:
raise e
except Exception as e:
logger.error(f"Ошибка в logout: {type(e).__name__} - {str(e)}")
2025-06-20 11:22:54 +05:00
raise HTTPException(status_code=500,
detail="Не удалось выйти из системы")
2025-06-09 14:43:25 +05:00
@router.get("/check_json")
async def check_users_file():
"""Проверяет, существует ли файл users.json и содержит ли он пользователей"""
try:
file_path = "/etc/gonets/users.json"
storage = JsonStorage(file_path=file_path)
if not os.path.exists(file_path):
logger.info(f"Файл {file_path} не существует")
return {
"exists": False,
"has_users": False,
2025-06-20 11:22:54 +05:00
"message": "Файл users.json не существует",
2025-06-09 14:43:25 +05:00
}
data = storage._read_data()
has_users = len(data.get("users", [])) > 0
if has_users:
2025-06-20 11:22:54 +05:00
logger.info(
f"Файл {file_path} существует и содержит пользователей")
2025-06-09 14:43:25 +05:00
return {
"exists": True,
"has_users": True,
2025-06-20 11:22:54 +05:00
"message":
"Файл users.json существует и содержит пользователей",
2025-06-09 14:43:25 +05:00
}
else:
2025-06-20 11:22:54 +05:00
logger.info(
f"Файл {file_path} существует, но не содержит пользователей")
2025-06-09 14:43:25 +05:00
return {
2025-06-20 11:22:54 +05:00
"exists":
True,
"has_users":
False,
"message":
"Файл users.json существует, но не содержит пользователей",
2025-06-09 14:43:25 +05:00
}
except Exception as e:
2025-06-20 11:22:54 +05:00
logger.error(
f"Ошибка при проверке файла users.json: {type(e).__name__} - {str(e)}"
)
raise HTTPException(status_code=500,
detail="Ошибка при проверке файла")