39 lines
1.6 KiB
TypeScript
39 lines
1.6 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback } from "react";
|
|
import type { LoginUser } from "@kri/common";
|
|
import { createAuthHook, type AuthState as CommonAuthState } from "@kri/common/hooks";
|
|
import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/store/storage/secure-storage";
|
|
import { StorageKeys } from "@/store/storage/storage-keys";
|
|
|
|
export type AuthState = CommonAuthState<LoginUser>;
|
|
const initialAuthState: AuthState = { user: null };
|
|
|
|
const loadInitialAuthState = (): AuthState => {
|
|
const stored = getLocalStorage(StorageKeys.AuthState);
|
|
return stored && typeof stored === "object" && "user" in stored
|
|
? { ...initialAuthState, ...(stored as Partial<AuthState>) }
|
|
: initialAuthState;
|
|
};
|
|
|
|
const { authAtom, useAuth: useCommonAuth } = createAuthHook<LoginUser>({ initialState: loadInitialAuthState() });
|
|
export const authStateAtom = authAtom;
|
|
|
|
export function useAuth() {
|
|
const { auth, setAuth: setCommonAuth } = useCommonAuth();
|
|
|
|
const setAuth = useCallback((next: AuthState | ((previous: AuthState) => AuthState)) => {
|
|
setCommonAuth((previous) => {
|
|
const resolved = typeof next === "function" ? next(previous) : next;
|
|
if (resolved.user === null) removeLocalStorage(StorageKeys.AuthState);
|
|
else setLocalStorage(StorageKeys.AuthState, resolved);
|
|
return resolved;
|
|
});
|
|
}, [setCommonAuth]);
|
|
|
|
const setFromLoginResponse = useCallback((user: LoginUser) => setAuth({ user }), [setAuth]);
|
|
const logout = useCallback(() => setAuth(initialAuthState), [setAuth]);
|
|
|
|
return { auth, setAuth, setFromLoginResponse, logout } as const;
|
|
}
|