第一版权限只做了“管理员/普通用户”,上线前评审时被问住:谁能改批次?谁能撤销审核?谁只能看?
后来把权限拆到动作级:录入、修改、审核、导出、删除,每个动作单独判断;角色只是动作的集合。更关键的是留痕:谁在什么时间改了哪个字段,旧值和新值都存。
function requireAction(string $action): void {
$user = current_user();
if (!in_array($action, $user['actions'], true)) {
http_response_code(403);
exit('无权限');
}
}
function audit(string $action, string $target, array $before, array $after): void {
db()->prepare('INSERT INTO audit_log (user_id, action, target, before_json, after_json, created_at)
VALUES (?, ?, ?, ?, ?, ?)')
->execute([current_user()['id'], $action, $target,
json_encode($before, JSON_UNESCAPED_UNICODE),
json_encode($after, JSON_UNESCAPED_UNICODE), now()]);
}审核不能只看按钮置灰:接口也要校验状态流转,否则直接构造请求就能跳过审核。
导出同样要控权限。追溯数据一旦流出,后面再谈“内部使用”就没有约束力了。