233 lines
9.6 KiB
TypeScript
233 lines
9.6 KiB
TypeScript
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
|
import { 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 "@hivegrid/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 SetPasswordScreen from "~/modules/users/components/SetPasswordScreen";
|
|
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 "@hivegrid/config";
|
|
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
|
import { acceptWorkspaceInvite, getWorkspaceInviteByToken, WorkspaceInviteDto, WorkspaceInviteError } from "@hivegrid/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>();
|
|
// WF-P2 / S01 — Davids "Neues Passwort setzen". Loader/Action unverändert (intent=set-password /
|
|
// intent=magic-link), nur die UI re-skinned auf Davids Auth-Optik.
|
|
return <SetPasswordScreen data={data} actionData={actionData} />;
|
|
}
|