DK2/src/model/user.php

53 lines
1.8 KiB
PHP

<?php
/**
* Find a user by username, email, or id.
*/
function user_find($user)
{
$result = db_query(db_auth(), "SELECT * FROM users WHERE username = :u OR email = :u OR id = :u", [':u' => $user]);
$user = $result->fetchArray(SQLITE3_ASSOC);
if (!$user) return false;
$result->finalize();
return $user;
}
/**
* Create a user with a username, email, and password. Optionally pass an auth level. This function will not check
* if the username or email already exists. It is up to the caller to check this before calling this function. It is
* also up to the caller to validate password strength. This function will hash the password with the PASSWORD_ARGON2ID
* algorithm.
*/
function user_create($username, $email, $password, $auth = 0)
{
return db_query(db_auth(), "INSERT INTO users (username, email, password, auth) VALUES (:u, :e, :p, :a)", [
':u' => $username,
':e' => $email,
':p' => password_hash($password, PASSWORD_ARGON2ID),
':a' => $auth
]);
}
/**
* Delete a user by username, email, or id.
*/
function user_delete($user)
{
return db_query(db_auth(), "DELETE FROM users WHERE username = :u OR email = :u OR id = :u", [':u' => $user]);
}
/**
* Creates an account wallet. Can optionally specify the starting balances of the wallet. Returns the created wallet's
* ID. If a currency is set to -1, the starting_silver or starting_star_gems fields from the env will be used.
*/
function wallet_create($user_id, $silver = -1, $starGems = -1)
{
if (db_query(db_live(), "INSERT INTO wallets (user_id, silver, stargem) VALUES (:u, :s, :sg)", [
':u' => $user_id,
':s' => $silver === -1 ? env('start_silver', 10) : $silver,
':sg' => $starGems === -1 ? env('start_star_gems', 0) : $starGems
]) === false) {
throw new Exception('Failed to create wallet. (wc)');
}
}