374 lines
17 KiB
TypeScript
374 lines
17 KiB
TypeScript
import Logo from "~/components/brand/Logo";
|
|
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
|
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
|
import { useEffect, useRef } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { Link, Form, useActionData, useLoaderData } from "react-router";
|
|
import { ActionFunction, LoaderFunctionArgs, MetaFunction } from "react-router";
|
|
import { withMetrics } from "~/lib/metrics/ssr";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
|
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
|
|
import { createTenantUser, getTenant } from "~/utils/db/tenants.db.server";
|
|
import { createUserSession, getUserInfo, setLoggedUser } from "~/utils/session.server";
|
|
import type { Tenant, User } from "@toolctrl/db/prisma-browser";
|
|
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
|
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
|
import { getAbsoluteUrl } from "~/utils/url.server";
|
|
import EventsService from "~/modules/events/services/.server/EventsService";
|
|
import { MemberInvitationAcceptedDto } from "~/modules/events/dtos/MemberInvitationAcceptedDto";
|
|
import SuccessBanner from "~/components/ui/banners/SuccessBanner";
|
|
import { Button } from "~/components/ui/button";
|
|
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
|
|
import { getMailTranslator } from "~/locale/mail-translator.server";
|
|
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
|
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
|
import { loadRequiredWebConfig } from "@toolctrl/config";
|
|
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
|
import { acceptWorkspaceInvite, getWorkspaceInviteByToken, WorkspaceInviteDto, WorkspaceInviteError } from "@toolctrl/db/workspace-invites.server";
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
invitation: (WorkspaceInviteDto & { tenant: Tenant }) | null;
|
|
existingUser: User | null;
|
|
appRootPath: string;
|
|
};
|
|
export const loader = withMetrics("invitation", async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t } = await getTranslations(request);
|
|
|
|
const appRootPath = absoluteAppRootPath(loadRequiredWebConfig().routing);
|
|
const invite = await getWorkspaceInviteByToken({ token: params.id ?? "" });
|
|
const tenant = invite?.tenantId ? await getTenant(invite.tenantId) : null;
|
|
const invitation = invite && tenant ? { ...invite, tenant } : null;
|
|
const existingUser = await getUserByEmail(invitation?.email);
|
|
const data: LoaderData = {
|
|
title: `${t("account.invitation.title")} | ${process.env.APP_NAME}`,
|
|
invitation,
|
|
existingUser,
|
|
appRootPath,
|
|
};
|
|
return data;
|
|
});
|
|
|
|
type ActionData = {
|
|
success?: string;
|
|
error?: string;
|
|
invitationAccepted?: boolean;
|
|
};
|
|
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
|
function workspaceInviteErrorResponse(error: unknown, t: (key: string) => string) {
|
|
if (error instanceof WorkspaceInviteError) {
|
|
return badRequest({
|
|
error: error.code === "invite_expired" ? t("auth:invitation.errors.expired") : t("auth:invitation.errors.invalid"),
|
|
});
|
|
}
|
|
throw error;
|
|
}
|
|
export function invitationCreatedUserDashboardPath(tenant: { slug?: string | null } | null) {
|
|
return tenant?.slug ? appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" }) : "/";
|
|
}
|
|
|
|
function getDefaultInvitationRoles(roles: Awaited<ReturnType<typeof getAllRoles>>) {
|
|
return roles.filter((role) => role.assignToNewUsers && role.isDefault);
|
|
}
|
|
|
|
export const action: ActionFunction = async ({ request, params }) => {
|
|
const { t } = await getTranslations(request);
|
|
const userInfo = await getUserInfo(request);
|
|
const form = await request.formData();
|
|
const intent = form.get("intent")?.toString() ?? "set-password";
|
|
const useMagicLink = intent === "magic-link";
|
|
const password = form.get("password")?.toString() ?? "";
|
|
const passwordConfirm = form.get("password-confirm")?.toString() ?? "";
|
|
|
|
const invite = await getWorkspaceInviteByToken({ token: params.id ?? "" });
|
|
const tenant = invite?.tenantId ? await getTenant(invite.tenantId) : null;
|
|
const invitation = invite && tenant ? { ...invite, tenant } : null;
|
|
if (!invitation?.pending) {
|
|
return badRequest({
|
|
error: t("auth:invitation.errors.invalid"),
|
|
});
|
|
}
|
|
const fromUser = invitation.fromUserId ? await getUser(invitation.fromUserId) : null;
|
|
|
|
let existingUser = await getUserByEmail(invitation.email);
|
|
if (!existingUser) {
|
|
// Register user. Two paths:
|
|
// - intent="magic-link": accept invitation without password — generate
|
|
// a strong random throwaway hash; the user signs in later via the
|
|
// forgot-password → magic-link flow (#19). Mirrors the spirit of the
|
|
// detail-MD's "magic-link invitation" feature without needing to
|
|
// overlay the magic-link-token infrastructure (which requires a User
|
|
// row to exist for its FK, which is exactly what's missing here).
|
|
// - intent="set-password" (default): traditional confirm+validate path.
|
|
let effectivePassword = password;
|
|
if (useMagicLink) {
|
|
// 32 bytes of crypto-random → 256 bits → far beyond any policy floor;
|
|
// the user never sees it and it's not stored anywhere outside the hash.
|
|
const { createInvitationMagicLinkPassword } = await import("~/services/auth/invitation-password.server");
|
|
effectivePassword = createInvitationMagicLinkPassword();
|
|
} else {
|
|
const passwordError = await UserValidationUtils.validatePasswords({ t, password, passwordConfirm, email: invitation.email });
|
|
if (passwordError) {
|
|
return badRequest({ error: passwordError });
|
|
}
|
|
}
|
|
|
|
const user = await register({
|
|
email: invitation.email,
|
|
password: effectivePassword,
|
|
firstName: invitation.firstName,
|
|
lastName: invitation.lastName,
|
|
locale: userInfo.lng,
|
|
request,
|
|
});
|
|
if (!user) {
|
|
return badRequest({ error: t("auth:invitation.errors.createUserFailed") });
|
|
}
|
|
try {
|
|
await acceptWorkspaceInvite({ tenantId: invitation.tenantId, inviteId: invitation.id, token: params.id ?? "", acceptedByUserId: user.id });
|
|
} catch (error) {
|
|
return workspaceInviteErrorResponse(error, t);
|
|
}
|
|
const roles = await getAllRoles("app");
|
|
await createTenantUser(
|
|
{
|
|
tenantId: invitation.tenantId,
|
|
userId: user.id,
|
|
type: invitation.type,
|
|
},
|
|
getDefaultInvitationRoles(roles)
|
|
);
|
|
await EventsService.create({
|
|
request,
|
|
event: "member.invitation.accepted",
|
|
tenantId: invitation.tenant.id,
|
|
userId: user.id,
|
|
data: {
|
|
newUser: true,
|
|
tenant: { id: invitation.tenantId, name: invitation.tenant.name, slug: invitation.tenant.slug },
|
|
user: { id: user.id, email: user.email, firstName: invitation.firstName, lastName: invitation.lastName, type: TenantUserType[invitation.type] },
|
|
fromUser: !fromUser ? null : { id: fromUser.id, email: fromUser.email },
|
|
invitation: { id: invitation.id },
|
|
} satisfies MemberInvitationAcceptedDto,
|
|
});
|
|
|
|
const welcomeTemplateData = {
|
|
action_url: getAbsoluteUrl(request, "/login"),
|
|
name: invitation.firstName,
|
|
};
|
|
const welcomeMailTranslator = await getMailTranslator(user.locale ?? userInfo.lng);
|
|
await queueTransactionalEmail({
|
|
to: invitation.email,
|
|
alias: "welcome",
|
|
tenantId: invitation.tenantId,
|
|
userId: user.id,
|
|
...EmailTemplates.WELCOME_EMAIL.parse({
|
|
appConfiguration: await getAppConfiguration({ request }),
|
|
data: welcomeTemplateData,
|
|
t: welcomeMailTranslator.t,
|
|
locale: welcomeMailTranslator.locale,
|
|
}),
|
|
data: welcomeTemplateData,
|
|
});
|
|
|
|
const userSession = await setLoggedUser(user);
|
|
const tenant = await getTenant(userSession.defaultTenantId);
|
|
return createUserSession(
|
|
{
|
|
...userInfo,
|
|
...userSession,
|
|
userId: user.id,
|
|
lng: user.locale ?? userInfo.lng,
|
|
},
|
|
invitationCreatedUserDashboardPath(tenant)
|
|
);
|
|
} else {
|
|
// Existing user
|
|
if (userInfo.userId !== existingUser.id) {
|
|
return badRequest({ error: t("auth:invitation.errors.signInAsInvitedUser") });
|
|
}
|
|
try {
|
|
await acceptWorkspaceInvite({ tenantId: invitation.tenantId, inviteId: invitation.id, token: params.id ?? "", acceptedByUserId: existingUser.id });
|
|
} catch (error) {
|
|
return workspaceInviteErrorResponse(error, t);
|
|
}
|
|
const roles = await getAllRoles("app");
|
|
await createTenantUser(
|
|
{
|
|
tenantId: invitation.tenantId,
|
|
userId: existingUser.id,
|
|
type: invitation.type,
|
|
},
|
|
getDefaultInvitationRoles(roles)
|
|
);
|
|
await EventsService.create({
|
|
request,
|
|
event: "member.invitation.accepted",
|
|
tenantId: invitation.tenant.id,
|
|
userId: existingUser.id,
|
|
data: {
|
|
newUser: false,
|
|
tenant: { id: invitation.tenantId, name: invitation.tenant.name, slug: invitation.tenant.slug },
|
|
fromUser: !fromUser ? null : { id: fromUser.id, email: fromUser.email },
|
|
user: {
|
|
id: existingUser.id,
|
|
email: existingUser.email,
|
|
firstName: existingUser.firstName,
|
|
lastName: existingUser.lastName,
|
|
type: TenantUserType[invitation.type],
|
|
},
|
|
invitation: { id: invitation.id },
|
|
} satisfies MemberInvitationAcceptedDto,
|
|
});
|
|
|
|
return { invitationAccepted: true };
|
|
}
|
|
};
|
|
|
|
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
|
|
|
export default function InvitationRoute() {
|
|
const data = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
const { t } = useTranslation();
|
|
|
|
const errorModal = useRef<RefErrorModal>(null);
|
|
|
|
useEffect(() => {
|
|
if (actionData?.error) {
|
|
errorModal.current?.show(actionData.error);
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [actionData]);
|
|
|
|
return (
|
|
<div>
|
|
<div>
|
|
<div className="flex min-h-screen flex-col items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
|
|
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
|
<Logo className="mx-auto h-12 w-auto" />
|
|
</div>
|
|
{(() => {
|
|
if (!data.invitation?.pending || actionData?.invitationAccepted) {
|
|
return (
|
|
<div className="mt-3 w-full space-y-5">
|
|
<div className="flex flex-col items-center">
|
|
<h1 className="text-left text-xl font-extrabold">{t("auth:invitation.accepted.title")}</h1>
|
|
<div className="mx-auto mt-4 w-full max-w-sm space-y-5">
|
|
<div className="w-full">
|
|
<SuccessBanner title={t("shared.success")} text={t("auth:invitation.accepted.description")} />
|
|
</div>
|
|
<div className="flex w-full justify-end">
|
|
<Button asChild variant="outline">
|
|
<Link to={data.appRootPath}>{t("account.shared.signIn")}</Link>
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
} else if (!data.invitation) {
|
|
return <div className="text-center text-red-500">{t("shared.invalidInvitation")}</div>;
|
|
} else {
|
|
return (
|
|
<div>
|
|
<h2 className="text-foreground mt-6 text-center text-lg font-extrabold dark:text-slate-200">
|
|
{t("shared.hi")} {data.invitation.firstName ? data.invitation.firstName : data.invitation.email}, {t("account.invitation.youWereInvited")}{" "}
|
|
{data.invitation.tenant.name}
|
|
</h2>
|
|
<p className="max-w text-muted-foreground mt-2 text-center text-sm leading-5">
|
|
{t("account.register.alreadyRegistered")}{" "}
|
|
<span className="text-primary font-medium hover:underline">
|
|
<Link to="/login">{t("account.register.clickHereToLogin")}</Link>
|
|
</span>
|
|
</p>
|
|
|
|
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
|
<div className="px-4 py-8 sm:rounded-sm sm:px-10">
|
|
<Form method="post" className="sm:w-96">
|
|
<div>
|
|
<label htmlFor="email" className="block text-sm leading-5 font-medium">
|
|
{t("account.shared.email")}
|
|
</label>
|
|
<div className="mt-1 rounded-sm shadow-2xs">
|
|
<input
|
|
disabled={true}
|
|
type="email"
|
|
id="email"
|
|
name="email"
|
|
defaultValue={data.invitation.email}
|
|
required
|
|
className="focus:border-theme-500 focus:ring-ring border-border text-foreground bg-secondary/90 relative block w-full appearance-none rounded-md border px-3 py-2 placeholder-gray-500 focus:z-10 focus:outline-hidden sm:text-sm dark:border-gray-700 dark:bg-slate-800 dark:text-slate-200"
|
|
/>
|
|
</div>
|
|
</div>
|
|
{!data.existingUser && (
|
|
<>
|
|
<div className="mt-6">
|
|
<label htmlFor="password" className="block text-sm leading-5 font-medium">
|
|
{t("account.shared.password")}
|
|
</label>
|
|
<div className="mt-1 rounded-sm shadow-2xs">
|
|
<input
|
|
type="password"
|
|
id="password"
|
|
name="password"
|
|
required
|
|
className="focus:border-theme-500 focus:ring-ring border-border text-foreground relative block w-full appearance-none rounded-md border px-3 py-2 placeholder-gray-500 focus:z-10 focus:outline-hidden sm:text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-slate-200"
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="mt-6">
|
|
<label htmlFor="password-confirm" className="block text-sm leading-5 font-medium">
|
|
{t("account.register.confirmPassword")}
|
|
</label>
|
|
<div className="mt-1 rounded-sm shadow-2xs">
|
|
<input
|
|
type="password"
|
|
id="password-confirm"
|
|
name="password-confirm"
|
|
required
|
|
className="focus:border-theme-500 focus:ring-ring border-border text-foreground relative block w-full appearance-none rounded-md border px-3 py-2 placeholder-gray-500 focus:z-10 focus:outline-hidden sm:text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-slate-200"
|
|
/>
|
|
</div>
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
<div className="mt-6 space-y-2">
|
|
<span className="block w-full rounded-sm shadow-2xs">
|
|
<button
|
|
type="submit"
|
|
name="intent"
|
|
value="set-password"
|
|
className="bg-primary text-primary-foreground hover:bg-primary/90 inline-flex h-10 w-full items-center justify-center rounded-md px-4 text-sm font-medium"
|
|
>
|
|
{t("account.invitation.button")}
|
|
</button>
|
|
</span>
|
|
{!data.existingUser && (
|
|
<button
|
|
type="submit"
|
|
name="intent"
|
|
value="magic-link"
|
|
className="text-foreground/80 hover:text-foreground w-full text-center text-sm font-medium underline-offset-4 hover:underline"
|
|
>
|
|
{t("auth:invitation.skipPasswordUseMagicLink")}
|
|
</button>
|
|
)}
|
|
</div>
|
|
</Form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
})()}
|
|
</div>
|
|
<ErrorModal ref={errorModal} />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|