feat: 权限模型——users.role 迁移、管理员认证与端点、活动发布限管理员、托管 admin-web
This commit is contained in:
@@ -5,6 +5,7 @@ const { v4: uuidv4 } = require('uuid');
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
require('dotenv').config({ path: path.join(__dirname, '.env') });
|
||||
|
||||
const app = express();
|
||||
@@ -310,6 +311,49 @@ function initDatabase() {
|
||||
chaishuTags.forEach(([name, count]) => insertTag.run(name, count));
|
||||
console.log('推荐标签已更新为拆书帮标签体系');
|
||||
}
|
||||
|
||||
// 迁移:用户角色体系(ht/002)——已有用户自动获得 DEFAULT 'user',旧代码不读该列不受影响
|
||||
if (!userInfoCols.some(col => col.name === 'role')) {
|
||||
db.prepare("ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'user'").run();
|
||||
console.log('已添加 users.role 字段');
|
||||
}
|
||||
if (!userInfoCols.some(col => col.name === 'role_granted_at')) {
|
||||
db.prepare('ALTER TABLE users ADD COLUMN role_granted_at DATETIME').run();
|
||||
console.log('已添加 users.role_granted_at 字段');
|
||||
}
|
||||
if (!userInfoCols.some(col => col.name === 'role_granted_by')) {
|
||||
db.prepare("ALTER TABLE users ADD COLUMN role_granted_by TEXT DEFAULT ''").run();
|
||||
console.log('已添加 users.role_granted_by 字段');
|
||||
}
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_users_role ON users(role)');
|
||||
|
||||
// 迁移:后台管理系统(ht/003)——管理员账号表 + 操作日志表 + 应用配置表
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS admins (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
display_name TEXT DEFAULT '',
|
||||
must_change_password INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login_at DATETIME
|
||||
)`);
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS admin_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
admin_id TEXT NOT NULL,
|
||||
admin_username TEXT DEFAULT '',
|
||||
action TEXT NOT NULL,
|
||||
target_type TEXT DEFAULT '',
|
||||
target_id TEXT DEFAULT '',
|
||||
detail TEXT DEFAULT '',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_admin_logs_created_at ON admin_logs(created_at)');
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS app_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT,
|
||||
updated_at DATETIME
|
||||
)`);
|
||||
console.log('权限模型表(users.role/admins/admin_logs/app_settings)已就绪');
|
||||
} catch (migrationError) {
|
||||
console.log('迁移检查:', migrationError.message);
|
||||
}
|
||||
@@ -361,10 +405,35 @@ function getUserWithCompanies(userId) {
|
||||
updatedAt: user.updated_at,
|
||||
companies: companies.map(c => c.company_name),
|
||||
chaishuVerified: !!user.chaishu_verified,
|
||||
role: user.role || 'user',
|
||||
isAdmin: (user.role || 'user') === 'admin',
|
||||
chaishu
|
||||
};
|
||||
}
|
||||
|
||||
// 用户身份校验:token 形如 token_<userId>_<ts>,校验归属防止简单冒充
|
||||
function authenticateUser(req) {
|
||||
const userId = req.headers['x-user-id'];
|
||||
const auth = req.headers['authorization'] || '';
|
||||
const token = auth.replace(/^Bearer\s+/i, '');
|
||||
if (!userId || !token || !token.startsWith(`token_${userId}_`)) return null;
|
||||
const user = db.prepare('SELECT id, role FROM users WHERE id = ?').get(userId);
|
||||
return user || null;
|
||||
}
|
||||
|
||||
// 活动管理权限(创建/编辑/删除):仅管理员
|
||||
function requireActivityAdmin(req, res, next) {
|
||||
const user = authenticateUser(req);
|
||||
if (!user) {
|
||||
return res.status(401).json({ success: false, message: '请先登录' });
|
||||
}
|
||||
if (user.role !== 'admin') {
|
||||
return res.status(403).json({ success: false, message: '仅管理员可创建或管理活动' });
|
||||
}
|
||||
req.authUser = user;
|
||||
next();
|
||||
}
|
||||
|
||||
// 请求日志
|
||||
app.use((req, res, next) => {
|
||||
console.log(`${new Date().toISOString()} ${req.method} ${req.path}`);
|
||||
@@ -673,7 +742,7 @@ app.get('/activities/templates', (req, res) => {
|
||||
|
||||
// 上传活动封面 - 必须在 /activities/:id 之前
|
||||
// 设置上传子目录
|
||||
app.post('/activities/upload/cover', (req, res, next) => {
|
||||
app.post('/activities/upload/cover', requireActivityAdmin, (req, res, next) => {
|
||||
req.uploadSubDir = 'covers';
|
||||
next();
|
||||
}, upload.single('file'), (req, res) => {
|
||||
@@ -768,7 +837,7 @@ app.get('/activities/:id', (req, res) => {
|
||||
});
|
||||
|
||||
// 创建活动
|
||||
app.post('/activities', (req, res) => {
|
||||
app.post('/activities', requireActivityAdmin, (req, res) => {
|
||||
try {
|
||||
const userId = req.headers['x-user-id'] || 'user-1';
|
||||
const { title, cover_url, description, location, start_time, duration, max_participants, tags, checkin_enabled, fee, organizer } = req.body;
|
||||
@@ -802,7 +871,7 @@ app.post('/activities', (req, res) => {
|
||||
});
|
||||
|
||||
// 更新活动
|
||||
app.put('/activities/:id', (req, res) => {
|
||||
app.put('/activities/:id', requireActivityAdmin, (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const userId = req.headers['x-user-id'] || 'user-1';
|
||||
@@ -1039,7 +1108,7 @@ app.post('/activities/:id/checkin', (req, res) => {
|
||||
});
|
||||
|
||||
// 删除活动
|
||||
app.delete('/activities/:id', (req, res) => {
|
||||
app.delete('/activities/:id', requireActivityAdmin, (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const userId = req.headers['x-user-id'] || 'user-1';
|
||||
@@ -1547,8 +1616,232 @@ app.post('/chaishu/tags/delete', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ==================== 后台管理系统(移植自 ht 分支) ====================
|
||||
|
||||
// --- 密码与令牌工具 ---
|
||||
function hashPassword(password) {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.scryptSync(password, salt, 64).toString('hex');
|
||||
return `${salt}:${hash}`;
|
||||
}
|
||||
function verifyPassword(password, stored) {
|
||||
const [salt, hash] = String(stored || '').split(':');
|
||||
if (!salt || !hash) return false;
|
||||
const calc = crypto.scryptSync(password, salt, 64).toString('hex');
|
||||
try {
|
||||
return crypto.timingSafeEqual(Buffer.from(hash, 'hex'), Buffer.from(calc, 'hex'));
|
||||
} catch (e) { return false; }
|
||||
}
|
||||
|
||||
// 后台会话密钥:首次生成后存入 app_settings,重启不变
|
||||
function getAdminSecret() {
|
||||
const row = db.prepare("SELECT value FROM app_settings WHERE key = 'admin_session_secret'").get();
|
||||
if (row && row.value) return row.value;
|
||||
const secret = crypto.randomBytes(32).toString('hex');
|
||||
db.prepare("INSERT OR REPLACE INTO app_settings (key, value, updated_at) VALUES ('admin_session_secret', ?, ?)")
|
||||
.run(secret, new Date().toISOString());
|
||||
return secret;
|
||||
}
|
||||
const ADMIN_TOKEN_TTL_MS = 12 * 60 * 60 * 1000; // 后台会话 12 小时
|
||||
|
||||
function signAdminToken(adminId) {
|
||||
const exp = Date.now() + ADMIN_TOKEN_TTL_MS;
|
||||
const payload = `${adminId}.${exp}`;
|
||||
const sig = crypto.createHmac('sha256', getAdminSecret()).update(payload).digest('hex');
|
||||
return `${payload}.${sig}`;
|
||||
}
|
||||
function verifyAdminToken(token) {
|
||||
const parts = String(token || '').split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
const [adminId, exp, sig] = parts;
|
||||
const payload = `${adminId}.${exp}`;
|
||||
const expect = crypto.createHmac('sha256', getAdminSecret()).update(payload).digest('hex');
|
||||
if (sig.length !== expect.length) return null;
|
||||
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
|
||||
if (Number(exp) < Date.now()) return null;
|
||||
const admin = db.prepare('SELECT id, username, display_name, must_change_password FROM admins WHERE id = ?').get(adminId);
|
||||
return admin || null;
|
||||
}
|
||||
|
||||
// 播种默认超管(仅当 admins 表为空)
|
||||
function ensureDefaultAdmin() {
|
||||
const count = db.prepare('SELECT COUNT(*) as count FROM admins').get();
|
||||
if (count.count > 0) return;
|
||||
db.prepare('INSERT INTO admins (id, username, password_hash, display_name, must_change_password) VALUES (?, ?, ?, ?, 1)')
|
||||
.run(uuidv4(), 'admin', hashPassword('yaoyue-admin-2026'), '超级管理员');
|
||||
console.log('==============================================');
|
||||
console.log('[后台] 已创建默认管理员账号:');
|
||||
console.log(' 用户名: admin');
|
||||
console.log(' 密码: yaoyue-admin-2026');
|
||||
console.log(' (首次登录后将强制修改密码)');
|
||||
console.log('==============================================');
|
||||
}
|
||||
|
||||
function writeAdminLog(admin, action, targetType, targetId, detail) {
|
||||
db.prepare('INSERT INTO admin_logs (admin_id, admin_username, action, target_type, target_id, detail) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.run(admin.id, admin.username, action, targetType, targetId || '', detail || '');
|
||||
}
|
||||
|
||||
// 后台鉴权中间件
|
||||
function requireAdmin(req, res, next) {
|
||||
const auth = req.headers['authorization'] || '';
|
||||
const token = auth.replace(/^Bearer\s+/i, '');
|
||||
const admin = verifyAdminToken(token);
|
||||
if (!admin) {
|
||||
return res.status(401).json({ success: false, message: '未登录或会话已过期' });
|
||||
}
|
||||
req.admin = admin;
|
||||
next();
|
||||
}
|
||||
|
||||
// --- 后台 API(/api/admin/*) ---
|
||||
|
||||
// 登录
|
||||
app.post('/api/admin/login', (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body || {};
|
||||
if (!username || !password) {
|
||||
return res.json({ success: false, message: '请输入用户名和密码' });
|
||||
}
|
||||
const admin = db.prepare('SELECT * FROM admins WHERE username = ?').get(String(username).trim());
|
||||
if (!admin || !verifyPassword(password, admin.password_hash)) {
|
||||
return res.status(401).json({ success: false, message: '用户名或密码错误' });
|
||||
}
|
||||
db.prepare('UPDATE admins SET last_login_at = ? WHERE id = ?').run(new Date().toISOString(), admin.id);
|
||||
writeAdminLog(admin, 'login', '', '', '');
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
token: signAdminToken(admin.id),
|
||||
mustChangePassword: !!admin.must_change_password,
|
||||
username: admin.username,
|
||||
displayName: admin.display_name,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('后台登录失败:', error);
|
||||
res.status(500).json({ success: false, message: '登录失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 当前会话信息
|
||||
app.get('/api/admin/me', requireAdmin, (req, res) => {
|
||||
res.json({ success: true, data: { username: req.admin.username, displayName: req.admin.display_name, mustChangePassword: !!req.admin.must_change_password } });
|
||||
});
|
||||
|
||||
// 修改自己的密码
|
||||
app.post('/api/admin/change-password', requireAdmin, (req, res) => {
|
||||
try {
|
||||
const { oldPassword, newPassword } = req.body || {};
|
||||
if (!newPassword || String(newPassword).length < 8) {
|
||||
return res.json({ success: false, message: '新密码至少 8 位' });
|
||||
}
|
||||
const admin = db.prepare('SELECT * FROM admins WHERE id = ?').get(req.admin.id);
|
||||
if (!verifyPassword(oldPassword || '', admin.password_hash)) {
|
||||
return res.json({ success: false, message: '原密码错误' });
|
||||
}
|
||||
db.prepare('UPDATE admins SET password_hash = ?, must_change_password = 0 WHERE id = ?')
|
||||
.run(hashPassword(String(newPassword)), admin.id);
|
||||
writeAdminLog(admin, 'change_password', '', '', '');
|
||||
res.json({ success: true, data: null });
|
||||
} catch (error) {
|
||||
console.error('修改密码失败:', error);
|
||||
res.status(500).json({ success: false, message: '修改失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 概览统计
|
||||
app.get('/api/admin/stats', requireAdmin, (req, res) => {
|
||||
try {
|
||||
const users = db.prepare('SELECT COUNT(*) as c FROM users').get().c;
|
||||
const admins = db.prepare("SELECT COUNT(*) as c FROM users WHERE role = 'admin'").get().c;
|
||||
const activities = db.prepare('SELECT COUNT(*) as c FROM activities').get().c;
|
||||
const activeActivities = db.prepare("SELECT COUNT(*) as c FROM activities WHERE status = 'active'").get().c;
|
||||
res.json({ success: true, data: { users, admins, activities, activeActivities } });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, message: '获取统计失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 用户列表(分页 + 搜索)
|
||||
app.get('/api/admin/users', requireAdmin, (req, res) => {
|
||||
try {
|
||||
const { search = '', page = 1, pageSize = 20 } = req.query;
|
||||
const pageNum = Math.max(1, parseInt(page) || 1);
|
||||
const pageSizeNum = Math.min(100, Math.max(1, parseInt(pageSize) || 20));
|
||||
const kw = `%${String(search).trim()}%`;
|
||||
const where = search.trim()
|
||||
? 'WHERE nickname LIKE ? OR phone LIKE ? OR id LIKE ? OR IFNULL(openid, \'\') LIKE ?'
|
||||
: '';
|
||||
const args = search.trim() ? [kw, kw, kw, kw] : [];
|
||||
const total = db.prepare(`SELECT COUNT(*) as c FROM users ${where}`).get(...args).c;
|
||||
const rows = db.prepare(`
|
||||
SELECT u.id, u.nickname, u.avatar_url, u.phone, u.role, u.created_at,
|
||||
(SELECT COUNT(*) FROM activities a WHERE a.creator_id = u.id) as created_count,
|
||||
(SELECT COUNT(*) FROM activity_participants ap WHERE ap.user_id = u.id AND ap.status != 'cancelled') as joined_count
|
||||
FROM users u ${where}
|
||||
ORDER BY u.created_at DESC LIMIT ? OFFSET ?
|
||||
`).all(...args, pageSizeNum, (pageNum - 1) * pageSizeNum);
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
total, page: pageNum, pageSize: pageSizeNum,
|
||||
list: rows.map(r => ({
|
||||
id: r.id, nickname: r.nickname, avatarUrl: r.avatar_url, phone: r.phone,
|
||||
role: r.role || 'user', isAdmin: (r.role || 'user') === 'admin',
|
||||
createdAt: r.created_at, createdCount: r.created_count, joinedCount: r.joined_count,
|
||||
})),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取用户列表失败:', error);
|
||||
res.status(500).json({ success: false, message: '获取失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 设置用户角色
|
||||
app.put('/api/admin/users/:id/role', requireAdmin, (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { role } = req.body || {};
|
||||
if (!['admin', 'user'].includes(role)) {
|
||||
return res.json({ success: false, message: 'role 只能是 admin 或 user' });
|
||||
}
|
||||
const target = db.prepare('SELECT id, nickname, role FROM users WHERE id = ?').get(id);
|
||||
if (!target) {
|
||||
return res.json({ success: false, message: '用户不存在' });
|
||||
}
|
||||
const now = new Date().toISOString();
|
||||
db.prepare('UPDATE users SET role = ?, role_granted_at = ?, role_granted_by = ? WHERE id = ?')
|
||||
.run(role, role === 'admin' ? now : null, role === 'admin' ? req.admin.username : '', id);
|
||||
writeAdminLog(req.admin, role === 'admin' ? 'grant_admin' : 'revoke_admin', 'user', id,
|
||||
`${target.nickname || target.id}: ${(target.role || 'user')} -> ${role}`);
|
||||
res.json({ success: true, data: { id, role, isAdmin: role === 'admin' } });
|
||||
} catch (error) {
|
||||
console.error('设置用户角色失败:', error);
|
||||
res.status(500).json({ success: false, message: '设置失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 操作日志
|
||||
app.get('/api/admin/logs', requireAdmin, (req, res) => {
|
||||
try {
|
||||
const rows = db.prepare('SELECT * FROM admin_logs ORDER BY id DESC LIMIT 50').all();
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, message: '获取日志失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 后台面板静态页面(yaoyue-sever/admin-web/index.html)
|
||||
const adminWebDir = path.join(__dirname, '../admin-web');
|
||||
if (fs.existsSync(adminWebDir)) {
|
||||
app.use('/admin', express.static(adminWebDir, { index: 'index.html' }));
|
||||
}
|
||||
|
||||
// 初始化数据库并启动服务器
|
||||
initDatabase();
|
||||
ensureDefaultAdmin();
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`\n服务器运行在 http://localhost:${PORT}`);
|
||||
|
||||
Reference in New Issue
Block a user