90 lines
3.4 KiB
Python
90 lines
3.4 KiB
Python
"""Flask-бэкенд визуализатора маршрутов Remnawave."""
|
|
from __future__ import annotations
|
|
|
|
import hmac
|
|
import logging
|
|
from datetime import datetime, timezone
|
|
from types import SimpleNamespace
|
|
|
|
from flask import Flask, abort, jsonify, request, send_from_directory
|
|
|
|
from .cache import SnapshotCache
|
|
from .config import Settings
|
|
from .positions import PositionStore
|
|
from .remnawave import RemnawaveClient
|
|
from .routes import bp
|
|
|
|
|
|
def create_app(settings: Settings | None = None, client=None) -> Flask:
|
|
settings = settings or Settings.from_env()
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
if client is None:
|
|
client = RemnawaveClient(settings.remnawave_url, settings.remnawave_token,
|
|
settings.http_timeout, settings.verify_tls, settings.extra_headers)
|
|
|
|
def load():
|
|
data = client.fetch_all()
|
|
data["fetchedAt"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
return data
|
|
|
|
app = Flask(__name__)
|
|
app.json.ensure_ascii = False
|
|
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
|
|
app.extensions["rwviz"] = SimpleNamespace(
|
|
settings=settings,
|
|
cache=SnapshotCache(load, settings.cache_ttl),
|
|
positions=PositionStore(settings.data_dir / "positions.json"),
|
|
)
|
|
app.register_blueprint(bp)
|
|
|
|
if settings.basic_user and settings.basic_password:
|
|
want_user, want_pass = settings.basic_user, settings.basic_password
|
|
|
|
@app.before_request
|
|
def _auth():
|
|
if request.method == "OPTIONS" or request.path == "/api/health":
|
|
return None
|
|
a = request.authorization
|
|
ok = (a is not None
|
|
and hmac.compare_digest(a.username or "", want_user)
|
|
and hmac.compare_digest(a.password or "", want_pass))
|
|
if not ok:
|
|
return jsonify(error="unauthorized", message="Нужна авторизация"), 401, {
|
|
"WWW-Authenticate": 'Basic realm="rw-viz"'}
|
|
return None
|
|
else:
|
|
logging.getLogger(__name__).warning(
|
|
"BASIC_AUTH_USER/PASSWORD не заданы: API открыт всем, кто достанет до порта")
|
|
|
|
if settings.cors_origins:
|
|
@app.after_request
|
|
def _cors(resp):
|
|
origin = request.headers.get("Origin")
|
|
if origin in settings.cors_origins:
|
|
resp.headers["Access-Control-Allow-Origin"] = origin
|
|
resp.headers["Vary"] = "Origin"
|
|
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
|
|
resp.headers["Access-Control-Allow-Methods"] = "GET, PUT, DELETE, OPTIONS"
|
|
return resp
|
|
|
|
dist = settings.frontend_dist
|
|
if dist and dist.is_dir():
|
|
@app.get("/", defaults={"path": ""})
|
|
@app.get("/<path:path>")
|
|
def _spa(path: str):
|
|
if path.startswith("api/"):
|
|
abort(404)
|
|
if path and (dist / path).is_file():
|
|
return send_from_directory(dist, path)
|
|
return send_from_directory(dist, "index.html")
|
|
|
|
@app.errorhandler(404)
|
|
def _404(_e):
|
|
return jsonify(error="not_found", message="Не найдено"), 404
|
|
|
|
@app.errorhandler(413)
|
|
def _413(_e):
|
|
return jsonify(error="too_large", message="Слишком большое тело запроса"), 413
|
|
|
|
return app
|