231 lines
10 KiB
TypeScript
231 lines
10 KiB
TypeScript
import { useEffect, useRef } from "react";
|
|
import { loadRequiredWebConfig } from "@hivegrid/config";
|
|
import { buildPortalAuthVM, type PortalAuthMode, type PortalLegalLinks } from "@hivegrid/view-models";
|
|
import { redirect, useFetcher, useLoaderData, useLocation, useNavigate, useRevalidator, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
|
|
|
import Captcha from "~/components/captcha/Captcha";
|
|
import { CustomerPortalAuthPage, type PortalAuthSubmission } from "~/components/screens/customer-portal/CustomerPortalInterimPages";
|
|
import {
|
|
consumePortalCapability,
|
|
requestPortalPasswordReset,
|
|
requestPortalSignInLink,
|
|
signInPortalWithPassword,
|
|
type PortalAuthResult,
|
|
} from "~/services/customer-portal/portal-auth-flow.server";
|
|
import { readPortalProjectContinuePath } from "~/services/customer-portal/portal-capability-continue.server";
|
|
import { validatePortalCsrfToken } from "~/services/customer-portal/portal-csrf.server";
|
|
import { portalNotFound, requirePortalTenantFromRequest } from "~/services/customer-portal/portal-data.server";
|
|
import { serializePortalSessionCookie } from "~/services/customer-portal/portal-session-cookie.server";
|
|
import { portalPublicPath, requireTrustedPortalOrigin } from "~/services/customer-portal/portal-origin.server";
|
|
|
|
type AuthDescriptor = {
|
|
readonly mode: PortalAuthMode;
|
|
readonly token: string | null;
|
|
readonly purpose: "magic_link" | "setup" | "verify_email" | "reset_password" | null;
|
|
};
|
|
|
|
export async function loader({ request, params }: LoaderFunctionArgs) {
|
|
const tenant = await requirePortalTenantFromRequest(request, params.tenant);
|
|
const origin = requireTrustedPortalOrigin(request, tenant.tenantSlug);
|
|
const descriptor = parseAuthDescriptor(resolveAuthPath(request, params["*"], origin.customHost));
|
|
const config = loadRequiredWebConfig();
|
|
return Response.json(
|
|
{
|
|
vm: buildPortalAuthVM({
|
|
tenantSlug: tenant.tenantSlug,
|
|
tenantName: tenant.tenantName,
|
|
portalName: tenant.portalTitle,
|
|
legalLinks: requirePortalLegalLinks(tenant),
|
|
mode: descriptor.mode,
|
|
allowPassword: descriptor.mode === "login",
|
|
captchaRequired: descriptor.mode !== "magic_sent" && descriptor.mode !== "invalid_token",
|
|
loginHref: portalPublicPath(origin, "login"),
|
|
passwordHref: portalPublicPath(origin, "forgot-password"),
|
|
supportEmail: config.supportEmail,
|
|
}),
|
|
captcha: {
|
|
provider: config.captcha.provider,
|
|
instanceUrl: config.captcha.instanceUrl,
|
|
sitekey: config.captcha.loginSiteKey,
|
|
},
|
|
brandingLogoHref: portalPublicPath(origin, "branding/logo"),
|
|
},
|
|
{ headers: getAuthSecurityHeaders(descriptor) }
|
|
);
|
|
}
|
|
|
|
export async function action({ request, params }: ActionFunctionArgs) {
|
|
const tenant = await requirePortalTenantFromRequest(request, params.tenant);
|
|
const origin = requireTrustedPortalOrigin(request, tenant.tenantSlug);
|
|
const descriptor = parseAuthDescriptor(resolveAuthPath(request, params["*"], origin.customHost));
|
|
if (descriptor.mode === "magic_sent" || descriptor.mode === "invalid_token") throw portalNotFound();
|
|
const continuePath = readPortalProjectContinuePath(request, origin);
|
|
const form = await request.clone().formData();
|
|
await validatePortalCsrfToken(request, form);
|
|
const captchaToken = stringValue(form.get("captchaToken")) ?? stringValue(form.get("cap-token")) ?? stringValue(form.get("mcaptcha__token"));
|
|
let result: PortalAuthResult;
|
|
|
|
if (descriptor.mode === "login") {
|
|
const intent = stringValue(form.get("intent"));
|
|
const email = stringValue(form.get("email")) ?? "";
|
|
result =
|
|
intent === "password"
|
|
? await signInPortalWithPassword({
|
|
request,
|
|
tenant,
|
|
email,
|
|
password: stringValue(form.get("password")) ?? "",
|
|
captchaToken,
|
|
})
|
|
: await requestPortalSignInLink({ request, tenant, email, captchaToken, continuePath });
|
|
} else if (descriptor.mode === "forgot_password") {
|
|
result = await requestPortalPasswordReset({
|
|
request,
|
|
tenant,
|
|
email: stringValue(form.get("email")) ?? "",
|
|
captchaToken,
|
|
});
|
|
} else {
|
|
if (!descriptor.token || !descriptor.purpose) throw portalNotFound();
|
|
const capabilityInput = {
|
|
request,
|
|
tenant,
|
|
rawToken: descriptor.token,
|
|
purpose: descriptor.purpose,
|
|
captchaToken,
|
|
password: stringValue(form.get("password")) ?? undefined,
|
|
passwordConfirmation: stringValue(form.get("passwordConfirmation")) ?? undefined,
|
|
privacyNoticeAcknowledged: optionalBooleanValue(form.get("privacyNoticeAcknowledged")),
|
|
privacyNoticeUrl: stringValue(form.get("privacyNoticeUrl")) ?? undefined,
|
|
};
|
|
result = await consumePortalCapability(capabilityInput);
|
|
}
|
|
|
|
if (!result.ok) {
|
|
return Response.json({ errorKey: result.errorKey }, { status: result.status, headers: { "Cache-Control": "no-store" } });
|
|
}
|
|
if (result.kind === "sent") {
|
|
throw redirect(withPortalContinue(portalPublicPath(origin, "login/magic-sent"), continuePath), { headers: { "Cache-Control": "no-store" } });
|
|
}
|
|
const redirectPath = continuePath ?? portalPublicPath(origin);
|
|
throw redirect(redirectPath, {
|
|
headers: {
|
|
"Cache-Control": "no-store",
|
|
"Set-Cookie": await serializePortalSessionCookie(result.rawSessionToken, result.expiresAt),
|
|
},
|
|
});
|
|
}
|
|
|
|
function withPortalContinue(path: string, continuePath: string | null): string {
|
|
return continuePath ? `${path}?continue=${encodeURIComponent(continuePath)}` : path;
|
|
}
|
|
|
|
export default function CustomerPortalAuthRoute() {
|
|
const { vm, captcha, brandingLogoHref } = useLoaderData<typeof loader>();
|
|
const fetcher = useFetcher<typeof action>();
|
|
const location = useLocation();
|
|
const navigate = useNavigate();
|
|
const { revalidate } = useRevalidator();
|
|
const revalidatedPrivacyFailure = useRef<unknown>(null);
|
|
const errorKey = fetcher.data && "errorKey" in fetcher.data ? fetcher.data.errorKey : null;
|
|
|
|
useEffect(() => {
|
|
if (errorKey !== "customerPortal.auth.errors.privacyNoticeChanged" || fetcher.data === revalidatedPrivacyFailure.current) {
|
|
return;
|
|
}
|
|
revalidatedPrivacyFailure.current = fetcher.data;
|
|
void revalidate();
|
|
}, [errorKey, fetcher.data, revalidate]);
|
|
|
|
const submit = (submission: PortalAuthSubmission) => {
|
|
const form = new FormData();
|
|
form.set("intent", submission.intent);
|
|
if (submission.email) form.set("email", submission.email);
|
|
if (submission.password) form.set("password", submission.password);
|
|
if (submission.passwordConfirmation) form.set("passwordConfirmation", submission.passwordConfirmation);
|
|
if (submission.captchaToken) form.set("captchaToken", submission.captchaToken);
|
|
if (submission.privacyNoticeAcknowledged !== undefined) {
|
|
form.set("privacyNoticeAcknowledged", String(submission.privacyNoticeAcknowledged));
|
|
}
|
|
if (submission.privacyNoticeUrl !== undefined) form.set("privacyNoticeUrl", submission.privacyNoticeUrl);
|
|
const csrf = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
if (csrf) form.set("csrf", csrf);
|
|
// Preserve the server-issued, strictly validated project continuation from
|
|
// a status-mail capability URL across the CAPTCHA form POST.
|
|
void fetcher.submit(form, { method: "post", action: `${location.pathname}${location.search}` });
|
|
};
|
|
const privacyNoticeVersion = vm.status === "ready" ? vm.data.legalLinks.privacyUrl : vm.status;
|
|
return (
|
|
<CustomerPortalAuthPage
|
|
key={`${location.pathname}:${privacyNoticeVersion}`}
|
|
vm={vm}
|
|
brandingLogoHref={brandingLogoHref}
|
|
busy={fetcher.state !== "idle"}
|
|
errorKey={errorKey}
|
|
captcha={<Captcha enabled provider={captcha.provider} instanceUrl={captcha.instanceUrl} sitekey={captcha.sitekey} />}
|
|
actions={{
|
|
onSubmit: submit,
|
|
onBackToLogin: () => {
|
|
if (vm.status === "ready") navigate(vm.data.loginHref);
|
|
},
|
|
onForgotPassword: () => {
|
|
if (vm.status === "ready" && vm.data.passwordHref) navigate(vm.data.passwordHref);
|
|
},
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function parseAuthDescriptor(rawPath: string): AuthDescriptor {
|
|
const path = rawPath.replace(/^\/+|\/+$/gu, "");
|
|
if (path === "login") return { mode: "login", token: null, purpose: null };
|
|
if (path === "login/magic-sent") return { mode: "magic_sent", token: null, purpose: null };
|
|
if (path === "forgot-password") return { mode: "forgot_password", token: null, purpose: null };
|
|
const match = /^(login\/magic|setup|verify-email|reset-password)\/([A-Za-z0-9_-]{43})$/u.exec(path);
|
|
if (!match) {
|
|
if (/^(login\/magic|setup|verify-email|reset-password)\//u.test(path)) {
|
|
return { mode: "invalid_token", token: null, purpose: null };
|
|
}
|
|
throw portalNotFound();
|
|
}
|
|
const token = match[2]!;
|
|
if (match[1] === "login/magic") return { mode: "magic_link", token, purpose: "magic_link" };
|
|
if (match[1] === "setup") return { mode: "setup", token, purpose: "setup" };
|
|
if (match[1] === "verify-email") return { mode: "verify_email", token, purpose: "verify_email" };
|
|
return { mode: "reset_password", token, purpose: "reset_password" };
|
|
}
|
|
|
|
function getAuthSecurityHeaders(descriptor: AuthDescriptor) {
|
|
return {
|
|
"Cache-Control": "no-store",
|
|
...(descriptor.token ? { "Referrer-Policy": "no-referrer" } : {}),
|
|
};
|
|
}
|
|
|
|
function resolveAuthPath(request: Request, wildcardPath: string | undefined, customHost: boolean): string {
|
|
if (!customHost) return wildcardPath ?? "";
|
|
return new URL(request.url).pathname.replace(/\.data$/u, "").replace(/^\/+|\/+$/gu, "");
|
|
}
|
|
|
|
function requirePortalLegalLinks(value: unknown): PortalLegalLinks {
|
|
if (!value || typeof value !== "object") throw portalNotFound();
|
|
const candidate = value as { readonly imprintUrl?: unknown; readonly privacyUrl?: unknown; readonly termsUrl?: unknown };
|
|
if (typeof candidate.imprintUrl !== "string" || !candidate.imprintUrl.trim()) throw portalNotFound();
|
|
if (typeof candidate.privacyUrl !== "string" || !candidate.privacyUrl.trim()) throw portalNotFound();
|
|
if (candidate.termsUrl !== null && typeof candidate.termsUrl !== "string") throw portalNotFound();
|
|
return {
|
|
imprintUrl: candidate.imprintUrl,
|
|
privacyUrl: candidate.privacyUrl,
|
|
termsUrl: candidate.termsUrl,
|
|
};
|
|
}
|
|
|
|
function stringValue(value: FormDataEntryValue | null): string | null {
|
|
return typeof value === "string" ? value : null;
|
|
}
|
|
|
|
function optionalBooleanValue(value: FormDataEntryValue | null): boolean | undefined {
|
|
const normalized = stringValue(value);
|
|
return normalized === null ? undefined : normalized === "true";
|
|
}
|