新增 管理员密码访问

This commit is contained in:
Chen committed 2025-12-07 09:58:37 +08:00
1 parent 85e7711c1a
commit 8ac08c41a7
16 files changed
+856 -51

No files matched your search

+13
View File
@@ -7,12 +7,14 @@ const express = require('express');
const cors = require('cors');
const path = require('path');
const { errorHandler } = require('./middleware/errorHandler');
const { createAuthMiddleware } = require('./middleware/authMiddleware');
// 导入服务
const LibraryService = require('./services/LibraryService');
const ImageService = require('./services/ImageService');
const ScanService = require('./services/ScanService');
const FileService = require('./services/FileService');
const AuthService = require('./services/AuthService');
/**
* 创建 Express 应用
@@ -34,6 +36,8 @@ function createApp(dependencies) {
app.use(express.json());
// 初始化服务
const authService = new AuthService(configManager);
const libraryService = new LibraryService(
configManager,
dbPool,
@@ -60,18 +64,27 @@ function createApp(dependencies) {
// 将服务和依赖注入到 app 中,供路由使用
app.set('configManager', configManager);
app.set('dbPool', dbPool);
app.set('authService', authService);
app.set('libraryService', libraryService);
app.set('imageService', imageService);
app.set('scanService', scanService);
app.set('fileService', fileService);
// 认证中间件(仅作用于 /api 路由,避免拦截前端静态页面)
app.use('/api', createAuthMiddleware(
() => authService.getPasswordHash(),
() => authService.getJwtSecret()
));
// API 路由
const authRouter = require('./routes/auth');
const libraryRouter = require('./routes/library');
const imageRouter = require('./routes/image');
const scanRouter = require('./routes/scan');
const fileRouter = require('./routes/file');
const uploadRouter = require('./routes/upload');
app.use('/api/auth', authRouter);
app.use('/api/library', libraryRouter);
app.use('/api/image', imageRouter);
app.use('/api/scan', scanRouter);
+106
View File
@@ -0,0 +1,106 @@
/**
* 认证中间件
* 轻量级访问密码验证
*/
const jwt = require('jsonwebtoken');
const TOKEN_EXPIRY = '30d'; // Token 有效期 30 天
/**
* 生成 JWT Token
* @param {string} jwtSecret - JWT 密钥(从配置文件读取)
*/
function generateToken(jwtSecret) {
if (!jwtSecret) {
throw new Error('JWT_SECRET is required');
}
return jwt.sign(
{ app: 'flypic', timestamp: Date.now() },
jwtSecret,
{ expiresIn: TOKEN_EXPIRY }
);
}
/**
* 验证 JWT Token
* @param {string} token - JWT Token
* @param {string} jwtSecret - JWT 密钥(从配置文件读取)
*/
function verifyToken(token, jwtSecret) {
if (!jwtSecret) {
return false;
}
try {
jwt.verify(token, jwtSecret);
return true;
} catch (error) {
return false;
}
}
/**
* 认证中间件工厂
* @param {Function} getPasswordHash - 获取密码哈希的函数
* @param {Function} getJwtSecret - 获取 JWT 密钥的函数
*/
function createAuthMiddleware(getPasswordHash, getJwtSecret) {
return (req, res, next) => {
// 如果没有设置密码,直接放行
const passwordHash = getPasswordHash();
if (!passwordHash) {
return next();
}
// 公开接口(登录相关 / 健康检查 / 图片资源)
// 使用 req.originalUrl 获取完整路径(包含 /api 前缀,去除查询字符串)
const fullPath = req.originalUrl.split('?')[0];
// 精确匹配的公开路径
const publicPaths = [
'/api/auth/status',
'/api/auth/login',
'/api/auth/setup',
'/api/health'
];
// 前缀匹配的公开路径(缩略图 & 原图资源)
const publicPrefixes = [
'/api/image/thumbnail/', // 缩略图
'/api/image/original/' // 原图
];
if (
publicPaths.includes(fullPath) ||
publicPrefixes.some(prefix => fullPath.startsWith(prefix))
) {
return next();
}
// 检查 Authorization header
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
success: false,
error: { message: '未授权访问,请先登录' }
});
}
const token = authHeader.substring(7);
const jwtSecret = getJwtSecret();
if (!verifyToken(token, jwtSecret)) {
return res.status(401).json({
success: false,
error: { message: 'Token 无效或已过期,请重新登录' }
});
}
next();
};
}
module.exports = {
createAuthMiddleware,
generateToken,
verifyToken
};
+3 -1
View File
@@ -60,7 +60,9 @@ const errorHandler = (err, req, res, next) => {
error: {
code: err.code,
message: err.message,
...(err.field && { field: err.field })
...(err.field && { field: err.field }),
...(err.remainingAttempts !== undefined && { remainingAttempts: err.remainingAttempts }),
...(err.currentAttempts !== undefined && { currentAttempts: err.currentAttempts })
}
});
}
+112
View File
@@ -0,0 +1,112 @@
/**
* 认证路由
*/
const express = require('express');
const router = express.Router();
/**
* GET /api/auth/status
* 获取认证状态
*/
router.get('/status', async (req, res, next) => {
try {
const authService = req.app.get('authService');
const status = authService.getStatus();
res.json({
success: true,
data: status
});
} catch (error) {
next(error);
}
});
/**
* POST /api/auth/setup
* 首次设置密码
* Body: { password: string }
*/
router.post('/setup', async (req, res, next) => {
try {
const authService = req.app.get('authService');
const { password } = req.body;
if (!password) {
return res.status(400).json({
success: false,
error: { message: '密码不能为空' }
});
}
const result = await authService.setupPassword(password);
res.json({
success: true,
data: result
});
} catch (error) {
next(error);
}
});
/**
* POST /api/auth/login
* 登录验证
* Body: { password: string }
*/
router.post('/login', async (req, res, next) => {
try {
const authService = req.app.get('authService');
const { password } = req.body;
if (!password) {
return res.status(400).json({
success: false,
error: { message: '密码不能为空' }
});
}
// 获取客户端 IP(用于防暴力破解)
const clientIP = req.ip || req.connection.remoteAddress || 'unknown';
const result = await authService.login(password, clientIP);
res.json({
success: true,
data: result
});
} catch (error) {
next(error);
}
});
/**
* POST /api/auth/change-password
* 修改密码(需要认证)
* Body: { oldPassword: string, newPassword: string }
*/
router.post('/change-password', async (req, res, next) => {
try {
const authService = req.app.get('authService');
const { oldPassword, newPassword } = req.body;
if (!oldPassword || !newPassword) {
return res.status(400).json({
success: false,
error: { message: '原密码和新密码不能为空' }
});
}
const result = await authService.changePassword(oldPassword, newPassword);
res.json({
success: true,
data: result
});
} catch (error) {
next(error);
}
});
module.exports = router;
+203
View File
@@ -0,0 +1,203 @@
/**
* 认证服务
* 处理密码设置、验证、修改
*/
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const { generateToken } = require('../middleware/authMiddleware');
const { AppError } = require('../middleware/errorHandler');
const SALT_ROUNDS = 10;
const MAX_LOGIN_ATTEMPTS = 30; // 最大登录尝试次数
const ATTEMPT_WINDOW = 5 * 60 * 1000; // 5分钟窗口期
class AuthService {
constructor(configManager) {
this.configManager = configManager;
// 登录失败记录:IP → { count, firstAttempt, lastAttempt }
this.loginAttempts = new Map();
// 定期清理过期的登录尝试记录(每10分钟)
setInterval(() => {
const now = Date.now();
for (const [ip, data] of this.loginAttempts.entries()) {
if (now - data.lastAttempt > ATTEMPT_WINDOW) {
this.loginAttempts.delete(ip);
}
}
}, 10 * 60 * 1000);
}
/**
* 检查是否已设置密码
*/
hasPassword() {
const config = this.configManager.loadConfig();
return !!config.passwordHash;
}
/**
* 获取密码哈希
*/
getPasswordHash() {
const config = this.configManager.loadConfig();
return config.passwordHash || null;
}
/**
* 获取 JWT 密钥
*/
getJwtSecret() {
const config = this.configManager.loadConfig();
return config.jwtSecret || null;
}
/**
* 设置密码(首次设置)
*/
async setupPassword(password) {
if (this.hasPassword()) {
// 已设置密码,属于业务错误
throw new AppError('密码已设置,请使用修改密码功能', 400, 'PASSWORD_ALREADY_SET');
}
if (!password || password.length < 4) {
throw new AppError('密码长度至少为 4 位', 400, 'INVALID_PASSWORD');
}
const passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
const config = this.configManager.loadConfig();
// 生成随机 JWT 密钥(首次设置时)
if (!config.jwtSecret) {
config.jwtSecret = crypto.randomBytes(32).toString('hex');
console.log('🔐 已生成随机 JWT 密钥');
}
config.passwordHash = passwordHash;
this.configManager.saveConfig(config);
return { token: generateToken(config.jwtSecret) };
}
/**
* 验证密码并登录
* @param {string} password - 密码
* @param {string} clientIP - 客户端IP(用于防暴力破解)
*/
async login(password, clientIP = 'unknown') {
if (!this.hasPassword()) {
// 未设置密码,提示先设置
throw new AppError('未设置密码,请先设置密码', 400, 'PASSWORD_NOT_SET');
}
// 检查登录尝试次数(防暴力破解)
const now = Date.now();
const attempts = this.loginAttempts.get(clientIP);
if (attempts) {
// 检查是否在窗口期内
if (now - attempts.firstAttempt < ATTEMPT_WINDOW) {
// 仍在窗口期内
if (attempts.count >= MAX_LOGIN_ATTEMPTS) {
const remainingTime = Math.ceil((ATTEMPT_WINDOW - (now - attempts.firstAttempt)) / 1000);
throw new AppError(
`登录尝试次数过多,请 ${remainingTime} 秒后再试`,
429,
'TOO_MANY_ATTEMPTS'
);
}
} else {
// 超过窗口期,重置计数
this.loginAttempts.delete(clientIP);
}
}
const passwordHash = this.getPasswordHash();
const jwtSecret = this.getJwtSecret();
if (!jwtSecret) {
throw new AppError('系统配置错误,请重新设置密码', 500, 'MISSING_JWT_SECRET');
}
const isValid = await bcrypt.compare(password, passwordHash);
if (!isValid) {
// 记录失败尝试
if (attempts) {
attempts.count++;
attempts.lastAttempt = now;
} else {
this.loginAttempts.set(clientIP, {
count: 1,
firstAttempt: now,
lastAttempt: now
});
}
// 密码错误:返回 401 未授权,并附带剩余尝试次数
const currentAttempts = attempts ? attempts.count : 1;
const remainingAttempts = MAX_LOGIN_ATTEMPTS - currentAttempts;
console.log(`⚠️ 登录失败 [${clientIP}]: 已尝试 ${currentAttempts} 次,剩余 ${remainingAttempts} 次`);
// 创建错误并附带额外信息
const error = new AppError('密码错误', 401, 'INVALID_PASSWORD');
error.remainingAttempts = remainingAttempts;
error.currentAttempts = currentAttempts;
throw error;
}
// 登录成功,清除尝试记录
this.loginAttempts.delete(clientIP);
console.log(`✅ 登录成功 [${clientIP}]`);
return { token: generateToken(jwtSecret) };
}
/**
* 修改密码
*/
async changePassword(oldPassword, newPassword) {
if (!this.hasPassword()) {
throw new AppError('未设置密码', 400, 'PASSWORD_NOT_SET');
}
if (!newPassword || newPassword.length < 4) {
throw new AppError('新密码长度至少为 4 位', 400, 'INVALID_NEW_PASSWORD');
}
// 验证旧密码
const passwordHash = this.getPasswordHash();
const isValid = await bcrypt.compare(oldPassword, passwordHash);
if (!isValid) {
throw new AppError('原密码错误', 401, 'INVALID_OLD_PASSWORD');
}
// 设置新密码
const newPasswordHash = await bcrypt.hash(newPassword, SALT_ROUNDS);
const config = this.configManager.loadConfig();
config.passwordHash = newPasswordHash;
this.configManager.saveConfig(config);
const jwtSecret = this.getJwtSecret();
if (!jwtSecret) {
throw new AppError('系统配置错误', 500, 'MISSING_JWT_SECRET');
}
return { token: generateToken(jwtSecret) };
}
/**
* 获取认证状态
*/
getStatus() {
return {
hasPassword: this.hasPassword(),
requireAuth: this.hasPassword()
};
}
}
module.exports = AuthService;