This commit is contained in:
phaichayon
2026-04-23 15:37:01 +07:00
parent 67960174d3
commit a330abf9b6
36 changed files with 4656 additions and 278 deletions

View File

@@ -0,0 +1,86 @@
"use client";
import {
createContext,
useContext,
useEffect,
useState,
type ReactNode,
} from "react";
import {
initKeycloak,
logout as keycloakLogout,
getUserInfo,
isAuthenticated as isKeycloakAuthenticated,
} from "@/lib/keycloak-client";
interface AuthContextType {
isAuthenticated: boolean;
isLoading: boolean;
userInfo: any;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [userInfo, setUserInfo] = useState<any>(null);
useEffect(() => {
let mounted = true;
async function initAuth() {
try {
const authenticated = await initKeycloak();
if (mounted) {
setIsAuthenticated(authenticated);
setIsLoading(false);
if (authenticated) {
setUserInfo(getUserInfo());
}
}
} catch (error) {
console.error("Auth initialization failed:", error);
if (mounted) {
setIsLoading(false);
}
}
}
initAuth();
return () => {
mounted = false;
};
}, []);
const handleLogout = async () => {
await keycloakLogout();
setIsAuthenticated(false);
setUserInfo(null);
};
return (
<AuthContext.Provider
value={{
isAuthenticated,
isLoading,
userInfo,
logout: handleLogout,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}