| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- /**
- * Browser helpers: mint / clear / read first-party portal session after any login method.
- */
- export type AuthMethod = "email" | "wallet" | "konnos" | "demo";
- export function userIdFromEngineBody(
- data: Record<string, unknown>,
- ): string | null {
- const user = data.user as { id?: string } | undefined;
- const session = data.session as { userId?: string } | undefined;
- const id =
- user?.id ||
- session?.userId ||
- (typeof data.userId === "string" ? data.userId : null);
- return id || null;
- }
- export async function establishPortalSession(input: {
- userId: string;
- email?: string;
- method?: AuthMethod;
- walletAddress?: string;
- }): Promise<void> {
- if (typeof window === "undefined") return;
- try {
- await fetch("/api/session", {
- method: "POST",
- credentials: "include",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
- userId: input.userId,
- email: input.email,
- method: input.method ?? "email",
- walletAddress: input.walletAddress,
- }),
- });
- } catch {
- /* soft gate */
- }
- }
- export async function clearPortalSession(): Promise<void> {
- if (typeof window === "undefined") return;
- try {
- await fetch("/api/session", { method: "DELETE", credentials: "include" });
- } catch {
- /* ignore */
- }
- }
- export type PortalSessionState =
- | {
- authenticated: true;
- userId: string;
- email?: string | null;
- method?: AuthMethod | null;
- walletAddress?: string | null;
- }
- | { authenticated: false };
- export async function fetchPortalSession(): Promise<PortalSessionState> {
- try {
- const res = await fetch("/api/session", { credentials: "include" });
- const data = (await res.json()) as {
- authenticated?: boolean;
- userId?: string;
- email?: string | null;
- method?: AuthMethod | null;
- walletAddress?: string | null;
- };
- if (data.authenticated && data.userId) {
- let email: string | null = data.email ?? null;
- let method: AuthMethod | null = data.method ?? null;
- let walletAddress: string | null = data.walletAddress ?? null;
- if (typeof document !== "undefined") {
- const em = document.cookie.match(/(?:^|;\s*)krypco_email=([^;]+)/);
- if (!email && em?.[1]) email = decodeURIComponent(em[1]);
- const m = document.cookie.match(/(?:^|;\s*)krypco_method=([^;]+)/);
- if (!method && m?.[1]) method = decodeURIComponent(m[1]) as AuthMethod;
- const w = document.cookie.match(/(?:^|;\s*)krypco_wallet=([^;]+)/);
- if (!walletAddress && w?.[1])
- walletAddress = decodeURIComponent(w[1]);
- }
- return {
- authenticated: true,
- userId: data.userId,
- email,
- method,
- walletAddress,
- };
- }
- return { authenticated: false };
- } catch {
- return { authenticated: false };
- }
- }
|