Files
sign/packages/trpc/server/auth-router/router.ts

55 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-06-09 18:21:18 +10:00
import { TRPCError } from '@trpc/server';
import { ErrorCode } from '@documenso/lib/next-auth/error-codes';
import { compareSync } from '@documenso/lib/server-only/auth/hash';
2023-06-09 18:21:18 +10:00
import { createUser } from '@documenso/lib/server-only/user/create-user';
import { sendConfirmationToken } from '@documenso/lib/server-only/user/send-confirmation-token';
2023-06-09 18:21:18 +10:00
import { authenticatedProcedure, procedure, router } from '../trpc';
import { ZSignUpMutationSchema, ZVerifyPasswordMutationSchema } from './schema';
2023-06-09 18:21:18 +10:00
export const authRouter = router({
signup: procedure.input(ZSignUpMutationSchema).mutation(async ({ input }) => {
try {
2023-09-01 19:46:44 +10:00
const { name, email, password, signature } = input;
2023-06-09 18:21:18 +10:00
const user = await createUser({ name, email, password, signature });
await sendConfirmationToken({ email: user.email });
return user;
2023-06-09 18:21:18 +10:00
} catch (err) {
let message =
'We were unable to create your account. Please review the information you provided and try again.';
if (err instanceof Error && err.message === 'User already exists') {
message = 'User with this email already exists. Please use a different email address.';
}
2023-06-09 18:21:18 +10:00
throw new TRPCError({
code: 'BAD_REQUEST',
message,
2023-06-09 18:21:18 +10:00
});
}
}),
verifyPassword: authenticatedProcedure
.input(ZVerifyPasswordMutationSchema)
.mutation(({ ctx, input }) => {
const user = ctx.user;
const { password } = input;
if (!user.password) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: ErrorCode.INCORRECT_PASSWORD,
});
}
const valid = compareSync(password, user.password);
return valid;
}),
2023-06-09 18:21:18 +10:00
});