fix: refactor trpc errors (#1511)

This commit is contained in:
David Nguyen
2024-12-06 16:01:24 +09:00
committed by GitHub
parent 3b6b96f551
commit 904948e2bc
27 changed files with 806 additions and 1518 deletions

View File

@ -2,7 +2,6 @@ import { z } from 'zod';
import { DOCUMENSO_ENCRYPTION_SECONDARY_KEY } from '@documenso/lib/constants/crypto';
import { symmetricEncrypt } from '@documenso/lib/universal/crypto';
import type { TEncryptSecondaryDataMutationSchema } from '@documenso/trpc/server/crypto/schema';
export const ZEncryptedDataSchema = z.object({
data: z.string(),
@ -25,7 +24,7 @@ export type EncryptDataOptions = {
*
* @returns The encrypted data.
*/
export const encryptSecondaryData = ({ data, expiresAt }: TEncryptSecondaryDataMutationSchema) => {
export const encryptSecondaryData = ({ data, expiresAt }: EncryptDataOptions) => {
if (!DOCUMENSO_ENCRYPTION_SECONDARY_KEY) {
throw new Error('Missing encryption key');
}

View File

@ -2,6 +2,7 @@ import sharp from 'sharp';
import { prisma } from '@documenso/prisma';
import { AppError, AppErrorCode } from '../../errors/app-error';
import type { RequestMetadata } from '../../universal/extract-request-metadata';
export type SetAvatarImageOptions = {
@ -29,7 +30,9 @@ export const setAvatarImage = async ({
});
if (!user) {
throw new Error('User not found');
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'User not found',
});
}
oldAvatarImageId = user.avatarImageId;
@ -47,7 +50,9 @@ export const setAvatarImage = async ({
});
if (!team) {
throw new Error('Team not found');
throw new AppError('TEAM_NOT_FOUND', {
statusCode: 404,
});
}
oldAvatarImageId = team.avatarImageId;

View File

@ -8,6 +8,7 @@ import { IdentityProvider, TeamMemberInviteStatus } from '@documenso/prisma/clie
import { IS_BILLING_ENABLED } from '../../constants/app';
import { SALT_ROUNDS } from '../../constants/auth';
import { AppError, AppErrorCode } from '../../errors/app-error';
import { buildLogger } from '../../utils/logger';
export interface CreateUserOptions {
name: string;
@ -27,7 +28,7 @@ export const createUser = async ({ name, email, password, signature, url }: Crea
});
if (userExists) {
throw new Error('User already exists');
throw new AppError(AppErrorCode.ALREADY_EXISTS);
}
if (url) {
@ -134,6 +135,18 @@ export const createUser = async ({ name, email, password, signature, url }: Crea
return await getStripeCustomerByUser(user).then((session) => session.user);
} catch (err) {
console.error(err);
const error = AppError.parseError(err);
const logger = buildLogger();
logger.error(error, {
method: 'createUser',
context: {
appError: AppError.toJSON(error),
userId: user.id,
},
});
}
}

View File

@ -4,6 +4,7 @@ import { prisma } from '@documenso/prisma';
import { UserSecurityAuditLogType } from '@documenso/prisma/client';
import { SALT_ROUNDS } from '../../constants/auth';
import { AppError, AppErrorCode } from '../../errors/app-error';
import type { RequestMetadata } from '../../universal/extract-request-metadata';
import { sendResetPassword } from '../auth/send-reset-password';
@ -15,7 +16,7 @@ export type ResetPasswordOptions = {
export const resetPassword = async ({ token, password, requestMetadata }: ResetPasswordOptions) => {
if (!token) {
throw new Error('Invalid token provided. Please try again.');
throw new AppError('INVALID_TOKEN');
}
const foundToken = await prisma.passwordResetToken.findFirst({
@ -28,19 +29,19 @@ export const resetPassword = async ({ token, password, requestMetadata }: ResetP
});
if (!foundToken) {
throw new Error('Invalid token provided. Please try again.');
throw new AppError('INVALID_TOKEN');
}
const now = new Date();
if (now > foundToken.expiry) {
throw new Error('Token has expired. Please try again.');
throw new AppError(AppErrorCode.EXPIRED_CODE);
}
const isSamePassword = await compare(password, foundToken.User.password || '');
if (isSamePassword) {
throw new Error('Your new password cannot be the same as your old password.');
throw new AppError('SAME_PASSWORD');
}
const hashedPassword = await hash(password, SALT_ROUNDS);

View File

@ -5,6 +5,8 @@ import type { RequestMetadata } from '@documenso/lib/universal/extract-request-m
import { prisma } from '@documenso/prisma';
import { UserSecurityAuditLogType } from '@documenso/prisma/client';
import { AppError } from '../../errors/app-error';
export type UpdatePasswordOptions = {
userId: number;
password: string;
@ -26,18 +28,18 @@ export const updatePassword = async ({
});
if (!user.password) {
throw new Error('User has no password');
throw new AppError('NO_PASSWORD');
}
const isCurrentPasswordValid = await compare(currentPassword, user.password);
if (!isCurrentPasswordValid) {
throw new Error('Current password is incorrect.');
throw new AppError('INCORRECT_PASSWORD');
}
// Compare the new password with the old password
const isSamePassword = await compare(password, user.password);
if (isSamePassword) {
throw new Error('Your new password cannot be the same as your old password.');
throw new AppError('SAME_PASSWORD');
}
const hashedNewPassword = await hash(password, SALT_ROUNDS);