IPAM Manager: API, UI-админка, журнал аудита
Backend (FastAPI, SQLAlchemy 2, Alembic, PostgreSQL 16): - организации, VRF, префиксы (дерево, использование, автоназначение), адреса, операторы связи, устройства и типы устройств; JWT, роли admin/viewer; - VRF принадлежит организации (составной FK), смена VRF у префикса переносит поддерево, имя VRF уникально в организации; - журнал аудита: поиск и фильтры, ротация (срок/количество), очистка по паролю с блокировкой, IP клиента и метаданные запроса (X-Forwarded-For только от TRUSTED_PROXIES). UI (web/, без сборки): экраны и диалоги по макетам «IPAM Manager», кликабельные строки реестров, локальные шрифты IBM Plex, собственные выпадающие списки. Окружение: docker-compose (postgres + app), миграции Alembic 0001-0004, scripts/gen_env.py, scripts/seed_demo.py, 11 автотестов (pytest). Документация: README.md и docs/changes/001-005 (планы и итоги). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
commit
a846d30872
64 files changed
+4194
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,28 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db import get_db
|
||||
from app.models import User
|
||||
from app.schemas import LoginIn, TokenOut, UserOut
|
||||
from app.security import create_token, current_user, verify_password
|
||||
from app.services import ANONYMOUS, audit
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenOut)
|
||||
def login(body: LoginIn, db: Session = Depends(get_db)):
|
||||
user = db.scalar(select(User).where(User.username == body.username, User.is_active))
|
||||
if user is None or not verify_password(body.password, user.password_hash):
|
||||
audit(db, ANONYMOUS, "session", None, "failed", body.username[:100], message="Неудачная попытка входа в UI")
|
||||
db.commit()
|
||||
raise HTTPException(401, "Неверный логин или пароль")
|
||||
audit(db, user, "session", None, "login", user.username, message=f"Вход в UI: {user.username}")
|
||||
db.commit()
|
||||
return TokenOut(access_token=create_token(user))
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def me(user: User = Depends(current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Журнал: поиск и фильтры, запись, настройки ротации, очистка с подтверждением пароля."""
|
||||
import ipaddress
|
||||
import uuid
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import String, cast, delete, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.db import get_db
|
||||
from app.models import AuditLog, ClearAttempt, User
|
||||
from app.rotation import get_settings, rotate, save_settings
|
||||
from app.security import admin_user, current_user, verify_password
|
||||
from app.services import audit, commit
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)], tags=["journal"])
|
||||
MAX_ATTEMPTS = 5
|
||||
LOCK_MINUTES = 10
|
||||
|
||||
|
||||
def _escape_like(q: str) -> str:
|
||||
return q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
|
||||
def _filtered(stmt, event_type: str, entity_type: str, actor: str, date_from: date | None, date_to: date | None, q: str, client_ip: str = ""):
|
||||
if event_type:
|
||||
et, _, action = event_type.partition(".")
|
||||
stmt = stmt.where(AuditLog.entity_type == et, AuditLog.action == action)
|
||||
if entity_type:
|
||||
stmt = stmt.where(AuditLog.entity_type == entity_type)
|
||||
if actor:
|
||||
stmt = stmt.where(AuditLog.username == actor.removeprefix("ui:"))
|
||||
if client_ip.strip():
|
||||
try:
|
||||
net = ipaddress.ip_network(client_ip.strip(), strict=False) # точный IP или подсеть
|
||||
except ValueError:
|
||||
raise HTTPException(422, "Некорректный IP-адрес или подсеть")
|
||||
stmt = stmt.where(AuditLog.client_ip.op("<<=")(str(net)))
|
||||
if date_from:
|
||||
stmt = stmt.where(AuditLog.ts >= datetime.combine(date_from, time.min, timezone.utc))
|
||||
if date_to:
|
||||
stmt = stmt.where(AuditLog.ts < datetime.combine(date_to + timedelta(days=1), time.min, timezone.utc))
|
||||
if q.strip():
|
||||
term = _escape_like(q.strip())
|
||||
like = f"%{term}%"
|
||||
uid_prefix = _escape_like(q.strip().removeprefix("evt_").lower()) + "%"
|
||||
stmt = stmt.where(or_(
|
||||
AuditLog.message.ilike(like, escape="\\"), AuditLog.entity_label.ilike(like, escape="\\"),
|
||||
cast(AuditLog.uid, String).ilike(uid_prefix, escape="\\"),
|
||||
func.host(AuditLog.client_ip).ilike(f"{term}%", escape="\\"),
|
||||
))
|
||||
return stmt
|
||||
|
||||
|
||||
@router.get("/audit", response_model=s.Page[s.AuditOut])
|
||||
def list_audit(
|
||||
event_type: str = "", entity_type: str = "", actor: str = "", date_from: date | None = None, date_to: date | None = None,
|
||||
q: str = "", client_ip: str = "", limit: int = Query(100, le=500), offset: int = 0, db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = _filtered(select(AuditLog), event_type, entity_type, actor, date_from, date_to, q, client_ip)
|
||||
total = db.scalar(select(func.count()).select_from(stmt.subquery())) or 0
|
||||
rows = db.scalars(stmt.order_by(AuditLog.id.desc()).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[s.AuditOut.from_row(r) for r in rows], total=total)
|
||||
|
||||
|
||||
class Summary(BaseModel):
|
||||
total: int
|
||||
oldest_ts: datetime | None
|
||||
retention_days: int
|
||||
max_entries: int
|
||||
|
||||
|
||||
@router.get("/audit/summary", response_model=Summary)
|
||||
def summary(db: Session = Depends(get_db)):
|
||||
cfg = get_settings(db)
|
||||
total, oldest = db.execute(select(func.count(), func.min(AuditLog.ts))).one()
|
||||
return Summary(total=total, oldest_ts=oldest, **cfg)
|
||||
|
||||
|
||||
class Facets(BaseModel):
|
||||
event_types: list[str]
|
||||
entity_types: list[str]
|
||||
actors: list[str]
|
||||
|
||||
|
||||
@router.get("/audit/facets", response_model=Facets)
|
||||
def facets(db: Session = Depends(get_db)):
|
||||
pairs = db.execute(select(AuditLog.entity_type, AuditLog.action).distinct().order_by(AuditLog.entity_type, AuditLog.action)).all()
|
||||
users = db.scalars(select(AuditLog.username).distinct().order_by(AuditLog.username)).all()
|
||||
return Facets(
|
||||
event_types=[f"{e}.{a}" for e, a in pairs], entity_types=sorted({e for e, _ in pairs}),
|
||||
actors=[u if u in ("system", "anonymous") else f"ui:{u}" for u in users],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/audit/{uid}", response_model=s.AuditOut)
|
||||
def get_entry(uid: uuid.UUID, db: Session = Depends(get_db)):
|
||||
row = db.scalar(select(AuditLog).where(AuditLog.uid == uid))
|
||||
if row is None:
|
||||
raise HTTPException(404, "Запись не найдена")
|
||||
return s.AuditOut.from_row(row)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- настройки
|
||||
class JournalSettings(BaseModel):
|
||||
retention_days: int = Field(ge=0, le=3650)
|
||||
max_entries: int = Field(ge=0, le=10_000_000)
|
||||
|
||||
|
||||
@router.get("/journal/settings", response_model=JournalSettings)
|
||||
def read_settings(db: Session = Depends(get_db)):
|
||||
return get_settings(db)
|
||||
|
||||
|
||||
class SettingsSaved(JournalSettings):
|
||||
deleted: int
|
||||
|
||||
|
||||
@router.put("/journal/settings", response_model=SettingsSaved)
|
||||
def update_settings(body: JournalSettings, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
old = get_settings(db)
|
||||
new = body.model_dump()
|
||||
save_settings(db, new)
|
||||
changed = {k: f"{old[k]} → {v}" for k, v in new.items() if old[k] != v}
|
||||
audit(db, user, "journal", None, "settings_updated", "settings", changed or None,
|
||||
message="Настройки журнала: " + ("; ".join(f"{k} {v}" for k, v in changed.items()) or "без изменений"))
|
||||
commit(db)
|
||||
result = rotate(db) or {"by_age": 0, "by_count": 0} # ротация сразу при сохранении
|
||||
return SettingsSaved(**new, deleted=result["by_age"] + result["by_count"])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- очистка
|
||||
class ClearIn(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
def _lock_state(db: Session, user_id: int) -> tuple[int, int]:
|
||||
"""(неудачных за окно, секунд до конца блокировки). Блокировка — LOCK_MINUTES после 5-й неудачи в пределах окна."""
|
||||
now = datetime.now(timezone.utc)
|
||||
last = db.scalars(select(ClearAttempt.ts).where(ClearAttempt.user_id == user_id).order_by(ClearAttempt.id.desc()).limit(MAX_ATTEMPTS)).all()
|
||||
window = timedelta(minutes=LOCK_MINUTES)
|
||||
in_window = sum(1 for ts in last if now - ts <= window)
|
||||
if len(last) == MAX_ATTEMPTS and last[0] - last[-1] <= window:
|
||||
remaining = (last[0] + window - now).total_seconds()
|
||||
if remaining > 0:
|
||||
return MAX_ATTEMPTS, int(remaining) + 1
|
||||
return in_window, 0
|
||||
|
||||
|
||||
@router.post("/journal/clear")
|
||||
def clear_journal(body: ClearIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
used, retry = _lock_state(db, user.id)
|
||||
if retry:
|
||||
raise HTTPException(429, {"message": "Слишком много неверных попыток", "retry_after_seconds": retry})
|
||||
if not verify_password(body.password, user.password_hash):
|
||||
db.add(ClearAttempt(user_id=user.id))
|
||||
db.commit()
|
||||
used, retry = _lock_state(db, user.id)
|
||||
if retry:
|
||||
raise HTTPException(429, {"message": "Слишком много неверных попыток", "retry_after_seconds": retry})
|
||||
raise HTTPException(403, {"message": "Неверный пароль", "attempts_left": MAX_ATTEMPTS - used})
|
||||
deleted = db.execute(delete(AuditLog)).rowcount
|
||||
db.execute(delete(ClearAttempt).where(ClearAttempt.user_id == user.id))
|
||||
audit(db, user, "journal", None, "cleared", "clear", {"deleted": deleted}, message=f"Журнал очищен: удалено записей {deleted}")
|
||||
commit(db)
|
||||
return {"deleted": deleted}
|
||||
@@ -0,0 +1,45 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.api.v1.prefixes import _prefix_outs
|
||||
from app.db import get_db
|
||||
from app.models import Address, AddressStatus, AuditLog, Prefix, PrefixStatus, Vrf
|
||||
from app.security import current_user
|
||||
from app.services import capacity, utilization
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)])
|
||||
|
||||
|
||||
class Overview(BaseModel):
|
||||
prefixes: int
|
||||
vrfs: int
|
||||
assigned: int
|
||||
capacity: int
|
||||
utilization: int
|
||||
reserved: int
|
||||
top_prefixes: list[s.PrefixOut]
|
||||
recent_changes: list[s.AuditOut]
|
||||
|
||||
|
||||
@router.get("/overview", response_model=Overview, tags=["overview"])
|
||||
def overview(db: Session = Depends(get_db)):
|
||||
prefixes = db.scalars(select(Prefix).where(Prefix.status == PrefixStatus.active)).all()
|
||||
outs = _prefix_outs(db, list(prefixes))
|
||||
parents = {p.parent_id for p in outs if p.parent_id}
|
||||
leaves = [p for p in outs if p.id not in parents] # ёмкость считаем по листьям, чтобы не удваивать
|
||||
leaves4 = [p for p in leaves if p.family == 4] # IPv6-пространство несопоставимо по размеру — в метрики использования не входит
|
||||
cap = sum(p.capacity for p in leaves4)
|
||||
v4 = func.family(Address.address) == 4
|
||||
assigned = db.scalar(select(func.count()).select_from(Address).where(Address.status == AddressStatus.assigned, v4)) or 0
|
||||
reserved = db.scalar(select(func.count()).select_from(Address).where(Address.status == AddressStatus.reserved, v4)) or 0
|
||||
top = sorted((p for p in leaves4 if p.capacity > 1), key=lambda p: p.utilization, reverse=True)[:4]
|
||||
recent = db.scalars(select(AuditLog).order_by(AuditLog.id.desc()).limit(4)).all()
|
||||
return Overview(
|
||||
prefixes=db.scalar(select(func.count()).select_from(Prefix)) or 0,
|
||||
vrfs=db.scalar(select(func.count()).select_from(Vrf)) or 0,
|
||||
assigned=assigned, capacity=cap, utilization=utilization(assigned, cap), reserved=reserved,
|
||||
top_prefixes=top, recent_changes=[s.AuditOut.from_row(r) for r in recent],
|
||||
)
|
||||
@@ -0,0 +1,329 @@
|
||||
import ipaddress
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import String, and_, cast, func, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.db import get_db
|
||||
from app.models import Address, AddressStatus, Device, Organization, Prefix, PrefixStatus, User, Vrf
|
||||
from app.security import admin_user, current_user
|
||||
from app.services import (
|
||||
MAX_CAPACITY, apply_update, audit, capacity, commit, count, flush, get_or_404, next_free, utilization,
|
||||
)
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)], tags=["prefixes"])
|
||||
FREE_LISTING_LIMIT = 4096 # «свободные» строки показываем, только если подсеть не больше /20
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- prefixes
|
||||
def _usage(db: Session, ids: list[int]) -> dict[int, tuple[int, int]]:
|
||||
"""{prefix_id: (assigned, stored)} с учётом вложенных префиксов того же VRF."""
|
||||
if not ids:
|
||||
return {}
|
||||
p, c = Prefix.__table__.alias("p"), Prefix.__table__.alias("c")
|
||||
a = Address.__table__
|
||||
rows = db.execute(
|
||||
select(
|
||||
p.c.id,
|
||||
func.count().filter(a.c.status == AddressStatus.assigned),
|
||||
func.count(a.c.id),
|
||||
)
|
||||
.select_from(p.join(c, and_(c.c.vrf_id == p.c.vrf_id, c.c.prefix.op("<<=")(p.c.prefix)))
|
||||
.join(a, a.c.prefix_id == c.c.id))
|
||||
.where(p.c.id.in_(ids))
|
||||
.group_by(p.c.id)
|
||||
).all()
|
||||
return {r[0]: (r[1], r[2]) for r in rows}
|
||||
|
||||
|
||||
def _depths(db: Session, organization_id: int) -> dict[int, int]:
|
||||
parents = dict(db.execute(select(Prefix.id, Prefix.parent_id).where(Prefix.organization_id == organization_id)).all())
|
||||
|
||||
def depth(i: int) -> int:
|
||||
d = 0
|
||||
while parents.get(i) is not None:
|
||||
i, d = parents[i], d + 1
|
||||
return d
|
||||
|
||||
return {i: depth(i) for i in parents}
|
||||
|
||||
|
||||
def _capacities(db: Session, organization_id: int) -> dict[int, int]:
|
||||
"""Ёмкость листа — размер подсети; ёмкость родителя — сумма ёмкостей вложенных листьев."""
|
||||
rows = db.execute(select(Prefix.id, Prefix.parent_id, Prefix.prefix).where(Prefix.organization_id == organization_id)).all()
|
||||
kids: dict[int, list[int]] = {}
|
||||
for i, parent, _ in rows:
|
||||
if parent is not None:
|
||||
kids.setdefault(parent, []).append(i)
|
||||
own = {i: capacity(str(cidr)) for i, _, cidr in rows}
|
||||
memo: dict[int, int] = {}
|
||||
|
||||
def cap(i: int) -> int:
|
||||
if i not in memo:
|
||||
memo[i] = sum(cap(k) for k in kids[i]) if i in kids else own[i]
|
||||
return memo[i]
|
||||
|
||||
return {i: min(cap(i), MAX_CAPACITY) for i in own}
|
||||
|
||||
|
||||
def _prefix_outs(db: Session, rows: list[Prefix]) -> list[s.PrefixOut]:
|
||||
usage = _usage(db, [r.id for r in rows])
|
||||
depths: dict[int, int] = {}
|
||||
caps: dict[int, int] = {}
|
||||
for org_id in {r.organization_id for r in rows}:
|
||||
depths.update(_depths(db, org_id))
|
||||
caps.update(_capacities(db, org_id))
|
||||
out = []
|
||||
for r in rows:
|
||||
used, stored = usage.get(r.id, (0, 0))
|
||||
cap = caps.get(r.id, capacity(str(r.prefix)))
|
||||
out.append(s.PrefixOut(
|
||||
id=r.id, organization_id=r.organization_id, vrf_id=r.vrf_id, vrf_name=r.vrf.name,
|
||||
prefix=str(r.prefix), family=ipaddress.ip_network(str(r.prefix)).version,
|
||||
description=r.description, status=r.status, parent_id=r.parent_id, depth=depths.get(r.id, 0),
|
||||
is_pool=r.is_pool, note=r.note, used=used, capacity=cap,
|
||||
utilization=utilization(used, cap), addresses_count=stored,
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
def attach_to_tree(db: Session, p: Prefix, keep_parent: bool = False, exclude: frozenset[int] = frozenset()) -> None:
|
||||
"""Вписывает префикс в дерево его VRF: находит самого узкого родителя и забирает под себя
|
||||
вложенные префиксы, чей текущий родитель шире (exclude — уже подчинённые ему, при переносе поддерева)."""
|
||||
cidr = str(p.prefix)
|
||||
if not keep_parent:
|
||||
p.parent_id = db.scalar(
|
||||
select(Prefix.id)
|
||||
.where(Prefix.vrf_id == p.vrf_id, Prefix.id != p.id, Prefix.prefix.op(">>")(cidr))
|
||||
.order_by(func.masklen(Prefix.prefix).desc()).limit(1)
|
||||
)
|
||||
plen = ipaddress.ip_network(cidr).prefixlen
|
||||
inner = db.scalars(
|
||||
select(Prefix).where(Prefix.vrf_id == p.vrf_id, Prefix.id != p.id, Prefix.prefix.op("<<")(cidr))
|
||||
).all()
|
||||
for c in inner:
|
||||
if c.id in exclude:
|
||||
continue
|
||||
cur = db.get(Prefix, c.parent_id) if c.parent_id else None
|
||||
if cur is None or ipaddress.ip_network(str(cur.prefix)).prefixlen < plen:
|
||||
c.parent_id = p.id
|
||||
|
||||
|
||||
def _subtree(db: Session, root: Prefix) -> list[Prefix]:
|
||||
"""Префикс и все вложенные по цепочке parent_id."""
|
||||
result, frontier = [root], [root.id]
|
||||
while frontier:
|
||||
kids = db.scalars(select(Prefix).where(Prefix.parent_id.in_(frontier))).all()
|
||||
result += kids
|
||||
frontier = [k.id for k in kids]
|
||||
return result
|
||||
|
||||
|
||||
def _move_to_vrf(db: Session, p: Prefix, vrf_id: int) -> tuple[dict, int]:
|
||||
"""Переносит префикс с поддеревом в другой VRF той же организации; возвращает (diff, число префиксов)."""
|
||||
vrf = get_or_404(db, Vrf, vrf_id, "VRF")
|
||||
if vrf.organization_id != p.organization_id:
|
||||
raise HTTPException(422, "Целевой VRF принадлежит другой организации")
|
||||
subtree = _subtree(db, p)
|
||||
taken = db.scalars(select(Prefix.prefix).where(Prefix.vrf_id == vrf.id, Prefix.prefix.in_([str(m.prefix) for m in subtree]))).all()
|
||||
if taken:
|
||||
raise HTTPException(409, f"В VRF «{vrf.name}» уже есть: {', '.join(str(x) for x in taken)}")
|
||||
old_name = p.vrf.name
|
||||
for m in subtree:
|
||||
m.vrf = vrf
|
||||
p.parent_id = None
|
||||
db.flush()
|
||||
attach_to_tree(db, p, exclude=frozenset(m.id for m in subtree))
|
||||
return {"vrf": f"{old_name} → {vrf.name}", "moved": len(subtree)}, len(subtree)
|
||||
|
||||
|
||||
@router.get("/prefixes", response_model=s.Page[s.PrefixOut])
|
||||
def list_prefixes(
|
||||
organization_id: int | None = None, vrf_id: int | None = None, status: PrefixStatus | None = None,
|
||||
family: int | None = Query(None, ge=4, le=6), q: str = "",
|
||||
limit: int = Query(100, le=1000), offset: int = 0, db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = select(Prefix)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Prefix.organization_id == organization_id)
|
||||
if vrf_id:
|
||||
stmt = stmt.where(Prefix.vrf_id == vrf_id)
|
||||
if status:
|
||||
stmt = stmt.where(Prefix.status == status)
|
||||
if family:
|
||||
stmt = stmt.where(func.family(Prefix.prefix) == (4 if family == 4 else 6))
|
||||
if q:
|
||||
stmt = stmt.where(or_(cast(Prefix.prefix, String).ilike(f"%{q.strip()}%"), Prefix.description.ilike(f"%{q.strip()}%")))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Prefix.vrf_id, Prefix.prefix).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=_prefix_outs(db, list(rows)), total=total)
|
||||
|
||||
|
||||
@router.get("/prefixes/{id}", response_model=s.PrefixOut)
|
||||
def get_prefix(id: int, db: Session = Depends(get_db)):
|
||||
return _prefix_outs(db, [get_or_404(db, Prefix, id, "Префикс")])[0]
|
||||
|
||||
|
||||
@router.post("/prefixes", response_model=s.PrefixOut, status_code=201)
|
||||
def create_prefix(body: s.PrefixIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
vrf = get_or_404(db, Vrf, body.vrf_id, "VRF")
|
||||
if vrf.organization_id != body.organization_id:
|
||||
raise HTTPException(422, "VRF принадлежит другой организации")
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
if db.scalar(select(Prefix.id).where(Prefix.vrf_id == vrf.id, Prefix.prefix == body.prefix)):
|
||||
raise HTTPException(409, "Такой префикс уже есть в этом VRF")
|
||||
|
||||
parent_id = body.parent_id
|
||||
if parent_id is not None:
|
||||
parent = get_or_404(db, Prefix, parent_id, "Родительский префикс")
|
||||
if parent.vrf_id != vrf.id or not ipaddress.ip_network(body.prefix).subnet_of(ipaddress.ip_network(str(parent.prefix))):
|
||||
raise HTTPException(422, "Родительский префикс должен содержать новый и быть в том же VRF")
|
||||
p = Prefix(**{**body.model_dump(), "parent_id": parent_id})
|
||||
db.add(p)
|
||||
flush(db, "Такой префикс уже есть в этом VRF")
|
||||
attach_to_tree(db, p, keep_parent=parent_id is not None)
|
||||
audit(db, user, "prefix", p, "created", str(p.prefix), {"vrf": vrf.name})
|
||||
commit(db, "Такой префикс уже есть в этом VRF")
|
||||
return _prefix_outs(db, [p])[0]
|
||||
|
||||
|
||||
@router.patch("/prefixes/{id}", response_model=s.PrefixOut)
|
||||
def update_prefix(id: int, body: s.PrefixUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
data = body.model_dump(exclude_unset=True, exclude_none=True)
|
||||
new_vrf = data.pop("vrf_id", None)
|
||||
changed = {k: str(v) for k, v in apply_update(p, data).items()}
|
||||
if new_vrf is not None and new_vrf != p.vrf_id:
|
||||
changed.update(_move_to_vrf(db, p, new_vrf)[0])
|
||||
audit(db, user, "prefix", p, "updated", str(p.prefix), changed)
|
||||
commit(db)
|
||||
return _prefix_outs(db, [p])[0]
|
||||
|
||||
|
||||
@router.delete("/prefixes/{id}", status_code=204)
|
||||
def delete_prefix(id: int, force: bool = False, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
if not force and count(db, select(Address.id).where(Address.prefix_id == id)):
|
||||
raise HTTPException(409, "В префиксе есть адреса; удалите их или используйте force=true")
|
||||
db.execute(update(Prefix).where(Prefix.parent_id == id).values(parent_id=p.parent_id))
|
||||
audit(db, user, "prefix", p, "deleted", str(p.prefix))
|
||||
db.delete(p)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- addresses
|
||||
def _addr_out(a: Address, device_name: str | None = None) -> s.AddressOut:
|
||||
return s.AddressOut(
|
||||
id=a.id, prefix_id=a.prefix_id, address=s.ip_text(a.address), status=a.status.value,
|
||||
dns_name=a.dns_name, description=a.description, device_id=a.device_id, device_name=device_name,
|
||||
note=a.note, updated_at=a.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _check_device(db: Session, prefix: Prefix, device_id: int | None):
|
||||
if device_id is not None:
|
||||
d = get_or_404(db, Device, device_id, "Устройство")
|
||||
if d.organization_id != prefix.organization_id:
|
||||
raise HTTPException(422, "Устройство принадлежит другой организации")
|
||||
|
||||
|
||||
@router.get("/prefixes/{id}/addresses", response_model=s.AddressPage)
|
||||
def list_addresses(
|
||||
id: int, status: str = "", q: str = "", limit: int = Query(100, le=500), offset: int = 0,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""status: assigned | reserved | deprecated | free | пусто (все; свободные подмешиваются для малых подсетей)."""
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
cap = capacity(str(p.prefix))
|
||||
counts = dict(db.execute(select(Address.status, func.count()).where(Address.prefix_id == id).group_by(Address.status)).all())
|
||||
stored = sum(counts.values())
|
||||
summary = s.AddressSummary(
|
||||
assigned=counts.get(AddressStatus.assigned, 0), reserved=counts.get(AddressStatus.reserved, 0),
|
||||
deprecated=counts.get(AddressStatus.deprecated, 0), free=max(cap - stored, 0), capacity=cap,
|
||||
)
|
||||
if status and status not in {"free", *(x.value for x in AddressStatus)}:
|
||||
raise HTTPException(422, "Неизвестный статус")
|
||||
|
||||
stmt = select(Address, Device.name).outerjoin(Device, Device.id == Address.device_id).where(Address.prefix_id == id)
|
||||
if status and status != "free":
|
||||
stmt = stmt.where(Address.status == AddressStatus(status))
|
||||
if q:
|
||||
like = f"%{q.strip()}%"
|
||||
stmt = stmt.where(or_(func.host(Address.address).ilike(like), Address.dns_name.ilike(like), Address.description.ilike(like)))
|
||||
rows = [_addr_out(a, dn) for a, dn in db.execute(stmt.order_by(Address.address)).all()] if status != "free" else []
|
||||
|
||||
net = ipaddress.ip_network(str(p.prefix))
|
||||
want_free = status == "free" or (not status and not q and cap <= FREE_LISTING_LIMIT)
|
||||
if want_free:
|
||||
used = {ipaddress.ip_address(s.ip_text(a)) for a in db.scalars(select(Address.address).where(Address.prefix_id == id))}
|
||||
hosts = net.hosts() if net.version == 4 and net.prefixlen <= 30 else iter(net)
|
||||
need = offset + limit if status == "free" else cap
|
||||
free = []
|
||||
for ip in hosts:
|
||||
if ip not in used:
|
||||
free.append(s.AddressOut(id=None, prefix_id=id, address=str(ip), status="free"))
|
||||
if len(free) >= need:
|
||||
break
|
||||
rows = sorted(rows + free, key=lambda r: ipaddress.ip_address(r.address))
|
||||
total = summary.free if status == "free" else (len(rows) if want_free or q or status else stored)
|
||||
return s.AddressPage(items=rows[offset:offset + limit], total=total, summary=summary)
|
||||
|
||||
|
||||
@router.post("/prefixes/{id}/addresses", response_model=s.AddressOut, status_code=201)
|
||||
def create_address(id: int, body: s.AddressIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
if ipaddress.ip_address(body.address) not in ipaddress.ip_network(str(p.prefix)):
|
||||
raise HTTPException(422, f"Адрес {body.address} не принадлежит префиксу {p.prefix}")
|
||||
_check_device(db, p, body.device_id)
|
||||
a = Address(prefix_id=id, **body.model_dump())
|
||||
db.add(a)
|
||||
flush(db, "Адрес уже есть в этом префиксе")
|
||||
audit(db, user, "address", a, "assigned" if a.status == AddressStatus.assigned else "created", body.address)
|
||||
commit(db, "Адрес уже есть в этом префиксе")
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
|
||||
|
||||
@router.post("/prefixes/{id}/addresses/next", response_model=s.AddressOut, status_code=201)
|
||||
def allocate_next(
|
||||
id: int, body: s.AddressUpdate | None = None, db: Session = Depends(get_db), user: User = Depends(admin_user)
|
||||
):
|
||||
"""Автоназначение первого свободного адреса; только для префиксов с флагом is_pool."""
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
if not p.is_pool:
|
||||
raise HTTPException(422, "Префикс не является пулом для автоназначения")
|
||||
ip = next_free(db, id, str(p.prefix))
|
||||
if ip is None:
|
||||
raise HTTPException(409, "В префиксе нет свободных адресов")
|
||||
data = body.model_dump(exclude_unset=True, exclude_none=True) if body else {}
|
||||
_check_device(db, p, data.get("device_id"))
|
||||
a = Address(prefix_id=id, address=ip, **data)
|
||||
db.add(a)
|
||||
flush(db, "Адрес уже занят, повторите запрос")
|
||||
audit(db, user, "address", a, "assigned", ip)
|
||||
commit(db, "Адрес уже занят, повторите запрос")
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
|
||||
|
||||
@router.patch("/addresses/{id}", response_model=s.AddressOut)
|
||||
def update_address(id: int, body: s.AddressUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
a = get_or_404(db, Address, id, "Адрес")
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if data.get("dns_name"):
|
||||
s.AddressIn(address=s.ip_text(a.address), dns_name=data["dns_name"]) # валидация FQDN
|
||||
_check_device(db, db.get(Prefix, a.prefix_id), data.get("device_id"))
|
||||
changed = apply_update(a, data)
|
||||
audit(db, user, "address", a, "updated", s.ip_text(a.address), {k: str(v) for k, v in changed.items()})
|
||||
commit(db)
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
|
||||
|
||||
@router.delete("/addresses/{id}", status_code=204)
|
||||
def delete_address(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
a = get_or_404(db, Address, id, "Адрес")
|
||||
audit(db, user, "address", a, "deleted", s.ip_text(a.address))
|
||||
db.delete(a)
|
||||
commit(db)
|
||||
@@ -0,0 +1,298 @@
|
||||
"""Справочники: организации, VRF, операторы, типы устройств, устройства."""
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import String, cast, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.db import get_db
|
||||
from app.models import (
|
||||
Address, AddressStatus, Device, DeviceType, Isp, IspNetwork, Organization, Prefix, User, Vrf,
|
||||
)
|
||||
from app.security import admin_user, current_user
|
||||
from app.services import apply_update, audit, commit, count, flush, get_or_404
|
||||
from fastapi import HTTPException
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)])
|
||||
|
||||
|
||||
def _like(q: str) -> str:
|
||||
return f"%{q.strip()}%"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- organizations
|
||||
def _org_out(db: Session, o: Organization) -> s.OrgOut:
|
||||
out = s.OrgOut.model_validate(o)
|
||||
out.prefixes_count = count(db, select(Prefix.id).where(Prefix.organization_id == o.id))
|
||||
out.addresses_count = count(
|
||||
db, select(Address.id).join(Prefix).where(Prefix.organization_id == o.id, Address.status == AddressStatus.assigned)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/organizations", response_model=s.Page[s.OrgOut], tags=["organizations"])
|
||||
def list_orgs(q: str = "", limit: int = Query(100, le=500), offset: int = 0, db: Session = Depends(get_db)):
|
||||
stmt = select(Organization)
|
||||
if q:
|
||||
stmt = stmt.where(or_(*(c.ilike(_like(q)) for c in (Organization.name, Organization.short_name, Organization.inn, Organization.address))))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Organization.id).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[_org_out(db, o) for o in rows], total=total)
|
||||
|
||||
|
||||
@router.get("/organizations/{id}", response_model=s.OrgOut, tags=["organizations"])
|
||||
def get_org(id: int, db: Session = Depends(get_db)):
|
||||
return _org_out(db, get_or_404(db, Organization, id, "Организация"))
|
||||
|
||||
|
||||
@router.post("/organizations", response_model=s.OrgOut, status_code=201, tags=["organizations"])
|
||||
def create_org(body: s.OrgIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
o = Organization(**body.model_dump())
|
||||
db.add(o)
|
||||
flush(db, "Организация с таким названием или ИНН уже существует")
|
||||
db.add(Vrf(organization_id=o.id, name="default"))
|
||||
audit(db, user, "organization", o, "created", o.name)
|
||||
commit(db, "Организация с таким названием или ИНН уже существует")
|
||||
return _org_out(db, o)
|
||||
|
||||
|
||||
@router.patch("/organizations/{id}", response_model=s.OrgOut, tags=["organizations"])
|
||||
def update_org(id: int, body: s.OrgIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
o = get_or_404(db, Organization, id, "Организация")
|
||||
changed = apply_update(o, body.model_dump())
|
||||
audit(db, user, "organization", o, "updated", o.name, changed)
|
||||
commit(db, "Организация с таким названием или ИНН уже существует")
|
||||
return _org_out(db, o)
|
||||
|
||||
|
||||
@router.delete("/organizations/{id}", status_code=204, tags=["organizations"])
|
||||
def delete_org(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
o = get_or_404(db, Organization, id, "Организация")
|
||||
busy = count(db, select(Prefix.id).where(Prefix.organization_id == id)) or count(
|
||||
db, select(Device.id).where(Device.organization_id == id)) or count(db, select(Isp.id).where(Isp.organization_id == id))
|
||||
if busy:
|
||||
raise HTTPException(409, "Нельзя удалить: у организации есть префиксы, устройства или операторы")
|
||||
for v in db.scalars(select(Vrf).where(Vrf.organization_id == id)):
|
||||
db.delete(v)
|
||||
audit(db, user, "organization", o, "deleted", o.name)
|
||||
db.delete(o)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------- VRF
|
||||
def _vrf_out(db: Session, v: Vrf) -> s.VrfOut:
|
||||
out = s.VrfOut.model_validate(v)
|
||||
out.prefixes_count = count(db, select(Prefix.id).where(Prefix.vrf_id == v.id))
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/vrfs", response_model=s.Page[s.VrfOut], tags=["vrf"])
|
||||
def list_vrfs(organization_id: int | None = None, db: Session = Depends(get_db)):
|
||||
stmt = select(Vrf)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Vrf.organization_id == organization_id)
|
||||
rows = db.scalars(stmt.order_by(Vrf.id)).all()
|
||||
return s.Page(items=[_vrf_out(db, v) for v in rows], total=len(rows))
|
||||
|
||||
|
||||
@router.post("/vrfs", response_model=s.VrfOut, status_code=201, tags=["vrf"])
|
||||
def create_vrf(body: s.VrfIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
v = Vrf(**body.model_dump())
|
||||
db.add(v)
|
||||
flush(db, "VRF с таким названием уже есть в организации")
|
||||
audit(db, user, "vrf", v, "created", v.name)
|
||||
commit(db, "VRF с таким названием уже есть в организации")
|
||||
return _vrf_out(db, v)
|
||||
|
||||
|
||||
@router.patch("/vrfs/{id}", response_model=s.VrfOut, tags=["vrf"])
|
||||
def update_vrf(id: int, body: s.VrfUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
v = get_or_404(db, Vrf, id, "VRF")
|
||||
changed = apply_update(v, body.model_dump(exclude_unset=True, exclude_none=True))
|
||||
audit(db, user, "vrf", v, "updated", v.name, changed)
|
||||
commit(db, "VRF с таким названием уже есть в организации")
|
||||
return _vrf_out(db, v)
|
||||
|
||||
|
||||
@router.delete("/vrfs/{id}", status_code=204, tags=["vrf"])
|
||||
def delete_vrf(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
v = get_or_404(db, Vrf, id, "VRF")
|
||||
if count(db, select(Prefix.id).where(Prefix.vrf_id == id)):
|
||||
raise HTTPException(409, "Нельзя удалить: VRF используется префиксами")
|
||||
audit(db, user, "vrf", v, "deleted", v.name)
|
||||
db.delete(v)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- device types
|
||||
def _type_out(db: Session, t: DeviceType) -> s.DeviceTypeOut:
|
||||
out = s.DeviceTypeOut.model_validate(t)
|
||||
out.devices_count = count(db, select(Device.id).where(Device.device_type_id == t.id))
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/device-types", response_model=s.Page[s.DeviceTypeOut], tags=["devices"])
|
||||
def list_types(db: Session = Depends(get_db)):
|
||||
rows = db.scalars(select(DeviceType).order_by(DeviceType.id)).all()
|
||||
return s.Page(items=[_type_out(db, t) for t in rows], total=len(rows))
|
||||
|
||||
|
||||
@router.post("/device-types", response_model=s.DeviceTypeOut, status_code=201, tags=["devices"])
|
||||
def create_type(body: s.DeviceTypeIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
t = DeviceType(name=body.name)
|
||||
db.add(t)
|
||||
flush(db, "Тип с таким названием уже существует")
|
||||
audit(db, user, "device_type", t, "created", t.name)
|
||||
commit(db, "Тип с таким названием уже существует")
|
||||
return _type_out(db, t)
|
||||
|
||||
|
||||
@router.patch("/device-types/{id}", response_model=s.DeviceTypeOut, tags=["devices"])
|
||||
def update_type(id: int, body: s.DeviceTypeIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
t = get_or_404(db, DeviceType, id, "Тип")
|
||||
changed = apply_update(t, {"name": body.name})
|
||||
audit(db, user, "device_type", t, "updated", t.name, changed)
|
||||
commit(db, "Тип с таким названием уже существует")
|
||||
return _type_out(db, t)
|
||||
|
||||
|
||||
@router.delete("/device-types/{id}", status_code=204, tags=["devices"])
|
||||
def delete_type(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
t = get_or_404(db, DeviceType, id, "Тип")
|
||||
if t.is_default:
|
||||
raise HTTPException(409, "Нельзя удалить тип по умолчанию")
|
||||
if count(db, select(Device.id).where(Device.device_type_id == id)):
|
||||
raise HTTPException(409, "Нельзя удалить: тип используется устройствами")
|
||||
audit(db, user, "device_type", t, "deleted", t.name)
|
||||
db.delete(t)
|
||||
commit(db)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- devices
|
||||
def _device_out(db: Session, d: Device) -> s.DeviceOut:
|
||||
rows = db.execute(
|
||||
select(Address.address, Address.prefix_id, Address.status).where(Address.device_id == d.id).order_by(Address.address)
|
||||
).all()
|
||||
t = db.get(DeviceType, d.device_type_id)
|
||||
return s.DeviceOut(
|
||||
id=d.id, name=d.name, device_type_id=d.device_type_id, device_type_name=t.name,
|
||||
organization_id=d.organization_id, mac=d.mac, note=d.note,
|
||||
ip_addresses=[s.ip_text(r[0]) for r in rows], first_prefix_id=rows[0][1] if rows else None,
|
||||
all_deprecated=bool(rows) and all(r[2] == AddressStatus.deprecated for r in rows),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/devices", response_model=s.Page[s.DeviceOut], tags=["devices"])
|
||||
def list_devices(
|
||||
organization_id: int | None = None, device_type_id: int | None = None, q: str = "",
|
||||
limit: int = Query(100, le=500), offset: int = 0, db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = select(Device)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Device.organization_id == organization_id)
|
||||
if device_type_id:
|
||||
stmt = stmt.where(Device.device_type_id == device_type_id)
|
||||
if q:
|
||||
ip_match = select(Address.device_id).where(func.host(Address.address).ilike(_like(q)))
|
||||
stmt = stmt.where(or_(Device.name.ilike(_like(q)), Device.note.ilike(_like(q)), Device.id.in_(ip_match)))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Device.id).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[_device_out(db, d) for d in rows], total=total)
|
||||
|
||||
|
||||
@router.post("/devices", response_model=s.DeviceOut, status_code=201, tags=["devices"])
|
||||
def create_device(body: s.DeviceIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
get_or_404(db, DeviceType, body.device_type_id, "Тип")
|
||||
d = Device(**body.model_dump())
|
||||
db.add(d)
|
||||
flush(db, "Устройство с таким именем уже есть в организации")
|
||||
audit(db, user, "device", d, "created", d.name)
|
||||
commit(db, "Устройство с таким именем уже есть в организации")
|
||||
return _device_out(db, d)
|
||||
|
||||
|
||||
@router.get("/devices/{id}", response_model=s.DeviceOut, tags=["devices"])
|
||||
def get_device(id: int, db: Session = Depends(get_db)):
|
||||
return _device_out(db, get_or_404(db, Device, id, "Устройство"))
|
||||
|
||||
|
||||
@router.patch("/devices/{id}", response_model=s.DeviceOut, tags=["devices"])
|
||||
def update_device(id: int, body: s.DeviceUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
d = get_or_404(db, Device, id, "Устройство")
|
||||
data = body.model_dump(exclude_unset=True, exclude_none=True)
|
||||
if "device_type_id" in data:
|
||||
get_or_404(db, DeviceType, data["device_type_id"], "Тип")
|
||||
changed = apply_update(d, data)
|
||||
audit(db, user, "device", d, "updated", d.name, changed)
|
||||
commit(db, "Устройство с таким именем уже есть в организации")
|
||||
return _device_out(db, d)
|
||||
|
||||
|
||||
@router.delete("/devices/{id}", status_code=204, tags=["devices"])
|
||||
def delete_device(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
d = get_or_404(db, Device, id, "Устройство")
|
||||
audit(db, user, "device", d, "deleted", d.name)
|
||||
db.delete(d)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------ ISPs
|
||||
def _isp_out(db: Session, i: Isp) -> s.IspOut:
|
||||
org = db.get(Organization, i.organization_id)
|
||||
return s.IspOut(
|
||||
id=i.id, name=i.name, organization_id=i.organization_id, organization_name=org.name,
|
||||
networks=[str(n.cidr) for n in i.networks], hotline=i.hotline,
|
||||
contract_number=i.contract_number, note=i.note,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/isps", response_model=s.Page[s.IspOut], tags=["isps"])
|
||||
def list_isps(
|
||||
organization_id: int | None = None, q: str = "", limit: int = Query(100, le=500), offset: int = 0,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = select(Isp)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Isp.organization_id == organization_id)
|
||||
if q:
|
||||
nets = select(IspNetwork.isp_id).where(cast(IspNetwork.cidr, String).ilike(_like(q)))
|
||||
orgs = select(Organization.id).where(Organization.name.ilike(_like(q)))
|
||||
stmt = stmt.where(or_(Isp.name.ilike(_like(q)), Isp.id.in_(nets), Isp.organization_id.in_(orgs)))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Isp.id).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[_isp_out(db, i) for i in rows], total=total)
|
||||
|
||||
|
||||
@router.post("/isps", response_model=s.IspOut, status_code=201, tags=["isps"])
|
||||
def create_isp(body: s.IspIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
data = body.model_dump()
|
||||
nets = data.pop("networks")
|
||||
i = Isp(**data, networks=[IspNetwork(cidr=n) for n in nets])
|
||||
db.add(i)
|
||||
db.flush()
|
||||
audit(db, user, "isp", i, "created", i.name)
|
||||
commit(db)
|
||||
return _isp_out(db, i)
|
||||
|
||||
|
||||
@router.put("/isps/{id}", response_model=s.IspOut, tags=["isps"])
|
||||
def update_isp(id: int, body: s.IspIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
i = get_or_404(db, Isp, id, "Оператор")
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
data = body.model_dump()
|
||||
nets = data.pop("networks")
|
||||
changed = apply_update(i, data)
|
||||
i.networks = [IspNetwork(cidr=n) for n in nets]
|
||||
audit(db, user, "isp", i, "updated", i.name, changed)
|
||||
commit(db)
|
||||
return _isp_out(db, i)
|
||||
|
||||
|
||||
@router.delete("/isps/{id}", status_code=204, tags=["isps"])
|
||||
def delete_isp(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
i = get_or_404(db, Isp, id, "Оператор")
|
||||
audit(db, user, "isp", i, "deleted", i.name)
|
||||
db.delete(i)
|
||||
commit(db)
|
||||
Reference in new issue
Block a user