Files
nanguaboss 71c6e8d9c1 v1.0.10
2026-08-03 00:07:01 +08:00

53 lines
1.8 KiB
PHP

<?php
/**
* 新增用户接口 POST /api/system/user_add.php
* 入参:username / password / real_name / role_id / is_active
*/
require_once __DIR__ . '/../common/db.php';
require_once __DIR__ . '/../common/response.php';
require_once __DIR__ . '/../common/auth.php';
require_once __DIR__ . '/../common/logger.php';
checkAjax();
checkPermission('system');
$username = trim($_POST['username'] ?? '');
$password = (string)($_POST['password'] ?? '');
$realName = trim($_POST['real_name'] ?? '');
$roleId = (int)($_POST['role_id'] ?? 0);
$isActive = isset($_POST['is_active']) ? ((int)$_POST['is_active'] ? 1 : 0) : 1;
if ($username === '' || !preg_match('/^[a-zA-Z0-9_]{3,50}$/', $username)) {
Response::error('账号需为3-50位字母/数字/下划线', 400);
}
if (strlen($password) < 6) {
Response::error('密码长度不能少于6位', 400);
}
if ($roleId <= 0) {
Response::error('请选择角色', 400);
}
$pdo = DB::getInstance()->getPdo();
$chk = $pdo->prepare("SELECT COUNT(*) FROM system_users WHERE username = ?");
$chk->execute([$username]);
if ((int)$chk->fetchColumn() > 0) {
Response::error('账号已存在');
}
$chkRole = $pdo->prepare("SELECT COUNT(*) FROM system_roles WHERE id = ?");
$chkRole->execute([$roleId]);
if ((int)$chkRole->fetchColumn() === 0) {
Response::error('角色不存在', 400);
}
$stmt = $pdo->prepare(
"INSERT INTO system_users (username, password, real_name, role_id, is_active)
VALUES (?, ?, ?, ?, ?)"
);
$stmt->execute([$username, sha1($password), $realName !== '' ? $realName : null, $roleId, $isActive]);
$newId = (int)$pdo->lastInsertId();
logCurrent('add', 'system', 'system_users', $newId, ['username' => $username, 'role_id' => $roleId, 'is_active' => $isActive]);
Response::success(['id' => $newId], '新增成功');