feat: check if user exist

This commit is contained in:
Methapon Metanipat 2024-08-29 13:18:25 +07:00
parent 8a2b122d7f
commit 09cb20c57d

View file

@ -290,7 +290,7 @@ export class UserController extends Controller {
@Post()
@Security("keycloak", ["system", "head_of_admin", "admin", "branch_admin"])
async createUser(@Request() req: RequestWithUser, @Body() body: UserCreate) {
const [province, district, subDistrict, branch] = await prisma.$transaction([
const [province, district, subDistrict, branch, user] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId ?? undefined } }),
prisma.district.findFirst({ where: { id: body.districtId ?? undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId ?? undefined } }),
@ -298,6 +298,9 @@ export class UserController extends Controller {
include: { user: { where: { userId: req.user.sub } } },
where: { id: { in: Array.isArray(body.branchId) ? body.branchId : [body.branchId] } },
}),
prisma.user.findFirst({
where: { username: body.username },
}),
]);
if (body.provinceId && !province) {
throw new HttpError(
@ -327,6 +330,9 @@ export class UserController extends Controller {
"minimumBranchNotMet",
);
}
if (user) {
throw new HttpError(HttpStatus.BAD_REQUEST, "User exists.", "userExists");
}
if (
!["system", "head_of_admin", "admin"].some((v) => req.user.roles?.includes(v)) &&
branch?.some((v) => !v.user.find((v) => v.userId === req.user.sub))