'管理员', 'member' => '家庭成员', 'guest' => '访客'][self::role()] ?? '成员'; } /** * 首页标题 —— 「以我为中心」最直接的一处落点。 * 登录后看到的不是「家书」,而是「老杨的家书」。 */ public static function homeTitle(): string { $name = self::name(); return $name === '' ? '家书' : $name . '的家书'; } /** 未登录跳登录页 */ public static function requireLogin(): void { if (!self::check()) { redirect('auth/login'); } } /** 需要「能写」的权限(访客会被挡下) */ public static function requireWrite(): void { self::requireLogin(); if (!self::canWrite()) { http_response_code(403); \App\View::render('error', [ 'title' => '访客只读', 'message' => '你的身份是访客,只能查看,不能新增或修改内容。', ], 'home'); exit; } } public static function requireAdmin(): void { self::requireLogin(); if (!self::isAdmin()) { http_response_code(403); \App\View::render('error', [ 'title' => '没有权限', 'message' => '这一页只有家庭管理员可以操作。', ], 'home'); exit; } } /** * 手机号 + 密码登录。 * 返回 true 表示成功并已写入会话。 */ public static function login(string $phone, string $password): bool { // 简单节流:5 次失败后 60 秒内不再尝试。 // 防爆破的关键不在判定多严,而在于「尝试次数有成本」。 $fail = $_SESSION['login_fail'] ?? ['n' => 0, 't' => 0]; if ($fail['n'] >= 5 && (time() - $fail['t']) < 60) { usleep(500000); return false; } $hash = Crypto::hash($phone); $stmt = Database::get()->prepare( 'SELECT a.id AS account_id, a.password_hash, a.role, a.status, p.id AS person_id, p.family_id, p.name, p.avatar FROM accounts a JOIN persons p ON p.id = a.person_id WHERE p.phone_hash = ? LIMIT 1' ); $stmt->execute([$hash]); $row = $stmt->fetch(); if (!$row || $row['status'] !== 'active' || !password_verify($password, (string)$row['password_hash'])) { $_SESSION['login_fail'] = ['n' => $fail['n'] + 1, 't' => time()]; usleep(300000); return false; } unset($_SESSION['login_fail']); session_regenerate_id(true); $_SESSION['account_id'] = (int)$row['account_id']; $_SESSION['person_id'] = (int)$row['person_id']; $_SESSION['family_id'] = (int)$row['family_id']; $_SESSION['name'] = $row['name']; $_SESSION['role'] = $row['role']; $_SESSION['avatar'] = $row['avatar']; Database::get()->prepare('UPDATE accounts SET last_login_at = NOW() WHERE id = ?') ->execute([$row['account_id']]); return true; } public static function logout(): void { $_SESSION = []; if (ini_get('session.use_cookies')) { $p = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']); } session_destroy(); } /** 头像改动后刷新会话里的缓存 */ public static function refreshAvatar(string $avatar): void { $_SESSION['avatar'] = $avatar; } }