diff --git a/backend/server.js b/backend/server.js index ebcbf6d..f856cb6 100644 --- a/backend/server.js +++ b/backend/server.js @@ -62,8 +62,11 @@ const io = new Server(server, { // 准备依赖注入 // 包装 config 函数为对象接口 const configManager = { + // 兼容两种命名风格 load: () => config.loadConfig(), save: (data) => config.saveConfig(data), + loadConfig: () => config.loadConfig(), + saveConfig: (data) => config.saveConfig(data), addLibrary: (name, path) => config.addLibrary(name, path), removeLibrary: (id) => config.removeLibrary(id), updateLibrary: (id, updates) => config.updateLibrary(id, updates), diff --git a/backend/src/app.js b/backend/src/app.js index 51a846a..8ea1194 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -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); diff --git a/backend/src/middleware/authMiddleware.js b/backend/src/middleware/authMiddleware.js new file mode 100644 index 0000000..b5f7fbb --- /dev/null +++ b/backend/src/middleware/authMiddleware.js @@ -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 +}; diff --git a/backend/src/middleware/errorHandler.js b/backend/src/middleware/errorHandler.js index 8f582ff..f2598e3 100644 --- a/backend/src/middleware/errorHandler.js +++ b/backend/src/middleware/errorHandler.js @@ -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 }) } }); } diff --git a/backend/src/routes/auth.js b/backend/src/routes/auth.js new file mode 100644 index 0000000..54e934d --- /dev/null +++ b/backend/src/routes/auth.js @@ -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; diff --git a/backend/src/services/AuthService.js b/backend/src/services/AuthService.js new file mode 100644 index 0000000..bf81573 --- /dev/null +++ b/backend/src/services/AuthService.js @@ -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; diff --git a/frontend/public/ICON_256.PNG b/frontend/public/ICON_256.PNG new file mode 100644 index 0000000..079d8e9 Binary files /dev/null and b/frontend/public/ICON_256.PNG differ diff --git a/frontend/src/api/auth.js b/frontend/src/api/auth.js new file mode 100644 index 0000000..608b356 --- /dev/null +++ b/frontend/src/api/auth.js @@ -0,0 +1,40 @@ +/** + * 认证 API + */ + +import { api } from './client'; + +/** + * 获取认证状态 + */ +export function getAuthStatus() { + return api.get('/auth/status'); +} + +/** + * 首次设置密码 + */ +export function setupPassword(password) { + return api.post('/auth/setup', { password }); +} + +/** + * 登录 + */ +export function login(password) { + return api.post('/auth/login', { password }); +} + +/** + * 修改密码 + */ +export function changePassword(oldPassword, newPassword) { + return api.post('/auth/change-password', { oldPassword, newPassword }); +} + +export const authAPI = { + getAuthStatus, + setupPassword, + login, + changePassword +}; diff --git a/frontend/src/api/client.js b/frontend/src/api/client.js index 33806ab..dec97ed 100644 --- a/frontend/src/api/client.js +++ b/frontend/src/api/client.js @@ -17,15 +17,41 @@ class APIError extends Error { } } +/** + * 获取存储的 Token + */ +function getToken() { + return localStorage.getItem('flypic_token'); +} + +/** + * 设置 Token + */ +function setToken(token) { + if (token) { + localStorage.setItem('flypic_token', token); + } else { + localStorage.removeItem('flypic_token'); + } +} + /** * 发送请求 */ async function request(url, options = {}) { + const token = getToken(); + const headers = { + 'Content-Type': 'application/json', + ...options.headers + }; + + // 自动添加 Authorization header + if (token) { + headers.Authorization = `Bearer ${token}`; + } + const config = { - headers: { - 'Content-Type': 'application/json', - ...options.headers - }, + headers, ...options }; @@ -34,6 +60,18 @@ async function request(url, options = {}) { const data = await response.json(); if (!response.ok) { + // 401 未授权处理 + if (response.status === 401) { + // 对于认证检查接口,不触发登出事件(避免循环) + const isAuthCheck = url.includes('/auth/status'); + + if (!isAuthCheck) { + setToken(null); + // 触发登录页面(由 AuthWrapper 处理) + window.dispatchEvent(new Event('auth:unauthorized')); + } + } + throw new APIError( data.error?.message || data.error || 'Request failed', response.status, @@ -86,6 +124,17 @@ function put(url, body, options = {}) { }); } +/** + * PATCH 请求 + */ +function patch(url, body, options = {}) { + return request(url, { + method: 'PATCH', + body: JSON.stringify(body), + ...options + }); +} + /** * DELETE 请求 */ @@ -97,7 +146,8 @@ export const api = { get, post, put, + patch, delete: del }; -export { APIError }; +export { APIError, getToken, setToken }; diff --git a/frontend/src/api/file.js b/frontend/src/api/file.js index ca08067..9cedca3 100644 --- a/frontend/src/api/file.js +++ b/frontend/src/api/file.js @@ -2,9 +2,10 @@ * 文件操作 API 客户端 */ +import { api, getToken } from './client'; import axios from 'axios'; -const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:15002'; +const API_BASE = '/api'; export const fileAPI = { /** @@ -13,10 +14,10 @@ export const fileAPI = { * @param {Array} items - 待删除项 [{type: 'file'|'folder', path: 'path'}] */ async delete(libraryId, items) { - const response = await axios.delete(`${API_BASE}/api/file/delete`, { - data: { libraryId, items } + return api.delete('/file/delete', { + body: JSON.stringify({ libraryId, items }), + headers: { 'Content-Type': 'application/json' } }); - return response.data; }, /** @@ -26,12 +27,11 @@ export const fileAPI = { * @param {string} newName - 新名称 */ async rename(libraryId, path, newName) { - const response = await axios.patch(`${API_BASE}/api/file/rename`, { + return api.patch('/file/rename', { libraryId, path, newName }); - return response.data; }, /** @@ -41,12 +41,11 @@ export const fileAPI = { * @param {string} targetFolder - 目标文件夹路径 */ async move(libraryId, items, targetFolder) { - const response = await axios.post(`${API_BASE}/api/file/move`, { + return api.post('/file/move', { libraryId, items, targetFolder }); - return response.data; }, /** @@ -57,13 +56,12 @@ export const fileAPI = { * @param {string} conflictAction - 冲突处理方式: 'skip'|'replace'|'rename' */ async copy(libraryId, items, targetFolder, conflictAction = 'rename') { - const response = await axios.post(`${API_BASE}/api/file/copy`, { + return api.post('/file/copy', { libraryId, items, targetFolder, conflictAction }); - return response.data; }, /** @@ -73,12 +71,11 @@ export const fileAPI = { * @param {Object} metadata - 元数据 {rating?, favorite?, tags?} */ async updateMetadata(libraryId, path, metadata) { - const response = await axios.patch(`${API_BASE}/api/file/metadata`, { + return api.patch('/file/metadata', { libraryId, path, ...metadata }); - return response.data; }, /** @@ -87,11 +84,10 @@ export const fileAPI = { * @param {Array} items - 待恢复项 [{type: 'file'|'folder', path: 'path'}] */ async restore(libraryId, items) { - const response = await axios.post(`${API_BASE}/api/file/restore`, { + return api.post('/file/restore', { libraryId, items }); - return response.data; }, /** @@ -100,11 +96,10 @@ export const fileAPI = { * @param {string} folderPath - 文件夹路径 */ async createFolder(libraryId, folderPath) { - const response = await axios.post(`${API_BASE}/api/file/create-folder`, { + return api.post('/file/create-folder', { libraryId, folderPath }); - return response.data; }, /** @@ -130,10 +125,15 @@ export const fileAPI = { formData.append('files', file); } - const response = await axios.post(`${API_BASE}/api/upload`, formData, { - headers: { - 'Content-Type': 'multipart/form-data' - }, + // 使用 Axios 处理上传(支持进度回调),手动添加 Authorization 头 + const token = getToken(); + const headers = {}; + if (token) { + headers.Authorization = `Bearer ${token}`; + } + + const response = await axios.post(`${API_BASE}/upload`, formData, { + headers, onUploadProgress: onProgress }); return response.data; diff --git a/frontend/src/components/AuthWrapper.jsx b/frontend/src/components/AuthWrapper.jsx new file mode 100644 index 0000000..c51981c --- /dev/null +++ b/frontend/src/components/AuthWrapper.jsx @@ -0,0 +1,80 @@ +/** + * 认证包装器 + * 检查认证状态,未认证时显示登录页面 + */ + +import { useEffect } from 'react'; +import { useAuthStore } from '../stores/useAuthStore'; +import { authAPI } from '../api/auth'; +import { getToken } from '../api/client'; +import Login from './Login'; + +export default function AuthWrapper({ children }) { + const { hasPassword, isAuthenticated, isChecking, setAuthStatus, logout } = useAuthStore(); + + useEffect(() => { + // 检查认证状态 + checkAuth(); + + // 监听 401 未授权事件 + const handleUnauthorized = () => { + logout(); + }; + + window.addEventListener('auth:unauthorized', handleUnauthorized); + return () => window.removeEventListener('auth:unauthorized', handleUnauthorized); + }, []); + + const checkAuth = async () => { + try { + const status = await authAPI.getAuthStatus(); + const token = getToken(); + + console.log('🔐 认证状态检查:', { hasPassword: status.hasPassword, hasToken: !!token }); + + // 已设置密码但没有 token,需要登录 + // 未设置密码或有有效 token,允许访问 + setAuthStatus(status.hasPassword, status.hasPassword ? !!token : true); + } catch (error) { + console.error('❌ 检查认证状态失败:', error); + + // 网络错误或服务器错误,假设未设置密码(允许访问) + // 避免因网络问题锁住用户 + if (error.status === 401) { + // 明确的 401 错误,说明需要认证 + setAuthStatus(true, false); + } else { + // 其他错误(网络问题等),假设未设置密码 + console.warn('⚠️ 无法验证认证状态,假设未设置密码'); + setAuthStatus(false, true); + } + } + }; + + // 检查中,显示加载状态 + if (isChecking) { + return ( +
+
+
+
+ 正在检查认证状态... +
+
+
+ ); + } + + // 未设置密码,强制设置(首次使用) + if (!hasPassword) { + return ; + } + + // 已设置密码但未认证,显示登录页面 + if (hasPassword && !isAuthenticated) { + return ; + } + + // 已认证,显示应用 + return children; +} diff --git a/frontend/src/components/ImageWaterfall.jsx b/frontend/src/components/ImageWaterfall.jsx index 60d41ac..78cbcdd 100644 --- a/frontend/src/components/ImageWaterfall.jsx +++ b/frontend/src/components/ImageWaterfall.jsx @@ -617,9 +617,9 @@ function ImageWaterfall() { imageAPI.getFolders(currentLibraryId) ]).then(([restoreResult, foldersRes]) => { // 检查恢复结果 - if (restoreResult.data.failed.length > 0) { - console.warn(`⚠️ 恢复失败: ${restoreResult.data.failed.length} 个文件`); - const errorMsg = restoreResult.data.failed[0].error || '未知错误'; + if (restoreResult.failed.length > 0) { + console.warn(`⚠️ 恢复失败: ${restoreResult.failed.length} 个文件`); + const errorMsg = restoreResult.failed[0].error || '未知错误'; // 失败时回滚UI setUndoHistory(undoHistory); @@ -757,8 +757,8 @@ function ImageWaterfall() { imageAPI.getFolders(currentLibraryId) ]).then(([deleteResult, foldersRes]) => { // 检查是否有失败的项 - if (deleteResult.data.failed.length > 0) { - console.warn(`⚠️ 删除失败: ${deleteResult.data.failed.length} 个文件`, deleteResult.data.failed); + if (deleteResult.failed.length > 0) { + console.warn(`⚠️ 删除失败: ${deleteResult.failed.length} 个文件`, deleteResult.failed); // 如果有失败,回滚UI setImages(images); setUndoHistory(undoHistory); @@ -1053,8 +1053,8 @@ function ImageWaterfall() { const result = await fileAPI.copy(currentLibraryId, items, targetFolder, conflictAction); // 处理结果 - const successCount = result.data.success?.length || 0; - const failedCount = result.data.failed?.length || 0; + const successCount = result.success?.length || 0; + const failedCount = result.failed?.length || 0; if (failedCount > 0) { // 有失败的项,更新Toast提示 @@ -1062,7 +1062,7 @@ function ImageWaterfall() { isVisible: true, message: successCount > 0 ? `已粘贴 ${successCount} 个文件,${failedCount} 个失败` - : `粘贴失败: ${result.data.failed[0].error}`, + : `粘贴失败: ${result.failed[0].error}`, count: successCount }); @@ -1127,11 +1127,11 @@ function ImageWaterfall() { ); // 上传完成 - setUploadProgress({ isUploading: false, percent: 100, current: result.data.success.length, total: pendingUpload.files.length }); + setUploadProgress({ isUploading: false, percent: 100, current: result.success.length, total: pendingUpload.files.length }); // 显示结果提示 - const successCount = result.data.success?.length || 0; - const failedCount = result.data.failed?.length || 0; + const successCount = result.success?.length || 0; + const failedCount = result.failed?.length || 0; let message = `上传完成: 成功 ${successCount} 个`; if (failedCount > 0) message += `, 失败 ${failedCount} 个`; @@ -1262,10 +1262,10 @@ function ImageWaterfall() { ); // 上传完成 - setUploadProgress({ isUploading: false, percent: 100, current: result.data.success.length, total: files.length }); + setUploadProgress({ isUploading: false, percent: 100, current: result.success.length, total: files.length }); // 检查是否有冲突 - const conflicts = result.data.conflicts || []; + const conflicts = result.conflicts || []; if (conflicts.length > 0) { // 有冲突,显示冲突对话框 console.log(`⚠️ 检测到 ${conflicts.length} 个文件冲突`); @@ -1285,8 +1285,8 @@ function ImageWaterfall() { } // 显示结果提示 - const successCount = result.data.success?.length || 0; - const failedCount = result.data.failed?.length || 0; + const successCount = result.success?.length || 0; + const failedCount = result.failed?.length || 0; let message = `上传完成: 成功 ${successCount} 个`; if (failedCount > 0) message += `, 失败 ${failedCount} 个`; @@ -1371,8 +1371,8 @@ function ImageWaterfall() { const result = await fileAPI.rename(currentLibraryId, renamingImage.path, newFilename); // 更新图片信息 - const newPath = result.data.newPath; - const actualNewName = result.data.newName; + const newPath = result.newPath; + const actualNewName = result.newName; updateImage(renamingImage.path, { path: newPath, filename: actualNewName diff --git a/frontend/src/components/Login.jsx b/frontend/src/components/Login.jsx new file mode 100644 index 0000000..32dbc3c --- /dev/null +++ b/frontend/src/components/Login.jsx @@ -0,0 +1,161 @@ +/** + * 登录页面 + */ + +import { useState } from 'react'; +import { authAPI } from '../api/auth'; +import { setToken } from '../api/client'; +import { useAuthStore } from '../stores/useAuthStore'; + +export default function Login() { + const [password, setPassword] = useState(''); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + + const { hasPassword, setAuthStatus } = useAuthStore(); + + const handleSubmit = async (e) => { + e.preventDefault(); + + if (!password) { + setError('请输入密码'); + return; + } + + if (password.length < 4) { + setError('密码长度至少为 4 位'); + return; + } + + setLoading(true); + setError(''); + + try { + let result; + + if (hasPassword) { + // 登录 + result = await authAPI.login(password); + } else { + // 首次设置密码 + result = await authAPI.setupPassword(password); + } + + // 保存 token + setToken(result.token); + + // 更新认证状态(已设置密码 + 已认证) + setAuthStatus(true, true); + + } catch (err) { + if (err.status === 401) { + // 密码错误,检查是否有剩余尝试次数信息 + if (err.data?.error?.remainingAttempts !== undefined) { + const remaining = err.data.error.remainingAttempts; + if (remaining > 0) { + setError(`密码错误,剩余 ${remaining} 次尝试机会`); + } else { + setError('密码错误,已达到最大尝试次数,请稍后再试'); + } + } else { + setError('密码错误'); + } + } else if (err.status === 429) { + // 尝试次数过多 + setError(err.message || '登录尝试次数过多,请稍后再试'); + } else if (err.status === 400 && err.message) { + setError(err.message); + } else { + setError(err.message || '操作失败,请稍后重试'); + } + } finally { + setLoading(false); + } + }; + + return ( +
+
+
+ {/* Logo */} +
+
+ FlyPic Logo { + // 如果 ICON_256.PNG 加载失败,尝试 favicon.png + e.target.src = '/favicon.png'; + }} + /> +
+

+ FlyPic 飞图 +

+

+ {hasPassword ? '请输入密码访问' : '首次使用,请设置访问密码'} +

+
+ + {/* 表单 */} +
+
+ + setPassword(e.target.value)} + placeholder={hasPassword ? '请输入密码' : '至少 4 位字符'} + className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition" + disabled={loading} + autoFocus + /> + {!hasPassword && ( +

