MicProtocol / apps /web /src /lib /auth.tsx
Benaah's picture
Upload folder using huggingface_hub
fb12607 verified
Raw History Blame Contribute Delete
2.34 kB
"use client";
import React, { useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
interface User {
id: string;
email: string;
name: string;
avatarUrl?: string;
}
interface AuthContextType {
user: User | null;
isLoading: boolean;
isAuthenticated: boolean;
login: (email: string, password: string) => Promise<void>;
register: (email: string, password: string, name: string) => Promise<void>;
logout: () => Promise<void>;
refreshUser: () => Promise<void>;
}
export function AuthProvider({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
export function useAuth() {
const { data: session, isPending } = authClient.useSession();
const router = useRouter();
const mappedUser = useMemo<User | null>(() => {
if (!session?.user) {
return null;
}
return {
id: session.user.id,
email: session.user.email ?? "",
name: session.user.name ?? session.user.email?.split("@")[0] ?? "MicProtocol User",
avatarUrl: session.user.image ?? undefined,
};
}, [session]);
const login = useCallback(async (email: string, password: string) => {
const { error } = await authClient.signIn.email({
email,
password,
});
if (error) {
throw new Error(error.message || "Login failed");
}
}, []);
const register = useCallback(async (email: string, password: string, name: string) => {
const { error } = await authClient.signUp.email({
email,
password,
name,
});
if (error) {
throw new Error(error.message || "Registration failed");
}
}, []);
const logout = useCallback(async () => {
await authClient.signOut({
fetchOptions: {
onSuccess: () => {
router.push("/login");
},
},
});
}, [router]);
const refreshUser = useCallback(async () => {
await authClient.getSession();
}, []);
return {
user: mappedUser,
isLoading: isPending,
isAuthenticated: !!mappedUser,
login,
register,
logout,
refreshUser,
} satisfies AuthContextType;
}
// Hook for protected routes
export function useRequireAuth() {
const { user, isLoading, isAuthenticated } = useAuth();
return {
user,
isLoading,
isAuthenticated,
};
}