添加了更多功能
This commit is contained in:
147
routes/users.js
147
routes/users.js
@@ -3,8 +3,16 @@ const jwt = require('jsonwebtoken')
|
||||
const bcrypt = require('bcryptjs')
|
||||
const { pool } = require('../db')
|
||||
|
||||
// 安全字段:不返回密码哈希
|
||||
const SAFE_FIELDS = 'id, username, real_name, role, status, created_at, updated_at'
|
||||
// 安全字段:关联查询 roles 和 employees
|
||||
const USER_LIST_SQL = `
|
||||
SELECT u.id, u.username, u.is_active, u.role_id, u.employee_id, u.department,
|
||||
u.created_at, u.updated_at,
|
||||
r.name AS role_name, r.description AS role_description,
|
||||
e.name AS real_name
|
||||
FROM users u
|
||||
LEFT JOIN roles r ON u.role_id = r.id
|
||||
LEFT JOIN employees e ON u.employee_id = e.id
|
||||
`
|
||||
|
||||
function pagination(query) {
|
||||
const page = Math.max(Number(query.page) || 1, 1)
|
||||
@@ -24,18 +32,22 @@ async function login(req, res) {
|
||||
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
'SELECT id, username, password, real_name, role, status FROM users WHERE username = ?',
|
||||
`SELECT u.id, u.username, u.password, u.is_active, u.role_id, u.department, u.employee_id,
|
||||
r.name AS role_name, e.name AS real_name
|
||||
FROM users u
|
||||
LEFT JOIN roles r ON u.role_id = r.id
|
||||
LEFT JOIN employees e ON u.employee_id = e.id
|
||||
WHERE u.username = ?`,
|
||||
[username]
|
||||
)
|
||||
|
||||
// 用户不存在或密码错,统一提示避免枚举
|
||||
if (rows.length === 0) {
|
||||
return res.status(400).json({ code: 400, message: '账号或密码错误' })
|
||||
}
|
||||
const user = rows[0]
|
||||
|
||||
// 检查账号是否被禁用
|
||||
if (user.status === 0) {
|
||||
if (user.is_active === 0) {
|
||||
return res.status(403).json({ code: 403, message: '账号已被禁用,请联系管理员' })
|
||||
}
|
||||
|
||||
@@ -44,8 +56,25 @@ async function login(req, res) {
|
||||
return res.status(400).json({ code: 400, message: '账号或密码错误' })
|
||||
}
|
||||
|
||||
// 查询该角色的所有权限标识
|
||||
const [perms] = await pool.query(
|
||||
`SELECT p.name FROM permissions p
|
||||
JOIN role_permissions rp ON p.id = rp.permission_id
|
||||
WHERE rp.role_id = ?`,
|
||||
[user.role_id]
|
||||
)
|
||||
const permissions = perms.map(p => p.name)
|
||||
|
||||
const token = jwt.sign(
|
||||
{ id: user.id, username: user.username, role: user.role },
|
||||
{
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.real_name || user.username,
|
||||
role_id: user.role_id,
|
||||
roleName: user.role_name,
|
||||
department: user.department,
|
||||
permissions,
|
||||
},
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: process.env.JWT_EXPIRES_IN || '2h' }
|
||||
)
|
||||
@@ -58,8 +87,11 @@ async function login(req, res) {
|
||||
userInfo: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
real_name: user.real_name,
|
||||
role: user.role,
|
||||
name: user.real_name || user.username,
|
||||
role_id: user.role_id,
|
||||
roleName: user.role_name,
|
||||
department: user.department,
|
||||
permissions,
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -73,7 +105,7 @@ async function login(req, res) {
|
||||
async function info(req, res) {
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT ${SAFE_FIELDS} FROM users WHERE id = ?`,
|
||||
`${USER_LIST_SQL} WHERE u.id = ?`,
|
||||
[req.user.id]
|
||||
)
|
||||
if (rows.length === 0) {
|
||||
@@ -126,35 +158,35 @@ async function changePassword(req, res) {
|
||||
|
||||
// ========== 用户管理 CRUD(管理员) ==========
|
||||
|
||||
// GET /api/users —— 用户列表(管理员)
|
||||
// GET /api/users —— 用户列表
|
||||
async function list(req, res) {
|
||||
try {
|
||||
const { page, pageSize, offset } = pagination(req.query)
|
||||
const { username, role, status } = req.query
|
||||
const { username, role_id, is_active } = req.query
|
||||
|
||||
let where = 'WHERE 1=1'
|
||||
const params = []
|
||||
|
||||
if (username) {
|
||||
where += ' AND username LIKE ?'
|
||||
where += ' AND u.username LIKE ?'
|
||||
params.push(`%${username}%`)
|
||||
}
|
||||
if (role) {
|
||||
where += ' AND role = ?'
|
||||
params.push(role)
|
||||
if (role_id) {
|
||||
where += ' AND u.role_id = ?'
|
||||
params.push(Number(role_id))
|
||||
}
|
||||
if (status !== undefined && status !== '') {
|
||||
where += ' AND status = ?'
|
||||
params.push(Number(status))
|
||||
if (is_active !== undefined && is_active !== '') {
|
||||
where += ' AND u.is_active = ?'
|
||||
params.push(Number(is_active))
|
||||
}
|
||||
|
||||
const [[{ total }]] = await pool.query(
|
||||
`SELECT COUNT(*) AS total FROM users ${where}`,
|
||||
`SELECT COUNT(*) AS total FROM users u ${where}`,
|
||||
params
|
||||
)
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT ${SAFE_FIELDS} FROM users ${where} ORDER BY id DESC LIMIT ? OFFSET ?`,
|
||||
`${USER_LIST_SQL} ${where} ORDER BY u.id DESC LIMIT ? OFFSET ?`,
|
||||
[...params, pageSize, offset]
|
||||
)
|
||||
|
||||
@@ -175,11 +207,11 @@ async function list(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/users/:id —— 用户详情(管理员)
|
||||
// GET /api/users/:id —— 用户详情
|
||||
async function detail(req, res) {
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT ${SAFE_FIELDS} FROM users WHERE id = ?`,
|
||||
`${USER_LIST_SQL} WHERE u.id = ?`,
|
||||
[req.params.id]
|
||||
)
|
||||
if (rows.length === 0) {
|
||||
@@ -192,9 +224,9 @@ async function detail(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/users —— 创建用户(管理员)
|
||||
// POST /api/users —— 创建用户
|
||||
async function create(req, res) {
|
||||
const { username, password, real_name = null, role = 'user', status = 1 } = req.body || {}
|
||||
const { username, password, role_id, employee_id, department, is_active = 1 } = req.body || {}
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ code: 400, message: '用户名和密码必填' })
|
||||
@@ -205,19 +237,36 @@ async function create(req, res) {
|
||||
if (typeof password !== 'string' || password.length < 6) {
|
||||
return res.status(400).json({ code: 400, message: '密码至少 6 位' })
|
||||
}
|
||||
if (!['admin', 'user'].includes(role)) {
|
||||
return res.status(400).json({ code: 400, message: '角色只能为 admin 或 user' })
|
||||
|
||||
// 校验 role_id 是否存在
|
||||
if (role_id) {
|
||||
const [role] = await pool.query('SELECT id FROM roles WHERE id = ?', [role_id])
|
||||
if (role.length === 0) {
|
||||
return res.status(400).json({ code: 400, message: '指定的角色不存在' })
|
||||
}
|
||||
}
|
||||
|
||||
// 校验 employee_id 是否存在
|
||||
if (employee_id) {
|
||||
const [emp] = await pool.query('SELECT id, department FROM employees WHERE id = ?', [employee_id])
|
||||
if (emp.length === 0) {
|
||||
return res.status(400).json({ code: 400, message: '指定的员工不存在' })
|
||||
}
|
||||
// 如果没传 department,自动从员工表同步
|
||||
if (!department) {
|
||||
req.body.department = emp[0].department
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const hash = await bcrypt.hash(password, 10)
|
||||
const [result] = await pool.query(
|
||||
'INSERT INTO users (username, password, real_name, role, status) VALUES (?, ?, ?, ?, ?)',
|
||||
[username, hash, real_name, role, status]
|
||||
'INSERT INTO users (username, password, is_active, role_id, employee_id, department) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[username, hash, is_active, role_id || null, employee_id || null, req.body.department || department || null]
|
||||
)
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT ${SAFE_FIELDS} FROM users WHERE id = ?`,
|
||||
`${USER_LIST_SQL} WHERE u.id = ?`,
|
||||
[result.insertId]
|
||||
)
|
||||
res.json({ code: 0, message: 'ok', data: rows[0] })
|
||||
@@ -230,38 +279,52 @@ async function create(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/users/:id —— 更新用户(管理员)
|
||||
// PUT /api/users/:id —— 更新用户
|
||||
async function update(req, res) {
|
||||
const { id } = req.params
|
||||
const fields = ['username', 'real_name', 'role', 'status']
|
||||
const fields = ['username', 'role_id', 'employee_id', 'department', 'is_active']
|
||||
|
||||
try {
|
||||
const [existing] = await pool.query('SELECT id, role FROM users WHERE id = ?', [id])
|
||||
const [existing] = await pool.query('SELECT id, role_id, is_active FROM users WHERE id = ?', [id])
|
||||
if (existing.length === 0) {
|
||||
return res.status(404).json({ code: 404, message: '用户不存在' })
|
||||
}
|
||||
|
||||
const targetUser = existing[0]
|
||||
|
||||
// 不允许修改自己的角色或禁用自己
|
||||
if (Number(id) === req.user.id) {
|
||||
if (req.body.role !== undefined && req.body.role !== req.user.role) {
|
||||
if (req.body.role_id !== undefined && req.body.role_id !== req.user.role_id) {
|
||||
return res.status(400).json({ code: 400, message: '不能修改自己的角色' })
|
||||
}
|
||||
if (req.body.status === 0) {
|
||||
if (req.body.is_active === 0) {
|
||||
return res.status(400).json({ code: 400, message: '不能禁用自己' })
|
||||
}
|
||||
}
|
||||
|
||||
// 校验 role_id
|
||||
if (req.body.role_id) {
|
||||
const [role] = await pool.query('SELECT id FROM roles WHERE id = ?', [req.body.role_id])
|
||||
if (role.length === 0) {
|
||||
return res.status(400).json({ code: 400, message: '指定的角色不存在' })
|
||||
}
|
||||
}
|
||||
|
||||
// 校验 employee_id
|
||||
if (req.body.employee_id) {
|
||||
const [emp] = await pool.query('SELECT id, department FROM employees WHERE id = ?', [req.body.employee_id])
|
||||
if (emp.length === 0) {
|
||||
return res.status(400).json({ code: 400, message: '指定的员工不存在' })
|
||||
}
|
||||
// 自动同步 department
|
||||
if (req.body.department === undefined) {
|
||||
req.body.department = emp[0].department
|
||||
}
|
||||
}
|
||||
|
||||
const sets = []
|
||||
const params = []
|
||||
|
||||
for (const f of fields) {
|
||||
if (req.body[f] !== undefined) {
|
||||
// role 字段只允许 admin / user
|
||||
if (f === 'role' && !['admin', 'user'].includes(req.body[f])) {
|
||||
return res.status(400).json({ code: 400, message: '角色只能为 admin 或 user' })
|
||||
}
|
||||
sets.push(`${f} = ?`)
|
||||
params.push(req.body[f])
|
||||
}
|
||||
@@ -285,7 +348,7 @@ async function update(req, res) {
|
||||
await pool.query(`UPDATE users SET ${sets.join(', ')} WHERE id = ?`, params)
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT ${SAFE_FIELDS} FROM users WHERE id = ?`,
|
||||
`${USER_LIST_SQL} WHERE u.id = ?`,
|
||||
[id]
|
||||
)
|
||||
res.json({ code: 0, message: 'ok', data: rows[0] })
|
||||
@@ -298,7 +361,7 @@ async function update(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/users/:id —— 删除用户(管理员)
|
||||
// DELETE /api/users/:id —— 删除用户
|
||||
async function remove(req, res) {
|
||||
const { id } = req.params
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user