124 lines
5 KiB
Python
124 lines
5 KiB
Python
# 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)}")
|
||
raise HTTPException(
|
||
status_code=500, detail="Не удалось зарегистрировать пользователя"
|
||
)
|
||
|
||
|
||
@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)
|
||
logger.info(
|
||
f"Успешная авторизация для client_id {client_id}, session_id: {result['session_id']}"
|
||
)
|
||
return result
|
||
except HTTPException as e:
|
||
raise e
|
||
except Exception as e:
|
||
logger.error(f"Ошибка в login: {type(e).__name__} - {str(e)}")
|
||
raise HTTPException(
|
||
status_code=500, detail="Не удалось авторизовать пользователя"
|
||
)
|
||
|
||
|
||
@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"],
|
||
"token_type": "bearer",
|
||
}
|
||
except HTTPException as e:
|
||
raise e
|
||
except Exception as e:
|
||
logger.error(f"Ошибка в get_current_user: {type(e).__name__} - {str(e)}")
|
||
raise HTTPException(
|
||
status_code=500, detail="Не удалось получить данные пользователя"
|
||
)
|
||
|
||
|
||
@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)}")
|
||
raise HTTPException(status_code=500, detail="Не удалось выйти из системы")
|
||
|
||
|
||
@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,
|
||
"message": "Файл users.json не существует",
|
||
}
|
||
|
||
data = storage._read_data()
|
||
has_users = len(data.get("users", [])) > 0
|
||
if has_users:
|
||
logger.info(f"Файл {file_path} существует и содержит пользователей")
|
||
return {
|
||
"exists": True,
|
||
"has_users": True,
|
||
"message": "Файл users.json существует и содержит пользователей",
|
||
}
|
||
else:
|
||
logger.info(f"Файл {file_path} существует, но не содержит пользователей")
|
||
return {
|
||
"exists": True,
|
||
"has_users": False,
|
||
"message": "Файл users.json существует, но не содержит пользователей",
|
||
}
|
||
except Exception as e:
|
||
logger.error(
|
||
f"Ошибка при проверке файла users.json: {type(e).__name__} - {str(e)}"
|
||
)
|
||
raise HTTPException(status_code=500, detail="Ошибка при проверке файла")
|