44 lines
1,021 B
TypeScript
44 lines
1,021 B
TypeScript
|
|
"use client";
|
||
|
|
|
||
|
|
import { createContext, useContext, ReactNode } from "react";
|
||
|
|
import { authClient, useSession } from "@/lib/auth-client";
|
||
|
|
|
||
|
|
type AuthContextType = {
|
||
|
|
session: ReturnType<typeof useSession>["data"];
|
||
|
|
isPending: boolean;
|
||
|
|
error: ReturnType<typeof useSession>["error"];
|
||
|
|
signOut: () => Promise<void>;
|
||
|
|
};
|
||
|
|
|
||
|
|
const AuthContext = createContext<AuthContextType | null>(null);
|
||
|
|
|
||
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
||
|
|
const { data: session, isPending, error } = useSession();
|
||
|
|
|
||
|
|
const handleSignOut = async () => {
|
||
|
|
await authClient.signOut();
|
||
|
|
window.location.href = "/auth/sign-in";
|
||
|
|
};
|
||
|
|
|
||
|
|
return (
|
||
|
|
<AuthContext.Provider
|
||
|
|
value={{
|
||
|
|
session,
|
||
|
|
isPending,
|
||
|
|
error,
|
||
|
|
signOut: handleSignOut,
|
||
|
|
}}
|
||
|
|
>
|
||
|
|
{children}
|
||
|
|
</AuthContext.Provider>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useAuth() {
|
||
|
|
const context = useContext(AuthContext);
|
||
|
|
if (!context) {
|
||
|
|
throw new Error("useAuth must be used within an AuthProvider");
|
||
|
|
}
|
||
|
|
return context;
|
||
|
|
}
|