c86f08c325
Co-Authored-By: Claude Code <noreply@anthropic.com>
65 lines
2.1 KiB
PHP
65 lines
2.1 KiB
PHP
<?php
|
|
/**
|
|
* 编辑用户接口(含角色分配) POST /api/system/user_update.php
|
|
* 入参:id / real_name / role_id / is_active / password(可选,留空不改密码)
|
|
*/
|
|
require_once __DIR__ . '/../common/Api.php';
|
|
|
|
$pdo = Api::boot(['module' => 'system']);
|
|
|
|
$id = (int)($_POST['id'] ?? 0);
|
|
if ($id <= 0) {
|
|
Response::error('参数错误', 400);
|
|
}
|
|
$check = $pdo->prepare("SELECT * FROM system_users WHERE id = ?");
|
|
$check->execute([$id]);
|
|
$old = $check->fetch();
|
|
if (!$old) {
|
|
Response::error('用户不存在');
|
|
}
|
|
|
|
// 内置管理员保护:不允许禁用 id=1(admin)
|
|
if ($id === 1 && isset($_POST['is_active']) && (int)$_POST['is_active'] === 0) {
|
|
Response::error('不允许禁用内置管理员账号', 400);
|
|
}
|
|
|
|
$sets = [];
|
|
$params = [];
|
|
|
|
if (isset($_POST['real_name'])) {
|
|
$sets[] = 'real_name = ?';
|
|
$params[] = trim($_POST['real_name']) !== '' ? trim($_POST['real_name']) : null;
|
|
}
|
|
if (isset($_POST['role_id'])) {
|
|
$roleId = (int)$_POST['role_id'];
|
|
$chkRole = $pdo->prepare("SELECT COUNT(*) FROM system_roles WHERE id = ?");
|
|
$chkRole->execute([$roleId]);
|
|
if ((int)$chkRole->fetchColumn() === 0) {
|
|
Response::error('角色不存在', 400);
|
|
}
|
|
$sets[] = 'role_id = ?';
|
|
$params[] = $roleId;
|
|
}
|
|
if (isset($_POST['is_active'])) {
|
|
$sets[] = 'is_active = ?';
|
|
$params[] = (int)$_POST['is_active'] ? 1 : 0;
|
|
}
|
|
$password = (string)($_POST['password'] ?? '');
|
|
if ($password !== '') {
|
|
if (strlen($password) < 8 || !preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
|
|
Response::error('密码需不少于8位,且同时包含字母和数字', 400);
|
|
}
|
|
$sets[] = 'password = ?';
|
|
$params[] = password_hash($password, PASSWORD_DEFAULT);
|
|
}
|
|
|
|
if (!$sets) {
|
|
Response::error('没有需要更新的字段', 400);
|
|
}
|
|
|
|
$params[] = $id;
|
|
$pdo->prepare("UPDATE system_users SET " . implode(', ', $sets) . " WHERE id = ?")->execute($params);
|
|
|
|
logCurrent('update', 'system', 'system_users', $id, ['before' => ['username' => $old['username'], 'role_id' => $old['role_id'], 'is_active' => $old['is_active']]]);
|
|
Response::success(null, '更新成功');
|