80 lines
2.3 KiB
PHP
80 lines
2.3 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Checks if the given username already exists.
|
|
*/
|
|
function auth_username_exists(string $username): bool
|
|
{
|
|
return db_exists(db_auth(), 'users', 'username', $username);
|
|
}
|
|
|
|
/**
|
|
* Checks if the given email already exists.
|
|
*/
|
|
function auth_email_exists(string $email): bool
|
|
{
|
|
return db_exists(db_auth(), 'users', 'email', $email);
|
|
}
|
|
|
|
/**
|
|
* Check for a user session. If $_SESSION['user'] already exists, return early. If not, check for a remember me
|
|
* cookie. If a remember me cookie exists, validate the session and set $_SESSION['user'].
|
|
*/
|
|
function auth_check(): bool
|
|
{
|
|
if (isset($_SESSION['user'])) return true;
|
|
|
|
if (isset($_COOKIE['remember_me'])) {
|
|
$session = session_validate($_COOKIE['remember_me']);
|
|
if ($session === true) {
|
|
$user = user_find($session['user_id']);
|
|
unset($user['password']);
|
|
$_SESSION['user'] = user_find($session['user_id']);
|
|
$_SESSION['char'] = char_find($user['char_id']);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Ensure a user is logged in, or redirect to the login page. This will also check for a remember me cookie and
|
|
* populate the $_SESSION['user'] array.
|
|
*/
|
|
function auth_only(): void
|
|
{
|
|
if (!auth_check()) redirect('/auth/login');
|
|
}
|
|
|
|
/**
|
|
* If there is a user logged in, redirect to the home page. Used for when we have a guest-only page.
|
|
*/
|
|
function guest_only(): void
|
|
{
|
|
if (auth_check()) redirect('/');
|
|
}
|
|
|
|
/**
|
|
* Ensure the user has a character selected. If they have no character, redirect to the character creation page. Otherwise,
|
|
* select the first character attached to the user.
|
|
*/
|
|
function must_have_character(): void
|
|
{
|
|
// If there is a character selected, make sure the session is up to date.
|
|
if ($_SESSION['user']['char_id'] !== 0) {
|
|
$char = db_query(db_live(), 'SELECT * FROM characters WHERE id = :c', [':c' => $_SESSION['user']['char_id']])->fetchArray(SQLITE3_ASSOC);
|
|
$_SESSION['char'] = $char;
|
|
return;
|
|
}
|
|
|
|
// if no characters, redirect to create first
|
|
if (char_count(user('id')) === 0) redirect('/character/create-first');
|
|
|
|
// if no character selected, select the first one
|
|
if ($_SESSION['user']['char_id'] === 0) {
|
|
$char = db_query(db_live(), 'SELECT * FROM characters WHERE user_id = :u ORDER BY id ASC LIMIT 1', [':u' => user('id')])->fetchArray(SQLITE3_ASSOC);
|
|
change_user_character($char['id']);
|
|
}
|
|
}
|