diff --git a/server/src/routes/accounts.controllers.ts b/server/src/routes/accounts.controllers.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7203dc681ea540299e82ce9ef8f9210ee74b091 --- /dev/null +++ b/server/src/routes/accounts.controllers.ts @@ -0,0 +1,49 @@ +import bcrypt from "bcrypt"; +import { Request, Response } from "express"; +import Worker from "../db/models/Worker"; + +export const createAccountController = async (req: Request, res: Response) => { + try { + if (!(res.locals.user.role === "coordinator")) { + return res + .status(403) + .json({ success: false, error: "MustBeCoordinator" }); + } + + const { first_name, last_name, email, password, role } = req.body; + + const account = await Worker.findAll({ + where: { + email: email, + }, + }); + + if (account.length > 0) { + return res + .status(409) + .json({ success: false, error: "AccountAlreadyExists" }); + } + + const hashedPassword = await bcrypt.hash(password, 10); + + const newAccount = await Worker.create({ + email, + firstName: first_name, + lastName: last_name, + password: hashedPassword, + role, + }); + + return res.status(201).send({ + success: true, + account: { + first_name: newAccount.firstName, + last_name: newAccount.lastName, + email: newAccount.email, + role: newAccount.role, + }, + }); + } catch { + return res.status(500).json({ success: false, error: "serverError" }); + } +}; diff --git a/server/src/routes/accounts.routes.ts b/server/src/routes/accounts.routes.ts new file mode 100644 index 0000000000000000000000000000000000000000..68dc6a5baac9f0e39598c2674abb9e9b94b53749 --- /dev/null +++ b/server/src/routes/accounts.routes.ts @@ -0,0 +1,21 @@ +import { Router } from "express"; +import { body } from "express-validator"; +import handleValidationResult from "../middleware/handleValidationResult"; +import validateToken from "../middleware/validateToken"; +import { createAccountController } from "./accounts.controllers"; + +const accountsRouter = Router(); + +accountsRouter.post( + "/api/accounts/", + body("first_name").not().isEmpty(), + body("last_name").not().isEmpty(), + body("email").isEmail().normalizeEmail(), + body("role").isIn(["coordinator", "boatManager"]), + body("password").isLength({ min: 6 }), + handleValidationResult, + validateToken, + createAccountController +); + +export default accountsRouter;