auth.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * 认证相关中间件
  3. */
  4. const logger = require('../logger');
  5. /**
  6. * 检查是否已登录的中间件
  7. */
  8. function requireLogin(req, res, next) {
  9. // 放开session检查,不强制要求登录
  10. if (req.url.startsWith('/api/documentation') ||
  11. req.url.startsWith('/api/system-resources') ||
  12. req.url.startsWith('/api/monitoring-config') ||
  13. req.url.startsWith('/api/toggle-monitoring') ||
  14. req.url.startsWith('/api/test-notification') ||
  15. req.url.includes('/docker/status')) {
  16. return next(); // 这些API路径不需要登录
  17. }
  18. // 检查用户是否登录
  19. if (req.session && req.session.user) {
  20. // 刷新会话
  21. req.session.touch();
  22. return next();
  23. }
  24. // 未登录返回401错误
  25. res.status(401).json({ error: '未登录或会话已过期', code: 'SESSION_EXPIRED' });
  26. }
  27. // 修改登录逻辑
  28. async function login(req, res) {
  29. try {
  30. const { username, password } = req.body;
  31. // 简单验证
  32. if (username === 'admin' && password === 'admin123') {
  33. req.session.user = { username };
  34. return res.json({ success: true });
  35. }
  36. res.status(401).json({ error: '用户名或密码错误' });
  37. } catch (error) {
  38. logger.error('登录失败:', error);
  39. res.status(500).json({ error: '登录失败' });
  40. }
  41. }
  42. /**
  43. * 记录会话活动的中间件
  44. */
  45. function sessionActivity(req, res, next) {
  46. if (req.session && req.session.user) {
  47. req.session.lastActivity = Date.now();
  48. req.session.touch(); // 确保会话刷新
  49. }
  50. next();
  51. }
  52. // 过滤敏感信息中间件
  53. function sanitizeRequestBody(req, res, next) {
  54. if (req.body) {
  55. const sanitizedBody = {...req.body};
  56. // 过滤敏感字段
  57. if (sanitizedBody.password) sanitizedBody.password = '[REDACTED]';
  58. if (sanitizedBody.currentPassword) sanitizedBody.currentPassword = '[REDACTED]';
  59. if (sanitizedBody.newPassword) sanitizedBody.newPassword = '[REDACTED]';
  60. // 保存清理后的请求体供日志使用
  61. req.sanitizedBody = sanitizedBody;
  62. }
  63. next();
  64. }
  65. // 安全头部中间件
  66. function securityHeaders(req, res, next) {
  67. // 添加安全头部
  68. res.setHeader('X-Content-Type-Options', 'nosniff');
  69. res.setHeader('X-Frame-Options', 'DENY');
  70. res.setHeader('X-XSS-Protection', '1; mode=block');
  71. next();
  72. }
  73. module.exports = {
  74. requireLogin,
  75. sessionActivity,
  76. sanitizeRequestBody,
  77. securityHeaders
  78. };