$_) { if (str_starts_with($key, 'flash_')) unset($_SESSION[$key]); } } /** * Create a CSRF token. */ function csrf(): string { if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = token(); return $_SESSION['csrf']; } /** * Verify a CSRF token. */ function csrf_verify(string $token): bool { if (hash_equals($_SESSION['csrf'] ?? '', $token)) { $_SESSION['csrf'] = token(); return true; } return false; } /** * Create a hidden input field for CSRF tokens. */ function csrf_field(): string { return ''; } /** * Kill the current request with a 418 error, if $_POST['csrf'] is invalid. */ function csrf_ensure(): void { if (!csrf_verify($_POST['csrf'] ?? '')) router_error(418); } /** * Set a cookie with secure and HTTP-only flags. */ function set_cookie(string $name, string $value, int $expires): void { setcookie($name, $value, [ 'expires' => $expires, 'path' => '/', 'domain' => '', // Defaults to the current domain 'secure' => true, // Ensure the cookie is only sent over HTTPS 'httponly' => true, // Prevent access to cookie via JavaScript 'samesite' => 'Strict' // Enforce SameSite=Strict ]); } /** * Get the current user's array from SESSION if it exists. Specify a key to get a specific value. */ function user(string $field = ''): mixed { if (empty($_SESSION['user'])) return false; if ($field === '') return $_SESSION['user']; return $_SESSION['user'][$field] ?? false; } /** * Check whether the user has selected a character. If so, return the character's ID. */ function user_selected_char(): int { return (int) $_SESSION['user']['char_id']; } /** * If the current user has a selected char and the data is in the session, retrieve either the full array of data * or a specific field. */ function char(string $field = ''): mixed { if (empty($_SESSION['char'])) return false; if ($field === '') return $_SESSION['char']; return $_SESSION['char'][$field] ?? false; } /** * Perform an authentication and optionally a character check. Failing user auth will redirect to the login page. Failing * the character check will redirect to the character creation page. */ function gate(bool $char = false, bool $user = true): void { if ($user && !auth_check()) redirect('/auth/login'); if ($char) auth_char_ensure(); }