chore: refactor

This commit is contained in:
Catalin Pit
2024-01-25 15:42:40 +02:00
parent ffee2b2c9a
commit 49ecfc1a2c
7 changed files with 13 additions and 66 deletions

View File

@ -20,25 +20,15 @@ export default function UnverifiedAccount() {
const token = searchParams?.get('t') ?? ''; const token = searchParams?.get('t') ?? '';
const { data: { email } = {} } = trpc.profile.getUserFromVerificationToken.useQuery({ token });
const { mutateAsync: sendConfirmationEmail } = trpc.profile.sendConfirmationEmail.useMutation(); const { mutateAsync: sendConfirmationEmail } = trpc.profile.sendConfirmationEmail.useMutation();
const onResendConfirmationEmail = async () => { const onResendConfirmationEmail = async () => {
if (!email) {
toast({
title: 'Unable to send confirmation email',
description: 'Something went wrong while sending the confirmation email. Please try again.',
variant: 'destructive',
});
return;
}
try { try {
setIsButtonDisabled(true); setIsButtonDisabled(true);
await sendConfirmationEmail({ email: email }); // TODO: decrypt email and send it
await sendConfirmationEmail({ email: token ?? '' });
toast({ toast({
title: 'Success', title: 'Success',

View File

@ -62,6 +62,8 @@ export const SignInForm = ({ className, isGoogleSSOEnabled }: SignInFormProps) =
useState(false); useState(false);
const router = useRouter(); const router = useRouter();
const { mutateAsync: encryptSecondaryData } = trpc.crypto.encryptSecondaryData.useMutation();
const [twoFactorAuthenticationMethod, setTwoFactorAuthenticationMethod] = useState< const [twoFactorAuthenticationMethod, setTwoFactorAuthenticationMethod] = useState<
'totp' | 'backup' 'totp' | 'backup'
>('totp'); >('totp');
@ -76,8 +78,6 @@ export const SignInForm = ({ className, isGoogleSSOEnabled }: SignInFormProps) =
resolver: zodResolver(ZSignInFormSchema), resolver: zodResolver(ZSignInFormSchema),
}); });
const { mutateAsync: getUser } = trpc.profile.getUserByEmail.useMutation();
const isSubmitting = form.formState.isSubmitting; const isSubmitting = form.formState.isSubmitting;
const onCloseTwoFactorAuthenticationDialog = () => { const onCloseTwoFactorAuthenticationDialog = () => {
@ -132,10 +132,9 @@ export const SignInForm = ({ className, isGoogleSSOEnabled }: SignInFormProps) =
const errorMessage = ERROR_MESSAGES[result.error]; const errorMessage = ERROR_MESSAGES[result.error];
if (result.error === ErrorCode.UNVERIFIED_EMAIL) { if (result.error === ErrorCode.UNVERIFIED_EMAIL) {
const user = await getUser({ email }); const encryptedEmail = await encryptSecondaryData({ data: email });
const token = user?.VerificationToken[user.VerificationToken.length - 1].token;
router.push(`/unverified-account?t=${token}`); router.push(`/unverified-account?t=${encryptedEmail}`);
return; return;
} }

View File

@ -62,12 +62,15 @@ export const SignUpForm = ({ className, isGoogleSSOEnabled }: SignUpFormProps) =
const isSubmitting = form.formState.isSubmitting; const isSubmitting = form.formState.isSubmitting;
const { mutateAsync: signup } = trpc.auth.signup.useMutation(); const { mutateAsync: signup } = trpc.auth.signup.useMutation();
const { mutateAsync: encryptSecondaryData } = trpc.crypto.encryptSecondaryData.useMutation();
const onFormSubmit = async ({ name, email, password, signature }: TSignUpFormSchema) => { const onFormSubmit = async ({ name, email, password, signature }: TSignUpFormSchema) => {
try { try {
await signup({ name, email, password, signature }); await signup({ name, email, password, signature });
router.push('/signin'); const encryptedEmail = await encryptSecondaryData({ data: email });
router.push(`/unverified-account?t=${encryptedEmail}`);
toast({ toast({
title: 'Registration Successful', title: 'Registration Successful',

View File

@ -11,7 +11,6 @@ import GoogleProvider from 'next-auth/providers/google';
import { prisma } from '@documenso/prisma'; import { prisma } from '@documenso/prisma';
import { IdentityProvider } from '@documenso/prisma/client'; import { IdentityProvider } from '@documenso/prisma/client';
import { ONE_DAY } from '../constants/time';
import { isTwoFactorAuthenticationEnabled } from '../server-only/2fa/is-2fa-availble'; import { isTwoFactorAuthenticationEnabled } from '../server-only/2fa/is-2fa-availble';
import { validateTwoFactorAuthentication } from '../server-only/2fa/validate-2fa'; import { validateTwoFactorAuthentication } from '../server-only/2fa/validate-2fa';
import { getUserByEmail } from '../server-only/user/get-user-by-email'; import { getUserByEmail } from '../server-only/user/get-user-by-email';
@ -71,14 +70,7 @@ export const NEXT_AUTH_OPTIONS: AuthOptions = {
} }
} }
const userCreationDate = user?.createdAt; if (!user.emailVerified) {
const createdWithinLast72Hours = userCreationDate > new Date(Date.now() - ONE_DAY * 3);
/*
avoid messing with the users who signed up before the email verification requirement
the error is thrown only if the user doesn't have a verified email and the account was created within the last 72 hours
*/
if (!user.emailVerified && createdWithinLast72Hours) {
throw new Error(ErrorCode.UNVERIFIED_EMAIL); throw new Error(ErrorCode.UNVERIFIED_EMAIL);
} }

View File

@ -9,8 +9,5 @@ export const getUserByEmail = async ({ email }: GetUserByEmailOptions) => {
where: { where: {
email: email.toLowerCase(), email: email.toLowerCase(),
}, },
include: {
VerificationToken: true,
},
}); });
}; };

View File

@ -1,17 +0,0 @@
import { prisma } from '@documenso/prisma';
export interface GetUserByVerificationTokenOptions {
token: string;
}
export const getUserByVerificationToken = async ({ token }: GetUserByVerificationTokenOptions) => {
return await prisma.user.findFirstOrThrow({
where: {
VerificationToken: {
some: {
token,
},
},
},
});
};

View File

@ -3,7 +3,6 @@ import { TRPCError } from '@trpc/server';
import { forgotPassword } from '@documenso/lib/server-only/user/forgot-password'; import { forgotPassword } from '@documenso/lib/server-only/user/forgot-password';
import { getUserByEmail } from '@documenso/lib/server-only/user/get-user-by-email'; import { getUserByEmail } from '@documenso/lib/server-only/user/get-user-by-email';
import { getUserById } from '@documenso/lib/server-only/user/get-user-by-id'; import { getUserById } from '@documenso/lib/server-only/user/get-user-by-id';
import { getUserByVerificationToken } from '@documenso/lib/server-only/user/get-user-by-verification-token';
import { resetPassword } from '@documenso/lib/server-only/user/reset-password'; import { resetPassword } from '@documenso/lib/server-only/user/reset-password';
import { sendConfirmationToken } from '@documenso/lib/server-only/user/send-confirmation-token'; import { sendConfirmationToken } from '@documenso/lib/server-only/user/send-confirmation-token';
import { updatePassword } from '@documenso/lib/server-only/user/update-password'; import { updatePassword } from '@documenso/lib/server-only/user/update-password';
@ -16,7 +15,6 @@ import {
ZResetPasswordFormSchema, ZResetPasswordFormSchema,
ZRetrieveUserByEmailMutationSchema, ZRetrieveUserByEmailMutationSchema,
ZRetrieveUserByIdQuerySchema, ZRetrieveUserByIdQuerySchema,
ZRetrieveUserByVerificationTokenQuerySchema,
ZUpdatePasswordMutationSchema, ZUpdatePasswordMutationSchema,
ZUpdateProfileMutationSchema, ZUpdateProfileMutationSchema,
} from './schema'; } from './schema';
@ -50,21 +48,6 @@ export const profileRouter = router({
} }
}), }),
getUserFromVerificationToken: procedure
.input(ZRetrieveUserByVerificationTokenQuerySchema)
.query(async ({ input }) => {
try {
const { token } = input;
return await getUserByVerificationToken({ token });
} catch (err) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'We were unable to retrieve the specified account. Please try again.',
});
}
}),
updateProfile: authenticatedProcedure updateProfile: authenticatedProcedure
.input(ZUpdateProfileMutationSchema) .input(ZUpdateProfileMutationSchema)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
@ -153,7 +136,7 @@ export const profileRouter = router({
try { try {
const { email } = input; const { email } = input;
return sendConfirmationToken({ email }); return await sendConfirmationToken({ email });
} catch (err) { } catch (err) {
let message = 'We were unable to send a confirmation email. Please try again.'; let message = 'We were unable to send a confirmation email. Please try again.';