Add app.py server core with static pages, sessions and the auth routes
This commit is contained in:
1 parent
5d8b89446c
commit
165c600529
1 file changed
+309
@@ -0,0 +1,309 @@
|
||||
"""Skuld: the HTTP server.
|
||||
|
||||
Every response is JSON or a file from static/. The session cookie is HttpOnly
|
||||
and SameSite=Strict; the CSRF secret sits in a script-readable cookie that
|
||||
static/session.js copies into the X-CSRF-Token header of every mutating call.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
from http.cookies import CookieError, SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import auth
|
||||
import database
|
||||
import export
|
||||
import ledger
|
||||
import rates
|
||||
import tax
|
||||
import validation
|
||||
|
||||
STATIC_DIR = Path(__file__).resolve().parent / "static"
|
||||
DEFAULT_HOST = "0.0.0.0"
|
||||
DEFAULT_PORT = 8080
|
||||
|
||||
CONTENT_TYPES = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
".csv": "text/csv; charset=utf-8",
|
||||
}
|
||||
|
||||
PAGES = {
|
||||
"/": "index.html",
|
||||
"/login": "login.html",
|
||||
"/transaksjonar": "transactions.html",
|
||||
"/transaksjon": "transaction.html",
|
||||
"/marknader": "markets.html",
|
||||
"/rapport": "report.html",
|
||||
"/innstillingar": "settings.html",
|
||||
}
|
||||
|
||||
ASSETS = ("app.js", "session.js", "style.css", "icon.svg")
|
||||
|
||||
# (method, path pattern, handler name). The handler is a method of the request
|
||||
# handler and returns the JSON payload.
|
||||
ROUTES = (
|
||||
("GET", r"^/api/auth/state$", "auth_state"),
|
||||
("POST", r"^/api/auth/setup$", "auth_setup"),
|
||||
("POST", r"^/api/auth/login$", "auth_login"),
|
||||
("POST", r"^/api/auth/logout$", "auth_logout"),
|
||||
("POST", r"^/api/auth/password$", "auth_password"),
|
||||
)
|
||||
|
||||
# Routes that answer without a session. The rest need one, and every mutating
|
||||
# call needs the CSRF header on top of it.
|
||||
OPEN_ROUTES = ("auth_state", "auth_setup", "auth_login", "auth_logout")
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
"""An error that is sent as {"error": message, "field": field}."""
|
||||
|
||||
def __init__(self, status, message, field=None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
self.field = field
|
||||
|
||||
|
||||
def _cookie(name, value, http_only, max_age=auth.SESSION_TTL_SECONDS):
|
||||
parts = ["%s=%s" % (name, value), "Path=/", "Max-Age=%d" % max_age,
|
||||
"SameSite=Strict"]
|
||||
if http_only:
|
||||
parts.append("HttpOnly")
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def _parse_year(value):
|
||||
text = str(value or "").strip()
|
||||
if not re.fullmatch(r"\d{4}", text):
|
||||
raise ApiError(400, "Året må vere eit firetal, t.d. 2025.", "year")
|
||||
return int(text)
|
||||
|
||||
|
||||
def _as_int(value, field, message="Verdien må vere eit heiltal."):
|
||||
try:
|
||||
return int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
raise ApiError(400, message, field)
|
||||
|
||||
|
||||
class SkuldHandler(BaseHTTPRequestHandler):
|
||||
"""One HTTP request."""
|
||||
|
||||
server_version = "Skuld"
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def do_GET(self):
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self):
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_PATCH(self):
|
||||
self._dispatch("PATCH")
|
||||
|
||||
def do_PUT(self):
|
||||
self._dispatch("PUT")
|
||||
|
||||
def do_DELETE(self):
|
||||
self._dispatch("DELETE")
|
||||
|
||||
# -- plumbing ---------------------------------------------------------
|
||||
|
||||
def _dispatch(self, method):
|
||||
self._pending_cookies = []
|
||||
parsed = urlparse(self.path)
|
||||
path = parsed.path
|
||||
query = parse_qs(parsed.query)
|
||||
try:
|
||||
if path == "/health":
|
||||
return self._send_json({"status": "ok"})
|
||||
if path.startswith("/api/"):
|
||||
return self._api(method, path, query)
|
||||
return self._static(path)
|
||||
except ApiError as error:
|
||||
return self._send_json(
|
||||
{"error": error.message, "field": error.field}, status=error.status
|
||||
)
|
||||
except Exception: # one bad request must not take the server down
|
||||
traceback.print_exc()
|
||||
return self._send_json(
|
||||
{"error": "Intern feil i Skuld.", "field": None}, status=500
|
||||
)
|
||||
|
||||
def _api(self, method, path, query):
|
||||
for route_method, pattern, name in ROUTES:
|
||||
match = re.match(pattern, path)
|
||||
if not match or route_method != method:
|
||||
continue
|
||||
token = self._session_token()
|
||||
if name not in OPEN_ROUTES:
|
||||
if not auth.session_valid(token):
|
||||
raise ApiError(401, "Du er ikkje innlogga.")
|
||||
if method != "GET":
|
||||
self._check_csrf(token)
|
||||
body = self._json_body() if method in ("POST", "PATCH", "PUT") else {}
|
||||
payload = getattr(self, name)(match.groupdict(), query, body)
|
||||
return self._send_json(payload, cookies=self._pending_cookies)
|
||||
raise ApiError(404, "Fann ikkje det du spurde etter.")
|
||||
|
||||
def _json_body(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if length <= 0:
|
||||
return {}
|
||||
raw = self.rfile.read(length)
|
||||
try:
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise ApiError(400, "Ugyldig JSON i førespurnaden.")
|
||||
if not isinstance(data, dict):
|
||||
raise ApiError(400, "Ugyldig JSON i førespurnaden.")
|
||||
return data
|
||||
|
||||
def _session_token(self):
|
||||
raw = self.headers.get("Cookie")
|
||||
if not raw:
|
||||
return None
|
||||
jar = SimpleCookie()
|
||||
try:
|
||||
jar.load(raw)
|
||||
except CookieError:
|
||||
return None
|
||||
morsel = jar.get(auth.SESSION_COOKIE)
|
||||
return morsel.value if morsel else None
|
||||
|
||||
def _check_csrf(self, token):
|
||||
sent = self.headers.get("X-CSRF-Token") or ""
|
||||
if not sent or not hmac.compare_digest(sent, auth.csrf_secret(token or "")):
|
||||
raise ApiError(403, "Manglande eller feil CSRF-token.")
|
||||
|
||||
def _send_json(self, payload, status=200, cookies=None, headers=None):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self._send_bytes(data, "application/json; charset=utf-8", status, cookies,
|
||||
headers)
|
||||
|
||||
def _send_bytes(self, data, content_type, status=200, cookies=None, headers=None):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
for cookie in cookies or ():
|
||||
self.send_header("Set-Cookie", cookie)
|
||||
for name, value in (headers or {}).items():
|
||||
self.send_header(name, value)
|
||||
self.end_headers()
|
||||
if self.command != "HEAD":
|
||||
self.wfile.write(data)
|
||||
|
||||
def _redirect(self, location):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", location)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
|
||||
# -- static pages -----------------------------------------------------
|
||||
|
||||
def _static(self, path):
|
||||
page = PAGES.get(path)
|
||||
if page is not None:
|
||||
if path != "/login" and not auth.session_valid(self._session_token()):
|
||||
return self._redirect("/login")
|
||||
return self._send_file(STATIC_DIR / page)
|
||||
name = path.lstrip("/")
|
||||
if name in ASSETS:
|
||||
return self._send_file(STATIC_DIR / name)
|
||||
raise ApiError(404, "Fann ikkje sida.")
|
||||
|
||||
def _send_file(self, target):
|
||||
if not target.is_file():
|
||||
raise ApiError(404, "Fann ikkje sida.")
|
||||
content_type = CONTENT_TYPES.get(target.suffix.lower()) or "application/octet-stream"
|
||||
return self._send_bytes(target.read_bytes(), content_type)
|
||||
|
||||
# -- auth -------------------------------------------------------------
|
||||
|
||||
def _admin_username(self):
|
||||
conn = database.connect()
|
||||
try:
|
||||
row = conn.execute("SELECT username FROM admin WHERE id = 1").fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
return row["username"] if row else None
|
||||
|
||||
def _start_session(self, payload):
|
||||
token = auth.create_session()
|
||||
self._pending_cookies.append(_cookie(auth.SESSION_COOKIE, token, True))
|
||||
self._pending_cookies.append(
|
||||
_cookie(auth.CSRF_COOKIE, auth.csrf_secret(token), False)
|
||||
)
|
||||
return payload
|
||||
|
||||
def auth_state(self, params, query, body):
|
||||
authenticated = auth.session_valid(self._session_token())
|
||||
return {
|
||||
"admin_exists": auth.admin_exists(),
|
||||
"authenticated": authenticated,
|
||||
"username": self._admin_username() if authenticated else None,
|
||||
}
|
||||
|
||||
def auth_setup(self, params, query, body):
|
||||
if auth.admin_exists():
|
||||
raise ApiError(400, "Administratoren finst alt.")
|
||||
username, error = validation.validate_username(body.get("username"))
|
||||
if error:
|
||||
raise ApiError(400, error, "username")
|
||||
password, error = validation.validate_password(body.get("password"))
|
||||
if error:
|
||||
raise ApiError(400, error, "password")
|
||||
auth.create_admin(username, password)
|
||||
return self._start_session({"username": username})
|
||||
|
||||
def auth_login(self, params, query, body):
|
||||
if not auth.verify_login(body.get("username"), body.get("password")):
|
||||
raise ApiError(401, "Feil brukarnamn eller passord.")
|
||||
return self._start_session({"username": self._admin_username()})
|
||||
|
||||
def auth_logout(self, params, query, body):
|
||||
auth.delete_session(self._session_token())
|
||||
self._pending_cookies.append(_cookie(auth.SESSION_COOKIE, "", True, max_age=0))
|
||||
self._pending_cookies.append(_cookie(auth.CSRF_COOKIE, "", False, max_age=0))
|
||||
return {"status": "ok"}
|
||||
|
||||
def auth_password(self, params, query, body):
|
||||
token = self._session_token()
|
||||
if not auth.session_valid(token):
|
||||
raise ApiError(401, "Du er ikkje innlogga.")
|
||||
self._check_csrf(token)
|
||||
new_password, error = validation.validate_password(body.get("new_password"))
|
||||
if error:
|
||||
raise ApiError(400, error, "new_password")
|
||||
if not auth.change_password(body.get("current_password"), new_password):
|
||||
raise ApiError(400, "Passordet stemmer ikkje.", "current_password")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def main():
|
||||
"""Serve until the process is stopped."""
|
||||
port = int(os.environ.get("PORT") or DEFAULT_PORT)
|
||||
database.connect().close()
|
||||
server = ThreadingHTTPServer((DEFAULT_HOST, port), SkuldHandler)
|
||||
print("Skuld listening on %s:%d" % (DEFAULT_HOST, port), flush=True)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user