Overlays no longer replace service: each names the Core apps it needs in .depends, merged into DEPENDS. The sign-in code is a module (oidc.py) that examples import; templates/postgres-sso is the combined example (sign-in, each person's visits counted in PostgreSQL). Tested with team-visits, including sign-in in a browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
146 lines
4.9 KiB
Python
146 lines
4.9 KiB
Python
"""{{TITLE}}: signs people in with the Core's Authelia, and counts each
|
|
person's visits in its PostgreSQL database.
|
|
|
|
The sign-in is in oidc.py. Settings come from the environment (.env on the
|
|
Core): DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, and oidc.py's.
|
|
"""
|
|
|
|
import html
|
|
import os
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
from http.cookies import SimpleCookie
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
import psycopg
|
|
|
|
import oidc
|
|
|
|
DB = {
|
|
"host": os.environ["DB_HOST"],
|
|
"port": os.environ.get("DB_PORT", "5432"),
|
|
"dbname": os.environ["DB_NAME"],
|
|
"user": os.environ["DB_USER"],
|
|
"password": os.environ["DB_PASSWORD"],
|
|
"connect_timeout": 5,
|
|
}
|
|
|
|
|
|
def connect():
|
|
return psycopg.connect(**DB, autocommit=True)
|
|
|
|
|
|
def setup():
|
|
# PostgreSQL may still be starting (after a reboot): keep trying
|
|
for attempt in range(60):
|
|
try:
|
|
with connect() as db:
|
|
db.execute(
|
|
"CREATE TABLE IF NOT EXISTS visits ("
|
|
" id bigserial PRIMARY KEY,"
|
|
" person text NOT NULL,"
|
|
" at timestamptz NOT NULL DEFAULT now())"
|
|
)
|
|
return
|
|
except psycopg.OperationalError as error:
|
|
print(f"Waiting for the database ({error})", flush=True)
|
|
time.sleep(5)
|
|
raise SystemExit("The database didn't answer for 5 minutes")
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
url = urllib.parse.urlsplit(self.path)
|
|
query = dict(urllib.parse.parse_qsl(url.query))
|
|
routes = {
|
|
"/": self.home,
|
|
"/login": self.login,
|
|
"/auth/callback": self.callback,
|
|
"/logout": self.logout,
|
|
"/health": lambda q: self.reply(200, "ok\n", "text/plain"),
|
|
}
|
|
route = routes.get(url.path)
|
|
if route is None:
|
|
self.reply(404, "Not found\n", "text/plain")
|
|
return
|
|
try:
|
|
route(query)
|
|
except oidc.SignInError as error:
|
|
self.reply(400, f"Sign-in failed: {error}\n", "text/plain")
|
|
except (urllib.error.URLError, KeyError, ValueError) as error:
|
|
self.reply(502, f"Sign-in failed: {error}\n", "text/plain")
|
|
except psycopg.Error as error:
|
|
self.reply(503, f"Database error: {error}\n", "text/plain")
|
|
|
|
def cookie(self, name):
|
|
cookies = SimpleCookie(self.headers.get("Cookie", ""))
|
|
return cookies[name].value if name in cookies else None
|
|
|
|
def home(self, query):
|
|
user = oidc.read_session(self.cookie("session"))
|
|
if not user:
|
|
self.page('<p><a href="/login">Sign in with your Core account</a></p>')
|
|
return
|
|
with connect() as db:
|
|
db.execute("INSERT INTO visits (person) VALUES (%s)", (user["sub"],))
|
|
mine = db.execute(
|
|
"SELECT count(*) FROM visits WHERE person = %s", (user["sub"],)
|
|
).fetchone()[0]
|
|
people = db.execute("SELECT count(DISTINCT person) FROM visits").fetchone()[0]
|
|
self.page(
|
|
f"<p>Signed in as <strong id=\"user\">{html.escape(user['name'])}</strong>"
|
|
f" ({html.escape(user['email'])}).</p>"
|
|
f"<p>Your visits: <strong id=\"visits\">{mine}</strong>"
|
|
f" (people who have visited: {people}), counted in PostgreSQL.</p>"
|
|
'<p><a href="/logout">Sign out</a></p>'
|
|
)
|
|
|
|
def login(self, query):
|
|
location, flow = oidc.start_login()
|
|
self.redirect(location, [("flow", flow, oidc.FLOW_SECONDS)])
|
|
|
|
def callback(self, query):
|
|
user = oidc.finish_login(query, self.cookie("flow"))
|
|
self.redirect("/", [("session", oidc.make_session(user), oidc.SESSION_SECONDS),
|
|
("flow", "", 0)])
|
|
|
|
def logout(self, query):
|
|
self.redirect("/", [("session", "", 0)])
|
|
|
|
def page(self, body):
|
|
self.reply(200, f"""<!doctype html>
|
|
<html lang="en">
|
|
<head><meta charset="utf-8"><title>{{TITLE}}</title></head>
|
|
<body>
|
|
<h1>{{TITLE}}</h1>
|
|
<p>Running on Federated Core, deployed with coreapp-dev.</p>
|
|
{body}
|
|
</body>
|
|
</html>
|
|
""", "text/html; charset=utf-8")
|
|
|
|
def redirect(self, location, cookies=()):
|
|
self.send_response(302)
|
|
self.send_header("Location", location)
|
|
for name, value, max_age in cookies:
|
|
self.send_header(
|
|
"Set-Cookie",
|
|
f"{name}={value}; Max-Age={max_age}; Path=/; Secure; HttpOnly; SameSite=Lax")
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
|
|
def reply(self, status, body, content_type):
|
|
data = body.encode()
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", content_type)
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
setup()
|
|
print("Listening on port 8080", flush=True)
|
|
ThreadingHTTPServer(("", 8080), Handler).serve_forever()
|