67 lines
2.3 KiB
TypeScript
67 lines
2.3 KiB
TypeScript
import type { BetterAuthClientOptions, InferSessionFromClient, InferUserFromClient } from 'better-auth/client';
|
|
import { authClient } from '~~/lib/auth-client';
|
|
|
|
export const useAuth = () => {
|
|
const session = useState<InferSessionFromClient<BetterAuthClientOptions> | null>('auth:session', () => null);
|
|
const user = useState<InferUserFromClient<BetterAuthClientOptions> | null>('auth:user', () => null);
|
|
const sessionFetching = import.meta.server ? ref(false) : useState('auth:sessionFetching', () => false);
|
|
|
|
const fetchSession = async () => {
|
|
if (sessionFetching.value) {
|
|
console.log('already fetching session');
|
|
return;
|
|
}
|
|
sessionFetching.value = true;
|
|
let data: {
|
|
session: InferSessionFromClient<BetterAuthClientOptions>;
|
|
user: InferUserFromClient<BetterAuthClientOptions>;
|
|
} | null = null;
|
|
if (import.meta.server) {
|
|
data =
|
|
(
|
|
await useFetch<{
|
|
session: InferSessionFromClient<BetterAuthClientOptions>;
|
|
user: InferUserFromClient<BetterAuthClientOptions>;
|
|
}>('/api/auth/get-session')
|
|
).data.value ?? null;
|
|
} else {
|
|
data = (await authClient.getSession()).data;
|
|
}
|
|
session.value = data?.session || null;
|
|
user.value = data?.user || null;
|
|
sessionFetching.value = false;
|
|
return data;
|
|
};
|
|
|
|
if (import.meta.client) {
|
|
authClient.$store.listen('$sessionSignal', async (signal) => {
|
|
if (!signal) return;
|
|
await fetchSession();
|
|
|
|
if (!session.value) return;
|
|
|
|
const triplit = useTriplitClient();
|
|
if ('updateOptions' in triplit) {
|
|
triplit.updateOptions({
|
|
token: session.value.token,
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
return {
|
|
session,
|
|
user,
|
|
loggedIn: computed(() => !!session.value),
|
|
signIn: authClient.signIn,
|
|
signUp: authClient.signUp,
|
|
async signOut() {
|
|
await authClient.signOut();
|
|
session.value = null;
|
|
user.value = null;
|
|
return navigateTo('/auth/login');
|
|
},
|
|
fetchSession,
|
|
};
|
|
};
|