13856e35bc
registerUser() declared `: string|true`; the bare `true` type requires PHP 8.2, so including auth.php was a fatal error on PHP 8.0/8.1 — every login/API call returned 500 while install.php (which doesn't include auth.php) worked. Use string|bool instead. Also install a JSON exception handler so future server errors surface a message to the SPA instead of a blank 500.
72 lines
1.9 KiB
PHP
72 lines
1.9 KiB
PHP
<?php
|
|
require_once __DIR__ . '/db.php';
|
|
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
function currentUserId(): ?int
|
|
{
|
|
return isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;
|
|
}
|
|
|
|
function currentUsername(): ?string
|
|
{
|
|
return $_SESSION['username'] ?? null;
|
|
}
|
|
|
|
function requireLogin(): int
|
|
{
|
|
$uid = currentUserId();
|
|
if ($uid === null) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
return $uid;
|
|
}
|
|
|
|
function requireLoginApi(): int
|
|
{
|
|
$uid = currentUserId();
|
|
if ($uid === null) {
|
|
http_response_code(401);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => 'Not logged in']);
|
|
exit;
|
|
}
|
|
return $uid;
|
|
}
|
|
|
|
function attemptLogin(string $username, string $password): bool
|
|
{
|
|
$stmt = db()->prepare('SELECT id, username, password_hash FROM users WHERE username = ?');
|
|
$stmt->execute([$username]);
|
|
$user = $stmt->fetch();
|
|
if ($user && password_verify($password, $user['password_hash'])) {
|
|
session_regenerate_id(true);
|
|
$_SESSION['user_id'] = (int)$user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** Returns true on success, or an error-message string. */
|
|
function registerUser(string $username, string $password): string|bool
|
|
{
|
|
if (!preg_match('/^[A-Za-z0-9_.-]{3,50}$/', $username)) {
|
|
return 'Username must be 3-50 characters (letters, digits, _ . -).';
|
|
}
|
|
if (strlen($password) < 6) {
|
|
return 'Password must be at least 6 characters.';
|
|
}
|
|
$stmt = db()->prepare('SELECT id FROM users WHERE username = ?');
|
|
$stmt->execute([$username]);
|
|
if ($stmt->fetch()) {
|
|
return 'That username is already taken.';
|
|
}
|
|
$stmt = db()->prepare('INSERT INTO users (username, password_hash) VALUES (?, ?)');
|
|
$stmt->execute([$username, password_hash($password, PASSWORD_DEFAULT)]);
|
|
return true;
|
|
}
|