addData([ 'me' => $me, 'whoami' => "$me->username#$me->userDiscriminator", 'noStatus' => false, 'isLogin' => $isLogin, 'isAllowed' => $isLogin && $me !== null && static::isAllowed($me->userId), ]); return $templates; } public static function getU(): ?Token { return Auth::decrypt($_COOKIE['u'] ?? ''); } public static function checkU(): bool { $token = static::getU(); if ($token === null) return false; if ($token->timestamp + $token->expires_in < time()) return false; return static::me() !== null; } public static function setU(Token $token): void { try { setcookie('u', Auth::encrypt($token), [ 'expires' => $token->timestamp + $token->expires_in, 'path' => '/', 'domain' => 'akanyan.oho.tw', 'samesite' => 'None', 'secure' => true, 'httponly' => true, ]); } catch (Exception) { error_log('Failed to setU.'); } } public static function unsetU(): void { try { setcookie('u', null, [ 'expires' => time() - 3600, 'path' => '/', 'domain' => 'akanyan.oho.tw', 'samesite' => 'None', 'secure' => true, 'httponly' => true, ]); } catch (Exception) { error_log('Failed to unsetU.'); } } public static function requireAuth(): void { if (!static::checkU()) { header('location: /login.php'); http_response_code(302); exit; } } public static function requireNonAuth(): void { if (static::checkU()) { header('location: /'); http_response_code(302); exit; } } public static function requireAllowed(): void { static::requireAuth(); $me = static::me(); if ($me === null || !static::isAllowed($me->userId)) { static::template([ 'title' => '您無權限使用本系統', 'body' => <<

您的 Discord 帳號不在白名單中。

若您認為這是個錯誤,請聯絡 小喵#3521 並提供您的使用者編號 $me->userId

HTML, ]); } } public static function auth(string $code): void { try { $token = Auth::getTokenByCode($code); if ($token !== null) static::setU($token); } catch (Exception) { error_log('Failed to getTokenByCode.'); } } public static function me(): ?Me { try { $u = static::getU(); if ($u === null) return null; return Auth::getMe($u); } catch (Exception) { error_log('Failed to getMe.'); return null; } } #[NoReturn] public static function template(array $params): void { $status = ''; if (static::checkU() && !$params['no_status']) { $me = static::me(); $status = <<您已使用 $me->username#$me->userDiscriminator 登入,點選此處以登出系統。 HTML; } $html = << $params[title]

$params[title]

$status
$params[body]
HTML; header('Content-Type: text/html; charset=utf-8'); header('Content-Length: ' . strlen($html)); http_response_code(200); echo($html); exit; } public static function authUrl(): string { return Auth::authorize(); } public static function isAllowed(string $userId): bool { return in_array($userId, static::allowedUsers); } #[NoReturn] public static function render(string $name, array $data = []): void { $html = static::getTemplate()->render($name, $data); header('Content-Type: text/html; charset=utf-8'); header('Content-Length: ' . strlen($html)); http_response_code(200); echo($html); exit; } }