Интернационализация для всех сервисов сервера

This commit is contained in:
parent 7491ce455d
commit ba8cea01e7
13 changed files with 1011 additions and 206 deletions

View file

@ -9,6 +9,8 @@ from typing import Optional
import configparser
import os
import logging
from utils.i18n import get_translations, _
from babel.support import Translations
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@ -16,7 +18,7 @@ logger = logging.getLogger(__name__)
config = configparser.ConfigParser()
config_path = "/etc/gonets/config.ini"
if not os.path.exists(config_path):
raise RuntimeError(f"Конфигурационный файл {config_path} не найден")
raise RuntimeError(f"Configuration file {config_path} not found")
config.read(config_path)
SECRET_KEY = config["JWT"]["secret_key"]
@ -25,13 +27,13 @@ ACCESS_TOKEN_EXPIRE_MINUTES = 30
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
class AuthService:
"""Сервис для регистрации, авторизации и управления сессиями"""
def __init__(self):
def __init__(self, translations: Translations = Depends(get_translations("services"))):
self.storage = JsonStorage()
self.session_storage = SessionStorage()
self.translations = translations
def create_access_token(self, data: dict) -> str:
"""Создаёт токен"""
@ -60,31 +62,31 @@ class AuthService:
return db_user
except ValueError as e:
logger.error(
f"Ошибка при регистрации пользователя {user.username}: {str(e)}"
f"Error registering user {user.username}: {str(e)}"
)
raise HTTPException(status_code=400, detail=str(e))
raise HTTPException(status_code=400, detail=self.translations.gettext(str(e)))
except Exception as e:
logger.error(
f"Ошибка при регистрации пользователя {user.username}: {type(e).__name__} - {str(e)}"
f"Error registering user {user.username}: {type(e).__name__} - {str(e)}"
)
raise HTTPException(status_code=500, detail="Ошибка регистрации")
raise HTTPException(status_code=500, detail=self.translations.gettext("Ошибка регистрации"))
def login(self, user: UserLogin, client_id: str) -> dict:
"""Авторизует пользователя, создаёт сессию и возвращает токен"""
try:
db_user = self.storage.get_user_by_username(user.username)
if not db_user:
logger.error(f"Пользователь {user.username} не найден")
raise HTTPException(status_code=401, detail="Неверный логин или пароль")
logger.error(f"User {user.username} not found")
raise HTTPException(status_code=401, detail=self.translations.gettext("Неверный логин или пароль"))
if not self.storage.verify_password(user.password, db_user["password_hash"]):
logger.error(
f"Неверный пароль для пользователя {user.username}")
raise HTTPException(status_code=401, detail="Неверный логин или пароль")
f"Invalid password for user {user.username}")
raise HTTPException(status_code=401, detail=self.translations.gettext("Неверный логин или пароль"))
access_token = self.create_access_token(
data={"sub": user.username})
session_id = self.session_storage.create_session(
user.username, access_token, client_id)
logger.info(f"Пользователь {user.username} успешно авторизован")
logger.info(f"User {user.username} successfully logged in")
return {
"access_token": access_token,
"token_type": "bearer",
@ -93,22 +95,22 @@ class AuthService:
}
except Exception as e:
logger.error(
f"Ошибка при авторизации пользователя {user.username}: {type(e).__name__} - {str(e)}"
f"Error logging in user {user.username}: {type(e).__name__} - {str(e)}"
)
raise HTTPException(status_code=500, detail="Ошибка авторизации")
raise HTTPException(status_code=500, detail=self.translations.gettext("Ошибка авторизации"))
def get_current_user(
self, token: str = Depends(oauth2_scheme)) -> UserResponse:
"""Получает текущего пользователя по токену"""
credentials = self.verify_token(token)
if not credentials:
logger.error("Неверный или истёкший токен")
raise HTTPException(status_code=401, detail="Неверный токен")
logger.error("Invalid or expired token")
raise HTTPException(status_code=401, detail=self.translations.gettext("Неверный токен"))
username = credentials["username"]
db_user = self.storage.get_user_by_username(username)
if not db_user:
logger.error(f"Пользователь {username} не найден")
raise HTTPException(status_code=401, detail="Пользователь не найден")
logger.error(f"User {username} not found")
raise HTTPException(status_code=401, detail=self.translations.gettext("Пользователь не найден"))
return UserResponse(id=db_user["id"], username=db_user["username"], is_admin=db_user["is_admin"])
def get_user_by_session(self, client_id: str) -> dict:
@ -116,14 +118,14 @@ class AuthService:
session = self.session_storage.get_latest_session(client_id)
if not session:
logger.error(
f"Сессия для client_id {client_id} не найдена или истекла")
raise HTTPException(status_code=401, detail="Сессия недействительна")
f"Session for client_id {client_id} not found or expired")
raise HTTPException(status_code=401, detail=self.translations.gettext("Сессия недействительна"))
username = session["username"]
token = session["token"]
db_user = self.storage.get_user_by_username(username)
if not db_user:
logger.error(f"Пользователь {username} не найден")
raise HTTPException(status_code=401, detail="Пользователь не найден")
logger.error(f"User {username} not found")
raise HTTPException(status_code=401, detail=self.translations.gettext("Пользователь не найден"))
return {
"user":
UserResponse(id=db_user["id"], username=db_user["username"], is_admin=db_user["is_admin"]),
@ -137,10 +139,10 @@ class AuthService:
if session:
self.session_storage.delete_session(session["session_id"])
logger.info(
f"Пользователь успешно вышел из системы для client_id {client_id}"
f"User successfully logged out for client_id {client_id}"
)
return {"message": "Успешный выход из системы"}
return {"message": self.translations.gettext("Успешный выход из системы")}
except Exception as e:
logger.error(
f"Ошибка при выходе из системы: {type(e).__name__} - {str(e)}")
raise HTTPException(status_code=500, detail="Ошибка при выходе из системы")
f"Error logging out: {type(e).__name__} - {str(e)}")
raise HTTPException(status_code=500, detail=self.translations.gettext("Ошибка при выходе из системы"))