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:
@@ -1,8 +1,7 @@
|
||||
import { api } from '$lib/api/httpClient'; // 通常不需要 .ts 后缀
|
||||
import type { AuthResponse, LoginPayload } from '$lib/types/auth';
|
||||
import { authStore } from '$lib/stores/authStore';
|
||||
import { toast } from '$lib/stores/toastStore';
|
||||
import { ResponseError } from '$lib/types/error.ts';
|
||||
import { ApiError } from '$lib/types/api.ts';
|
||||
|
||||
|
||||
export const authService = {
|
||||
/**
|
||||
@@ -13,23 +12,22 @@ export const authService = {
|
||||
const response = await api.post<AuthResponse>('/auth/login', payload);
|
||||
|
||||
if (response.code !== 200 || !response.data) {
|
||||
throw new ResponseError(response);
|
||||
throw new ApiError(response);
|
||||
}
|
||||
|
||||
const { token, tokenHead,userProfile } = response.data;
|
||||
|
||||
authStore.update(s => ({ ...s, token, tokenHead, isAuthenticated: true,user: userProfile }));
|
||||
|
||||
|
||||
return response.data;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* 登出流程
|
||||
*/
|
||||
logout: async () => {
|
||||
authStore.logout();
|
||||
toast.success('退出登录成功');
|
||||
try {
|
||||
// Optionally call the backend logout endpoint
|
||||
await api.post('/auth/logout', {});
|
||||
} catch (error) {
|
||||
// Even if the backend call fails, we still want to clear local state
|
||||
console.warn('Logout API call failed:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user