(fastify: FastifyInstance)
| 58 | } |
| 59 | |
| 60 | export function authRoutes(fastify: FastifyInstance) { |
| 61 | // Register a new user |
| 62 | fastify.post( |
| 63 | "/api/v1/auth/user/register", |
| 64 | { |
| 65 | schema: { |
| 66 | body: { |
| 67 | type: "object", |
| 68 | properties: { |
| 69 | email: { type: "string" }, |
| 70 | password: { type: "string" }, |
| 71 | admin: { type: "boolean" }, |
| 72 | name: { type: "string" }, |
| 73 | }, |
| 74 | required: ["email", "password", "name", "admin"], |
| 75 | }, |
| 76 | }, |
| 77 | }, |
| 78 | async (request: FastifyRequest, reply: FastifyReply) => { |
| 79 | let { email, password, admin, name } = request.body as { |
| 80 | email: string; |
| 81 | password: string; |
| 82 | admin: boolean; |
| 83 | name: string; |
| 84 | }; |
| 85 | |
| 86 | const requester = await checkSession(request); |
| 87 | |
| 88 | if (!requester?.isAdmin) { |
| 89 | return reply.code(401).send({ |
| 90 | message: "Unauthorized", |
| 91 | }); |
| 92 | } |
| 93 | |
| 94 | // Checks if email already exists |
| 95 | let record = await prisma.user.findUnique({ |
| 96 | where: { email }, |
| 97 | }); |
| 98 | |
| 99 | // if exists, return 400 |
| 100 | if (record) { |
| 101 | return reply.code(400).send({ |
| 102 | message: "Email already exists", |
| 103 | }); |
| 104 | } |
| 105 | |
| 106 | const user = await prisma.user.create({ |
| 107 | data: { |
| 108 | email, |
| 109 | password: await bcrypt.hash(password, 10), |
| 110 | name, |
| 111 | isAdmin: admin, |
| 112 | }, |
| 113 | }); |
| 114 | |
| 115 | const hog = track(); |
| 116 | |
| 117 | hog.capture({ |
no test coverage detected