DK2/src/auth.php

72 lines
1.7 KiB
PHP

<?php
/**
* Checks if the given username already exists.
*/
function auth_usernameExists(string $username): bool
{
return db_exists(db_auth(), 'users', 'username', $username);
}
/**
* Checks if the given email already exists.
*/
function auth_emailExists(string $email): bool
{
return db_exists(db_auth(), 'users', 'email', $email);
}
/**
* Create a long-lived session for the user.
*/
function auth_rememberMe()
{
$token = token();
$expires = strtotime('+30 days');
$result = db_query(db_auth(), "INSERT INTO sessions (token, user_id, expires) VALUES (:t, :u, :e)", [
':t' => $token,
':u' => $_SESSION['user']['id'],
':e' => $expires
]);
if (!$result) router_error(400);
set_cookie('remember_me', $token, $expires);
}
/**
* 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']);
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_ensure(): 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 auth_guest(): void
{
if (auth_check()) redirect('/');
}