'use strict'; /* Create account + operator + capital POP + first token in one transaction. The password hash and token hash are * computed by the route before the transaction (scrypt is async, a transaction never spans an await). */ const { GameError } = require('../errors'); const joinWorld = require('./joinWorld'); module.exports = function signup(ctx, { username, passHash, tokenHash, device, worldId }) { const { db, now } = ctx; if (db.get('SELECT 1 AS x FROM users WHERE username = ?', username)) throw new GameError('username_taken'); const w = worldId !== undefined ? db.get("SELECT id FROM worlds WHERE id = ? AND status = 'running'", worldId) : db.get("SELECT id FROM worlds WHERE status = 'running' ORDER BY id LIMIT 1"); if (!w) throw new GameError('not_found', { what: 'world' }); const u = db.run('INSERT INTO users (username, pass_hash, created_at) VALUES (?, ?, ?)', username, passHash, now); const userId = Number(u.lastInsertRowid); const joined = joinWorld(ctx, { userId, worldId: w.id }); const t = db.run('INSERT INTO tokens (user_id, token_hash, device, created_at, last_used_at) VALUES (?, ?, ?, ?, ?)', userId, tokenHash, device || '', now, now); return Object.assign({ userId, tokenId: Number(t.lastInsertRowid) }, joined); };