From 5418d7b790c76723962a075a836abdb8fac700fa Mon Sep 17 00:00:00 2001 From: Stephan <57194608+stephan418@users.noreply.github.com> Date: Sun, 2 Jan 2022 17:36:21 +0100 Subject: [PATCH] Refactor the endpoints to share common code --- src/Controllers/admin.controller.ts | 20 +++++++------------- src/Controllers/admin_auth.controller.ts | 8 ++------ 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/Controllers/admin.controller.ts b/src/Controllers/admin.controller.ts index 69dd28f..714d98c 100644 --- a/src/Controllers/admin.controller.ts +++ b/src/Controllers/admin.controller.ts @@ -87,19 +87,13 @@ export const createAdmin = async (req: Request<{}, {}, CreateAdminBody>, res: Re if ( !(typeof name === "string" && typeof password == "string" && isPermissionLevel(permission_level) && groupsIsValid) ) { - return res.status(400).json({ - type: "error", - payload: { - message: "The body of your request did not conform to the requirements", - schema: { - body: { - name: "string", - password_level: "string", - permission_level: "'STANDARD' | 'ELEVATED'", - }, - }, - }, - }); + return res.status(400).json( + generateInvalidBodyError({ + name: DataType.STRING, + password: DataType.STRING, + permission_level: DataType.PERMISSION_LEVEL, + }) + ); } const password_hash = await argon2.hash(password, { type: argon2.argon2id }); diff --git a/src/Controllers/admin_auth.controller.ts b/src/Controllers/admin_auth.controller.ts index 8d1ec0e..33ce37b 100644 --- a/src/Controllers/admin_auth.controller.ts +++ b/src/Controllers/admin_auth.controller.ts @@ -4,6 +4,7 @@ import { authClient } from "../lib/redis"; import prisma from "../lib/prisma"; import argon2 from "argon2"; import jwt from "jsonwebtoken"; +import { DataType, generateInvalidBodyError } from "./common"; const JWT_SECRET = process.env.JWT_SECRET || "secret"; const TOKEN_EXPIRY = "4 days"; @@ -39,12 +40,7 @@ export const authenticateUser = async (req: Request<{}, {}, AuthenticateUserBody const { name, password } = req.body || {}; if (name == null || password == null) { - return res.status(400).json({ - type: "error", - payload: { - message: "The body must contain 'name' and 'password' attributes of type string", - }, - }); + return res.status(400).json(generateInvalidBodyError({ name: DataType.STRING, password: DataType.STRING })); } const user = await prisma.admin.findFirst({ where: { name }, include: { groups: true } });