fix(invite): look up the invitation and route correctly (register vs sign in)

The invite link is token-only, so the landing page couldn't tell the invited
email or whether an account existed — it dumped everyone on an empty register
screen. Now it calls a public lookup (/api/invite/lookup → be-crm) and:
- first-time invitee → register with the email prefilled + locked;
- email already registered → sign in with the email prefilled;
- signed-in + registered → accept immediately; signed-in + no profile → onboarding.
Login now redeems the pending invite after sign-in (password/OTP/OAuth), so an
existing user's invite is accepted on login (not only when already logged in).
This commit is contained in:
tanweer919
2026-07-13 20:25:25 +05:30
parent cc71516278
commit be4bd5f41d
4 changed files with 126 additions and 48 deletions
+54 -32
View File
@@ -1,60 +1,82 @@
"use client";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
import { PortalAside, PanelBrand } from "@/components/portal/parts";
import { CookieBanner, Spinner } from "@/components/portal/bits";
import { isShellConfigured } from "@/lib/appshell";
interface InviteInfo { ok: boolean; status?: string; email?: string; roleNames?: string[]; hasAccount?: boolean }
/**
* Team invitation landing page (/portal/invite?token=…). Redeems the invite:
* - not signed in → send to registration; it redeems the stashed token on finish.
* - signed in but no CRM profile → send to onboarding; it redeems on finish.
* - signed in + registered → accept now (creates the membership with the invited role).
* The token (a 128-hex secret emailed to the invitee) is the authorization.
* Team invitation landing page (/portal/invite?token=…). It looks the token up
* (public, pre-auth) to learn the invited email and whether an account exists, then:
* - signed in + registered → accept now (creates the membership with the invited role);
* - signed in, no CRM profile → onboarding, which redeems the token on finish;
* - not signed in + email already has an account → sign in (email prefilled);
* - not signed in + first-time invitee → register (email prefilled + locked).
* The register/login/onboarding flows redeem the stashed token on completion.
*/
export default function InvitePage() {
const router = useRouter();
const { status, getUserEmail } = useAuth();
const { ready, sdk } = useAppShell();
const [error, setError] = useState("");
const started = useRef(false);
useEffect(() => {
let token = "";
try { token = new URLSearchParams(window.location.search).get("token") ?? ""; } catch { /* ignore */ }
if (!token) { setError("This invitation link is invalid or incomplete."); return; }
try { sessionStorage.setItem("invite_token", token); } catch { /* ignore */ }
if (!isShellConfigured()) { try { sessionStorage.setItem("invite_token", token); } catch { /* ignore */ } router.replace("/portal/register"); return; }
if (!ready || started.current) return;
started.current = true;
// No Shell (local/mock) → just go register.
if (!isShellConfigured()) { router.replace("/portal/register"); return; }
if (!ready) return;
let cancelled = false;
(async () => {
if (status === "unauthenticated") {
router.replace("/portal/register"); // sign up first; finish() redeems the token
try { sessionStorage.setItem("invite_token", token); } catch { /* ignore */ }
// Look the invitation up (pre-auth) to get the email + account state.
let info: InviteInfo = { ok: false };
try {
const res = await fetch(`/api/invite/lookup?token=${encodeURIComponent(token)}`, { cache: "no-store" });
info = await res.json();
} catch { /* treat as unavailable below */ }
if (!info.ok) {
const msg = info.status === "expired" ? "This invitation has expired. Ask for a new one."
: info.status === "accepted" ? "This invitation has already been used."
: info.status === "revoked" ? "This invitation was revoked."
: "This invitation link is invalid.";
setError(msg);
try { sessionStorage.removeItem("invite_token"); } catch { /* ignore */ }
return;
}
// Authenticated: registered users accept immediately; profile-less users onboard.
try {
const st = await sdk.query<{ registered: boolean }>("crm.account.registrationStatus");
if (!st?.registered) {
try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ }
router.replace("/portal/onboarding");
return;
}
} catch { /* fall through to accept */ }
if (info.email) { try { sessionStorage.setItem("invite_email", info.email); } catch { /* ignore */ } }
try {
await sdk.command("crm.team.invitation.accept", { token });
try { sessionStorage.removeItem("invite_token"); } catch { /* ignore */ }
router.replace("/dashboard");
} catch {
if (!cancelled) setError("We couldn't accept this invitation — it may have expired or already been used.");
// Signed in already: accept if registered, else finish onboarding first.
if (status === "authenticated") {
try {
const st = await sdk.query<{ registered: boolean }>("crm.account.registrationStatus");
if (!st?.registered) {
try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ }
router.replace("/portal/onboarding");
return;
}
} catch { /* fall through to accept */ }
try {
await sdk.command("crm.team.invitation.accept", { token });
try { sessionStorage.removeItem("invite_token"); sessionStorage.removeItem("invite_email"); } catch { /* ignore */ }
router.replace("/dashboard");
} catch {
setError("We couldn't accept this invitation — it may have expired or already been used.");
}
return;
}
// Not signed in: existing account → sign in; first-time invitee → register.
router.replace(info.hasAccount ? "/portal/login" : "/portal/register");
})();
return () => { cancelled = true; };
}, [ready, status, router, sdk, getUserEmail]);
return (
@@ -77,8 +99,8 @@ export default function InvitePage() {
) : (
<div className="interstitial">
<Spinner lg />
<h1 style={{ fontSize: 20, marginTop: 8 }}>Accepting your invitation</h1>
<p className="sub">Setting up your team access.</p>
<h1 style={{ fontSize: 20, marginTop: 8 }}>Checking your invitation</h1>
<p className="sub">One moment while we set things up.</p>
</div>
)}
</div>