146 lines
5.1 KiB
Python
146 lines
5.1 KiB
Python
import json
|
|
import os
|
|
import secrets
|
|
from datetime import timedelta
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
import sentry_sdk
|
|
from flask import Flask, abort, g, redirect, request, session, url_for
|
|
from werkzeug.security import generate_password_hash
|
|
|
|
from .db import get_db, init_db, now
|
|
|
|
|
|
def create_app(config=None):
|
|
app = Flask(__name__)
|
|
app.config.update(
|
|
DATABASE=os.getenv("DATABASE_PATH", "data/hunter.sqlite3"),
|
|
SECRET_KEY=os.getenv("SECRET_KEY"),
|
|
SESSION_COOKIE_HTTPONLY=True,
|
|
SESSION_COOKIE_SAMESITE="Lax",
|
|
SESSION_COOKIE_SECURE=os.getenv("COOKIE_SECURE", "0") == "1",
|
|
PERMANENT_SESSION_LIFETIME=timedelta(hours=12),
|
|
MAX_CONTENT_LENGTH=100_000,
|
|
PUBLIC_SENTRY_DSN=os.getenv("PUBLIC_SENTRY_DSN", ""),
|
|
)
|
|
if config:
|
|
app.config.update(config)
|
|
if not app.config["SECRET_KEY"]:
|
|
if os.getenv("APP_ENV") == "production":
|
|
raise RuntimeError("SECRET_KEY is required in production")
|
|
# Stable local-only secret; excluded from git along with the database.
|
|
secret_path = Path(app.config["DATABASE"]).parent / ".session-secret"
|
|
secret_path.parent.mkdir(parents=True, exist_ok=True)
|
|
try:
|
|
fd = os.open(secret_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
except FileExistsError:
|
|
pass
|
|
else:
|
|
with os.fdopen(fd, "w") as output:
|
|
output.write(secrets.token_hex(32))
|
|
app.config["SECRET_KEY"] = secret_path.read_text()
|
|
init_db(app.config["DATABASE"])
|
|
if os.getenv("SENTRY_DSN"):
|
|
sentry_sdk.init(
|
|
dsn=os.environ["SENTRY_DSN"],
|
|
release=os.getenv("SENTRY_RELEASE"),
|
|
environment=os.getenv("SENTRY_ENVIRONMENT", "dev"),
|
|
send_default_pii=False,
|
|
include_local_variables=False,
|
|
before_send=scrub_event,
|
|
)
|
|
locales = {
|
|
code: json.loads((Path(__file__).parent / "locales" / f"{code}.json").read_text())
|
|
for code in ("ru", "kk", "en")
|
|
}
|
|
|
|
@app.before_request
|
|
def prepare():
|
|
g.lang = session.get("lang", "ru")
|
|
g.t = lambda key: locales[g.lang].get(key, key)
|
|
g.user = (
|
|
get_db()
|
|
.execute("SELECT id,email,role FROM users WHERE id=?", (session.get("user_id"),))
|
|
.fetchone()
|
|
)
|
|
session.setdefault("csrf", secrets.token_urlsafe(32))
|
|
if request.method == "POST":
|
|
if not secrets.compare_digest(session["csrf"], request.form.get("csrf", "")):
|
|
abort(400)
|
|
if (
|
|
request.endpoint
|
|
not in ("web.login", "web.register", "web.health", "static", "web.language")
|
|
and not g.user
|
|
):
|
|
return redirect(url_for("web.login"))
|
|
|
|
@app.context_processor
|
|
def shared():
|
|
return dict(
|
|
t=g.t,
|
|
lang=g.lang,
|
|
user=g.user,
|
|
csrf=session.get("csrf"),
|
|
ai_ready=bool(os.getenv("AI_API_KEY")),
|
|
brand="AI Trend Hunter",
|
|
public_sentry_dsn=app.config["PUBLIC_SENTRY_DSN"],
|
|
sentry_release=os.getenv("SENTRY_RELEASE", ""),
|
|
sentry_environment=os.getenv("SENTRY_ENVIRONMENT", "dev"),
|
|
)
|
|
|
|
@app.teardown_appcontext
|
|
def close(_error):
|
|
db = g.pop("db", None)
|
|
if db:
|
|
db.close()
|
|
|
|
@app.after_request
|
|
def headers(response):
|
|
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
response.headers["X-Frame-Options"] = "DENY"
|
|
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
|
|
dsn = urlsplit(app.config["PUBLIC_SENTRY_DSN"])
|
|
sentry_origin = f"https://{dsn.hostname}" if dsn.scheme == "https" and dsn.hostname else ""
|
|
response.headers["Content-Security-Policy"] = (
|
|
"default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; "
|
|
"frame-ancestors 'none'; form-action 'self'; connect-src 'self' " + sentry_origin
|
|
)
|
|
response.headers["Cache-Control"] = "no-store"
|
|
return response
|
|
|
|
from .web import bp
|
|
|
|
app.register_blueprint(bp)
|
|
|
|
@app.cli.command("create-admin")
|
|
def create_admin():
|
|
import click
|
|
|
|
email = click.prompt("Email").strip().lower()
|
|
password = click.prompt("Password", hide_input=True, confirmation_prompt=True)
|
|
if len(password) < 12 or "@" not in email:
|
|
raise click.ClickException("Use an email and a password of at least 12 characters")
|
|
with get_db() as db:
|
|
db.execute(
|
|
"INSERT INTO users(email,password,role,created) VALUES(?,?,?,?)",
|
|
(email, generate_password_hash(password), "admin", now()),
|
|
)
|
|
click.echo("Administrator created")
|
|
|
|
@app.cli.command("collect")
|
|
def collect_command():
|
|
from .monitor import collect
|
|
|
|
print(json.dumps(collect(app.config["DATABASE"])))
|
|
|
|
return app
|
|
|
|
|
|
def scrub_event(event, hint):
|
|
event.pop("user", None)
|
|
event.pop("breadcrumbs", None)
|
|
if "request" in event:
|
|
event["request"] = {k: v for k, v in event["request"].items() if k in ("url", "method")}
|
|
return event
|