From 0022a7befbc66b13cb10ead7ae147f5d84a9f321 Mon Sep 17 00:00:00 2001 From: Johann150 Date: Wed, 21 Sep 2022 17:58:42 +0200 Subject: [PATCH] backend: proper error messages for creating accounts Admins will now get proper error messages when they try to create a new user account and an error occurs. Changelog: Fixed --- .../backend/src/server/api/common/signup.ts | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/packages/backend/src/server/api/common/signup.ts b/packages/backend/src/server/api/common/signup.ts index f246a454e..3ac4ac0ba 100644 --- a/packages/backend/src/server/api/common/signup.ts +++ b/packages/backend/src/server/api/common/signup.ts @@ -10,6 +10,7 @@ import { UserKeypair } from '@/models/entities/user-keypair.js'; import { usersChart } from '@/services/chart/index.js'; import { UsedUsername } from '@/models/entities/used-username.js'; import { db } from '@/db/postgre.js'; +import { ApiError } from '@/server/api/error.js'; import generateUserToken from './generate-native-user-token.js'; export async function signup(opts: { @@ -23,13 +24,25 @@ export async function signup(opts: { // Validate username if (!Users.validateLocalUsername(username)) { - throw new Error('INVALID_USERNAME'); + throw new ApiError({ + message: 'This username is invalid.', + code: 'INVALID_USERNAME', + id: 'ece89f3c-d845-4d9a-850b-1735285e8cd4', + kind: 'client', + httpStatusCode: 400, + }); } if (password != null && passwordHash == null) { // Validate password if (!Users.validatePassword(password)) { - throw new Error('INVALID_PASSWORD'); + throw new ApiError({ + message: 'This password is invalid.', + code: 'INVALID_PASSWORD', + id: 'a941905b-fe7b-43e2-8ecd-50ad3a2287ab', + kind: 'client', + httpStatusCode: 400, + }); } // Generate hash of password @@ -40,14 +53,22 @@ export async function signup(opts: { // Generate secret const secret = generateUserToken(); + const duplicateUsernameError = { + message: 'This username is not available.', + code: 'USED_USERNAME', + id: '7ddd595e-6860-4593-93c5-9fdbcb80cd81', + kind: 'client', + httpStatusCode: 409, + }; + // Check username duplication if (await Users.findOneBy({ usernameLower: username.toLowerCase(), host: IsNull() })) { - throw new Error('DUPLICATED_USERNAME'); + throw new ApiError(duplicateUsernameError); } // Check deleted username duplication if (await UsedUsernames.findOneBy({ username: username.toLowerCase() })) { - throw new Error('USED_USERNAME'); + throw new ApiError(duplicateUsernameError); } const keyPair = await new Promise((res, rej) => @@ -76,7 +97,7 @@ export async function signup(opts: { host: IsNull(), }); - if (exist) throw new Error(' the username is already used'); + if (exist) throw new ApiError(duplicateUsernameError); account = await transactionalEntityManager.save(new User({ id: genId(),