beta sign up sends an email with a magic token. then a separate email to login.
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
// app/(account)/AccountChrome.tsx
|
||||
"use client";
|
||||
|
||||
import TopNav from "@/components/TopNav";
|
||||
import BuilderNav from "@/components/BuilderNav";
|
||||
|
||||
export default function AccountChrome() {
|
||||
return (
|
||||
<>
|
||||
<TopNav />
|
||||
<BuilderNav />
|
||||
</>
|
||||
);
|
||||
}
|
||||
+188
-22
@@ -3,41 +3,207 @@
|
||||
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
|
||||
function StatChip({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string;
|
||||
value: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-lg border border-white/10 bg-white/5 px-3 py-2">
|
||||
<div className="text-[11px] uppercase tracking-[0.18em] text-white/50">
|
||||
{label}
|
||||
</div>
|
||||
<div className="text-sm font-semibold text-white/90">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Card({
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
badge,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
children: React.ReactNode;
|
||||
badge?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-white/90">{title}</h3>
|
||||
{description ? (
|
||||
<p className="mt-1 text-sm text-white/60">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{badge ? <div className="shrink-0">{badge}</div> : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-4">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, value }: { label: string; value: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4 py-2">
|
||||
<div className="text-sm text-white/60">{label}</div>
|
||||
<div className="text-sm font-medium text-white/90">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AccountPage() {
|
||||
const { user, loading } = useAuth();
|
||||
|
||||
if (loading) return <div className="text-sm opacity-70">Loading…</div>;
|
||||
if (loading) return <div className="text-sm text-white/60">Loading…</div>;
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="text-sm opacity-70">
|
||||
You’re not logged in. Please log in to view your account.
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-6">
|
||||
<h2 className="text-base font-semibold text-white/90">
|
||||
You’re not logged in
|
||||
</h2>
|
||||
<p className="mt-2 text-sm text-white/60">
|
||||
Please log in to view your account.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const planLabel = user.role === "ADMIN" ? "Admin" : "Beta Access";
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Profile</h2>
|
||||
<p className="text-sm opacity-70">
|
||||
Basic account info (we’ll expand this soon).
|
||||
</p>
|
||||
<div className="space-y-6">
|
||||
{/* Quick stats (lightweight “premium” feel) */}
|
||||
{/* <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<StatChip label="Email" value={user.email} />
|
||||
<StatChip label="Display Name" value={user.displayName || "—"} />
|
||||
<StatChip label="Role" value={user.role} />
|
||||
<StatChip label="Plan" value={planLabel} />
|
||||
</div> */}
|
||||
|
||||
<div id="profile">
|
||||
<Card
|
||||
title="Profile"
|
||||
description="Basic account info."
|
||||
badge={
|
||||
<span className="rounded-full border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-white/60">
|
||||
Read-only (for now)
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="divide-y divide-white/10">
|
||||
<Row label="Email" value={user.email} />
|
||||
<Row label="Display name" value={user.displayName || "—"} />
|
||||
<Row label="Role" value={user.role} />
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-white/10 bg-white/5 p-4 space-y-2">
|
||||
<div className="text-sm">
|
||||
<span className="opacity-70">Email:</span>{" "}
|
||||
<span className="font-medium">{user.email}</span>
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<span className="opacity-70">Display name:</span>{" "}
|
||||
<span className="font-medium">{user.displayName || "—"}</span>
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<span className="opacity-70">Role:</span>{" "}
|
||||
<span className="font-medium">{user.role}</span>
|
||||
</div>
|
||||
<div id="preferences">
|
||||
<Card
|
||||
title="Preferences"
|
||||
description="Placeholders until we wire the backend."
|
||||
badge={
|
||||
<span className="rounded-full border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-white/60">
|
||||
Coming soon
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<label className="flex items-center justify-between gap-4 rounded-xl border border-white/10 bg-white/5 p-3">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-white/90">
|
||||
Default new builds to private
|
||||
</div>
|
||||
<div className="text-sm text-white/60">
|
||||
Keeps builds off the public feed until you publish.
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled
|
||||
className="h-4 w-4 accent-orange-400"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="flex items-center justify-between gap-4 rounded-xl border border-white/10 bg-white/5 p-3">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-white/90">
|
||||
Weekly digest
|
||||
</div>
|
||||
<div className="text-sm text-white/60">
|
||||
Price drops, new parts, and updates.
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled
|
||||
className="h-4 w-4 accent-orange-400"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div id="security">
|
||||
<Card
|
||||
title="Security"
|
||||
description="Sessions, password change, and 2FA will live here."
|
||||
badge={
|
||||
<span className="rounded-full border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-white/60">
|
||||
Coming soon
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-xl border border-white/10 bg-white/5 p-3">
|
||||
<div className="text-sm font-medium text-white/90">2FA</div>
|
||||
<div className="text-sm text-white/60">
|
||||
Not enabled yet (on the roadmap).
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-white/10 bg-white/5 p-3">
|
||||
<div className="text-sm font-medium text-white/90">
|
||||
Active sessions
|
||||
</div>
|
||||
<div className="text-sm text-white/60">
|
||||
We’ll show devices + allow logout everywhere.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div id="danger">
|
||||
<Card
|
||||
title="Danger Zone"
|
||||
description="Destructive actions. Handle with care."
|
||||
>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-white/90">
|
||||
Delete account
|
||||
</div>
|
||||
<div className="text-sm text-white/60">
|
||||
Removes your account and builds. (We’ll add this flow later.)
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
className="inline-flex items-center justify-center rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm font-semibold text-red-200/90 opacity-60"
|
||||
>
|
||||
Delete (coming soon)
|
||||
</button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+22
-21
@@ -1,56 +1,57 @@
|
||||
// app/(account)/layout.tsx
|
||||
import Link from "next/link";
|
||||
import AccountChrome from "./AccountChrome";
|
||||
|
||||
const nav = [
|
||||
{ href: "/account", label: "My Account" },
|
||||
{ href: "/account/settings", label: "Settings" },
|
||||
{ href: "/vault", label: "My Vault" },
|
||||
];
|
||||
|
||||
export default function AccountLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
export default function AccountLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<div className="mx-auto max-w-6xl px-4 py-6">
|
||||
<AccountChrome />
|
||||
|
||||
<div className="mx-auto w-full max-w-6xl px-4 py-6">
|
||||
{/* Header */}
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Account</h1>
|
||||
<p className="text-sm opacity-70">
|
||||
<div className="text-[11px] uppercase tracking-[0.22em] text-white/50">
|
||||
Account
|
||||
</div>
|
||||
<h1 className="mt-1 text-2xl font-semibold text-white/90">
|
||||
Settings & Profile
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-white/60">
|
||||
Profile, password, and account settings.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Link href="/builder" className="text-sm opacity-80 hover:underline">
|
||||
<Link
|
||||
href="/builder"
|
||||
className="inline-flex items-center justify-center rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm font-semibold text-white/80 hover:bg-white/10"
|
||||
>
|
||||
← Back to Builder
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-[240px_1fr]">
|
||||
<aside className="rounded-xl border border-white/10 bg-white/5 p-3">
|
||||
<div className="grid gap-6 lg:grid-cols-12">
|
||||
<aside className="lg:col-span-3 rounded-2xl border border-white/10 bg-white/5 p-4">
|
||||
<nav className="flex flex-col gap-1">
|
||||
{nav.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className="rounded-lg px-3 py-2 text-sm opacity-80 hover:bg-white/10 hover:opacity-100"
|
||||
className="rounded-lg px-3 py-2 text-sm text-white/70 hover:bg-white/10 hover:text-white"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
<div className="my-2 border-t border-white/10" />
|
||||
<Link
|
||||
href="/vault"
|
||||
className="rounded-lg px-3 py-2 text-sm opacity-80 hover:bg-white/10 hover:opacity-100"
|
||||
>
|
||||
My Vault
|
||||
</Link>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<main className="rounded-xl border border-white/10 bg-white/5 p-4">
|
||||
<main className="lg:col-span-9 rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -1,61 +1,28 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
const BREVO_API_KEY = process.env.BREVO_API_KEY;
|
||||
const BREVO_LIST_ID = process.env.BREVO_LIST_ID; // optional
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
if (!BREVO_API_KEY) {
|
||||
console.error("BREVO_API_KEY is not set");
|
||||
return NextResponse.json(
|
||||
{ error: "Server not configured" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const { email } = await req.json();
|
||||
const body = await req.json();
|
||||
|
||||
if (!email || typeof email !== "string") {
|
||||
return NextResponse.json(
|
||||
{ error: "Valid email is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Brevo contacts API
|
||||
const res = await fetch("https://api.brevo.com/v3/contacts", {
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/beta/signup`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"api-key": BREVO_API_KEY,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
updateEnabled: true, // update if already exists
|
||||
...(BREVO_LIST_ID
|
||||
? { listIds: [Number(BREVO_LIST_ID)] }
|
||||
: {}),
|
||||
attributes: {
|
||||
SOURCE: "Battl Builders Beta",
|
||||
},
|
||||
}),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
// Always return ok=true (matches your server behavior)
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
console.error("Brevo error:", res.status, text);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to subscribe" },
|
||||
{ status: 500 }
|
||||
);
|
||||
// Optional: log server response for debugging
|
||||
const text = await res.text().catch(() => "");
|
||||
console.error("beta-signup proxy failed:", res.status, text);
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return NextResponse.json(
|
||||
{ error: "Something went wrong" },
|
||||
{ status: 500 }
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("beta-signup proxy error:", e);
|
||||
return NextResponse.json({ ok: true }); // keep “no enumeration”
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// app/beta/confirm/page.tsx
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
type Status = "loading" | "success" | "error";
|
||||
|
||||
export default function BetaConfirmPage() {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams.get("token");
|
||||
|
||||
const [status, setStatus] = useState<Status>("loading");
|
||||
const [message, setMessage] = useState<string>("Please hang tight.");
|
||||
|
||||
// Prevent double-fire in React Strict Mode (dev)
|
||||
const ran = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setStatus("error");
|
||||
setMessage("Missing token.");
|
||||
return;
|
||||
}
|
||||
|
||||
// StrictMode can run effects twice in dev; bail out after first
|
||||
if (ran.current) return;
|
||||
ran.current = true;
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
setStatus("loading");
|
||||
setMessage("Confirming your email…");
|
||||
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/beta/confirm`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
// If request was aborted, do nothing
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
if (!res.ok) {
|
||||
// Don’t assume expired—just say it didn’t work
|
||||
throw new Error("Confirm failed");
|
||||
}
|
||||
|
||||
setStatus("success");
|
||||
setMessage("Check your inbox for your secure sign-in link.");
|
||||
} catch (err) {
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
setStatus("error");
|
||||
setMessage("This link is invalid or expired. Please request a new one.");
|
||||
}
|
||||
})();
|
||||
|
||||
return () => controller.abort();
|
||||
}, [token]);
|
||||
|
||||
return (
|
||||
<main className="min-h-screen flex items-center justify-center bg-black text-white px-6">
|
||||
<div className="max-w-md w-full text-center space-y-4">
|
||||
{status === "loading" && (
|
||||
<>
|
||||
<h1 className="text-xl font-semibold">Confirming email…</h1>
|
||||
<p className="text-sm text-zinc-400">{message}</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === "success" && (
|
||||
<>
|
||||
<h1 className="text-xl font-semibold">Email confirmed ✅</h1>
|
||||
<p className="text-sm text-zinc-400">{message}</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === "error" && (
|
||||
<>
|
||||
<h1 className="text-xl font-semibold">Link expired or invalid</h1>
|
||||
<p className="text-sm text-zinc-400">{message}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
|
||||
export default function BetaMagicPage() {
|
||||
const params = useSearchParams();
|
||||
const token = params.get("token");
|
||||
const router = useRouter();
|
||||
const { setSession } = useAuth();
|
||||
const ran = useRef(false);
|
||||
|
||||
const [status, setStatus] = useState<"loading" | "success" | "error">("loading");
|
||||
const [message, setMessage] = useState("Signing you in…");
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setStatus("error");
|
||||
setMessage("Missing token.");
|
||||
return;
|
||||
}
|
||||
|
||||
// ✅ Prevent double-call (Strict Mode / rerenders)
|
||||
if (ran.current) return;
|
||||
ran.current = true;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080"}/api/auth/magic/exchange`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(text || "Magic link failed");
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
// Your AuthContext expects { token, email, displayName, role }
|
||||
// and stores it in localStorage.
|
||||
// We can simulate "login" by directly setting localStorage like AuthContext does,
|
||||
// but easiest is just to store it here in the same shape.
|
||||
setSession(data.token ?? data.accessToken, {
|
||||
email: data.email,
|
||||
displayName: data.displayName ?? null,
|
||||
role: data.role ?? "USER",
|
||||
});
|
||||
|
||||
setStatus("success");
|
||||
setMessage("You’re in. Redirecting…");
|
||||
router.replace("/builder");
|
||||
} catch (e: any) {
|
||||
setStatus("error");
|
||||
setMessage(e?.message || "Magic link expired. Request a new one.");
|
||||
}
|
||||
})();
|
||||
}, [token, router, setSession]);
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-black text-zinc-50 flex items-center justify-center px-4">
|
||||
<div className="max-w-md w-full rounded-xl border border-white/10 bg-white/5 p-6">
|
||||
<h1 className="text-lg font-semibold">Battl Builders</h1>
|
||||
<p className="mt-2 text-sm text-zinc-300">{message}</p>
|
||||
|
||||
{status === "error" && (
|
||||
<div className="mt-4 text-xs text-zinc-400">
|
||||
Try going back to your inbox and requesting a fresh sign-in link.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -95,4 +95,5 @@ export function TopNav() {
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
}
|
||||
export default TopNav;
|
||||
+49
-29
@@ -30,6 +30,19 @@ type AuthContextValue = {
|
||||
}) => Promise<void>;
|
||||
logout: () => void;
|
||||
getAuthHeaders: () => HeadersInit;
|
||||
|
||||
/**
|
||||
* Used for non-password auth flows (ex: magic link).
|
||||
* Persists session exactly like login/register.
|
||||
*/
|
||||
setSession: (
|
||||
token: string,
|
||||
user: {
|
||||
email: string;
|
||||
displayName: string | null;
|
||||
role: string;
|
||||
}
|
||||
) => void;
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
@@ -42,6 +55,25 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<AuthUser>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
|
||||
const persistAuth = useCallback(
|
||||
(nextToken: string | null, nextUser: AuthUser) => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
if (nextToken) {
|
||||
window.localStorage.setItem(TOKEN_KEY, nextToken);
|
||||
} else {
|
||||
window.localStorage.removeItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
if (nextUser) {
|
||||
window.localStorage.setItem(USER_KEY, JSON.stringify(nextUser));
|
||||
} else {
|
||||
window.localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// Hydrate from localStorage on first load
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
@@ -49,15 +81,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const storedToken = window.localStorage.getItem(TOKEN_KEY);
|
||||
const storedUser = window.localStorage.getItem(USER_KEY);
|
||||
|
||||
if (storedToken) {
|
||||
setToken(storedToken);
|
||||
}
|
||||
if (storedToken) setToken(storedToken);
|
||||
|
||||
if (storedUser) {
|
||||
try {
|
||||
setUser(JSON.parse(storedUser));
|
||||
} catch {
|
||||
// bad JSON? wipe it
|
||||
window.localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
}
|
||||
@@ -65,21 +94,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
const persistAuth = useCallback((nextToken: string | null, nextUser: AuthUser) => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
if (nextToken) {
|
||||
window.localStorage.setItem(TOKEN_KEY, nextToken);
|
||||
} else {
|
||||
window.localStorage.removeItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
if (nextUser) {
|
||||
window.localStorage.setItem(USER_KEY, JSON.stringify(nextUser));
|
||||
} else {
|
||||
window.localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
}, []);
|
||||
const setSession = useCallback(
|
||||
(
|
||||
nextToken: string,
|
||||
nextUser: { email: string; displayName: string | null; role: string }
|
||||
) => {
|
||||
setToken(nextToken);
|
||||
setUser(nextUser);
|
||||
persistAuth(nextToken, nextUser);
|
||||
},
|
||||
[persistAuth]
|
||||
);
|
||||
|
||||
const login = useCallback(
|
||||
async ({ email, password }: { email: string; password: string }) => {
|
||||
@@ -98,7 +123,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
// Adjust these to match your backend response shape
|
||||
const nextToken: string = data.token ?? data.accessToken;
|
||||
const nextUser: AuthUser =
|
||||
data.user ??
|
||||
@@ -108,14 +132,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
role: data.role ?? "USER",
|
||||
} as AuthUser);
|
||||
|
||||
setToken(nextToken);
|
||||
setUser(nextUser);
|
||||
persistAuth(nextToken, nextUser);
|
||||
setSession(nextToken, nextUser as NonNullable<AuthUser>);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[persistAuth]
|
||||
[setSession]
|
||||
);
|
||||
|
||||
const register = useCallback(
|
||||
@@ -152,14 +174,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
role: data.role ?? "USER",
|
||||
} as AuthUser);
|
||||
|
||||
setToken(nextToken);
|
||||
setUser(nextUser);
|
||||
persistAuth(nextToken, nextUser);
|
||||
setSession(nextToken, nextUser as NonNullable<AuthUser>);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[persistAuth]
|
||||
[setSession]
|
||||
);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
@@ -180,12 +200,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
register,
|
||||
logout,
|
||||
getAuthHeaders,
|
||||
setSession, // ✅ important
|
||||
};
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
// 🔑 This is what your useApi hook imports
|
||||
export function useAuth(): AuthContextValue {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) {
|
||||
|
||||
Reference in New Issue
Block a user