import Link from 'next/link';
import { notFound, redirect } from 'next/navigation';
import { ArrowLeft } from 'lucide-react';
import { AuthLayoutShell } from '@kit/auth/shared';
import { MultiFactorAuthError, requireUser } from '@kit/supabase/require-user';
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { createTeamAccountsApi } from '@kit/team-accounts/api';
import { AcceptInvitationContainer } from '@kit/team-accounts/components';
import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading';
import { Trans } from '@kit/ui/trans';
import { AppLogo } from '~/components/app-logo';
import pathsConfig from '~/config/paths.config';
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';
interface JoinTeamAccountPageProps {
searchParams: Promise<{
invite_token?: string;
email?: string;
}>;
}
export const generateMetadata = async () => {
const i18n = await createI18nServerInstance();
return {
title: i18n.t('teams:joinTeamAccount'),
};
};
async function JoinTeamAccountPage(props: JoinTeamAccountPageProps) {
const searchParams = await props.searchParams;
const token = searchParams.invite_token;
// no token, redirect to 404
if (!token) {
notFound();
}
const client = getSupabaseServerClient();
const auth = await requireUser(client);
// if the user is not logged in or there is an error
// redirect to the sign up page with the invite token
// so that they will get back to this page after signing up
if (auth.error ?? !auth.data) {
if (auth.error instanceof MultiFactorAuthError) {
const urlParams = new URLSearchParams({
next: `${pathsConfig.app.joinTeam}?invite_token=${token}&email=${searchParams.email ?? ''}`,
});
const verifyMfaUrl = `${pathsConfig.auth.verifyMfa}?${urlParams.toString()}`;
// if the user needs to verify MFA
// redirect them to the MFA verification page
redirect(verifyMfaUrl);
} else {
const urlParams = new URLSearchParams({
invite_token: token,
});
const nextUrl = `${pathsConfig.auth.signUp}?${urlParams.toString()}`;
// redirect to the sign up page with the invite token
redirect(nextUrl);
}
}
// get api to interact with team accounts
const adminClient = getSupabaseServerAdminClient();
const api = createTeamAccountsApi(client);
// the user is logged in, we can now check if the token is valid
const invitation = await api.getInvitation(adminClient, token);
// the invitation is not found or expired or the email is not the same as the user's email
const isInvitationValid = invitation?.email === auth.data.email;
if (!isInvitationValid) {
return (