feat(auth): 实现基于令牌的用户认证和访问控制

- 在用户相关页面服务端加载函数中添加令牌检查,防止未授权访问
- 更新用户服务方法以支持携带认证令牌请求API
- 修改用户资料和用户列表组件以适配新的认证流程
- 引入侧边栏状态管理并在布局中注册上下文
- 调整HTTP客户端逻辑以正确传递请求头信息
- 更新用户类型定义以匹配后端返回的角色结构
- 优化应用头部和侧边栏组件的UI细节和交互逻辑
This commit is contained in:
Chaos
2025-11-25 23:33:32 +08:00
parent 81c61f433d
commit 7d627a45fb
14 changed files with 523 additions and 137 deletions

View File

@@ -14,6 +14,7 @@ const API_BASE_URL = import.meta.env.VITE_PUBLIC_API_URL || 'http://localhost:18
const normalizeHeaders = (headers?: HeadersInit):Record<string, string> =>{
const result:Record<string,string> = {};
console.log('normalizeHeaders', headers);
if (!headers){
return result;
}
@@ -28,9 +29,14 @@ const normalizeHeaders = (headers?: HeadersInit):Record<string, string> =>{
})
}else {
Object.keys(headers).forEach(key => {
result[key.toLowerCase()] = headers[key.toLowerCase()] as string;
const value = (headers as Record<string, string>)[key];
if (value !== undefined && value !== null) {
result[key.toLowerCase()] = value;
}
})
}
console.log('normalizeHeaders result:', result);
return result;
}
export class HttpError extends Error {
@@ -59,13 +65,14 @@ const httpRequest = async <T>(
const fullUrl = `${API_BASE_URL}${url}`;
const { body, headers, ...rest } = options;
const requestHeaders: Record<string, string> = normalizeHeaders(headers);
let requestBody: BodyInit | undefined;
const canHaveBody = method !== 'GET' ;
if (canHaveBody) {
console.log('body', body);
if (body instanceof FormData) {
requestBody = body;
} else if (body) {
@@ -74,12 +81,11 @@ const httpRequest = async <T>(
}
}
// ... Token 处理逻辑保持不变 ...
// if (currentToken && currentTokenHead) {
// requestHeaders['authorization'] = `${currentTokenHead} ${currentToken}`;
// }
try {
const response = await fetch(fullUrl, {
method,
headers: requestHeaders,
@@ -89,6 +95,8 @@ const httpRequest = async <T>(
...rest
});
console.log('response', response);
if (!response.ok) {
let errorDetail;
try {