Examples/Accounts_with_the_SQLite_module_register_login_and_stats

A server-only script that keeps accounts and statistics in a database with the object oriented lu_sqlite2 module (appendix C.4). A player registers once with /register <password> and logs in with /login <password> on the next visit. Kills, deaths and cash are stored in the accounts.db file next to Server.exe, /stats shows them (yours, a player id, or any name, also when that player is offline) and /top lists the five best killers. Passwords are never stored: each account keeps a random salt and the SHA1 of salt + password (lu_hashing).

LoadModule("lu_sqlite2");
LoadModule("lu_hashing");

db <- null;                                   // the open database
loggedIn <- array(GetMaxPlayers(), false);    // true once a slot has logged in

function onScriptLoad()
{
    srand(time());                            // so the salts differ after every restart
    db = SQLiteConnection("accounts.db");     // created next to Server.exe
    db.exec("CREATE TABLE IF NOT EXISTS accounts ("
        + "id INTEGER PRIMARY KEY, "
        + "name TEXT UNIQUE COLLATE NOCASE, "  // one account per name, any case
        + "salt TEXT, hash TEXT, "
        + "kills INTEGER NOT NULL DEFAULT 0, "
        + "deaths INTEGER NOT NULL DEFAULT 0, "
        + "cash INTEGER NOT NULL DEFAULT 0, "
        + "joined INTEGER)");
    print("accounts loaded: " + db.queryValue("SELECT COUNT(*) FROM accounts"));
}

function onScriptUnload()
{
    if (db) db.close();
}

// ---- helpers ------------------------------------------------------------------

function newSalt()
{
    local s = "";
    for (local i = 0; i < 12; i++) s += (rand() % 10).tostring();
    return s;
}

function hashPassword(salt, password)
{
    return SHA1(salt + password);
}

function accountExists(name)
{
    return db.queryValue("SELECT COUNT(*) FROM accounts WHERE name = ?", name) > 0;
}

// returns null when it worked, otherwise the text to show the player
function registerAccount(name, password)
{
    if (accountExists(name))
        return "That name is already registered. Use /login <password>";
    if (password.len() < 4)
        return "The password needs at least 4 characters.";
    local salt = newSalt();
    db.exec("INSERT INTO accounts (name, salt, hash, joined) VALUES (?, ?, ?, ?)",
            name, salt, hashPassword(salt, password), time());
    return null;
}

// returns the account row (a table) when the password is right, otherwise null
function checkLogin(name, password)
{
    local row = db.queryRow("SELECT * FROM accounts WHERE name = ?", name);
    if (row == null) return null;
    if (hashPassword(row.salt, password) != row.hash) return null;
    return row;
}

// "Tom: 12 kills, 5 deaths, K/D 2.40, $1500" - or null when nobody has that name
function statsLine(name)
{
    local r = db.queryRow(
        "SELECT name, kills, deaths, cash FROM accounts WHERE name = ?", name);
    if (r == null) return null;
    local kd = r.kills.tofloat();
    if (r.deaths > 0) kd = r.kills.tofloat() / r.deaths;
    return r.name + ": " + r.kills + " kills, " + r.deaths + " deaths, K/D "
        + format("%.2f", kd) + ", $" + r.cash;
}

function saveCash(player)
{
    if (!loggedIn[player.ID]) return;
    db.exec("UPDATE accounts SET cash = ? WHERE name = ?",
            player.Cash.tointeger(), player.Name);
}

function say(player, text)
{
    MessagePlayer(text, player);
}

// ---- events -------------------------------------------------------------------

function onPlayerJoin(player)
{
    loggedIn[player.ID] = false;
    if (accountExists(player.Name))
        say(player, "Welcome back, " + player.Name + "! Type /login <password>");
    else
        say(player, "Welcome! Create an account with /register <password>");
}

function onPlayerRequestSpawn(player, classID)
{
    if (!loggedIn[player.ID])
    {
        say(player, "Log in first: /login <password> (or /register <password>)");
        return false;                          // stays on the class selection screen
    }
    return true;
}

function onPlayerPart(player, reason)
{
    saveCash(player);
    loggedIn[player.ID] = false;
}

function onPlayerDeath(player, reason)
{
    if (!loggedIn[player.ID]) return;
    db.exec("UPDATE accounts SET deaths = deaths + 1 WHERE name = ?", player.Name);
    saveCash(player);
}

function onPlayerKill(killer, victim, weaponID, bodyPartID)
{
    if (!loggedIn[killer.ID]) return;
    db.exec("UPDATE accounts SET kills = kills + 1 WHERE name = ?", killer.Name);
    saveCash(killer);
}

function onPlayerCommand(player, cmd, params)
{
    if (cmd == "register")
    {
        if (loggedIn[player.ID]) { say(player, "You are already logged in."); return true; }
        local err = registerAccount(player.Name, params);
        if (err) { say(player, err); return true; }
        loggedIn[player.ID] = true;
        say(player, "Account created, you are logged in. Press spawn!");
        return true;
    }

    if (cmd == "login")
    {
        if (loggedIn[player.ID]) { say(player, "You are already logged in."); return true; }
        local row = checkLogin(player.Name, params);
        if (row == null)
        {
            say(player, "Wrong password, or no account yet (/register).");
            return true;
        }
        loggedIn[player.ID] = true;
        player.Cash = row.cash;                // the saved money comes back
        say(player, "Logged in. " + statsLine(player.Name));
        return true;
    }

    if (cmd == "stats")
    {
        // /stats = yours, /stats 3 = player id 3, /stats Tom = by name (also offline)
        local name = player.Name;
        if (params != "")
        {
            name = params;
            if (IsNum(params))
            {
                local p = FindPlayer(params.tointeger());
                if (!p) { say(player, "No player with that id."); return true; }
                name = p.Name;
            }
        }
        local line = statsLine(name);
        say(player, line ? line : "No account called " + name);
        return true;
    }

    if (cmd == "top")                          // the 5 best killers
    {
        local res = db.query(
            "SELECT name, kills FROM accounts ORDER BY kills DESC, name LIMIT 5");
        local n = 1;
        while (res.next())
        {
            say(player, n + ". " + res.get("name") + ": " + res.getInt("kills") + " kills");
            n++;
        }
        if (n == 1) say(player, "Nobody has an account yet.");
        return true;
    }

    return false;
}

How it works: every SQL statement uses ? parameters, so a password or a name with a quote in it cannot break the query. queryValue answers "does this name exist", queryRow returns one account as a table (row.salt, row.kills), and query + next() walks the /top list. onPlayerRequestSpawn returns false until the player is logged in, so he stays on the class selection screen. Cash is saved on every kill, death and when the player leaves; a server crash can lose the cash earned since then.

NoteThis is the smallest useful version. Real servers also limit login attempts (11.7 kicks after 3 tries) and ask for the password with a dialog (DIALOG_STYLE_PASSWORD) so it does not stay in the chat box.
Categories: Worked examples