first commit
This commit is contained in:
0
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
28
backend/app/api/deps.py
Normal file
28
backend/app/api/deps.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from fastapi import Depends, HTTPException, Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.db import get_session
|
||||
from app.core.security import read_session_token, SESSION_COOKIE
|
||||
from app.models.user import User
|
||||
|
||||
async def db_session() -> AsyncSession:
|
||||
async for s in get_session():
|
||||
yield s
|
||||
|
||||
async def get_current_user(request: Request, session: AsyncSession = Depends(db_session)) -> User:
|
||||
token = request.cookies.get(SESSION_COOKIE)
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
uid = read_session_token(token)
|
||||
if not uid:
|
||||
raise HTTPException(status_code=401, detail="Invalid session")
|
||||
res = await session.execute(select(User).where(User.id == uid))
|
||||
user = res.scalar_one_or_none()
|
||||
if not user or not user.is_active:
|
||||
raise HTTPException(status_code=401, detail="User inactive")
|
||||
return user
|
||||
|
||||
def require_admin(user: User) -> None:
|
||||
if user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="Admin only")
|
||||
57
backend/app/api/routes_auth.py
Normal file
57
backend/app/api/routes_auth.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from fastapi import APIRouter, Depends, Response, HTTPException, Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import db_session, get_current_user
|
||||
from app.core.config import settings
|
||||
from app.core.security import (
|
||||
verify_password, create_session_token, new_csrf_token,
|
||||
SESSION_COOKIE, CSRF_COOKIE
|
||||
)
|
||||
from app.models.user import User
|
||||
from app.schemas.user import LoginIn, UserOut
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/login")
|
||||
async def login(payload: LoginIn, response: Response, session: AsyncSession = Depends(db_session)):
|
||||
res = await session.execute(select(User).where(User.email == payload.email))
|
||||
user = res.scalar_one_or_none()
|
||||
if not user or not verify_password(payload.password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Bad credentials")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=403, detail="Inactive")
|
||||
|
||||
token = create_session_token(user.id)
|
||||
csrf = new_csrf_token()
|
||||
|
||||
response.set_cookie(
|
||||
key=SESSION_COOKIE,
|
||||
value=token,
|
||||
httponly=True,
|
||||
secure=settings.COOKIE_SECURE,
|
||||
samesite=settings.COOKIE_SAMESITE,
|
||||
max_age=60 * 60 * 24 * 7,
|
||||
path="/",
|
||||
)
|
||||
# CSRF token czytelny dla JS (nie httponly)
|
||||
response.set_cookie(
|
||||
key=CSRF_COOKIE,
|
||||
value=csrf,
|
||||
httponly=False,
|
||||
secure=settings.COOKIE_SECURE,
|
||||
samesite=settings.COOKIE_SAMESITE,
|
||||
max_age=60 * 60 * 24 * 7,
|
||||
path="/",
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(response: Response):
|
||||
response.delete_cookie(SESSION_COOKIE, path="/")
|
||||
response.delete_cookie(CSRF_COOKIE, path="/")
|
||||
return {"ok": True}
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
async def me(user: User = Depends(get_current_user)):
|
||||
return UserOut(id=user.id, email=user.email, role=user.role)
|
||||
70
backend/app/api/routes_dashboards.py
Normal file
70
backend/app/api/routes_dashboards.py
Normal file
@@ -0,0 +1,70 @@
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import db_session, get_current_user
|
||||
from app.api.routes_routers import require_csrf
|
||||
from app.models.user import User
|
||||
from app.models.dashboard import Dashboard, DashboardPanel, Permission
|
||||
from app.models.router import Router
|
||||
from app.schemas.dashboard import DashboardCreate, DashboardOut, PanelCreate, PanelOut
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("", response_model=list[DashboardOut])
|
||||
async def list_dashboards(user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
res = await session.execute(select(Dashboard).where(Dashboard.owner_user_id == user.id))
|
||||
rows = res.scalars().all()
|
||||
return [DashboardOut(id=d.id, name=d.name, is_shared=d.is_shared) for d in rows]
|
||||
|
||||
@router.post("", response_model=DashboardOut)
|
||||
async def create_dashboard(payload: DashboardCreate, request: Request, user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
require_csrf(request)
|
||||
d = Dashboard(owner_user_id=user.id, name=payload.name, is_shared=payload.is_shared)
|
||||
session.add(d)
|
||||
await session.commit()
|
||||
await session.refresh(d)
|
||||
return DashboardOut(id=d.id, name=d.name, is_shared=d.is_shared)
|
||||
|
||||
@router.get("/{dashboard_id}")
|
||||
async def get_dashboard(dashboard_id: int, user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
res = await session.execute(select(Dashboard).where(Dashboard.id == dashboard_id))
|
||||
d = res.scalar_one_or_none()
|
||||
if not d or d.owner_user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
pres = await session.execute(select(DashboardPanel).where(DashboardPanel.dashboard_id == d.id))
|
||||
panels = pres.scalars().all()
|
||||
out_panels = []
|
||||
for p in panels:
|
||||
out_panels.append(PanelOut(
|
||||
id=p.id, dashboard_id=p.dashboard_id, title=p.title,
|
||||
router_id=p.router_id, config=json.loads(p.config_json or "{}")
|
||||
).model_dump())
|
||||
return {"dashboard": DashboardOut(id=d.id, name=d.name, is_shared=d.is_shared).model_dump(), "panels": out_panels}
|
||||
|
||||
@router.post("/{dashboard_id}/panels", response_model=PanelOut)
|
||||
async def create_panel(dashboard_id: int, payload: PanelCreate, request: Request, user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
require_csrf(request)
|
||||
# dashboard ownership
|
||||
res = await session.execute(select(Dashboard).where(Dashboard.id == dashboard_id))
|
||||
d = res.scalar_one_or_none()
|
||||
if not d or d.owner_user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
|
||||
# check permission to router
|
||||
if user.role != "admin":
|
||||
pres = await session.execute(select(Permission).where(Permission.user_id == user.id, Permission.router_id == payload.router_id, Permission.can_view == True)) # noqa
|
||||
if not pres.scalar_one_or_none():
|
||||
raise HTTPException(status_code=403, detail="No access to router")
|
||||
|
||||
p = DashboardPanel(
|
||||
dashboard_id=dashboard_id,
|
||||
title=payload.title,
|
||||
router_id=payload.router_id,
|
||||
config_json=json.dumps(payload.config or {}),
|
||||
)
|
||||
session.add(p)
|
||||
await session.commit()
|
||||
await session.refresh(p)
|
||||
return PanelOut(id=p.id, dashboard_id=p.dashboard_id, title=p.title, router_id=p.router_id, config=payload.config)
|
||||
93
backend/app/api/routes_routers.py
Normal file
93
backend/app/api/routes_routers.py
Normal file
@@ -0,0 +1,93 @@
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, delete
|
||||
|
||||
from app.api.deps import db_session, get_current_user, require_admin
|
||||
from app.core.security import encrypt_secret, CSRF_COOKIE
|
||||
from app.models.user import User
|
||||
from app.models.router import Router, RouterCredential, CredentialMethod
|
||||
from app.models.dashboard import Permission
|
||||
from app.schemas.router import RouterCreate, RouterOut, CredentialCreate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
def require_csrf(request: Request):
|
||||
# minimalny CSRF: nagłówek X-CSRF-Token musi równać się cookie mt_csrf
|
||||
cookie = request.cookies.get(CSRF_COOKIE)
|
||||
header = request.headers.get("X-CSRF-Token")
|
||||
if not cookie or not header or cookie != header:
|
||||
raise HTTPException(status_code=403, detail="CSRF check failed")
|
||||
|
||||
@router.get("", response_model=list[RouterOut])
|
||||
async def list_routers(user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
if user.role == "admin":
|
||||
res = await session.execute(select(Router))
|
||||
rows = res.scalars().all()
|
||||
else:
|
||||
res = await session.execute(
|
||||
select(Router).join(Permission, Permission.router_id == Router.id)
|
||||
.where(Permission.user_id == user.id, Permission.can_view == True) # noqa
|
||||
)
|
||||
rows = res.scalars().all()
|
||||
return [RouterOut(
|
||||
id=r.id, name=r.name, host=r.host,
|
||||
port_rest=r.port_rest, port_ssh=r.port_ssh, port_api=r.port_api,
|
||||
verify_ssl=r.verify_ssl, preferred_method=r.preferred_method,
|
||||
tags=r.tags
|
||||
) for r in rows]
|
||||
|
||||
@router.post("", response_model=RouterOut)
|
||||
async def create_router(payload: RouterCreate, request: Request, user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
require_admin(user)
|
||||
require_csrf(request)
|
||||
r = Router(**payload.model_dump())
|
||||
session.add(r)
|
||||
await session.commit()
|
||||
await session.refresh(r)
|
||||
return RouterOut(
|
||||
id=r.id, name=r.name, host=r.host,
|
||||
port_rest=r.port_rest, port_ssh=r.port_ssh, port_api=r.port_api,
|
||||
verify_ssl=r.verify_ssl, preferred_method=r.preferred_method, tags=r.tags
|
||||
)
|
||||
|
||||
@router.post("/{router_id}/credentials")
|
||||
async def add_credential(router_id: int, payload: CredentialCreate, request: Request, user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
require_admin(user)
|
||||
require_csrf(request)
|
||||
res = await session.execute(select(Router).where(Router.id == router_id))
|
||||
r = res.scalar_one_or_none()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Router not found")
|
||||
|
||||
method = payload.method.lower()
|
||||
if method not in ("rest", "ssh", "api"):
|
||||
raise HTTPException(status_code=400, detail="Bad method")
|
||||
|
||||
c = RouterCredential(
|
||||
router_id=router_id,
|
||||
method=CredentialMethod(method),
|
||||
username=payload.username,
|
||||
secret_encrypted=encrypt_secret(payload.secret),
|
||||
extra_json=json.dumps(payload.extra_json or {}),
|
||||
)
|
||||
session.add(c)
|
||||
await session.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@router.post("/{router_id}/grant")
|
||||
async def grant_router(router_id: int, target_user_id: int, can_edit: bool = False, request: Request = None,
|
||||
user: User = Depends(get_current_user), session: AsyncSession = Depends(db_session)):
|
||||
require_admin(user)
|
||||
require_csrf(request)
|
||||
# upsert permission
|
||||
res = await session.execute(select(Permission).where(Permission.user_id == target_user_id, Permission.router_id == router_id))
|
||||
p = res.scalar_one_or_none()
|
||||
if not p:
|
||||
p = Permission(user_id=target_user_id, router_id=router_id, can_view=True, can_edit=can_edit)
|
||||
session.add(p)
|
||||
else:
|
||||
p.can_view = True
|
||||
p.can_edit = bool(can_edit)
|
||||
await session.commit()
|
||||
return {"ok": True}
|
||||
75
backend/app/api/routes_stream.py
Normal file
75
backend/app/api/routes_stream.py
Normal file
@@ -0,0 +1,75 @@
|
||||
import json
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import db_session
|
||||
from app.core.security import read_session_token, SESSION_COOKIE
|
||||
from app.models.user import User
|
||||
from app.models.dashboard import DashboardPanel, Permission, Dashboard
|
||||
from app.services.streaming.hub import hub
|
||||
from app.services.streaming.poller import panel_poller
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
async def ws_current_user(ws: WebSocket, session: AsyncSession) -> User | None:
|
||||
token = ws.cookies.get(SESSION_COOKIE)
|
||||
uid = read_session_token(token) if token else None
|
||||
if not uid:
|
||||
return None
|
||||
res = await session.execute(select(User).where(User.id == uid))
|
||||
return res.scalar_one_or_none()
|
||||
|
||||
@router.websocket("/ws/stream")
|
||||
async def ws_stream(websocket: WebSocket, session: AsyncSession = Depends(db_session)):
|
||||
await websocket.accept()
|
||||
user = await ws_current_user(websocket, session)
|
||||
if not user or not user.is_active:
|
||||
await websocket.close(code=4401)
|
||||
return
|
||||
|
||||
subscribed_panel_id = None
|
||||
try:
|
||||
# pierwszy msg: {"panelId": 123}
|
||||
first = await websocket.receive_text()
|
||||
msg = json.loads(first)
|
||||
panel_id = int(msg.get("panelId"))
|
||||
subscribed_panel_id = panel_id
|
||||
|
||||
pres = await session.execute(select(DashboardPanel).where(DashboardPanel.id == panel_id))
|
||||
panel = pres.scalar_one_or_none()
|
||||
if not panel:
|
||||
await websocket.close(code=4404)
|
||||
return
|
||||
|
||||
# dashboard ownership lub (w przyszłości) shared
|
||||
dres = await session.execute(select(Dashboard).where(Dashboard.id == panel.dashboard_id))
|
||||
dash = dres.scalar_one_or_none()
|
||||
if not dash or dash.owner_user_id != user.id:
|
||||
await websocket.close(code=4403)
|
||||
return
|
||||
|
||||
# permission do routera
|
||||
if user.role != "admin":
|
||||
pr = await session.execute(select(Permission).where(Permission.user_id == user.id, Permission.router_id == panel.router_id, Permission.can_view == True)) # noqa
|
||||
if not pr.scalar_one_or_none():
|
||||
await websocket.close(code=4403)
|
||||
return
|
||||
|
||||
await hub.subscribe(panel_id, websocket)
|
||||
await panel_poller.ensure_running(panel_id, session)
|
||||
|
||||
# keepalive loop: klient może wysyłać ping
|
||||
while True:
|
||||
_ = await websocket.receive_text()
|
||||
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if subscribed_panel_id is not None:
|
||||
try:
|
||||
await hub.unsubscribe(subscribed_panel_id, websocket)
|
||||
except Exception:
|
||||
pass
|
||||
27
backend/app/core/config.py
Normal file
27
backend/app/core/config.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
APP_ENV: str = "dev"
|
||||
APP_NAME: str = "mt-traffic"
|
||||
BASE_URL: str = "http://localhost:8000"
|
||||
|
||||
DATABASE_URL: str = "sqlite+aiosqlite:///./mt_traffic.db"
|
||||
DOCKER_DATABASE_URL: str = "sqlite+aiosqlite:////data/mt_traffic.db"
|
||||
|
||||
SESSION_SECRET: str = "change_me"
|
||||
CREDENTIALS_MASTER_KEY: str = "change_me_32bytes_base64_fernet"
|
||||
PASSWORD_HASH_ALG: str = "argon2"
|
||||
|
||||
COOKIE_SECURE: bool = False
|
||||
COOKIE_SAMESITE: str = "lax"
|
||||
CORS_ORIGINS: str = "http://localhost:3000"
|
||||
|
||||
DEFAULT_POLL_INTERVAL_MS: int = 1000
|
||||
MAX_WS_SUBSCRIPTIONS_PER_USER: int = 10
|
||||
|
||||
ADMIN_BOOTSTRAP_EMAIL: str = "admin@example.com"
|
||||
ADMIN_BOOTSTRAP_PASSWORD: str = "admin1234"
|
||||
|
||||
settings = Settings()
|
||||
24
backend/app/core/db.py
Normal file
24
backend/app/core/db.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from typing import AsyncGenerator
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
def _db_url() -> str:
|
||||
# w dockerze zwykle ustawiamy DATABASE_URL przez env, więc preferujemy settings.DATABASE_URL
|
||||
return settings.DATABASE_URL
|
||||
|
||||
engine = create_async_engine(_db_url(), future=True, echo=False)
|
||||
SessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
||||
|
||||
async def init_db() -> None:
|
||||
from app.models import user, router, dashboard # noqa
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
7
backend/app/core/logging.py
Normal file
7
backend/app/core/logging.py
Normal file
@@ -0,0 +1,7 @@
|
||||
import logging
|
||||
|
||||
def setup_logging():
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
68
backend/app/core/security.py
Normal file
68
backend/app/core/security.py
Normal file
@@ -0,0 +1,68 @@
|
||||
import base64
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
|
||||
from passlib.context import CryptContext
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models.user import User, UserRole
|
||||
|
||||
pwd_context = CryptContext(schemes=["argon2", "bcrypt"], deprecated="auto")
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
return pwd_context.verify(password, password_hash)
|
||||
|
||||
def session_serializer() -> URLSafeTimedSerializer:
|
||||
return URLSafeTimedSerializer(settings.SESSION_SECRET, salt="session")
|
||||
|
||||
SESSION_COOKIE = "mt_session"
|
||||
CSRF_COOKIE = "mt_csrf"
|
||||
|
||||
def create_session_token(user_id: int) -> str:
|
||||
s = session_serializer()
|
||||
return s.dumps({"uid": user_id})
|
||||
|
||||
def read_session_token(token: str, max_age_seconds: int = 60 * 60 * 24 * 7) -> Optional[int]:
|
||||
s = session_serializer()
|
||||
try:
|
||||
data = s.loads(token, max_age=max_age_seconds)
|
||||
uid = int(data.get("uid"))
|
||||
return uid
|
||||
except (BadSignature, SignatureExpired, Exception):
|
||||
return None
|
||||
|
||||
def new_csrf_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
def fernet() -> Fernet:
|
||||
# CREDENTIALS_MASTER_KEY powinien być base64 urlsafe 32 bytes
|
||||
key = settings.CREDENTIALS_MASTER_KEY.encode("utf-8")
|
||||
return Fernet(key)
|
||||
|
||||
def encrypt_secret(plain: str) -> str:
|
||||
return fernet().encrypt(plain.encode("utf-8")).decode("utf-8")
|
||||
|
||||
def decrypt_secret(enc: str) -> str:
|
||||
return fernet().decrypt(enc.encode("utf-8")).decode("utf-8")
|
||||
|
||||
async def bootstrap_admin_if_needed(session: AsyncSession) -> None:
|
||||
res = await session.execute(select(User).limit(1))
|
||||
first = res.scalar_one_or_none()
|
||||
if first:
|
||||
return
|
||||
admin = User(
|
||||
email=settings.ADMIN_BOOTSTRAP_EMAIL,
|
||||
password_hash=hash_password(settings.ADMIN_BOOTSTRAP_PASSWORD),
|
||||
role=UserRole.ADMIN,
|
||||
is_active=True,
|
||||
)
|
||||
session.add(admin)
|
||||
await session.commit()
|
||||
45
backend/app/main.py
Normal file
45
backend/app/main.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import Response
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import setup_logging
|
||||
from app.core.db import init_db, get_session
|
||||
from app.core.security import bootstrap_admin_if_needed
|
||||
from app.api.routes_auth import router as auth_router
|
||||
from app.api.routes_routers import router as routers_router
|
||||
from app.api.routes_dashboards import router as dashboards_router
|
||||
from app.api.routes_stream import router as stream_router
|
||||
|
||||
setup_logging()
|
||||
|
||||
app = FastAPI(title=settings.APP_NAME)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[o.strip() for o in settings.CORS_ORIGINS.split(",") if o.strip()],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@app.on_event("startup")
|
||||
async def on_startup():
|
||||
await init_db()
|
||||
async for session in get_session():
|
||||
await bootstrap_admin_if_needed(session)
|
||||
break
|
||||
|
||||
@app.get("/healthz")
|
||||
async def healthz():
|
||||
return {"ok": True}
|
||||
|
||||
# 204 na favicon (ucisza spam)
|
||||
@app.get("/favicon.ico")
|
||||
async def favicon():
|
||||
return Response(status_code=204)
|
||||
|
||||
app.include_router(auth_router, prefix="/auth", tags=["auth"])
|
||||
app.include_router(routers_router, prefix="/api/routers", tags=["routers"])
|
||||
app.include_router(dashboards_router, prefix="/api/dashboards", tags=["dashboards"])
|
||||
app.include_router(stream_router, tags=["stream"])
|
||||
1
backend/app/models/__init__.py
Normal file
1
backend/app/models/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from app.core.db import Base
|
||||
31
backend/app/models/dashboard.py
Normal file
31
backend/app/models/dashboard.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from sqlalchemy import String, Boolean, Integer, ForeignKey, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.core.db import Base
|
||||
|
||||
class Permission(Base):
|
||||
__tablename__ = "permissions"
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
|
||||
router_id: Mapped[int] = mapped_column(ForeignKey("routers.id", ondelete="CASCADE"), primary_key=True)
|
||||
can_view: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
can_edit: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
class Dashboard(Base):
|
||||
__tablename__ = "dashboards"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
name: Mapped[str] = mapped_column(String(200))
|
||||
is_shared: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
class DashboardPanel(Base):
|
||||
__tablename__ = "dashboard_panels"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
dashboard_id: Mapped[int] = mapped_column(ForeignKey("dashboards.id", ondelete="CASCADE"), index=True)
|
||||
title: Mapped[str] = mapped_column(String(200))
|
||||
router_id: Mapped[int] = mapped_column(ForeignKey("routers.id", ondelete="CASCADE"), index=True)
|
||||
# config_json: {"interfaces":["ether1"],"metrics":["rx_bps","tx_bps"],"interval_ms":1000,"window":120}
|
||||
config_json: Mapped[str] = mapped_column(Text, default="{}")
|
||||
|
||||
dashboard = relationship("Dashboard")
|
||||
41
backend/app/models/router.py
Normal file
41
backend/app/models/router.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from enum import Enum
|
||||
from sqlalchemy import String, Boolean, Integer, ForeignKey, Enum as SAEnum, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.core.db import Base
|
||||
|
||||
class RouterMethod(str, Enum):
|
||||
AUTO = "auto"
|
||||
REST = "rest"
|
||||
SSH = "ssh"
|
||||
API = "api"
|
||||
|
||||
class Router(Base):
|
||||
__tablename__ = "routers"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200), unique=True, index=True)
|
||||
host: Mapped[str] = mapped_column(String(255))
|
||||
port_rest: Mapped[int] = mapped_column(Integer, default=443)
|
||||
port_ssh: Mapped[int] = mapped_column(Integer, default=22)
|
||||
port_api: Mapped[int] = mapped_column(Integer, default=8728)
|
||||
verify_ssl: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
preferred_method: Mapped[RouterMethod] = mapped_column(SAEnum(RouterMethod), default=RouterMethod.AUTO)
|
||||
tags: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
class CredentialMethod(str, Enum):
|
||||
REST = "rest"
|
||||
SSH = "ssh"
|
||||
API = "api"
|
||||
|
||||
class RouterCredential(Base):
|
||||
__tablename__ = "router_credentials"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
router_id: Mapped[int] = mapped_column(ForeignKey("routers.id", ondelete="CASCADE"), index=True)
|
||||
method: Mapped[CredentialMethod] = mapped_column(SAEnum(CredentialMethod))
|
||||
username: Mapped[str] = mapped_column(String(255))
|
||||
secret_encrypted: Mapped[str] = mapped_column(Text)
|
||||
extra_json: Mapped[str] = mapped_column(Text, default="{}")
|
||||
|
||||
router = relationship("Router")
|
||||
18
backend/app/models/user.py
Normal file
18
backend/app/models/user.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from enum import Enum
|
||||
from sqlalchemy import String, Boolean, Enum as SAEnum
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.db import Base
|
||||
|
||||
class UserRole(str, Enum):
|
||||
ADMIN = "admin"
|
||||
USER = "user"
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
role: Mapped[UserRole] = mapped_column(SAEnum(UserRole), default=UserRole.USER)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
22
backend/app/schemas/dashboard.py
Normal file
22
backend/app/schemas/dashboard.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
class DashboardCreate(BaseModel):
|
||||
name: str
|
||||
is_shared: bool = False
|
||||
|
||||
class DashboardOut(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
is_shared: bool
|
||||
|
||||
class PanelCreate(BaseModel):
|
||||
title: str
|
||||
router_id: int
|
||||
config: dict # {"interfaces":[...],"metrics":[...],"interval_ms":1000,"window":120}
|
||||
|
||||
class PanelOut(BaseModel):
|
||||
id: int
|
||||
dashboard_id: int
|
||||
title: str
|
||||
router_id: int
|
||||
config: dict
|
||||
28
backend/app/schemas/router.py
Normal file
28
backend/app/schemas/router.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
class RouterCreate(BaseModel):
|
||||
name: str
|
||||
host: str
|
||||
port_rest: int = 443
|
||||
port_ssh: int = 22
|
||||
port_api: int = 8728
|
||||
verify_ssl: bool = False
|
||||
preferred_method: str = "auto"
|
||||
tags: str = ""
|
||||
|
||||
class RouterOut(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
host: str
|
||||
port_rest: int
|
||||
port_ssh: int
|
||||
port_api: int
|
||||
verify_ssl: bool
|
||||
preferred_method: str
|
||||
tags: str
|
||||
|
||||
class CredentialCreate(BaseModel):
|
||||
method: str # rest|ssh|api
|
||||
username: str
|
||||
secret: str
|
||||
extra_json: dict = {}
|
||||
10
backend/app/schemas/user.py
Normal file
10
backend/app/schemas/user.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
class UserOut(BaseModel):
|
||||
id: int
|
||||
email: EmailStr
|
||||
role: str
|
||||
|
||||
class LoginIn(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
18
backend/app/services/mikrotik/client_api.py
Normal file
18
backend/app/services/mikrotik/client_api.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Szkielet – do dopisania.
|
||||
# Zalecane: librouteros (synch) w executorze lub biblioteka async jeśli użyjesz.
|
||||
from typing import Any, Dict, List
|
||||
from app.services.mikrotik.client_base import MikroTikClient
|
||||
|
||||
class MikroTikAPIClient(MikroTikClient):
|
||||
def __init__(self, host: str, port: int, username: str, password: str, use_ssl: bool = False):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.use_ssl = use_ssl
|
||||
|
||||
async def list_interfaces(self) -> List[Dict[str, Any]]:
|
||||
raise NotImplementedError("API list_interfaces not implemented")
|
||||
|
||||
async def monitor_traffic_once(self, iface: str) -> Dict[str, Any]:
|
||||
raise NotImplementedError("API monitor_traffic_once not implemented")
|
||||
11
backend/app/services/mikrotik/client_base.py
Normal file
11
backend/app/services/mikrotik/client_base.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, Dict, List
|
||||
|
||||
class MikroTikClient(ABC):
|
||||
@abstractmethod
|
||||
async def list_interfaces(self) -> List[Dict[str, Any]]:
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def monitor_traffic_once(self, iface: str) -> Dict[str, Any]:
|
||||
...
|
||||
62
backend/app/services/mikrotik/client_rest.py
Normal file
62
backend/app/services/mikrotik/client_rest.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import json
|
||||
from typing import Any, Dict, List
|
||||
import httpx
|
||||
|
||||
from app.services.mikrotik.client_base import MikroTikClient
|
||||
|
||||
def parse_bps(value: Any) -> float:
|
||||
if value is None:
|
||||
return 0.0
|
||||
s = str(value).strip().lower().replace(" ", "")
|
||||
if s == "":
|
||||
return 0.0
|
||||
try:
|
||||
return float(s)
|
||||
except ValueError:
|
||||
pass
|
||||
multipliers = {"bps": 1.0, "kbps": 1_000.0, "mbps": 1_000_000.0, "gbps": 1_000_000_000.0}
|
||||
for unit, mul in multipliers.items():
|
||||
if s.endswith(unit):
|
||||
num = s[: -len(unit)]
|
||||
try:
|
||||
return float(num) * mul
|
||||
except ValueError:
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
class MikroTikRESTClient(MikroTikClient):
|
||||
def __init__(self, base_url: str, username: str, password: str, verify_ssl: bool):
|
||||
self.base = base_url.rstrip("/") + "/rest"
|
||||
self.auth = (username, password)
|
||||
self.verify = verify_ssl
|
||||
|
||||
async def _client(self) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(
|
||||
base_url=self.base,
|
||||
auth=self.auth,
|
||||
verify=self.verify,
|
||||
timeout=httpx.Timeout(10.0),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
async def list_interfaces(self) -> List[Dict[str, Any]]:
|
||||
params = {".proplist": "name,type,disabled,running"}
|
||||
async with await self._client() as c:
|
||||
r = await c.get("/interface", params=params)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
if isinstance(data, dict):
|
||||
return [data]
|
||||
return data
|
||||
|
||||
async def monitor_traffic_once(self, iface: str) -> Dict[str, Any]:
|
||||
payload = {"interface": iface, "once": ""}
|
||||
async with await self._client() as c:
|
||||
r = await c.post("/interface/monitor-traffic", content=json.dumps(payload))
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
if isinstance(data, list) and data:
|
||||
return data[0]
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
return {}
|
||||
19
backend/app/services/mikrotik/client_ssh.py
Normal file
19
backend/app/services/mikrotik/client_ssh.py
Normal file
@@ -0,0 +1,19 @@
|
||||
# Szkielet – do dopisania.
|
||||
# Zalecane: asyncssh + komenda:
|
||||
# /interface/monitor-traffic interface=ether1 once
|
||||
# i parsowanie wyjścia.
|
||||
from typing import Any, Dict, List
|
||||
from app.services.mikrotik.client_base import MikroTikClient
|
||||
|
||||
class MikroTikSSHClient(MikroTikClient):
|
||||
def __init__(self, host: str, port: int, username: str, password: str):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.username = username
|
||||
self.password = password
|
||||
|
||||
async def list_interfaces(self) -> List[Dict[str, Any]]:
|
||||
raise NotImplementedError("SSH list_interfaces not implemented")
|
||||
|
||||
async def monitor_traffic_once(self, iface: str) -> Dict[str, Any]:
|
||||
raise NotImplementedError("SSH monitor_traffic_once not implemented")
|
||||
54
backend/app/services/mikrotik/factory.py
Normal file
54
backend/app/services/mikrotik/factory.py
Normal file
@@ -0,0 +1,54 @@
|
||||
import json
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import decrypt_secret
|
||||
from app.models.router import Router, RouterCredential, CredentialMethod, RouterMethod
|
||||
from app.services.mikrotik.client_rest import MikroTikRESTClient
|
||||
from app.services.mikrotik.client_ssh import MikroTikSSHClient
|
||||
from app.services.mikrotik.client_api import MikroTikAPIClient
|
||||
|
||||
async def build_client(session: AsyncSession, router_id: int):
|
||||
rres = await session.execute(select(Router).where(Router.id == router_id))
|
||||
router = rres.scalar_one_or_none()
|
||||
if not router:
|
||||
return None
|
||||
|
||||
cres = await session.execute(select(RouterCredential).where(RouterCredential.router_id == router_id))
|
||||
creds = cres.scalars().all()
|
||||
|
||||
# wybór: preferowana metoda albo auto: REST -> API -> SSH
|
||||
order = []
|
||||
pref = router.preferred_method
|
||||
if pref == RouterMethod.REST:
|
||||
order = [CredentialMethod.REST]
|
||||
elif pref == RouterMethod.API:
|
||||
order = [CredentialMethod.API]
|
||||
elif pref == RouterMethod.SSH:
|
||||
order = [CredentialMethod.SSH]
|
||||
else:
|
||||
order = [CredentialMethod.REST, CredentialMethod.API, CredentialMethod.SSH]
|
||||
|
||||
cred_by_method = {c.method: c for c in creds}
|
||||
for m in order:
|
||||
c = cred_by_method.get(m)
|
||||
if not c:
|
||||
continue
|
||||
secret = decrypt_secret(c.secret_encrypted)
|
||||
extra = {}
|
||||
try:
|
||||
extra = json.loads(c.extra_json or "{}")
|
||||
except Exception:
|
||||
extra = {}
|
||||
|
||||
if m == CredentialMethod.REST:
|
||||
base_url = f"https://{router.host}:{router.port_rest}"
|
||||
if extra.get("scheme") in ("http", "https"):
|
||||
base_url = f"{extra['scheme']}://{router.host}:{router.port_rest}"
|
||||
return MikroTikRESTClient(base_url, c.username, secret, router.verify_ssl)
|
||||
if m == CredentialMethod.SSH:
|
||||
return MikroTikSSHClient(router.host, router.port_ssh, c.username, secret)
|
||||
if m == CredentialMethod.API:
|
||||
return MikroTikAPIClient(router.host, router.port_api, c.username, secret, use_ssl=bool(extra.get("ssl", False)))
|
||||
|
||||
return None
|
||||
25
backend/app/services/streaming/hub.py
Normal file
25
backend/app/services/streaming/hub.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import asyncio
|
||||
from typing import Dict, Set, Any
|
||||
|
||||
class Hub:
|
||||
def __init__(self):
|
||||
self._lock = asyncio.Lock()
|
||||
self._subs: Dict[int, Set[Any]] = {} # panel_id -> set[WebSocket]
|
||||
|
||||
async def subscribe(self, panel_id: int, ws):
|
||||
async with self._lock:
|
||||
self._subs.setdefault(panel_id, set()).add(ws)
|
||||
|
||||
async def unsubscribe(self, panel_id: int, ws):
|
||||
async with self._lock:
|
||||
s = self._subs.get(panel_id)
|
||||
if s and ws in s:
|
||||
s.remove(ws)
|
||||
if s and len(s) == 0:
|
||||
self._subs.pop(panel_id, None)
|
||||
|
||||
async def connections(self, panel_id: int):
|
||||
async with self._lock:
|
||||
return list(self._subs.get(panel_id, set()))
|
||||
|
||||
hub = Hub()
|
||||
98
backend/app/services/streaming/poller.py
Normal file
98
backend/app/services/streaming/poller.py
Normal file
@@ -0,0 +1,98 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Dict, Any, Optional, List
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models.dashboard import DashboardPanel
|
||||
from app.services.mikrotik.factory import build_client
|
||||
from app.services.mikrotik.client_rest import parse_bps
|
||||
from app.services.streaming.hub import hub
|
||||
|
||||
log = logging.getLogger("poller")
|
||||
|
||||
class PanelPoller:
|
||||
def __init__(self):
|
||||
self._tasks: Dict[int, asyncio.Task] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def ensure_running(self, panel_id: int, session: AsyncSession):
|
||||
async with self._lock:
|
||||
t = self._tasks.get(panel_id)
|
||||
if t and not t.done():
|
||||
return
|
||||
self._tasks[panel_id] = asyncio.create_task(self._run(panel_id, session))
|
||||
|
||||
async def _run(self, panel_id: int, session: AsyncSession):
|
||||
# UWAGA: session jest z zewnątrz; do prostoty używamy jednego session per WS.
|
||||
# W prod lepiej robić osobne sesje w pętli / użyć SessionLocal.
|
||||
while True:
|
||||
conns = await hub.connections(panel_id)
|
||||
if not conns:
|
||||
# nikt nie subskrybuje -> zakończ
|
||||
async with self._lock:
|
||||
self._tasks.pop(panel_id, None)
|
||||
return
|
||||
|
||||
pres = await session.execute(select(DashboardPanel).where(DashboardPanel.id == panel_id))
|
||||
panel = pres.scalar_one_or_none()
|
||||
if not panel:
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
|
||||
cfg = {}
|
||||
try:
|
||||
cfg = json.loads(panel.config_json or "{}")
|
||||
except Exception:
|
||||
cfg = {}
|
||||
|
||||
interfaces: List[str] = [str(x) for x in (cfg.get("interfaces") or [])]
|
||||
metrics: List[str] = [str(x) for x in (cfg.get("metrics") or ["rx_bps","tx_bps"])]
|
||||
interval_ms = int(cfg.get("interval_ms") or settings.DEFAULT_POLL_INTERVAL_MS)
|
||||
interval_ms = max(250, min(interval_ms, 5000))
|
||||
|
||||
client = await build_client(session, panel.router_id)
|
||||
if not client:
|
||||
payload = {"type":"error","message":"No client/credentials for router"}
|
||||
for ws in conns:
|
||||
try: await ws.send_text(json.dumps(payload))
|
||||
except Exception: pass
|
||||
await asyncio.sleep(interval_ms/1000)
|
||||
continue
|
||||
|
||||
# jeśli brak interfaces, pobierz i ogranicz (żeby nie zabić routera)
|
||||
if not interfaces:
|
||||
try:
|
||||
ifs = await client.list_interfaces()
|
||||
interfaces = [i.get("name") for i in ifs if i.get("name")][:10]
|
||||
except Exception:
|
||||
interfaces = []
|
||||
|
||||
ts = int(asyncio.get_event_loop().time() * 1000)
|
||||
rows = []
|
||||
for iface in interfaces:
|
||||
try:
|
||||
raw = await client.monitor_traffic_once(iface)
|
||||
row = {"iface": iface, "ts": ts}
|
||||
# RouterOS REST typowo ma rx-bits-per-second / tx-bits-per-second
|
||||
rx = parse_bps(raw.get("rx-bits-per-second"))
|
||||
tx = parse_bps(raw.get("tx-bits-per-second"))
|
||||
row["rx_bps"] = rx
|
||||
row["tx_bps"] = tx
|
||||
rows.append(row)
|
||||
except Exception as e:
|
||||
log.info("poll error panel=%s iface=%s err=%s", panel_id, iface, e)
|
||||
|
||||
msg = {"type":"traffic","panelId": panel_id, "data": rows, "metrics": metrics}
|
||||
for ws in conns:
|
||||
try:
|
||||
await ws.send_text(json.dumps(msg))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await asyncio.sleep(interval_ms / 1000)
|
||||
|
||||
panel_poller = PanelPoller()
|
||||
Reference in New Issue
Block a user