Each vote can require N fresh codes read off the projector (default 3, off for rooms without a projector); voters enrolled with a paper or rescue code are exempt. Rescue codes enroll a phone without camera. Projector keeps the QR up while such a vote is open. Server pings every socket every 25s so proxies keep them open. Composer no longer closes on enter. Schema migrates existing databases.
273 lines
10 KiB
Python
273 lines
10 KiB
Python
import json
|
|
import secrets
|
|
import sqlite3
|
|
from contextlib import contextmanager
|
|
|
|
from . import config
|
|
from .tokens import new_id, new_key, now_ms, sha
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS polls(
|
|
id TEXT PRIMARY KEY,
|
|
title TEXT NOT NULL,
|
|
admin_hash TEXT NOT NULL,
|
|
screen_hash TEXT NOT NULL,
|
|
secret BLOB NOT NULL,
|
|
interval_ms INTEGER NOT NULL,
|
|
scans_required INTEGER NOT NULL,
|
|
enrollment_open INTEGER NOT NULL DEFAULT 0,
|
|
max_voters INTEGER,
|
|
expected INTEGER,
|
|
require_code INTEGER NOT NULL DEFAULT 0,
|
|
vote_scans INTEGER NOT NULL DEFAULT 0,
|
|
focus_qid INTEGER,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
-- random ids + WITHOUT ROWID so storage order says nothing about enrollment or vote order
|
|
CREATE TABLE IF NOT EXISTS voters(
|
|
id TEXT PRIMARY KEY,
|
|
poll_id TEXT NOT NULL,
|
|
cred_hash TEXT NOT NULL UNIQUE,
|
|
via_code INTEGER NOT NULL DEFAULT 0
|
|
) WITHOUT ROWID;
|
|
CREATE INDEX IF NOT EXISTS voters_poll ON voters(poll_id);
|
|
CREATE TABLE IF NOT EXISTS access_codes(
|
|
poll_id TEXT NOT NULL,
|
|
code TEXT NOT NULL,
|
|
used INTEGER NOT NULL DEFAULT 0,
|
|
rescue INTEGER NOT NULL DEFAULT 0,
|
|
PRIMARY KEY(poll_id, code)
|
|
) WITHOUT ROWID;
|
|
CREATE TABLE IF NOT EXISTS questions(
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
poll_id TEXT NOT NULL,
|
|
position INTEGER NOT NULL,
|
|
text TEXT NOT NULL,
|
|
kind TEXT NOT NULL,
|
|
options TEXT NOT NULL,
|
|
max_choices INTEGER NOT NULL DEFAULT 1,
|
|
allow_blank INTEGER NOT NULL DEFAULT 1,
|
|
state TEXT NOT NULL DEFAULT 'draft',
|
|
results_public INTEGER NOT NULL DEFAULT 0
|
|
);
|
|
CREATE INDEX IF NOT EXISTS questions_poll ON questions(poll_id);
|
|
-- who took part, never what they chose
|
|
CREATE TABLE IF NOT EXISTS participation(
|
|
question_id INTEGER NOT NULL,
|
|
voter_id TEXT NOT NULL,
|
|
PRIMARY KEY(question_id, voter_id)
|
|
) WITHOUT ROWID;
|
|
-- what was chosen, never by whom. no timestamp on purpose
|
|
CREATE TABLE IF NOT EXISTS ballots(
|
|
id TEXT PRIMARY KEY,
|
|
question_id INTEGER NOT NULL,
|
|
choices TEXT NOT NULL
|
|
) WITHOUT ROWID;
|
|
CREATE INDEX IF NOT EXISTS ballots_q ON ballots(question_id);
|
|
"""
|
|
|
|
|
|
class DB:
|
|
def __init__(self, path: str):
|
|
# all access happens on the event loop thread, so one connection is enough
|
|
self.c = sqlite3.connect(path, isolation_level=None, check_same_thread=False)
|
|
self.c.row_factory = sqlite3.Row
|
|
# rollback journal (not WAL) so no log of recent inserts stays on disk
|
|
self.c.execute("PRAGMA journal_mode=DELETE")
|
|
self.c.execute("PRAGMA secure_delete=ON")
|
|
self.c.execute("PRAGMA foreign_keys=ON")
|
|
self.c.executescript(SCHEMA)
|
|
self._migrate()
|
|
|
|
def _migrate(self):
|
|
# columns added after the first release, old databases get them here
|
|
for table, col, ddl in (
|
|
("polls", "vote_scans", "INTEGER NOT NULL DEFAULT 0"),
|
|
("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"),
|
|
("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"),
|
|
):
|
|
cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")}
|
|
if col not in cols:
|
|
self.c.execute(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")
|
|
|
|
@contextmanager
|
|
def tx(self):
|
|
self.c.execute("BEGIN IMMEDIATE")
|
|
try:
|
|
yield self.c
|
|
self.c.execute("COMMIT")
|
|
except BaseException:
|
|
self.c.execute("ROLLBACK")
|
|
raise
|
|
|
|
def one(self, sql, *args):
|
|
return self.c.execute(sql, args).fetchone()
|
|
|
|
def all(self, sql, *args):
|
|
return self.c.execute(sql, args).fetchall()
|
|
|
|
|
|
def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters, vote_scans=0):
|
|
pid = new_id()
|
|
while self.one("SELECT 1 FROM polls WHERE id=?", pid):
|
|
pid = new_id()
|
|
admin_key, screen_key = new_key(), new_key()
|
|
self.c.execute(
|
|
"INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required,"
|
|
"require_code,expected,max_voters,vote_scans,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
|
|
(pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms,
|
|
scans_required, int(require_code), expected, max_voters, vote_scans, now_ms()),
|
|
)
|
|
return pid, admin_key, screen_key
|
|
|
|
def poll(self, pid):
|
|
return self.one("SELECT * FROM polls WHERE id=?", pid)
|
|
|
|
def update_poll(self, pid, **fields):
|
|
allowed = {"title", "interval_ms", "scans_required", "enrollment_open", "max_voters",
|
|
"expected", "require_code", "focus_qid", "vote_scans"}
|
|
fields = {k: v for k, v in fields.items() if k in allowed}
|
|
if not fields:
|
|
return
|
|
sets = ",".join(f"{k}=?" for k in fields)
|
|
self.c.execute(f"UPDATE polls SET {sets} WHERE id=?", (*fields.values(), pid))
|
|
|
|
def voter_count(self, pid):
|
|
return self.one("SELECT COUNT(*) n FROM voters WHERE poll_id=?", pid)["n"]
|
|
|
|
|
|
def voter_by_cred(self, pid, cred):
|
|
if not cred:
|
|
return None
|
|
return self.one("SELECT * FROM voters WHERE poll_id=? AND cred_hash=?", pid, sha(cred))
|
|
|
|
def enroll(self, pid, code=None, rescue_code=None):
|
|
"""creates a voter atomically. returns (cred, error)
|
|
rescue_code: a one-time code that replaces the scan (broken camera)"""
|
|
with self.tx() as c:
|
|
p = c.execute("SELECT * FROM polls WHERE id=?", (pid,)).fetchone()
|
|
if not p["enrollment_open"]:
|
|
return None, "closed"
|
|
if p["max_voters"] is not None:
|
|
n = c.execute("SELECT COUNT(*) FROM voters WHERE poll_id=?", (pid,)).fetchone()[0]
|
|
if n >= p["max_voters"]:
|
|
return None, "full"
|
|
if rescue_code is not None:
|
|
cur = c.execute("UPDATE access_codes SET used=1 WHERE poll_id=? AND code=? AND used=0 AND rescue=1",
|
|
(pid, normalize_code(rescue_code)))
|
|
if cur.rowcount != 1:
|
|
return None, "bad_code"
|
|
elif p["require_code"]:
|
|
cur = c.execute("UPDATE access_codes SET used=1 WHERE poll_id=? AND code=? AND used=0 AND rescue=0",
|
|
(pid, normalize_code(code or "")))
|
|
if cur.rowcount != 1:
|
|
return None, "bad_code"
|
|
cred = secrets.token_urlsafe(32)
|
|
# people who came in with a paper code skip the per-vote scan
|
|
via_code = rescue_code is not None or bool(p["require_code"])
|
|
c.execute("INSERT INTO voters(id,poll_id,cred_hash,via_code) VALUES(?,?,?,?)",
|
|
(secrets.token_hex(16), pid, sha(cred), int(via_code)))
|
|
return cred, None
|
|
|
|
|
|
def add_codes(self, pid, count, rescue=False):
|
|
codes = []
|
|
with self.tx() as c:
|
|
while len(codes) < count:
|
|
code = gen_code()
|
|
try:
|
|
c.execute("INSERT INTO access_codes(poll_id,code,rescue) VALUES(?,?,?)", (pid, code, int(rescue)))
|
|
codes.append(code)
|
|
except sqlite3.IntegrityError:
|
|
pass
|
|
return codes
|
|
|
|
def codes(self, pid):
|
|
return [dict(r) for r in self.all(
|
|
"SELECT code, used, rescue FROM access_codes WHERE poll_id=? ORDER BY code", pid)]
|
|
|
|
|
|
def add_question(self, pid, text, kind, options, max_choices, allow_blank):
|
|
pos = self.one("SELECT COALESCE(MAX(position),0)+1 p FROM questions WHERE poll_id=?", pid)["p"]
|
|
cur = self.c.execute(
|
|
"INSERT INTO questions(poll_id,position,text,kind,options,max_choices,allow_blank) "
|
|
"VALUES(?,?,?,?,?,?,?)",
|
|
(pid, pos, text, kind, json.dumps(options, ensure_ascii=False), max_choices, int(allow_blank)),
|
|
)
|
|
return cur.lastrowid
|
|
|
|
def question(self, pid, qid):
|
|
return self.one("SELECT * FROM questions WHERE poll_id=? AND id=?", pid, qid)
|
|
|
|
def questions(self, pid):
|
|
return self.all("SELECT * FROM questions WHERE poll_id=? ORDER BY position", pid)
|
|
|
|
def set_question(self, qid, **fields):
|
|
allowed = {"state", "results_public"}
|
|
fields = {k: v for k, v in fields.items() if k in allowed}
|
|
sets = ",".join(f"{k}=?" for k in fields)
|
|
self.c.execute(f"UPDATE questions SET {sets} WHERE id=?", (*fields.values(), qid))
|
|
|
|
def delete_question(self, qid):
|
|
self.c.execute("DELETE FROM questions WHERE id=? AND state='draft'", (qid,))
|
|
|
|
def participants(self, qid):
|
|
return self.one("SELECT COUNT(*) n FROM participation WHERE question_id=?", qid)["n"]
|
|
|
|
def voted_qids(self, voter_id, pid):
|
|
rows = self.all(
|
|
"SELECT p.question_id FROM participation p JOIN questions q ON q.id=p.question_id "
|
|
"WHERE p.voter_id=? AND q.poll_id=?", voter_id, pid)
|
|
return {r[0] for r in rows}
|
|
|
|
def cast(self, pid, qid, voter_id, choices):
|
|
"""participation + ballot in one tx. returns error string or None"""
|
|
with self.tx() as c:
|
|
q = c.execute("SELECT state FROM questions WHERE id=? AND poll_id=?", (qid, pid)).fetchone()
|
|
if not q or q["state"] != "open":
|
|
return "not_open"
|
|
try:
|
|
c.execute("INSERT INTO participation(question_id,voter_id) VALUES(?,?)", (qid, voter_id))
|
|
except sqlite3.IntegrityError:
|
|
return "already_voted"
|
|
c.execute("INSERT INTO ballots(id,question_id,choices) VALUES(?,?,?)",
|
|
(secrets.token_hex(16), qid, json.dumps(sorted(choices))))
|
|
return None
|
|
|
|
def results(self, q):
|
|
opts = json.loads(q["options"])
|
|
counts = [0] * len(opts)
|
|
blank = 0
|
|
total = 0
|
|
for r in self.all("SELECT choices FROM ballots WHERE question_id=?", q["id"]):
|
|
total += 1
|
|
ch = json.loads(r["choices"])
|
|
if not ch:
|
|
blank += 1
|
|
for i in ch:
|
|
if 0 <= i < len(counts):
|
|
counts[i] += 1
|
|
return {"counts": counts, "blank": blank, "ballots": total}
|
|
|
|
def ballots(self, qid):
|
|
# pk is random so this order is meaningless, which is the point
|
|
return [json.loads(r["choices"]) for r in self.all(
|
|
"SELECT choices FROM ballots WHERE question_id=? ORDER BY id", qid)]
|
|
|
|
|
|
CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
|
|
|
|
|
def gen_code():
|
|
raw = "".join(secrets.choice(CODE_ALPHABET) for _ in range(8))
|
|
return f"{raw[:4]}-{raw[4:]}"
|
|
|
|
|
|
def normalize_code(s: str) -> str:
|
|
s = "".join(ch for ch in s.upper() if ch.isalnum())
|
|
return f"{s[:4]}-{s[4:8]}" if len(s) == 8 else s
|
|
|
|
|
|
def open_db():
|
|
return DB(config.DB_PATH)
|