refactor(auth): implement token-based authentication with JWT parsing

- Replace authStore with tokenService for authentication management
- Add JWT parsing utility to extract user info from tokens
- Update login flow to use cookie-based token storage
- Modify logout to properly clear auth state and cookies
- Integrate user data into page context for SSR compatibility
- Remove deprecated authStore and related localStorage logic
- Add cookie constants for consistent token handling
- Implement server-side token validation in hooks
- Update HTTP client to use token from cookies instead of store
- Refactor error handling to use unified ApiError class
- Replace manual redirect logic with resolved paths
- Improve type safety with explicit user and auth interfaces
- Add toast notifications for login/logout feedback
- Remove unused sidebar store and related UI logic
- Migrate theme handling to use cookies and context
- Update icon definitions and component references
- Clean up legacy code and unused imports
This commit is contained in:
Chaos
2025-11-25 16:53:48 +08:00
parent 8f3f2d63a0
commit 4ec8e88e58
32 changed files with 437 additions and 381 deletions

View File

@@ -1,8 +1,6 @@
// src/lib/api/httpClient.ts
import { browser } from '$app/environment';
import type { HttpMethod, JsonObject, JsonValue } from '$lib/types/http.ts';
import { authStore } from '$lib/stores/authStore.ts';
import type { ApiResult } from '$lib/types/api.ts';
@@ -11,16 +9,8 @@ interface RequestOptions extends Omit<RequestInit, 'method' | 'body'> {
}
const API_BASE_URL = import.meta.env.VITE_PUBLIC_API_URL || 'http://localhost:18888/api';
let currentToken: string | null = null;
let currentTokenHead: string | null = null;
if (browser) {
// 只有在浏览器环境下才订阅,防止 SSR 内存泄漏
authStore.subscribe(state => {
currentToken = state.token;
currentTokenHead = state.tokenHead;
});
}
const normalizeHeaders = (headers?: HeadersInit):Record<string, string> =>{
const result:Record<string,string> = {};
@@ -74,8 +64,8 @@ const httpRequest = async <T>(
const canHaveBody = method !== 'GET' ;
// 【修改点 2】只有在允许携带 Body 时才处理
if (canHaveBody) {
console.log('body', body);
if (body instanceof FormData) {
requestBody = body;
} else if (body) {
@@ -85,9 +75,9 @@ const httpRequest = async <T>(
}
// ... Token 处理逻辑保持不变 ...
if (currentToken && currentTokenHead) {
requestHeaders['authorization'] = `${currentTokenHead} ${currentToken}`;
}
// if (currentToken && currentTokenHead) {
// requestHeaders['authorization'] = `${currentTokenHead} ${currentToken}`;
// }
try {
const response = await fetch(fullUrl, {