server: auth schema, keys, sessions, connection registry (#17)
This commit is contained in:
+29
-4
@@ -18,7 +18,9 @@ type
|
||||
Migration* = object
|
||||
version*: int
|
||||
name*: string
|
||||
sql*: string
|
||||
stmts*: seq[string]
|
||||
## One or more DDL statements, run in order inside the step's transaction.
|
||||
## db_connector's exec() prepares a single statement, so they cannot be one string.
|
||||
MigrationRow* = tuple[version: int, name: string]
|
||||
|
||||
const
|
||||
@@ -29,11 +31,33 @@ CREATE TABLE IF NOT EXISTS schema_migration (
|
||||
applied_at TEXT NOT NULL
|
||||
)"""
|
||||
migrations* = [
|
||||
Migration(version: 1, name: "meta", sql: """
|
||||
Migration(version: 1, name: "meta", stmts: @["""
|
||||
CREATE TABLE meta (
|
||||
k TEXT PRIMARY KEY,
|
||||
v TEXT NOT NULL
|
||||
)"""),
|
||||
)"""]),
|
||||
Migration(version: 2, name: "auth", stmts: @["""
|
||||
CREATE TABLE player (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT UNIQUE, -- NULL until first sign-in; unique among players
|
||||
role TEXT NOT NULL CHECK (role IN ('gm', 'player')),
|
||||
colour TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
)""", """
|
||||
CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm'""", """
|
||||
CREATE TABLE player_key (
|
||||
player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE,
|
||||
secret TEXT NOT NULL, -- plaintext: the GM can re-show it (Q11)
|
||||
created_at TEXT NOT NULL
|
||||
)""", """
|
||||
CREATE TABLE session (
|
||||
id INTEGER PRIMARY KEY,
|
||||
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the cookie token; the token is never stored
|
||||
created_at TEXT NOT NULL,
|
||||
last_seen TEXT NOT NULL
|
||||
)""", """
|
||||
CREATE INDEX session_player ON session(player_id)"""]),
|
||||
]
|
||||
LatestVersion* = migrations[^1].version
|
||||
## Derived, so adding a step cannot leave it stale.
|
||||
@@ -77,7 +101,8 @@ proc migrate*(db: DbConn): int =
|
||||
if m.version <= version: continue
|
||||
db.exec(sql"BEGIN")
|
||||
try:
|
||||
db.exec(sql(m.sql))
|
||||
for stmt in m.stmts:
|
||||
db.exec(sql(stmt))
|
||||
let stamp = now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
|
||||
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, ?)",
|
||||
m.version, m.name, stamp)
|
||||
|
||||
Reference in New Issue
Block a user