generated from muhtadeetaron/nextjs-template
fix(nav): fix exam flow navigation
chore(zustand): refactor auth code for zustand store
This commit is contained in:
33
lib/auth.ts
33
lib/auth.ts
@ -17,6 +17,15 @@ const setCookie = (name: string, value: string | null, days: number = 7) => {
|
||||
}
|
||||
};
|
||||
|
||||
export const getToken = async (): Promise<string | null> => {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = document.cookie.match(/(?:^|;\s*)authToken=([^;]*)/);
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
};
|
||||
|
||||
type SetTokenFn = (token: string) => void;
|
||||
|
||||
// Optional: Create a custom error type to carry extra data
|
||||
@ -69,27 +78,3 @@ export const register = async (
|
||||
setCookie("authToken", data.token);
|
||||
setToken(data.token);
|
||||
};
|
||||
|
||||
export const getTokenFromCookie = (): string | null => {
|
||||
if (typeof document === "undefined") return null;
|
||||
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; authToken=`);
|
||||
if (parts.length === 2) {
|
||||
return parts.pop()?.split(";").shift() || null;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const clearAuthToken = (): void => {
|
||||
setCookie("authToken", null);
|
||||
};
|
||||
|
||||
export const getToken = async (): Promise<string | null> => {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = document.cookie.match(/(?:^|;\s*)authToken=([^;]*)/);
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user