WOOHOO
This commit is contained in:
55
lib/auth-utils.ts
Normal file
55
lib/auth-utils.ts
Normal 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';
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user