2026-02-26 10:10:14 +00:00
|
|
|
import { useEffect, useState, useMemo } from "react";
|
|
|
|
|
import { UserProfile } from "../types";
|
2026-02-10 09:48:44 +00:00
|
|
|
|
|
|
|
|
export function useAuth() {
|
|
|
|
|
const [accessToken, setAccessToken] = useState<string | null>(() => localStorage.getItem("accessToken"));
|
|
|
|
|
|
2026-03-02 01:09:53 +00:00
|
|
|
const parseJwtPayload = (token: string) => {
|
|
|
|
|
try {
|
|
|
|
|
const payloadPart = token.split(".")[1];
|
|
|
|
|
if (!payloadPart) return null;
|
|
|
|
|
const normalized = payloadPart.replace(/-/g, "+").replace(/_/g, "/");
|
|
|
|
|
const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
|
|
|
|
|
return JSON.parse(atob(padded));
|
|
|
|
|
} catch (e) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-02-10 09:48:44 +00:00
|
|
|
useEffect(() => {
|
|
|
|
|
const handler = () => setAccessToken(localStorage.getItem("accessToken"));
|
|
|
|
|
window.addEventListener("storage", handler);
|
|
|
|
|
return () => window.removeEventListener("storage", handler);
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-02-26 10:10:14 +00:00
|
|
|
const profile = useMemo<UserProfile | null>(() => {
|
|
|
|
|
const data = sessionStorage.getItem("userProfile");
|
2026-03-02 01:09:53 +00:00
|
|
|
if (data) {
|
|
|
|
|
return JSON.parse(data);
|
|
|
|
|
}
|
|
|
|
|
if (!accessToken) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
const payload = parseJwtPayload(accessToken);
|
|
|
|
|
if (payload && (payload.pwdResetRequired === 0 || payload.pwdResetRequired === 1)) {
|
|
|
|
|
return { pwdResetRequired: Number(payload.pwdResetRequired) } as UserProfile;
|
|
|
|
|
}
|
|
|
|
|
return null;
|
2026-02-26 10:10:14 +00:00
|
|
|
}, [accessToken]);
|
|
|
|
|
|
2026-02-10 09:48:44 +00:00
|
|
|
const isAuthed = !!accessToken;
|
|
|
|
|
const logout = () => {
|
|
|
|
|
localStorage.removeItem("accessToken");
|
|
|
|
|
localStorage.removeItem("refreshToken");
|
|
|
|
|
sessionStorage.removeItem("userProfile");
|
2026-02-26 10:10:14 +00:00
|
|
|
setAccessToken(null);
|
2026-02-10 09:48:44 +00:00
|
|
|
};
|
|
|
|
|
|
2026-02-26 10:10:14 +00:00
|
|
|
return { accessToken, isAuthed, profile, logout };
|
2026-02-10 09:48:44 +00:00
|
|
|
}
|
|
|
|
|
|