148 lines
4.7 KiB
TypeScript
148 lines
4.7 KiB
TypeScript
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
import client from "@/lib/mongodb";
|
|
import { withIronSessionApiRoute } from "iron-session/next";
|
|
import { sessionOptions } from "@/lib/session";
|
|
import { Code, Group, Type } from "@/interfaces/user";
|
|
import { PERMISSIONS } from "@/constants/userPermissions";
|
|
import { prepareMailer, prepareMailOptions } from "@/email";
|
|
import { isAdmin } from "@/utils/users";
|
|
import { requestUser } from "@/utils/api";
|
|
import { doesEntityAllow } from "@/utils/permissions";
|
|
import { getEntity, getEntityWithRoles } from "@/utils/entities.be";
|
|
import { findBy } from "@/utils";
|
|
import { EntityWithRoles } from "@/interfaces/entity";
|
|
|
|
const db = client.db(process.env.MONGODB_DB);
|
|
|
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
if (req.method === "GET") return get(req, res);
|
|
if (req.method === "POST") return post(req, res);
|
|
if (req.method === "DELETE") return del(req, res);
|
|
|
|
return res.status(404).json({ ok: false });
|
|
}
|
|
|
|
async function get(req: NextApiRequest, res: NextApiResponse) {
|
|
if (!req.session.user) {
|
|
res.status(401).json({ ok: false, reason: "You must be logged in to generate a code!" });
|
|
return;
|
|
}
|
|
|
|
const { entity } = req.query as { entity?: string };
|
|
|
|
const snapshot = await db.collection("codes").find(entity ? { entity } : {}).toArray();
|
|
|
|
res.status(200).json(snapshot);
|
|
}
|
|
|
|
const generateAndSendCode = async (
|
|
code: string,
|
|
type: Type,
|
|
creator: string,
|
|
expiryDate: null | Date,
|
|
entity?: string,
|
|
info?: {
|
|
email: string; name: string; passport_id?: string
|
|
}) => {
|
|
if (!info) {
|
|
await db.collection("codes").insertOne({
|
|
code, type, creator, expiryDate, entity, creationDate: new Date().toISOString()
|
|
})
|
|
return true
|
|
}
|
|
|
|
const previousCode = await db.collection("codes").findOne<Code>({ email: info.email, entity })
|
|
|
|
const transport = prepareMailer();
|
|
const mailOptions = prepareMailOptions(
|
|
{
|
|
type,
|
|
code: previousCode ? previousCode.code : code,
|
|
environment: process.env.ENVIRONMENT,
|
|
},
|
|
[info.email.toLowerCase().trim()],
|
|
"EnCoach Registration",
|
|
"main",
|
|
);
|
|
|
|
try {
|
|
await transport.sendMail(mailOptions);
|
|
if (!previousCode) {
|
|
await db.collection("codes").insertOne({
|
|
code, type, creator, expiryDate, entity, name: info.name.trim(), email: info.email.trim().toLowerCase(),
|
|
...(info.passport_id ? { passport_id: info.passport_id.trim() } : {}),
|
|
creationDate: new Date().toISOString()
|
|
})
|
|
}
|
|
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
const countAvailableCodes = async (entity: EntityWithRoles) => {
|
|
const usedUp = await db.collection("codes").countDocuments({ entity: entity.id })
|
|
const total = entity.licenses
|
|
|
|
return total - usedUp
|
|
}
|
|
|
|
async function post(req: NextApiRequest, res: NextApiResponse) {
|
|
const user = await requestUser(req, res)
|
|
if (!user) return res.status(401).json({ ok: false, reason: "You must be logged in to generate a code!" });
|
|
|
|
const { type, codes, infos, expiryDate, entity } = req.body as {
|
|
type: Type;
|
|
codes: string[];
|
|
infos?: { email: string; name: string; passport_id?: string, code: string }[];
|
|
expiryDate: null | Date;
|
|
entity?: string
|
|
};
|
|
|
|
if (!entity && !isAdmin(user))
|
|
return res.status(403).json({ ok: false, reason: "You must be an admin to generate a code without an entity!" });
|
|
|
|
const entityObj = entity ? await getEntityWithRoles(entity) : undefined
|
|
const isAllowed = entityObj ? doesEntityAllow(user, entityObj, 'create_code') : true
|
|
if (!isAllowed) return res.status(403).json({ ok: false, reason: "You do not have permissions to generate a code!" });
|
|
|
|
if (entityObj) {
|
|
const availableCodes = await countAvailableCodes(entityObj)
|
|
if (availableCodes < codes.length)
|
|
return res.status(400).json({
|
|
ok: false,
|
|
reason: `You only have ${availableCodes} codes available, while trying to create ${codes.length} codes`
|
|
})
|
|
}
|
|
const valid = []
|
|
for (const code of codes) {
|
|
const info = findBy(infos || [], 'code', code)
|
|
const isValid = await generateAndSendCode(code, type, user.id, expiryDate, entity, info)
|
|
valid.push(isValid)
|
|
}
|
|
|
|
return res.status(200).json({ ok: true, valid: valid.length });
|
|
}
|
|
|
|
async function del(req: NextApiRequest, res: NextApiResponse) {
|
|
if (!req.session.user) {
|
|
res.status(401).json({ ok: false, reason: "You must be logged in to generate a code!" });
|
|
return;
|
|
}
|
|
|
|
const codes = req.query.code as string[];
|
|
|
|
for (const code of codes) {
|
|
const snapshot = await db.collection("codes").findOne<Code>({ id: code as string });
|
|
if (!snapshot) continue;
|
|
|
|
await db.collection("codes").deleteOne({ id: snapshot.id });
|
|
}
|
|
|
|
res.status(200).json({ codes });
|
|
}
|