Files

201 lines
8.4 KiB
Nim

## Players, player keys and sessions (DESIGN 3.2, 4.4, 8; issue #17).
## DDL is migration step 2 in db.nim. Choices recorded FIXED (owner-delegated, #17) in DESIGN 3.2:
## player(id, name NULL until first sign-in, role gm|player, colour, created_at);
## player_key(player_id PK FK, secret plaintext, created_at) - one current key, replace overwrites;
## session(id, player_id FK, token_hash UNIQUE, created_at, last_seen) - never expires;
## exactly one GM (partial unique index); max 6 non-GM players, unused keys count.
## Keys are plaintext so the GM can re-show them (Q11); sessions store only SHA-256(token).
## Names (#23, 6.1): `player.setname` fills a NULL name once, `player.rename` overwrites it, and both
## go through `nameTaken` (case-insensitive, "GM" included) and text.validPlayerName. The name is the
## only player field a player writes, and it is also what `roster` publishes to everyone (3.1, Q9).
## This module does no locking: the caller serializes access to the one DbConn (4.3).
import std/[options, strutils, times]
import db_connector/db_sqlite
import crypto, text
type
PlayerRole* = enum
prGm = "gm"
prPlayer = "player"
Player* = object
id*: int
name*: Option[string] ## none = NULL (never signed in, so no display name yet)
role*: PlayerRole
colour*: string
KeyCreated* = object
key*: string
created*: bool
rotated*: bool
const
MaxPlayers* = 6
## Non-GM players; unused keys count toward the cap (DESIGN 3.2).
GmName* = "GM"
PlayerColours* = ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6", "#06b6d4"]
GmColour* = "#6b7280"
proc nowStamp(): string =
now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
proc rowToPlayer(row: Row): Player =
Player(id: parseInt(row[0]),
name: if row[1].len == 0: none(string) else: some(row[1]),
role: parseEnum[PlayerRole](row[2]),
colour: row[3])
proc gmPlayer*(db: DbConn): Option[Player] =
for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player WHERE role = 'gm'"):
return some(rowToPlayer(row))
proc playerById*(db: DbConn, id: int): Option[Player] =
for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player WHERE id = ?", id):
return some(rowToPlayer(row))
proc playerCount*(db: DbConn): int =
## Non-GM players, named or not (unused keys count toward the 6-player cap).
parseInt(db.getValue(sql"SELECT count(*) FROM player WHERE role = 'player'"))
proc allPlayers*(db: DbConn): seq[Player] =
## Every player row, in id order: the roster (6.1) and the GM's character list walk this.
for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player ORDER BY id"):
result.add rowToPlayer(row)
proc nameTaken*(db: DbConn, name: string, exceptId = 0): bool =
## 6.5 `name-taken`: a player name is unique regardless of case, and the GM's name ("GM") is a
## name like any other - so taking it is refused here, not by a special case.
for row in db.getAllRows(sql"SELECT id, name FROM player WHERE name IS NOT NULL"):
if parseInt(row[0]) == exceptId: continue
if sameName(row[1], name): return true
proc setName*(db: DbConn, playerId: int, name: string): bool =
## `player.setname`: only while the player has no name yet (6.1). false = it already had one.
db.execAffectedRows(sql"UPDATE player SET name = ? WHERE id = ? AND name IS NULL",
name, playerId) > 0
proc renamePlayer*(db: DbConn, playerId: int, name: string): bool =
## `player.rename` (GM only): a named or unnamed player takes the new name.
db.execAffectedRows(sql"UPDATE player SET name = ? WHERE id = ?", name, playerId) > 0
proc keyOf*(db: DbConn, playerId: int): Option[string] =
let s = db.getValue(sql"SELECT secret FROM player_key WHERE player_id = ?", playerId)
if s.len == 0: none(string) else: some(s)
proc insertKey(db: DbConn, playerId: int, key: string) =
db.exec(sql"INSERT INTO player_key (player_id, secret, created_at) VALUES (?, ?, ?)",
playerId, key, nowStamp())
proc ensureGm*(db: DbConn, rotate = false): KeyCreated =
## Creates the single GM (role gm, name "GM") if absent; prints the same key on re-run.
## rotate = true: new key, all GM sessions revoked. Caller guarantees no server holds the lock.
let gm = gmPlayer(db)
if gm.isSome:
let id = gm.get.id
if rotate:
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
db.exec(sql"UPDATE player_key SET secret = ?, created_at = ? WHERE player_id = ?",
key, nowStamp(), id)
db.exec(sql"DELETE FROM session WHERE player_id = ?", id)
db.exec(sql"COMMIT")
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
return KeyCreated(key: key, rotated: true)
let existing = keyOf(db, id)
if existing.isSome:
return KeyCreated(key: existing.get)
# Degraded DB (key row missing): heal it rather than print nothing.
let key = generatePlayerKey()
insertKey(db, id, key)
return KeyCreated(key: key, created: true)
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
let id = int(insertID(db,
sql"INSERT INTO player (name, role, colour, created_at) VALUES (?, 'gm', ?, ?)",
GmName, GmColour, nowStamp()))
insertKey(db, id, key)
db.exec(sql"COMMIT")
result = KeyCreated(key: key, created: true)
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
proc createPlayerWithKey*(db: DbConn): tuple[id: int, key: string] =
## key.create: no name at creation (the player types it at first sign-in, DESIGN 3.2).
let colour = PlayerColours[playerCount(db) mod PlayerColours.len]
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
let id = int(insertID(db,
sql"INSERT INTO player (name, role, colour, created_at) VALUES (NULL, 'player', ?, ?)",
colour, nowStamp()))
insertKey(db, id, key)
db.exec(sql"COMMIT")
result = (id: id, key: key)
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
proc findPlayerByKey*(db: DbConn, input: string): Option[Player] =
## Every row is compared without an early exit; comparison ignores case, dashes and spaces.
let wanted = normalizeKey(input)
if wanted.len == 0: return none(Player)
var found: Option[Player]
for row in db.getAllRows(sql"""
SELECT p.id, p.name, p.role, p.colour, k.secret
FROM player p JOIN player_key k ON k.player_id = p.id ORDER BY p.id"""):
if constantTimeEqual(normalizeKey(row[4]), wanted):
found = some(rowToPlayer(row))
found
proc replacePlayerKey*(db: DbConn, playerId: int): Option[string] =
## key.replace: new secret, all sessions of that player revoked. The GM's own key never rotates
## here (CLI only, DESIGN 3.2) - the caller refuses before calling.
let player = playerById(db, playerId)
if player.isNone or player.get.role == prGm: return none(string)
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
db.exec(sql"UPDATE player_key SET secret = ?, created_at = ? WHERE player_id = ?",
key, nowStamp(), playerId)
db.exec(sql"DELETE FROM session WHERE player_id = ?", playerId)
db.exec(sql"COMMIT")
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
some(key)
proc removePlayer*(db: DbConn, playerId: int): bool =
## player.remove: key and sessions go with the player (ON DELETE CASCADE). Characters and
## controlled tokens are the GM's from slice 8 on; those tables do not exist in slice 2.
db.execAffectedRows(sql"DELETE FROM player WHERE id = ? AND role = 'player'", playerId) > 0
proc createSession*(db: DbConn, playerId: int, tokenHash: string) =
let stamp = nowStamp()
db.exec(sql"INSERT INTO session (player_id, token_hash, created_at, last_seen) VALUES (?, ?, ?, ?)",
playerId, tokenHash, stamp, stamp)
proc sessionPlayer*(db: DbConn, tokenHash: string): Option[Player] =
if tokenHash.len == 0: return none(Player)
for row in db.getAllRows(sql"""
SELECT p.id, p.name, p.role, p.colour
FROM session s JOIN player p ON p.id = s.player_id
WHERE s.token_hash = ? ORDER BY s.id""", tokenHash):
return some(rowToPlayer(row))
proc revokeSessions*(db: DbConn, playerId: int) =
db.exec(sql"DELETE FROM session WHERE player_id = ?", playerId)
proc sessionCount*(db: DbConn, playerId: int): int =
parseInt(db.getValue(sql"SELECT count(*) FROM session WHERE player_id = ?", playerId))