This commit is contained in:
NotII
2025-03-14 17:03:54 +00:00
parent 87a58a6736
commit 0c64b5be79
5 changed files with 183 additions and 51 deletions

55
lib/auth-utils.ts Normal file
View File

@@ -0,0 +1,55 @@
/**
* Auth utilities for managing authentication state
*/
/**
* Get the authentication token from cookies or localStorage
*/
export function getAuthToken(): string | null {
return document.cookie
.split('; ')
.find(row => row.startsWith('Authorization='))
?.split('=')[1] || localStorage.getItem('Authorization');
}
/**
* Check if the user is logged in
*/
export function isLoggedIn(): boolean {
return !!getAuthToken();
}
/**
* Logout the user by removing auth tokens and redirecting
*/
export async function logoutUser(): Promise<void> {
const token = getAuthToken();
if (token) {
try {
// Try to logout on the server (if this fails, we still proceed with client logout)
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/logout`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}).catch(err => {
// Silently catch errors - we still want to proceed with local logout
console.warn('Server logout failed:', err);
});
} catch (error) {
console.warn('Error during server logout:', error);
// Continue with client-side logout regardless of server response
}
}
// Remove the auth token from cookies
document.cookie = 'Authorization=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; SameSite=Strict';
// Remove from localStorage as backup
localStorage.removeItem('Authorization');
// Redirect to login page
window.location.href = '/auth/login';
}

View File

@@ -47,6 +47,12 @@ export const addShippingMethod = async (
}
);
// If fetchData returns directly (not a Response object), just return it
if (!res.ok && !res.status) {
return res;
}
// Handle if it's a Response object
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.message || "Failed to add shipping method");
@@ -102,7 +108,7 @@ export const updateShippingMethod = async (
);
if (!res) throw new Error("Failed to update shipping method");
return res
return res;
} catch (error) {
console.error("Error updating shipping method:", error);
throw error;