Files
FamilyBook/app/Auth.php
T

178 lines
5.3 KiB
PHP
Raw Normal View History

<?php
/**
* 登录态与权限。
*
* 一个重要设计:**人(Person)≠ 账号(Account)**。
* 六岁的孩子应该出现在家庭名册、照片、活动参与人里,但不必有密码。
* 所以 person 可以先于 account 存在,将来再「开通账号」。
*/
declare(strict_types=1);
namespace App;
final class Auth
{
public static function check(): bool
{
return !empty($_SESSION['account_id']);
}
public static function id(): ?int
{
return isset($_SESSION['account_id']) ? (int)$_SESSION['account_id'] : null;
}
public static function personId(): ?int
{
return isset($_SESSION['person_id']) ? (int)$_SESSION['person_id'] : null;
}
public static function familyId(): ?int
{
return isset($_SESSION['family_id']) ? (int)$_SESSION['family_id'] : null;
}
public static function name(): string
{
return $_SESSION['name'] ?? '';
}
public static function isAdmin(): bool
{
return ($_SESSION['role'] ?? '') === 'admin';
}
/** 访客:只能看被授权的信息,不能创建/编辑任何东西 */
public static function isGuest(): bool
{
return ($_SESSION['role'] ?? '') === 'guest';
}
/** 能正常使用系统的人(管理员或家庭成员)—— 判断「能否写」用这个 */
public static function canWrite(): bool
{
$r = $_SESSION['role'] ?? '';
return $r === 'admin' || $r === 'member';
}
public static function role(): string
{
return (string)($_SESSION['role'] ?? '');
}
public static function roleWord(): string
{
return ['admin' => '管理员', '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;
}
}