新增 管理员密码访问

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

+3
View File
@@ -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),
+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;
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+40
View File
@@ -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
};
+55 -5
View File
@@ -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 };
+20 -20
View File
@@ -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;
+80
View File
@@ -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 (
<div className="flex flex-col items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
<div className="flex flex-col items-center gap-4">
<div className="w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
<div className="text-lg font-medium text-gray-700 dark:text-gray-300">
正在检查认证状态...
</div>
</div>
</div>
);
}
// 未设置密码,强制设置(首次使用)
if (!hasPassword) {
return <Login />;
}
// 已设置密码但未认证,显示登录页面
if (hasPassword && !isAuthenticated) {
return <Login />;
}
// 已认证,显示应用
return children;
}
+17 -17
View File
@@ -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
+161
View File
@@ -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 (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800">
<div className="w-full max-w-md">
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-8">
{/* Logo */}
<div className="text-center mb-8">
<div className="inline-flex items-center justify-center mb-4">
<img
src="/ICON_256.PNG"
alt="FlyPic Logo"
className="w-20 h-20 object-contain"
onError={(e) => {
// 如果 ICON_256.PNG 加载失败,尝试 favicon.png
e.target.src = '/favicon.png';
}}
/>
</div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
FlyPic 飞图
</h1>
<p className="text-gray-600 dark:text-gray-400">
{hasPassword ? '请输入密码访问' : '首次使用,请设置访问密码'}
</p>
</div>
{/* 表单 */}
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{hasPassword ? '访问密码' : '设置密码'}
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => 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 && (
<p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
💡 密码将加密存储,请妥善保管
</p>
)}
</div>
{error && (
<div className="p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800">
<p className="text-sm text-red-600 dark:text-red-400">
{error}
</p>
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full py-3 px-4 bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white font-medium rounded-lg shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? (
<span className="flex items-center justify-center">
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
处理中...
</span>
) : (
hasPassword ? '登录' : '设置密码并进入'
)}
</button>
</form>
{/* 底部信息 */}
<div className="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
<p className="text-center text-xs text-gray-500 dark:text-gray-400">
轻量 · 快速 · 稳定的图片素材管理
</p>
</div>
</div>
</div>
</div>
);
}
+7 -7
View File
@@ -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}`);
+4 -1
View File
@@ -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(
<React.StrictMode>
<App />
<AuthWrapper>
<App />
</AuthWrapper>
</React.StrictMode>,
)
+32
View File
@@ -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 })
}));