+ 💡 密码将加密存储,请妥善保管 +

+ )} +
+ + {error && ( +
+

+ {error} +

+
+ )} + + +
+ + {/* 底部信息 */} +
+

+ 轻量 · 快速 · 稳定的图片素材管理 +

+
+
+
+
+ ); +} diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx index 5953e94..e475c04 100644 --- a/frontend/src/components/Sidebar.jsx +++ b/frontend/src/components/Sidebar.jsx @@ -286,13 +286,13 @@ function Sidebar() { imageAPI.getFolders(currentLibraryId) ]).then(([deleteResult, foldersRes]) => { const { setFolders } = useImageStore.getState(); - if (deleteResult.data.failed.length > 0) { - console.warn(`⚠️ 删除失败:`, deleteResult.data.failed); + if (deleteResult.failed.length > 0) { + console.warn(`⚠️ 删除失败:`, deleteResult.failed); // 失败时回滚 setUndoHistory(undoHistory); setUndoToast({ isVisible: false, message: '', count: 0 }); setFolders(foldersRes.folders); - alert('删除失败: ' + deleteResult.data.failed[0].error); + alert('删除失败: ' + deleteResult.failed[0].error); } else { // 成功时刷新文件夹列表以确保同步 setFolders(foldersRes.folders); @@ -351,9 +351,9 @@ function Sidebar() { ]).then(([restoreResult, foldersRes]) => { const { setFolders } = useImageStore.getState(); // 检查恢复结果 - if (restoreResult.data.failed.length > 0) { - console.warn(`⚠️ 恢复失败: ${restoreResult.data.failed.length} 个文件`); - const errorMsg = restoreResult.data.failed[0].error || '未知错误'; + if (restoreResult.failed.length > 0) { + console.warn(`⚠️ 恢复失败: ${restoreResult.failed.length} 个文件`); + const errorMsg = restoreResult.failed[0].error || '未知错误'; // 失败时回滚 setUndoHistory(undoHistory); @@ -523,7 +523,7 @@ function Sidebar() { try { // 调用重命名API const result = await fileAPI.rename(currentLibraryId, oldPath, newName); - const newPath = result.data.newPath; + const newPath = result.newPath; console.log(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`); diff --git a/frontend/src/main.jsx b/frontend/src/main.jsx index 5cc5991..ac14d5f 100644 --- a/frontend/src/main.jsx +++ b/frontend/src/main.jsx @@ -1,10 +1,13 @@ import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' +import AuthWrapper from './components/AuthWrapper' import './index.css' ReactDOM.createRoot(document.getElementById('root')).render( - + + + , ) diff --git a/frontend/src/stores/useAuthStore.js b/frontend/src/stores/useAuthStore.js new file mode 100644 index 0000000..81385a3 --- /dev/null +++ b/frontend/src/stores/useAuthStore.js @@ -0,0 +1,32 @@ +/** + * 认证状态管理 + */ + +import { create } from 'zustand'; + +export const useAuthStore = create((set) => ({ + // 是否已设置密码 + hasPassword: false, + + // 是否已通过认证 + isAuthenticated: false, + + // 是否正在检查认证状态 + isChecking: true, + + // 设置认证状态 + setAuthStatus: (hasPassword, isAuthenticated) => set({ + hasPassword, + isAuthenticated, + isChecking: false + }), + + // 设置检查状态 + setChecking: (isChecking) => set({ isChecking }), + + // 登录成功 + setAuthenticated: () => set({ isAuthenticated: true }), + + // 登出 + logout: () => set({ isAuthenticated: false }) +}));