71 lines
2.2 KiB
PHP
71 lines
2.2 KiB
PHP
<?php
|
|||
|
|
/**
|
||
|
|
* 登录账号。一个人最多一个账号,账号依附于「人」而存在。
|
||
|
|
*/
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App;
|
||
|
|
|
||
|
|
final class Account
|
||
|
|
{
|
||
|
|
public static function findByPerson(int $personId): ?array
|
||
|
|
{
|
||
|
|
$st = Database::get()->prepare('SELECT * FROM accounts WHERE person_id = ?');
|
||
|
|
$st->execute([$personId]);
|
||
|
|
$row = $st->fetch();
|
||
|
|
return $row ?: null;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function create(int $personId, string $password, string $role = 'member'): int
|
||
|
|
{
|
||
|
|
$st = Database::get()->prepare(
|
||
|
|
'INSERT INTO accounts (person_id, password_hash, role) VALUES (?, ?, ?)'
|
||
|
|
);
|
||
|
|
$st->execute([$personId, password_hash($password, PASSWORD_DEFAULT), $role]);
|
||
|
|
return (int)Database::get()->lastInsertId();
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function setPassword(int $accountId, string $password): void
|
||
|
|
{
|
||
|
|
Database::get()->prepare('UPDATE accounts SET password_hash = ? WHERE id = ?')
|
||
|
|
->execute([password_hash($password, PASSWORD_DEFAULT), $accountId]);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function setRole(int $accountId, string $role): void
|
||
|
|
{
|
||
|
|
Database::get()->prepare('UPDATE accounts SET role = ? WHERE id = ?')
|
||
|
|
->execute([$role, $accountId]);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function setStatus(int $accountId, string $status): void
|
||
|
|
{
|
||
|
|
Database::get()->prepare('UPDATE accounts SET status = ? WHERE id = ?')
|
||
|
|
->execute([$status, $accountId]);
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 管理员不能被停用/降权 —— 否则全家人都会被锁在系统外面 */
|
||
|
|
public static function adminCount(): int
|
||
|
|
{
|
||
|
|
$st = Database::get()->prepare(
|
||
|
|
"SELECT COUNT(*) FROM accounts a
|
||
|
|
JOIN persons p ON p.id = a.person_id
|
||
|
|
WHERE a.role = 'admin' AND a.status = 'active'"
|
||
|
|
);
|
||
|
|
$st->execute();
|
||
|
|
return (int)$st->fetchColumn();
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function validatePassword(string $password): array
|
||
|
|
{
|
||
|
|
$err = [];
|
||
|
|
if (strlen($password) < 8) {
|
||
|
|
$err[] = '密码至少 8 位';
|
||
|
|
}
|
||
|
|
if (!preg_match('/[0-9]/', $password) || !preg_match('/[A-Za-z]/', $password)) {
|
||
|
|
$err[] = '密码要同时包含字母和数字';
|
||
|
|
}
|
||
|
|
return $err;
|
||
|
|
}
|
||
|
|
}
|