From 56c9f004407d3dd696c531faca4e8383a2ac2086 Mon Sep 17 00:00:00 2001 From: Xiao Yijun Date: Wed, 16 Feb 2022 16:34:32 +0800 Subject: [PATCH] feat(core): post `/users` (#238) --- packages/core/src/routes/admin-user.ts | 52 +++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/core/src/routes/admin-user.ts b/packages/core/src/routes/admin-user.ts index 4d14e65ea..86af33887 100644 --- a/packages/core/src/routes/admin-user.ts +++ b/packages/core/src/routes/admin-user.ts @@ -3,10 +3,20 @@ import pick from 'lodash.pick'; import { InvalidInputError } from 'slonik'; import { object, string } from 'zod'; +import RequestError from '@/errors/RequestError'; +import { encryptUserPassword, generateUserId } from '@/lib/user'; import koaGuard from '@/middleware/koa-guard'; import koaPagination from '@/middleware/koa-pagination'; import { findRolesByRoleNames } from '@/queries/roles'; -import { findAllUsers, findTotalNumberOfUsers, findUserById, updateUserById } from '@/queries/user'; +import { + findAllUsers, + findTotalNumberOfUsers, + findUserById, + hasUser, + insertUser, + updateUserById, +} from '@/queries/user'; +import assertThat from '@/utils/assert-that'; import { AuthedRouter } from './types'; @@ -43,6 +53,46 @@ export default function adminUserRoutes(router: T) { } ); + router.post( + '/users', + koaGuard({ + body: object({ + username: string().min(3), + password: string().min(6), + name: string().min(3), + }), + }), + async (ctx, next) => { + const { username, password, name } = ctx.guard.body; + + assertThat( + !(await hasUser(username)), + new RequestError({ + code: 'user.username_exists_register', + status: 422, + }) + ); + + const id = await generateUserId(); + + const { passwordEncryptionSalt, passwordEncrypted, passwordEncryptionMethod } = + encryptUserPassword(id, password); + + const user = await insertUser({ + id, + username, + passwordEncrypted, + passwordEncryptionMethod, + passwordEncryptionSalt, + name, + }); + + ctx.body = pick(user, ...userInfoSelectFields); + + return next(); + } + ); + router.patch( '/users/:userId/roleNames', koaGuard({