From 4df48360b5f5fab7d4b878dbd791ebd673f51764 Mon Sep 17 00:00:00 2001 From: Stefan-5422 <32109571+Stefan-5422@users.noreply.github.com> Date: Wed, 23 Mar 2022 12:55:48 +0100 Subject: [PATCH] Create Register endpoint; --- src/controller/auth.controller.ts | 67 +++++++++++++++++++++++++++++++ src/routes/auth.route.ts | 8 ++++ 2 files changed, 75 insertions(+) create mode 100644 src/controller/auth.controller.ts create mode 100644 src/routes/auth.route.ts diff --git a/src/controller/auth.controller.ts b/src/controller/auth.controller.ts new file mode 100644 index 0000000..e8f3b14 --- /dev/null +++ b/src/controller/auth.controller.ts @@ -0,0 +1,67 @@ +import express from "express"; +import { Request, Response } from "express"; +import prisma from "../lib/prisma.lib"; +import { Role } from "@prisma/client"; +import { createDefaultError, createDefaultSucces } from "../lib/standardResponse"; +import argon2 from "argon2"; + +interface registerBody { + name: string; + password: string; + role: string; + organization?: number; +} + +export interface authJwt { + id: number; + role: string; +} + +const ROLES: readonly string[] = [Role.ADMIN, Role.USER]; + +export const register = async (req: Request, res: Response) => { + const { name, password, role, organization } = req.body || {}; + + console.log(name); + + if ( + !( + typeof name === "string" && + typeof password === "string" && + ROLES.includes(role) && + typeof organization === "number" + ) + ) { + return res.status(400).json( + createDefaultError("Request body does not match required parameters", { + name: "string", + password: "string", + role: "USER | ADMIN", + organization: "int", + }) + ); + } + + const hash = await argon2.hash("salty" + password + "salty"); + + if (!(await prisma.organization.findUnique({ where: { id: organization } }))) { + return res.status(404).json(createDefaultError(`Could not find organization with id ${organization}`, {})); + } + + const user = await prisma.user.create({ + data: { + email: name, + passwordSalt: "salty", + passwordHash: hash, + role: role as Role, + organization: { connect: { id: organization } || undefined }, + }, + select: { + id: true, + email: true, + role: true, + }, + }); + + res.status(201).json(createDefaultSucces("User created succesfully", user)); +}; diff --git a/src/routes/auth.route.ts b/src/routes/auth.route.ts new file mode 100644 index 0000000..2aed2db --- /dev/null +++ b/src/routes/auth.route.ts @@ -0,0 +1,8 @@ +import { Router } from "express"; +import { register } from "../controller/auth.controller"; + +const router = Router(); + +router.post("/register", register); + +export default router;