composables/useUser.ts:
import type { publicUser } from "~/types/User";
import { Role } from "~/types/User";
export const useCurrentUser = () => {
return useState<publicUser | null>("user", () => null);
};
export const isLoggedIn = computed(() => {
return !!useCurrentUser().value;
});
export const isAdmin = computed(() => {
return useCurrentUser().value?.role === Role.Admin;
});
export async function useUser(): Promise<publicUser | null> {
const authCookie = useCookie("authToken");
const user = useCurrentUser().value;
if (authCookie && !user) {
const cookieHeaders = useRequestHeaders(["cookie"]);
const { data } = await useFetch<publicUser>("/api/auth/currentUser", {
method: "GET",
headers: cookieHeaders as HeadersInit,
});
if (!data.value) return null;
useCurrentUser().value = data.value;
}
return user;
}