"""Admin (CMS) routes — password protected, custom UI (no Flask-Admin).""" import functools import hmac import os import re import uuid from datetime import datetime, timedelta, timezone from urllib.parse import urlsplit from flask import ( Blueprint, abort, flash, jsonify, redirect, render_template, request, session, url_for, ) from . import auth from .db import ( _all_albums, _album_by_id, _album_by_slug, _album_media, _comment_by_id, _comment_counts, _pending_comments, _slugify, _ungrouped_media, _media_by_id, _utcnow, get_db, parse_date, ) from .markdown import render_markdown, to_html from .images import make_thumbnail from . import wxr_export, wxr_import bp = Blueprint("admin", __name__, url_prefix="/admin") # Project root (this file lives in blog/admin.py, so climb up twice). APP_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) UPLOAD_DIR = os.path.join(APP_ROOT, "static", "uploads") # Created eagerly so uploaded images are served even before the first upload. os.makedirs(UPLOAD_DIR, exist_ok=True) # CSS lives here; the constant must be defined before _default_font_stack() # runs (it used to sit 200 lines further down the module). CSS_DIR = os.path.join(APP_ROOT, "static", "css") os.makedirs(CSS_DIR, exist_ok=True) # Read the default font stack straight from static/css/style.css so the editor's # "System (default)" preset always matches the built-in theme, no hardcoding. @functools.lru_cache(maxsize=1) def _default_font_stack(): try: with open(os.path.join(CSS_DIR, "style.css"), "r", encoding="utf-8") as handle: for line in handle: if line.startswith("--font-stack"): return line.split(":", 1)[1].strip().rstrip("}").strip() except OSError: pass return "Inter, Roboto, sans-serif" def _admin_username(): return os.environ.get("BLOG_ADMIN_NAME", "admin") def _valid_status(value): """Only the statuses the editor offers are ever stored.""" return value if value in ("published", "draft") else "published" def _post_timestamp(date_value, current=""): """Combine a YYYY-MM-DD form date with the post's existing time of day. Returns "" when the field is blank or not a real date, so callers can keep the stored value (a new post then simply uses the current time). Keeping the old clock time means backdating a post does not reshuffle posts made on the same day, and it avoids every backdated post landing at midnight. """ value = (date_value or "").strip() if not value: return "" try: chosen = datetime.strptime(value, "%Y-%m-%d") except ValueError: return "" current = str(current or "") clock = current[11:19] if len(current) >= 19 else "" if len(clock) != 8: clock = datetime.now(timezone.utc).strftime("%H:%M:%S") return chosen.strftime("%Y-%m-%d") + " " + clock def _csrf(): """Per-session CSRF token (rotated on sign-in).""" return session.get("csrf_token") def _check_csrf(): """Constant-time CSRF check; the token may arrive as a form field or a header.""" expected = _csrf() if not expected: flash("Invalid request.", "error") return False token = request.form.get("csrf_token") or request.headers.get("X-CSRFToken") if not token or not hmac.compare_digest(str(token), str(expected)): flash("Invalid CSRF token.", "error") return False return True # --------------------------------------------------------------------------- # # Auth # --------------------------------------------------------------------------- # def _login_required(fn): """Require an active admin session (see session['logged_in']).""" @functools.wraps(fn) def wrapper(*args, **kwargs): if not auth.is_logged_in(): return redirect(url_for("admin.admin_login")) return fn(*args, **kwargs) return wrapper @bp.route("/") @_login_required def index(): """/admin (no trailing path) used to 404; send it to the dashboard.""" return redirect(url_for("admin.dashboard")) # Image uploads ------------------------------------------------------------- # Accepted image types and their leading magic bytes (used to reject non-images # and format-spoofing). Maps extension -> (signature, min_length). _IMAGE_SIGNATURES = { "png": (b"\x89PNG\r\n\x1a\n", 8), "jpg": (b"\xff\xd8\xff", 4), "jpeg": (b"\xff\xd8\xff", 4), "gif": (b"GIF8", 4), "webp": (b"RIFF\x00\x00\x00\x14WEBP", 12), } @bp.route("/upload", methods=["POST"]) @_login_required def upload(): """Store uploaded image(s) and return their public URLs. Accepts one or more ``file`` parts. When a single image is uploaded the response keeps the legacy shape ``{"url": ...}`` (so the inline post/page rich editor still works). When several are uploaded at once it returns a JSON list of ``{"url": ..., "id": ..., "album_id": ...}`` objects. Each image may be attached to an album via the optional ``album`` slug. If an album slug is supplied we validate it up front (so no file is written for a bad album); without one we keep the old behaviour and just return the URL. Deleting an album later only uncouples photos; it never deletes the file on disk. """ if not _check_csrf(): flash("Invalid request.", "error"); abort(400) files = list(request.files.getlist("file")) if request.files else [] if not files: flash("No image selected.", "error"); abort(400) db = get_db() album_slug = (request.form.get("album") or "").strip() if album_slug: album = _album_by_slug(album_slug) if not album: flash("Album not found.", "error"); abort(400) results = [] for file in files: filename = file.filename if not filename or filename.startswith("("): flash("Invalid file.", "error"); abort(400) ext = os.path.splitext(filename)[1].lower().lstrip(".") if ext not in _IMAGE_SIGNATURES: flash("Unsupported image type.", "error"); abort(400) data = file.read() signature, min_len = _IMAGE_SIGNATURES[ext] if len(data) < min_len or data[:len(signature)] != signature: flash("That doesn't look like a valid image.", "error"); abort(400) new_filename = "%s.%s" % (uuid.uuid4().hex, ext) try: with open(os.path.join(UPLOAD_DIR, new_filename), "wb") as handle: handle.write(data) except OSError: flash("Could not store the image.", "error"); abort(500) # Downscaled copy for galleries/lists; empty when the format can't be # thumbnailed (e.g. animated GIF), in which case the UI uses the original. thumb = make_thumbnail(os.path.join(UPLOAD_DIR, new_filename)) url = url_for("static", filename="uploads/" + new_filename) thumb_url = url_for("static", filename="uploads/" + thumb) if thumb else "" # NOTE: on this sqlite3 build, execute(...).fetchone() returns None # for an INSERT (the row is still written), so we rely on lastrowid. # We ALWAYS persist the photo (album_id NULL when ungrouped) so it shows # in /photos and can later be grouped via media_assign. Previously only # selecting an album created a row — otherwise the file was orphaned on # disk and the upload silently never appeared. cur = db.execute( "INSERT INTO media (filename, url, thumb_url, album_id, position, created_at) " "VALUES (?, ?, ?, ?, 0, ?)", (new_filename, url, thumb_url, album["id"] if album_slug else None, _utcnow()), ) db.commit() results.append({"url": url, "thumb_url": thumb_url, "id": cur.lastrowid, "album_id": album["id"] if album_slug else None}) if len(results) == 1: return jsonify(results[0]) return jsonify(results) # --------------------------------------------------------------------------- # # Appearance (header image + custom CSS) # --------------------------------------------------------------------------- # @bp.route("/appearance", methods=["GET", "POST"]) @_login_required def appearance(): """Set the site header image and custom CSS.""" if request.method == "POST": if not _check_csrf(): return redirect(url_for("admin.appearance")) db = get_db() # NOTE: this page has TWO independent forms that both POST here — the # "Site identity" form (site_title / site_tagline / comments_enabled) and # the "Theme editor" form (custom_css, header_image). Each form only # carries its own fields, so we must do a PARTIAL update: only write the # keys that were actually submitted. Otherwise saving one section would # clobber the other (e.g. saving the title wiped custom_css to ""). if "site_title" in request.form: site_title = (request.form.get("site_title") or "").strip() db.execute("UPDATE settings SET value = ? WHERE key = 'site_title'", (site_title,)) if "site_tagline" in request.form: site_tagline = (request.form.get("site_tagline") or "").strip() db.execute("UPDATE settings SET value = ? WHERE key = 'site_tagline'", (site_tagline,)) # Fallback search/social description for pages without their own. if "meta_description" in request.form: meta_description = (request.form.get("meta_description") or "").strip() db.execute( "UPDATE settings SET value = ? WHERE key = 'meta_description'", (meta_description,), ) # Comments toggle — stored as 0/1 in settings; the public comment form is # gated on it so admins can switch engagement off without touching routes. # Comments toggle — stored as 0/1 in settings; the public comment form is # gated on it so admins can switch engagement off without touching routes. # NOTE: "0" is a *truthy* Python string, so the old `if value.strip()` test # treated an unchecked box's "0" as enabled. The form now uses radio buttons # (explicit 1/0), and we compare against ("", "0") explicitly to be safe. if "comments_enabled" in request.form: comments_enabled = "1" if (request.form.get("comments_enabled") or "").strip() not in ("", "0") else "0" db.execute( "UPDATE settings SET value = ? WHERE key = 'comments_enabled'", (comments_enabled,), ) # Custom CSS is stored verbatim in settings and mirrored to a static file # so public pages can load it efficiently via a (browser-cached). if "custom_css" in request.form: custom_css = (request.form.get("custom_css") or "").strip() db.execute("UPDATE settings SET value = ? WHERE key = 'custom_css'", (custom_css,)) # Only rewrite the static file when the theme form is actually # submitted. The identity form never carries custom_css, so we must # NOT touch this file here — otherwise saving the title would wipe # the saved theme off every public page. css_path = os.path.join(CSS_DIR, "custom.css") with open(css_path, "w") as handle: handle.write(custom_css) if not custom_css: handle.write("\n/* (custom CSS) */\n") # Header image reuses the same signature validation as /upload. img_file = request.files.get("header_image") if img_file and img_file.filename: ext = os.path.splitext(img_file.filename)[1].lower().lstrip(".") if ext not in _IMAGE_SIGNATURES: flash("Unsupported image type.", "error") return redirect(url_for("admin.appearance")) data = img_file.read() signature, min_len = _IMAGE_SIGNATURES[ext] if len(data) < min_len or data[:len(signature)] != signature: flash("That doesn't look like a valid image.", "error") return redirect(url_for("admin.appearance")) filename = "%s.%s" % (uuid.uuid4().hex, ext) try: with open(os.path.join(UPLOAD_DIR, filename), "wb") as handle: handle.write(data) except OSError: flash("Could not store the header image.", "error") return redirect(url_for("admin.appearance")) url = url_for("static", filename="uploads/" + filename) db.execute("UPDATE settings SET value = ? WHERE key = 'header_image'", (url,)) elif request.form.get("remove_header"): # No new file uploaded and removal requested: clear the setting. db.execute("UPDATE settings SET value = '' WHERE key = 'header_image'") db.commit() flash("Appearance saved.", "success") return redirect(url_for("admin.appearance")) db = get_db() header_image = db.execute( "SELECT value FROM settings WHERE key = 'header_image'").fetchone()[0] or "" custom_css = db.execute( "SELECT value FROM settings WHERE key = 'custom_css'").fetchone()[0] or "" # --- Build the theme state for the GUI editor. Values are parsed out of the # stored custom CSS (so a saved theme round-trips); anything missing falls # back to the built-in defaults so a fresh site looks unchanged. def pick(var, default): # Match the value up to the end of its line (or a ';'); buildVars emits # newline-separated declarations without trailing ';', so require only that # the value is terminated by a newline or semicolon (handles both formats). m = re.search(r"--" + re.escape(var) + r"\s*:\s*([^;\n]+)", custom_css) return m.group(1).strip() if m else default def has_dark(): # Detect dark mode via the explicit marker buildTheme() emits, not a # literal background colour (which can be user-chosen), so dark mode # round-trips reliably even with a custom background. return "theme-dark" in custom_css m_posts = re.search(r"\.posts-grid \{[^}]*grid-template-columns:\s*repeat\((\d+),[^}]*\}", custom_css) theme = { "accent": pick("color-accent", "#00a0d1"), "background": pick("color-bg", "#ffffff"), "text": pick("color-text", "#1e1e1e"), "sidebar": pick("color-sidebar-bg", "#f2f2f2"), "font": pick("font-stack", _default_font_stack()), "posts": int(m_posts.group(1)) if m_posts else 1, "header": "stacked" if "flex-direction: column" in custom_css else "side", "radius": int(re.search(r"border-radius:\s*(\d+)px", custom_css).group(1)) if re.search(r"border-radius:\s*\d+px", custom_css) else 6, "dark": has_dark(), "fonts": [ {"value": _default_font_stack(), "label": "System (default)"}, {"value": '"Inter", "Segoe UI", system-ui, sans-serif', "label": "Inter / Modern"}, {"value": 'Georgia, "Times New Roman", serif', "label": "Serif (Georgia)"}, {"value": '"SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace', "label": "Mono (code)"}, {"value": '"Verdana", "Trebuchet MS", sans-serif', "label": "Rounded (Verdana)"} ], "post_columns": [ {"value": 1, "label": "1 column"}, {"value": 2, "label": "2 columns"}, {"value": 3, "label": "3 columns"} ], "header_layouts": [ {"value": "side", "label": "Logo + nav side by side"}, {"value": "stacked", "label": "Logo above nav"} ] } return render_template( "admin/appearance.html", header_image=header_image, custom_css=custom_css, theme=theme, active_page="appearance", ) # --------------------------------------------------------------------------- # # Auth # --------------------------------------------------------------------------- # def _lockout_message(seconds): """Human-readable backoff message without confirming any credentials.""" if seconds >= 60: minutes = (seconds + 59) // 60 return "Too many failed sign-in attempts. Try again in %d minute%s." % ( minutes, "" if minutes == 1 else "s") return "Too many failed sign-in attempts. Try again in %d seconds." % max(1, seconds) @bp.route("/login", methods=["GET", "POST"]) def admin_login(): if auth.is_logged_in(): return redirect(url_for("admin.dashboard")) if request.method == "POST": if not _check_csrf(): return render_template("login.html", title="Sign in"), 400 # Throttle by client address before touching the password hash, so a # brute-force loop cannot keep the CPU busy either. ip = request.remote_addr remaining = auth.lockout_remaining(ip) if remaining: flash(_lockout_message(remaining), "error") return render_template("login.html", title="Sign in"), 429 password = request.form.get("password", "") if auth.verify_admin_password(password): # login_admin() clears the session and rotates the CSRF token # (session-fixation defence) and remembers the display name used # for comment ownership. auth.login_admin(_admin_username()) flash("Welcome back.", "success") return redirect(url_for("admin.dashboard")) locked = auth.record_failed_login(ip) if locked: flash(_lockout_message(locked), "error") else: flash("Invalid password. Please try again.", "error") return render_template("login.html", title="Sign in") @bp.route("/logout", methods=["POST"]) @_login_required def admin_logout(): # POST + CSRF so a third-party page cannot sign the admin out; a GET link # would be triggerable from any tag. if not _check_csrf(): abort(400) auth.logout_admin() flash("You have been signed out.", "info") return redirect(url_for("public.index")) @bp.route("/password", methods=["GET", "POST"]) @_login_required def admin_password(): """Let a signed-in admin change the admin password from the browser. The current password is required even though the session is already authenticated: otherwise anyone who got hold of an unlocked browser could lock the real owner out. Changing the password invalidates every existing session (they carry the old password stamp), so this session is signed in again afterwards to keep the person who just changed it logged in. """ if request.method == "POST": if not _check_csrf(): return redirect(url_for("admin.admin_password")) current = request.form.get("current_password", "") new = request.form.get("new_password", "") confirm = request.form.get("confirm_password", "") if not auth.verify_admin_password(current): flash("Current password is incorrect.", "error") elif new != confirm: flash("The new passwords do not match.", "error") else: problem = auth.password_problem(new) if problem: flash("Password rejected: %s." % problem, "error") else: auth.set_admin_password(new) # set_admin_password() bumped the stamp, which invalidated this # session too; re-establish it so the admin is not kicked out. auth.login_admin(_admin_username()) flash( "Password updated. Any other signed-in sessions have been " "signed out.", "success", ) return redirect(url_for("admin.admin_password")) return render_template( "admin/password.html", min_length=auth.MIN_PASSWORD_LENGTH, active_page="password", ) # --------------------------------------------------------------------------- # # Media galleries (albums) # --------------------------------------------------------------------------- # @bp.route("/albums") @_login_required def albums(): db = get_db() albums_list = _all_albums() ungrouped_count = len(_ungrouped_media()) album_counts = {a["id"]: len(_album_media(a["id"])) for a in albums_list} return render_template( "admin/albums.html", albums=albums_list, ungrouped_count=ungrouped_count, album_counts=album_counts, active_page="albums", ) @bp.route("/albums/new", methods=["GET", "POST"]) @_login_required def album_new(): db = get_db() if request.method == "POST": if not _check_csrf(): flash("Invalid request.", "error") return redirect(url_for("admin.albums")) name = (request.form.get("name") or "").strip() if not name: flash("Name is required.", "error") return redirect(url_for("admin.albums")) slug = _slugify(name) base, n = slug, 1 while db.execute("SELECT 1 FROM media_albums WHERE slug = ?", (slug,)).fetchone(): slug = f"{base}-{n}" n += 1 db.execute( "INSERT INTO media_albums (name, slug, description, created_at) VALUES (?, ?, ?, ?)", (name, slug, (request.form.get("description") or "").strip(), _utcnow()), ) db.commit() flash(f"Album '{name}' created.", "success") return redirect(url_for("admin.albums")) return render_template( "admin/albums.html", albums=_all_albums(), ungrouped_count=len(_ungrouped_media()), # The template reads album_counts.get(...), so a missing value made the # "new album" page fail with an UndefinedError (HTTP 500). album_counts={}, active_page="albums", ) @bp.route("/albums//edit", methods=["GET", "POST"]) @_login_required def album_edit(slug): db = get_db() album = _album_by_slug(slug) if not album: abort(404) if request.method == "POST": if not _check_csrf(): flash("Invalid request.", "error") return redirect(url_for("admin.albums")) name = (request.form.get("name") or "").strip() if not name: flash("Name is required.", "error") return redirect(url_for("admin.albums")) # The slug is the album's public URL (/photos/), so a rename must # not silently break existing links: only the name and description are # updated here. db.execute( "UPDATE media_albums SET name = ?, description = ? WHERE id = ?", (name, (request.form.get("description") or "").strip(), album["id"]), ) db.commit() flash("Album updated.", "success") return redirect(url_for("admin.albums")) return render_template( "admin/albums.html", albums=_all_albums(), editing=album, ungrouped_count=len(_ungrouped_media()), album_counts={album["id"]: len(_album_media(album["id"]))}, active_page="albums", ) @bp.route("/albums//delete", methods=["POST"]) @_login_required def album_delete(slug): db = get_db() album = _album_by_slug(slug) if not album: abort(404) if not _check_csrf(): flash("Invalid request.", "error") return redirect(url_for("admin.albums")) # Uncouple, don't delete: photos stay in /uploads and become ungrouped. db.execute("UPDATE media SET album_id = NULL WHERE album_id = ?", (album["id"],)) db.execute("DELETE FROM media_albums WHERE id = ?", (album["id"],)) db.commit() flash(f"Album '{album['name']}' deleted.", "success") return redirect(url_for("admin.albums")) # --------------------------------------------------------------------------- # # Media management (assign / remove photos from albums) # --------------------------------------------------------------------------- # @bp.route("/media") @_login_required def media_list(): db = get_db() albums = _all_albums() album_names = {a["id"]: a["name"] for a in albums} grouped, ungrouped = {}, [] for row in db.execute( "SELECT * FROM media ORDER BY COALESCE(album_id, 0) ASC, position ASC, id ASC" ).fetchall(): aid = row["album_id"] (grouped.setdefault(aid, []) if aid is not None else ungrouped).append(row) return render_template( "admin/media.html", albums=albums, album_names=album_names, grouped=grouped, ungrouped=ungrouped, active_page="media", ) @bp.route("/media//assign", methods=["POST"]) @_login_required def media_assign(mid): db = get_db() photo = _media_by_id(mid) if not photo: abort(404) if not _check_csrf(): flash("Invalid request.", "error") return redirect(url_for("admin.media_list")) try: album_id = int(request.form.get("album_id") or 0) except (TypeError, ValueError): album_id = 0 if album_id <= 0 or not _album_by_id(album_id): # A missing/non-numeric album_id raised ValueError (HTTP 500), and a # stale form could point at an album that no longer exists. flash("Please choose a valid album.", "error") return redirect(url_for("admin.media_list")) db.execute( "UPDATE media SET album_id = ?, position = (SELECT COALESCE(MAX(position), 0) + 1 FROM media WHERE album_id = ?) WHERE id = ?", (album_id, album_id, mid), ) db.commit() flash("Photo added to album.", "success") return redirect(url_for("admin.media_list")) @bp.route("/media//remove", methods=["POST"]) @_login_required def media_remove(mid): db = get_db() photo = _media_by_id(mid) if not photo: abort(404) if not _check_csrf(): flash("Invalid request.", "error") return redirect(url_for("admin.media_list")) # Delete the photo entirely: remove the file on disk and the DB row. try: os.remove(os.path.join(UPLOAD_DIR, photo["filename"])) except OSError: pass # The generated thumbnail lives next to the original; remove it too so # deleted photos don't leave files behind. thumb_name = os.path.basename((photo["thumb_url"] or "").strip()) if thumb_name: try: os.remove(os.path.join(UPLOAD_DIR, thumb_name)) except OSError: pass db.execute("DELETE FROM media WHERE id = ?", (mid,)) db.commit() flash("Photo removed.", "success") return redirect(url_for("admin.media_list")) # --------------------------------------------------------------------------- # # Dashboard # --------------------------------------------------------------------------- # @bp.route("/dashboard") @_login_required def dashboard(): db = get_db() count = db.execute("SELECT COUNT(*) FROM posts").fetchone()[0] published = db.execute("SELECT COUNT(*) FROM posts WHERE status = 'published'").fetchone()[0] drafts = db.execute("SELECT COUNT(*) FROM posts WHERE status = 'draft'").fetchone()[0] posts = db.execute("SELECT * FROM posts ORDER BY created_at DESC").fetchall() return render_template( "admin/dashboard.html", count=count, published=published, drafts=drafts, posts=posts, pending=_pending_comments()[:5], active_page="dashboard", ) # --------------------------------------------------------------------------- # # Posts CRUD # --------------------------------------------------------------------------- # @bp.route("/posts") @_login_required def posts(): db = get_db() posts = db.execute("SELECT * FROM posts ORDER BY created_at DESC").fetchall() return render_template("admin/posts.html", posts=posts) @bp.route("/posts/new", methods=["GET", "POST"]) @_login_required def post_new(): body_html = "" if request.method == "POST": if not _check_csrf(): return render_template("admin/post_edit.html", post=None, categories=[], body_html=body_html, active_page="posts") db = get_db() title = (request.form.get("title") or "").strip() if not title: flash("Title is required.", "error") return render_template("admin/post_edit.html", post=None, categories=[], body_html=body_html, active_page="posts") slug = _slugify(request.form.get("slug") or title) base, n = slug, 1 while db.execute("SELECT 1 FROM posts WHERE slug = ?", (slug,)).fetchone(): slug = f"{base}-{n}" n += 1 now = _utcnow() # An optional backdate: the public site displays and orders posts by # created_at, so that is the field a "post date" really controls. created_at = _post_timestamp(request.form.get("post_date"), now) or now db.execute( """ INSERT INTO posts (title, slug, body, excerpt, author, category, tags, status, created_at, updated_at, published_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (title, slug, request.form.get("body", ""), request.form.get("excerpt", ""), request.form.get("author") or "editor", request.form.get("category") or "General", request.form.get("tags") or "", _valid_status(request.form.get("status")), created_at, now, now), ) db.commit() flash("Post created.", "success") return redirect(url_for("admin.posts")) return render_template("admin/post_edit.html", post=None, categories=[], body_html=body_html, active_page="posts") @bp.route("/posts//edit", methods=["GET", "POST"]) @_login_required def post_edit(pid): db = get_db() row = db.execute("SELECT * FROM posts WHERE id = ?", (pid,)).fetchone() post = dict(row) if row else None if not post: abort(404) cats = db.execute("SELECT slug, name FROM categories ORDER BY name").fetchall() if request.method == "POST": if not _check_csrf(): return render_template("admin/post_edit.html", post=post, categories=cats, body_html=to_html(post["body"]), active_page="posts") new_slug = _slugify(request.form.get("slug") or request.form.get("title") or "") base, n = new_slug, 1 while db.execute("SELECT 1 FROM posts WHERE slug = ? AND id != ?", (new_slug, pid,)).fetchone(): new_slug = f"{base}-{n}" n += 1 now = _utcnow() status = _valid_status(request.form.get("status")) # Keep an existing publish time (so a scheduled post stays scheduled); # stamp one the first time the post actually goes live. published_at = post.get("published_at") or "" if status == "published" and not published_at: published_at = now # Blank/invalid date input keeps the stored date; a real one backdates # the post (created_at drives display, ordering and archive months). created_at = ( _post_timestamp( request.form.get("post_date"), post.get("created_at") or now ) or post.get("created_at") or now ) db.execute( """ UPDATE posts SET title = ?, slug = ?, body = ?, excerpt = ?, author = ?, category = ?, tags = ?, status = ?, updated_at = ?, published_at = ?, created_at = ? WHERE id = ? """, (request.form.get("title") or "", new_slug, request.form.get("body", ""), request.form.get("excerpt", ""), request.form.get("author") or "editor", request.form.get("category") or "General", request.form.get("tags") or "", status, now, published_at, created_at, pid), ) db.commit() flash("Post updated.", "success") return redirect(url_for("admin.post_edit", pid=pid)) return render_template("admin/post_edit.html", post=post, categories=cats, body_html=to_html(post["body"]), active_page="posts") @bp.route("/posts//delete", methods=["POST"]) @_login_required def post_delete(pid): if not _check_csrf(): return redirect(url_for("admin.posts")) db = get_db() if db.execute("SELECT 1 FROM posts WHERE id = ?", (pid,)).fetchone(): # Delete the post's comments too; they used to linger forever and kept # showing up in moderation counts. db.execute( "DELETE FROM comments WHERE object_type = 'post' AND object_id = ?", (pid,) ) db.execute("DELETE FROM posts WHERE id = ?", (pid,)) db.commit() flash("Post deleted.", "info") return redirect(url_for("admin.posts")) # --------------------------------------------------------------------------- # # Categories CRUD # --------------------------------------------------------------------------- # @bp.route("/categories") @_login_required def categories(): db = get_db() cats = db.execute("SELECT slug, name FROM categories ORDER BY name").fetchall() return render_template("admin/categories.html", categories=cats, active_page="categories") @bp.route("/categories/new", methods=["GET", "POST"]) @_login_required def category_new(): if request.method == "POST": if not _check_csrf(): return render_template("admin/categories.html", categories=None, active_page="posts") db = get_db() name = (request.form.get("name") or "").strip() if not name: flash("Name is required.", "error") return render_template("admin/categories.html", categories=None, active_page="posts") slug = _slugify(name) base, n = slug, 1 while db.execute("SELECT 1 FROM categories WHERE slug = ?", (slug,)).fetchone(): slug = f"{base}-{n}" n += 1 db.execute("INSERT INTO categories (slug, name) VALUES (?, ?)", (slug, name)) db.commit() flash("Category created.", "success") return redirect(url_for("admin.categories")) return render_template("admin/categories.html", categories=None, active_page="categories") @bp.route("/categories//delete", methods=["POST"]) @_login_required def category_delete(slug): if not _check_csrf(): return redirect(url_for("admin.categories")) db = get_db() if slug != "general": # never delete the default category db.execute("DELETE FROM categories WHERE slug = ?", (slug,)) db.commit() flash("Category deleted.", "info") return redirect(url_for("admin.categories")) # --------------------------------------------------------------------------- # # Sidebar link tree # --------------------------------------------------------------------------- # # Schemes a sidebar link may use. Anything else (notably javascript:) is # rejected, so a mistyped/pasted URL can never become script on every page. _LINK_SCHEMES = ("http", "https", "mailto") def _link_url(raw): """Normalise a submitted link URL; return "" when it is unusable. Bare domains ("example.com") get https:// so the common case works without the admin having to type a scheme. Site-relative targets (/p/about, #top) are kept as-is. """ url = (raw or "").strip() if not url or any(ch.isspace() for ch in url): return "" lowered = url.lower() if lowered.startswith(("/", "#", "?")): return url if "://" not in url and not lowered.startswith("mailto:"): # Reject a non-allowlisted scheme outright (javascript:, data:, …) # rather than turning it into a bogus https URL. A trailing port # (example.com:8080) is not a scheme, hence the (?!\d) guard. if re.match(r"^[a-z][a-z0-9+.\-]*:(?!\d)", lowered): return "" url = "https://" + url parts = urlsplit(url) scheme = parts.scheme.lower() if scheme not in _LINK_SCHEMES: return "" if scheme in ("http", "https") and not parts.netloc: return "" return url @bp.route("/links", methods=["GET", "POST"]) @_login_required def links(): """Manage the sidebar link tree. The public panel is hidden while empty.""" db = get_db() if request.method == "POST": if not _check_csrf(): return redirect(url_for("admin.links")) label = (request.form.get("label") or "").strip()[:80] url = _link_url(request.form.get("url")) if not label or not url: flash("A label and a valid http(s) or mailto URL are required.", "error") return redirect(url_for("admin.links")) # Same pattern as pages: append after whatever is already listed. position = db.execute( "SELECT COALESCE(MAX(position), 0) + 1 FROM links" ).fetchone()[0] db.execute( "INSERT INTO links (label, url, position, created_at) VALUES (?, ?, ?, ?)", (label, url, position, _utcnow()), ) db.commit() flash("Link added.", "success") return redirect(url_for("admin.links")) rows = db.execute("SELECT * FROM links ORDER BY position ASC, id ASC").fetchall() return render_template("admin/links.html", links=rows, active_page="links") @bp.route("/links//delete", methods=["POST"]) @_login_required def link_delete(lid): if not _check_csrf(): return redirect(url_for("admin.links")) db = get_db() db.execute("DELETE FROM links WHERE id = ?", (lid,)) db.commit() flash("Link removed.", "info") return redirect(url_for("admin.links")) # --------------------------------------------------------------------------- # # Pages CRUD (content pages shown in the top nav) # --------------------------------------------------------------------------- # @bp.route("/pages") @_login_required def pages(): db = get_db() all_pages = db.execute( "SELECT id, slug, title, content, position, published FROM pages " "ORDER BY position, id" ).fetchall() return render_template("admin/pages.html", pages=all_pages, active_page="pages") @bp.route("/pages/new", methods=["GET", "POST"]) @_login_required def page_new(): if request.method == "POST": if not _check_csrf(): return render_template("admin/page_edit.html", page=None, categories=[], body_html="", active_page="pages") db = get_db() title = (request.form.get("title") or "").strip() if not title: flash("Title is required.", "error") return render_template("admin/page_edit.html", page=None, categories=[], body_html="", active_page="pages") slug = _slugify(request.form.get("slug") or title) base, n = slug, 1 while db.execute("SELECT 1 FROM pages WHERE slug = ?", (slug,)).fetchone(): slug = f"{base}-{n}" n += 1 now = _utcnow() # New pages are appended after existing ones. position = db.execute("SELECT COALESCE(MAX(position), 0) + 1 FROM pages").fetchone()[0] db.execute( "INSERT INTO pages (slug, title, content, position, published, created_at, updated_at) " "VALUES (?, ?, ?, ?, 1, ?, ?)", (slug, title, request.form.get("content", ""), position, now, now), ) db.commit() flash("Page created.", "success") return redirect(url_for("admin.pages")) return render_template("admin/page_edit.html", page=None, categories=[], body_html="", active_page="pages") @bp.route("/pages//edit", methods=["GET", "POST"]) @_login_required def page_edit(pid): db = get_db() row = db.execute("SELECT * FROM pages WHERE id = ?", (pid,)).fetchone() page = dict(row) if row else None if not page: abort(404) if request.method == "POST": if not _check_csrf(): return render_template("admin/page_edit.html", page=page, categories=[], body_html=page["content"], active_page="pages") new_slug = _slugify(request.form.get("slug") or request.form.get("title") or "") base, n = new_slug, 1 while db.execute("SELECT 1 FROM pages WHERE slug = ? AND id != ?", (new_slug, pid,)).fetchone(): new_slug = f"{base}-{n}" n += 1 # Preserve display order unless the editor explicitly moved it. position = request.form.get("position") if position and position.strip().isdigit(): try: position = int(position.strip()) except (ValueError, TypeError): position = None now = _utcnow() db.execute( "UPDATE pages SET title = ?, slug = ?, content = ?, position = ?, updated_at = ? WHERE id = ?", (request.form.get("title") or "", new_slug, request.form.get("content", ""), position if position is not None else page["position"], now, pid), ) db.commit() flash("Page updated.", "success") return redirect(url_for("admin.page_edit", pid=pid)) return render_template("admin/page_edit.html", page=page, categories=[], body_html=page["content"], active_page="pages") @bp.route("/pages//delete", methods=["POST"]) @_login_required def page_delete(pid): if not _check_csrf(): return redirect(url_for("admin.pages")) db = get_db() if db.execute("SELECT 1 FROM pages WHERE id = ?", (pid,)).fetchone(): db.execute( "DELETE FROM comments WHERE object_type = 'page' AND object_id = ?", (pid,) ) db.execute("DELETE FROM pages WHERE id = ?", (pid,)) db.commit() flash("Page deleted.", "info") return redirect(url_for("admin.pages")) # --------------------------------------------------------------------------- # # Visitor analytics (tracking) # --------------------------------------------------------------------------- # @bp.route("/analytics") @_login_required def analytics(): """Overview: how many people visited, where they came from, what they saw.""" db = get_db() total_visitors = db.execute("SELECT COUNT(*) FROM visitors").fetchone()[0] total_visits = db.execute("SELECT COUNT(*) FROM visits").fetchone()[0] unique_pages = db.execute("SELECT COUNT(DISTINCT page_path) FROM visits").fetchone()[0] total_countries = db.execute( "SELECT COUNT(DISTINCT country_code) FROM visitors WHERE country_code <> ''" ).fetchone()[0] total_cities = db.execute( "SELECT COUNT(DISTINCT city) FROM visitors WHERE city <> ''" ).fetchone()[0] top_pages = db.execute( """SELECT page_path, title, COUNT(*) AS c FROM visits GROUP BY page_path ORDER BY c DESC, timestamp DESC LIMIT 15""" ).fetchall() top_browsers = db.execute( "SELECT browser, COUNT(*) AS c FROM visitors GROUP BY browser ORDER BY c DESC" ).fetchall() top_sources = db.execute( "SELECT source, COUNT(*) AS c FROM visitors GROUP BY source ORDER BY c DESC" ).fetchall() top_domains = db.execute( "SELECT referrer_domain, COUNT(*) AS c FROM visitors WHERE referrer_domain <> '' " "GROUP BY referrer_domain ORDER BY c DESC LIMIT 15" ).fetchall() top_devices = db.execute( "SELECT device, COUNT(*) AS c FROM visitors GROUP BY device ORDER BY c DESC" ).fetchall() # --- Locations -------------------------------------------------------- # top_countries = db.execute( """ SELECT v.country AS country, v.country_code AS country_code, COUNT(DISTINCT v.visitor_id) AS visitors, COUNT(t.id) AS visits FROM visitors v LEFT JOIN visits t ON t.visitor_id = v.visitor_id WHERE v.country <> '' GROUP BY v.country, v.country_code ORDER BY visits DESC, visitors DESC LIMIT 15 """ ).fetchall() top_cities = db.execute( """ SELECT v.city AS city, v.region AS region, v.country AS country, v.country_code AS country_code, COUNT(DISTINCT v.visitor_id) AS visitors, COUNT(t.id) AS visits FROM visitors v LEFT JOIN visits t ON t.visitor_id = v.visitor_id WHERE v.city <> '' GROUP BY v.city, v.region, v.country, v.country_code ORDER BY visits DESC, visitors DESC LIMIT 15 """ ).fetchall() # One point per (rounded) city coordinate. Rounding collapses the tiny # coordinate differences the geolocation API returns for the same city. map_rows = db.execute( """ SELECT v.city AS city, v.region AS region, v.country AS country, v.country_code AS country_code, ROUND(v.latitude, 2) AS latitude, ROUND(v.longitude, 2) AS longitude, COUNT(DISTINCT v.visitor_id) AS visitors, COUNT(t.id) AS visits FROM visitors v LEFT JOIN visits t ON t.visitor_id = v.visitor_id WHERE v.latitude IS NOT NULL AND v.longitude IS NOT NULL GROUP BY city, region, country, country_code, latitude, longitude ORDER BY visits DESC LIMIT 500 """ ).fetchall() map_points = [ { "city": row["city"], "region": row["region"], "country": row["country"], "country_code": row["country_code"], "lat": row["latitude"], "lon": row["longitude"], "visitors": row["visitors"], "visits": row["visits"], } for row in map_rows ] # --- Location trends (last 30 days) ---------------------------------- # trend_days = 30 today = datetime.now(timezone.utc).date() day_labels = [ (today - timedelta(days=trend_days - 1 - offset)).isoformat() for offset in range(trend_days) ] trend_rows = db.execute( """ SELECT substr(t.timestamp, 1, 10) AS day, CASE WHEN IFNULL(v.country, '') = '' THEN 'Unknown' ELSE v.country END AS country, COUNT(*) AS visits FROM visits t LEFT JOIN visitors v ON v.visitor_id = t.visitor_id WHERE t.timestamp >= ? GROUP BY day, country """, (day_labels[0],), ).fetchall() country_totals = {} for row in trend_rows: country_totals[row["country"]] = ( country_totals.get(row["country"], 0) + row["visits"] ) # The five busiest countries get their own line; the rest are grouped so the # chart stays readable no matter how many countries show up. top_names = [ name for name, _count in sorted( country_totals.items(), key=lambda item: item[1], reverse=True )[:5] ] series_values = {name: [0] * trend_days for name in top_names} if len(country_totals) > len(top_names): series_values["Other"] = [0] * trend_days day_index = {day: index for index, day in enumerate(day_labels)} for row in trend_rows: name = row["country"] if row["country"] in series_values else "Other" index = day_index.get(row["day"]) if index is not None and name in series_values: series_values[name][index] += row["visits"] location_trend = { "labels": day_labels, "series": [ {"name": name, "data": values} for name, values in series_values.items() ], } # --- Where visitors to each page come from --------------------------- # # Bounded to the 15 busiest pages so the dashboard stays fast on a large # archive; each page then lists its five top countries. page_location_rows = db.execute( """ WITH busiest AS ( SELECT page_path, COUNT(*) AS total FROM visits GROUP BY page_path ORDER BY total DESC LIMIT 15 ) SELECT t.page_path AS page_path, MAX(t.title) AS title, CASE WHEN IFNULL(v.country, '') = '' THEN 'Unknown' ELSE v.country END AS country, IFNULL(v.country_code, '') AS country_code, COUNT(DISTINCT v.visitor_id) AS visitors, COUNT(*) AS visits FROM visits t JOIN busiest b ON b.page_path = t.page_path LEFT JOIN visitors v ON v.visitor_id = t.visitor_id GROUP BY t.page_path, country, v.country_code """ ).fetchall() pages_by_path = {} for row in page_location_rows: page = pages_by_path.setdefault( row["page_path"], { "path": row["page_path"], "title": row["title"] or "", "visits": 0, "countries": {}, }, ) page["visits"] += row["visits"] key = (row["country"], row["country_code"]) entry = page["countries"].setdefault( key, { "country": row["country"], "country_code": row["country_code"], "visitors": 0, "visits": 0, }, ) entry["visitors"] += row["visitors"] entry["visits"] += row["visits"] page_locations = sorted( pages_by_path.values(), key=lambda item: item["visits"], reverse=True ) for page in page_locations: countries = sorted( page["countries"].values(), key=lambda item: (item["visits"], item["visitors"]), reverse=True, ) page["countries"] = countries[:5] page["more_countries"] = max(0, len(countries) - 5) return render_template( "admin/analytics.html", total_visitors=total_visitors, total_visits=total_visits, unique_pages=unique_pages, total_countries=total_countries, total_cities=total_cities, top_pages=top_pages, top_browsers=top_browsers, top_sources=top_sources, top_domains=top_domains, top_devices=top_devices, top_countries=top_countries, top_cities=top_cities, map_points=map_points, location_trend=location_trend, page_locations=page_locations, active_page="analytics", ) @bp.route("/visitors") @_login_required def visitors(): """List tracked visitors, optionally filtered by country or city.""" db = get_db() country = (request.args.get("country") or "").strip().upper() city = (request.args.get("city") or "").strip() conditions = [] params = [] if country: conditions.append("v.country_code = ?") params.append(country) if city: conditions.append("v.city = ?") params.append(city) where = (" WHERE " + " AND ".join(conditions)) if conditions else "" rows = db.execute( """ SELECT v.visitor_id, v.browser, v.os, v.device, v.source, v.referrer_domain, v.country, v.country_code, v.city, v.region, v.first_seen, v.last_seen, (SELECT COUNT(*) FROM visits WHERE visitor_id = v.visitor_id) AS visits FROM visitors v """ + where + """ ORDER BY v.last_seen DESC, v.visitor_id DESC LIMIT 300 """, params, ).fetchall() countries = db.execute( """ SELECT country_code, country, COUNT(*) AS c FROM visitors WHERE country_code <> '' GROUP BY country_code, country ORDER BY country """ ).fetchall() # Cities are scoped to the selected country so the second dropdown never # offers a place that cannot match. if country: city_rows = db.execute( "SELECT DISTINCT city FROM visitors WHERE city <> '' " "AND country_code = ? ORDER BY city", (country,), ).fetchall() else: city_rows = db.execute( "SELECT DISTINCT city FROM visitors WHERE city <> '' ORDER BY city" ).fetchall() return render_template( "admin/visitors.html", rows=rows, countries=countries, cities=[row["city"] for row in city_rows], selected_country=country, selected_city=city, active_page="visitors", ) @bp.route("/visits/") @_login_required def visit_history(vid): """Show every page a single visitor visited, most recent first.""" v = get_db().execute("SELECT * FROM visitors WHERE visitor_id = ?", (vid,)).fetchone() if not v: abort(404) visits = get_db().execute( """SELECT page_path, title, timestamp FROM visits WHERE visitor_id = ? ORDER BY timestamp DESC""", (vid,), ).fetchall() return render_template( "admin/visit_history.html", visitor=v, visits=visits, active_page="visitors", ) # --------------------------------------------------------------------------- # # Comments moderation # --------------------------------------------------------------------------- # @bp.route("/comments") @_login_required def comments(): """Moderation dashboard: counts + every comment that needs a human eye. Pending comments get full action buttons (approve/reject/spam/delete). A rejected or spam comment leaves the pending queue but is still rendered below so an admin can review what they flagged and un-reject if they changed their mind — otherwise the dashboard would only ever show the counts, never the text. """ counts = _comment_counts() pending = _pending_comments() db = get_db() rejected = db.execute( "SELECT * FROM comments WHERE status='rejected' ORDER BY created_at DESC, id DESC" ).fetchall() spam = db.execute( "SELECT * FROM comments WHERE status='spam' ORDER BY created_at DESC, id DESC" ).fetchall() return render_template("admin/comments.html", counts=counts, comments=pending, rejected=rejected, spam=spam) @bp.route("/comments//approve", methods=["POST"]) @_login_required def comment_approve(cid): if not _check_csrf(): return redirect(url_for("admin.comments")) db = get_db() row = _comment_by_id(cid) if not row: abort(404) db.execute("UPDATE comments SET status='approved', updated_at=? WHERE id=?", (_utcnow(), cid)) db.commit() flash("Comment approved.", "success") return redirect(url_for("admin.comments")) @bp.route("/comments//reject", methods=["POST"]) @_login_required def comment_reject(cid): if not _check_csrf(): return redirect(url_for("admin.comments")) db = get_db() row = _comment_by_id(cid) if not row: abort(404) # Rejected comments are hidden from the public but retained for review. db.execute("UPDATE comments SET status='rejected', updated_at=? WHERE id=?", (_utcnow(), cid)) db.commit() flash("Comment rejected.", "info") return redirect(url_for("admin.comments")) @bp.route("/comments//unreject", methods=["POST"]) @_login_required def comment_unreject(cid): """Move a rejected comment back to pending so it can be reviewed again.""" if not _check_csrf(): return redirect(url_for("admin.comments")) db = get_db() row = _comment_by_id(cid) if not row: abort(404) db.execute("UPDATE comments SET status='pending', updated_at=? WHERE id=?", (_utcnow(), cid)) db.commit() flash("Comment returned to moderation.", "success") return redirect(url_for("admin.comments")) @bp.route("/comments//spam", methods=["POST"]) @_login_required def comment_spam(cid): if not _check_csrf(): return redirect(url_for("admin.comments")) db = get_db() row = _comment_by_id(cid) if not row: abort(404) db.execute("UPDATE comments SET status='spam', updated_at=? WHERE id=?", (_utcnow(), cid)) db.commit() flash("Comment marked as spam.", "info") return redirect(url_for("admin.comments")) @bp.route("/comments//delete", methods=["POST"]) @_login_required def comment_delete(cid): if not _check_csrf(): return redirect(url_for("admin.comments")) db = get_db() row = _comment_by_id(cid) if not row: abort(404) db.execute("DELETE FROM comments WHERE id=?", (cid,)) db.commit() flash("Comment deleted.", "info") return redirect(url_for("admin.comments")) # --------------------------------------------------------------------------- # # Comments moderation # --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- # # Import / Export (WXR) — move content to and from a WordPress site. # --------------------------------------------------------------------------- # def _site_meta(db): """Return (title, url, description) for the WXR channel. Each setting is optional; a missing row falls back to a sensible default so an unconfigured blog still renders its admin pages instead of 500ing. """ title = db.execute("SELECT value FROM settings WHERE key = 'site_title'").fetchone() tagline = db.execute("SELECT value FROM settings WHERE key = 'site_tagline'").fetchone() meta = db.execute("SELECT value FROM settings WHERE key = 'meta_description'").fetchone() title = title[0] if title else "My Blog" tagline = tagline[0] if tagline else "" desc = meta[0] if meta else tagline url = os.environ.get("BLOG_URL", "http://localhost:8000") return title, url, desc @bp.route("/import-export", methods=["GET", "POST"]) @_login_required def import_export(): """Page with an Export button and a WXR file-upload form.""" if request.method == "POST" and "export" in request.form: db = get_db() title, url, desc = _site_meta(db) wxr = wxr_export.build_wxr(db, title, url, desc) from io import BytesIO from flask import send_file return send_file( BytesIO(wxr.encode("utf-8")), mimetype="application/xml", as_attachment=True, download_name="simple-blog-export.xml", ) # Only the title is displayed on this page. title = _site_meta(get_db())[0] return render_template("admin/import_export.html", site_title=title, active_page="import-export") @bp.route("/import-wxr", methods=["POST"]) @_login_required def import_wxr_route(): """Run a WXR import from an uploaded file and report the results.""" if not _check_csrf(): flash("Invalid CSRF token.", "error") return redirect(url_for("admin.import_export")) upload = request.files.get("file") if not upload or not upload.filename.lower().endswith(".xml"): flash("Please choose a .xml (WXR) file to import.", "error") return redirect(url_for("admin.import_export")) try: import tempfile, os.path as _osp with tempfile.NamedTemporaryFile("wb", delete=False) as tmp: tmp.write(upload.read()) tmp_path = tmp.name try: result = wxr_import.import_wxr(tmp_path) finally: _osp.unlink(tmp_path) except Exception as exc: # pragma: no cover - defensive flash(f"Import failed: {exc}", "error") return redirect(url_for("admin.import_export")) for err in result.get("errors", []): flash(f"Import error: {err}", "error") flash( f"Import done — {result['posts_imported']} post(s) added, " f"{result['categories_added']} category(ies), " f"{result['comments_imported']} comment(s). " + (f"{result['posts_skipped']} skipped as duplicates." if result.get("posts_skipped") else ""), "success", ) return redirect(url_for("admin.import_export"))