| 17 | * Updates auth store based on the result |
| 18 | */ |
| 19 | export const validateToken = async (): Promise<boolean> => { |
| 20 | const token = localStorage.getItem("token"); |
| 21 | |
| 22 | // If no token exists, user is not authenticated |
| 23 | if (!token) { |
| 24 | useAuthStore.getState().reset(); |
| 25 | return false; |
| 26 | } |
| 27 | |
| 28 | // Set token in store |
| 29 | useAuthStore.getState().setToken(token); |
| 30 | useAuthStore.getState().setLoading(true); |
| 31 | |
| 32 | try { |
| 33 | const response = await apiRequest<UserResponse>({ |
| 34 | method: "GET", |
| 35 | url: "/core/user", |
| 36 | }); |
| 37 | |
| 38 | if (response.success && response.data) { |
| 39 | // User is authenticated and we have user data |
| 40 | useAuthStore.getState().setUser(response.data); |
| 41 | useAuthStore.getState().setAuthenticated(true); |
| 42 | useAuthStore.getState().setError(null); |
| 43 | return true; |
| 44 | } else { |
| 45 | // Invalid response - clear auth state |
| 46 | localStorage.removeItem("token"); |
| 47 | useAuthStore.getState().reset(); |
| 48 | return false; |
| 49 | } |
| 50 | } catch (error) { |
| 51 | // Request failed - clear auth state |
| 52 | localStorage.removeItem("token"); |
| 53 | useAuthStore.getState().reset(); |
| 54 | return false; |
| 55 | } finally { |
| 56 | useAuthStore.getState().setLoading(false); |
| 57 | } |
| 58 | }; |
| 59 | |
| 60 | /** |
| 61 | * Logs the user out by clearing token and auth state |