Add JWT authentication with user/password login, role-based access control, and Bearer token support while maintaining legacy API key compatibility for transition; update README with comprehensive JWT security guidelines, installation instructions for Python/SSH, development startup scripts (.env, run_dev.sh/ps1), and migrate all API examples to JWT authentication; update Ansible inventory SSH key paths from Docker container paths to local user paths
This commit is contained in:
@@ -3,6 +3,9 @@ from .bootstrap_status import BootstrapStatusRepository
|
||||
from .task import TaskRepository
|
||||
from .schedule import ScheduleRepository
|
||||
from .log import LogRepository
|
||||
from .user import UserRepository
|
||||
from .alert import AlertRepository
|
||||
from .app_setting import AppSettingRepository
|
||||
|
||||
__all__ = [
|
||||
"HostRepository",
|
||||
@@ -10,4 +13,7 @@ __all__ = [
|
||||
"TaskRepository",
|
||||
"ScheduleRepository",
|
||||
"LogRepository",
|
||||
"AlertRepository",
|
||||
"UserRepository",
|
||||
"AppSettingRepository",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select, func, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.alert import Alert
|
||||
|
||||
|
||||
class AlertRepository:
|
||||
def __init__(self, session: AsyncSession):
|
||||
self.session = session
|
||||
|
||||
async def list(
|
||||
self,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
unread_only: bool = False,
|
||||
category: Optional[str] = None,
|
||||
user_id: Optional[int] = None,
|
||||
) -> list[Alert]:
|
||||
stmt = select(Alert).order_by(Alert.created_at.desc()).offset(offset).limit(limit)
|
||||
if user_id is not None:
|
||||
stmt = stmt.where(Alert.user_id == user_id)
|
||||
if unread_only:
|
||||
stmt = stmt.where(Alert.read_at.is_(None))
|
||||
if category:
|
||||
stmt = stmt.where(Alert.category == category)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
async def get(self, alert_id: str) -> Optional[Alert]:
|
||||
stmt = select(Alert).where(Alert.id == alert_id)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def count_unread(self, user_id: Optional[int] = None) -> int:
|
||||
stmt = select(func.count()).select_from(Alert).where(Alert.read_at.is_(None))
|
||||
if user_id is not None:
|
||||
stmt = stmt.where(Alert.user_id == user_id)
|
||||
result = await self.session.execute(stmt)
|
||||
return int(result.scalar() or 0)
|
||||
|
||||
async def create(self, **fields) -> Alert:
|
||||
alert = Alert(**fields)
|
||||
self.session.add(alert)
|
||||
await self.session.flush()
|
||||
return alert
|
||||
|
||||
async def mark_as_read(self, alert_id: str) -> bool:
|
||||
stmt = select(Alert).where(Alert.id == alert_id)
|
||||
result = await self.session.execute(stmt)
|
||||
alert = result.scalar_one_or_none()
|
||||
if not alert:
|
||||
return False
|
||||
if alert.read_at is None:
|
||||
alert.read_at = datetime.now(timezone.utc)
|
||||
await self.session.flush()
|
||||
return True
|
||||
|
||||
async def mark_all_as_read(self, user_id: Optional[int] = None) -> int:
|
||||
stmt = update(Alert).where(Alert.read_at.is_(None)).values(read_at=datetime.now(timezone.utc))
|
||||
if user_id is not None:
|
||||
stmt = stmt.where(Alert.user_id == user_id)
|
||||
result = await self.session.execute(stmt)
|
||||
return int(result.rowcount or 0)
|
||||
|
||||
async def delete(self, alert_id: str) -> bool:
|
||||
alert = await self.get(alert_id)
|
||||
if alert:
|
||||
await self.session.delete(alert)
|
||||
await self.session.flush()
|
||||
return True
|
||||
return False
|
||||
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.app_setting import AppSetting
|
||||
|
||||
|
||||
class AppSettingRepository:
|
||||
def __init__(self, session: AsyncSession):
|
||||
self.session = session
|
||||
|
||||
async def get(self, key: str) -> Optional[AppSetting]:
|
||||
stmt = select(AppSetting).where(AppSetting.key == key)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_value(self, key: str, default: Optional[str] = None) -> Optional[str]:
|
||||
row = await self.get(key)
|
||||
if row is None:
|
||||
return default
|
||||
return row.value if row.value is not None else default
|
||||
|
||||
async def set_value(self, key: str, value: Optional[str]) -> AppSetting:
|
||||
row = await self.get(key)
|
||||
if row is None:
|
||||
row = AppSetting(key=key, value=value)
|
||||
self.session.add(row)
|
||||
await self.session.flush()
|
||||
return row
|
||||
|
||||
row.value = value
|
||||
await self.session.flush()
|
||||
return row
|
||||
|
||||
# Alias for compatibility
|
||||
async def set(self, key: str, value: Optional[str]) -> AppSetting:
|
||||
"""Alias for set_value."""
|
||||
return await self.set_value(key, value)
|
||||
@@ -5,7 +5,7 @@ from typing import Optional
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from models.bootstrap_status import BootstrapStatus
|
||||
from app.models.bootstrap_status import BootstrapStatus
|
||||
|
||||
|
||||
class BootstrapStatusRepository:
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from models.host import Host
|
||||
from app.models.host import Host
|
||||
|
||||
|
||||
class HostRepository:
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from sqlalchemy import select, delete, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.host_metrics import HostMetrics
|
||||
|
||||
|
||||
class HostMetricsRepository:
|
||||
"""Repository pour gérer les métriques des hôtes"""
|
||||
|
||||
def __init__(self, session: AsyncSession):
|
||||
self.session = session
|
||||
|
||||
async def create(self, **fields) -> HostMetrics:
|
||||
"""Crée une nouvelle entrée de métriques"""
|
||||
metrics = HostMetrics(**fields)
|
||||
self.session.add(metrics)
|
||||
await self.session.flush()
|
||||
return metrics
|
||||
|
||||
async def get(self, metrics_id: int) -> Optional[HostMetrics]:
|
||||
"""Récupère une entrée de métriques par son ID"""
|
||||
stmt = select(HostMetrics).where(HostMetrics.id == metrics_id)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_latest_for_host(self, host_id: str, metric_type: str = None) -> Optional[HostMetrics]:
|
||||
"""Récupère les dernières métriques pour un hôte"""
|
||||
stmt = select(HostMetrics).where(HostMetrics.host_id == host_id)
|
||||
if metric_type:
|
||||
stmt = stmt.where(HostMetrics.metric_type == metric_type)
|
||||
stmt = stmt.order_by(HostMetrics.collected_at.desc()).limit(1)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def list_for_host(
|
||||
self,
|
||||
host_id: str,
|
||||
metric_type: str = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0
|
||||
) -> List[HostMetrics]:
|
||||
"""Liste les métriques pour un hôte avec pagination"""
|
||||
stmt = select(HostMetrics).where(HostMetrics.host_id == host_id)
|
||||
if metric_type:
|
||||
stmt = stmt.where(HostMetrics.metric_type == metric_type)
|
||||
stmt = stmt.order_by(HostMetrics.collected_at.desc()).offset(offset).limit(limit)
|
||||
result = await self.session.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def get_all_latest(self, metric_type: str = "system_info") -> Dict[str, HostMetrics]:
|
||||
"""Récupère les dernières métriques pour tous les hôtes
|
||||
|
||||
Returns:
|
||||
Dict mapping host_id to latest HostMetrics
|
||||
"""
|
||||
# Sous-requête pour obtenir la date max par host_id
|
||||
subq = (
|
||||
select(
|
||||
HostMetrics.host_id,
|
||||
func.max(HostMetrics.collected_at).label("max_collected")
|
||||
)
|
||||
.where(HostMetrics.metric_type == metric_type)
|
||||
.group_by(HostMetrics.host_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
# Jointure pour récupérer les enregistrements complets
|
||||
stmt = (
|
||||
select(HostMetrics)
|
||||
.join(
|
||||
subq,
|
||||
(HostMetrics.host_id == subq.c.host_id) &
|
||||
(HostMetrics.collected_at == subq.c.max_collected)
|
||||
)
|
||||
.where(HostMetrics.metric_type == metric_type)
|
||||
)
|
||||
|
||||
result = await self.session.execute(stmt)
|
||||
metrics_list = result.scalars().all()
|
||||
|
||||
return {m.host_id: m for m in metrics_list}
|
||||
|
||||
async def cleanup_old_metrics(self, days_to_keep: int = 30) -> int:
|
||||
"""Supprime les métriques plus anciennes que le nombre de jours spécifié
|
||||
|
||||
Returns:
|
||||
Nombre d'entrées supprimées
|
||||
"""
|
||||
cutoff_date = datetime.utcnow() - timedelta(days=days_to_keep)
|
||||
stmt = delete(HostMetrics).where(HostMetrics.collected_at < cutoff_date)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.rowcount
|
||||
|
||||
async def get_metrics_history(
|
||||
self,
|
||||
host_id: str,
|
||||
metric_type: str = "system_info",
|
||||
hours: int = 24
|
||||
) -> List[HostMetrics]:
|
||||
"""Récupère l'historique des métriques pour les dernières heures"""
|
||||
cutoff = datetime.utcnow() - timedelta(hours=hours)
|
||||
stmt = (
|
||||
select(HostMetrics)
|
||||
.where(HostMetrics.host_id == host_id)
|
||||
.where(HostMetrics.metric_type == metric_type)
|
||||
.where(HostMetrics.collected_at >= cutoff)
|
||||
.order_by(HostMetrics.collected_at.asc())
|
||||
)
|
||||
result = await self.session.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def count_for_host(self, host_id: str) -> int:
|
||||
"""Compte le nombre d'entrées de métriques pour un hôte"""
|
||||
stmt = select(func.count(HostMetrics.id)).where(HostMetrics.host_id == host_id)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar() or 0
|
||||
+1
-1
@@ -5,7 +5,7 @@ from typing import Optional
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from models.log import Log
|
||||
from app.models.log import Log
|
||||
|
||||
|
||||
class LogRepository:
|
||||
|
||||
+13
-2
@@ -7,8 +7,8 @@ from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from models.schedule import Schedule
|
||||
from models.schedule_run import ScheduleRun
|
||||
from app.models.schedule import Schedule
|
||||
from app.models.schedule_run import ScheduleRun
|
||||
|
||||
|
||||
class ScheduleRepository:
|
||||
@@ -22,6 +22,17 @@ class ScheduleRepository:
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
async def list_active(self, limit: int = 100) -> list[Schedule]:
|
||||
"""Liste les schedules actifs (enabled=True et non supprimés)."""
|
||||
stmt = (
|
||||
select(Schedule)
|
||||
.where(Schedule.enabled == True, Schedule.deleted_at.is_(None))
|
||||
.order_by(Schedule.created_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
async def get(self, schedule_id: str, include_deleted: bool = False) -> Optional[Schedule]:
|
||||
stmt = select(Schedule).where(Schedule.id == schedule_id).options(
|
||||
selectinload(Schedule.runs)
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Optional
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from models.schedule_run import ScheduleRun
|
||||
from app.models.schedule_run import ScheduleRun
|
||||
|
||||
|
||||
class ScheduleRunRepository:
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from models.task import Task
|
||||
from app.models.task import Task
|
||||
|
||||
|
||||
class TaskRepository:
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""User repository for CRUD operations."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class UserRepository:
|
||||
"""Repository for User CRUD operations."""
|
||||
|
||||
def __init__(self, session: AsyncSession):
|
||||
self.session = session
|
||||
|
||||
async def count(self, include_deleted: bool = False) -> int:
|
||||
"""Count total users."""
|
||||
stmt = select(func.count(User.id))
|
||||
if not include_deleted:
|
||||
stmt = stmt.where(User.deleted_at.is_(None))
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar() or 0
|
||||
|
||||
async def list(
|
||||
self,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
include_deleted: bool = False
|
||||
) -> list[User]:
|
||||
"""List all users with pagination."""
|
||||
stmt = select(User).order_by(User.created_at.desc()).offset(offset).limit(limit)
|
||||
if not include_deleted:
|
||||
stmt = stmt.where(User.deleted_at.is_(None))
|
||||
result = await self.session.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def get(self, user_id: int, include_deleted: bool = False) -> Optional[User]:
|
||||
"""Get user by ID."""
|
||||
stmt = select(User).where(User.id == user_id)
|
||||
if not include_deleted:
|
||||
stmt = stmt.where(User.deleted_at.is_(None))
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_by_username(
|
||||
self,
|
||||
username: str,
|
||||
include_deleted: bool = False
|
||||
) -> Optional[User]:
|
||||
"""Get user by username."""
|
||||
stmt = select(User).where(User.username == username)
|
||||
if not include_deleted:
|
||||
stmt = stmt.where(User.deleted_at.is_(None))
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def get_by_email(
|
||||
self,
|
||||
email: str,
|
||||
include_deleted: bool = False
|
||||
) -> Optional[User]:
|
||||
"""Get user by email."""
|
||||
stmt = select(User).where(User.email == email)
|
||||
if not include_deleted:
|
||||
stmt = stmt.where(User.deleted_at.is_(None))
|
||||
result = await self.session.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def create(
|
||||
self,
|
||||
*,
|
||||
username: str,
|
||||
hashed_password: str,
|
||||
email: Optional[str] = None,
|
||||
display_name: Optional[str] = None,
|
||||
role: str = "admin",
|
||||
is_active: bool = True,
|
||||
is_superuser: bool = False,
|
||||
) -> User:
|
||||
"""Create a new user."""
|
||||
user = User(
|
||||
username=username,
|
||||
hashed_password=hashed_password,
|
||||
email=email,
|
||||
display_name=display_name,
|
||||
role=role,
|
||||
is_active=is_active,
|
||||
is_superuser=is_superuser,
|
||||
password_changed_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self.session.add(user)
|
||||
await self.session.flush()
|
||||
return user
|
||||
|
||||
async def update(self, user: User, **fields) -> User:
|
||||
"""Update user fields."""
|
||||
for key, value in fields.items():
|
||||
if value is not None:
|
||||
setattr(user, key, value)
|
||||
await self.session.flush()
|
||||
return user
|
||||
|
||||
async def update_password(self, user: User, hashed_password: str) -> User:
|
||||
"""Update user password and timestamp."""
|
||||
user.hashed_password = hashed_password
|
||||
user.password_changed_at = datetime.now(timezone.utc)
|
||||
await self.session.flush()
|
||||
return user
|
||||
|
||||
async def update_last_login(self, user: User) -> User:
|
||||
"""Update last login timestamp."""
|
||||
user.last_login = datetime.now(timezone.utc)
|
||||
await self.session.flush()
|
||||
return user
|
||||
|
||||
async def soft_delete(self, user_id: int) -> bool:
|
||||
"""Soft delete a user."""
|
||||
stmt = (
|
||||
update(User)
|
||||
.where(User.id == user_id, User.deleted_at.is_(None))
|
||||
.values(deleted_at=datetime.now(timezone.utc), is_active=False)
|
||||
)
|
||||
result = await self.session.execute(stmt)
|
||||
return result.rowcount > 0
|
||||
|
||||
async def hard_delete(self, user_id: int) -> bool:
|
||||
"""Permanently delete a user (use with caution)."""
|
||||
user = await self.get(user_id, include_deleted=True)
|
||||
if user:
|
||||
await self.session.delete(user)
|
||||
await self.session.flush()
|
||||
return True
|
||||
return False
|
||||
|
||||
async def exists_any(self) -> bool:
|
||||
"""Check if any user exists (for initial setup check)."""
|
||||
stmt = select(func.count(User.id)).where(User.deleted_at.is_(None))
|
||||
result = await self.session.execute(stmt)
|
||||
count = result.scalar() or 0
|
||||
return count > 0
|
||||
Reference in New Issue
Block a user