- 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
45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { api } from '$lib/api/httpClient';
|
|
import type { ApiResult } from '$lib/types/api';
|
|
import { authStore } from '$lib/stores/authStore';
|
|
import { browser } from '$app/environment';
|
|
|
|
export const tokenService = {
|
|
/**
|
|
* Check if the current token is valid
|
|
*/
|
|
validateToken: async (): Promise<boolean> => {
|
|
if (!browser) return false;
|
|
|
|
try {
|
|
const response = await api.get<null>('/auth/validate');
|
|
return response.code === 200;
|
|
} catch (error) {
|
|
console.error('Token validation failed:', error);
|
|
return false;
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Refresh the current token
|
|
*/
|
|
refreshToken: async (): Promise<boolean> => {
|
|
if (!browser) return false;
|
|
|
|
try {
|
|
const response = await api.post<{token: string, tokenHead: string}>('/auth/refresh', {});
|
|
if (response.code === 200 && response.data) {
|
|
// Update the auth store with new token
|
|
authStore.update(state => ({
|
|
...state,
|
|
token: response.data!.token,
|
|
tokenHead: response.data!.tokenHead
|
|
}));
|
|
return true;
|
|
}
|
|
return false;
|
|
} catch (error) {
|
|
console.error('Token refresh failed:', error);
|
|
return false;
|
|
}
|
|
}
|
|
}; |