新增 管理员密码访问

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

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 })
}));