Merged develop into feature/ExamGenRework
This commit is contained in:
36
src/pages/api/code/entities.ts
Normal file
36
src/pages/api/code/entities.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
// 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);
|
||||
|
||||
return res.status(404).json({ ok: false });
|
||||
}
|
||||
|
||||
async function get(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!" })
|
||||
|
||||
const { entities } = req.query as { entities?: string[] };
|
||||
if (entities)
|
||||
return res.status(200).json(await db.collection("codes").find<Code>({ entity: { $in: entities } }).toArray());
|
||||
|
||||
return res.status(200).json(await db.collection("codes").find<Code>({}).toArray());
|
||||
}
|
||||
@@ -6,6 +6,12 @@ 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);
|
||||
|
||||
@@ -25,117 +31,100 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { creator } = req.query as { creator?: string };
|
||||
const snapshot = await db.collection("codes").find(creator ? { creator: creator } : {}).toArray();
|
||||
const { entity } = req.query as { entity?: string };
|
||||
const snapshot = await db.collection("codes").find(entity ? { entity } : {}).toArray();
|
||||
|
||||
res.status(200).json(snapshot);
|
||||
}
|
||||
|
||||
async function post(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 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 { type, codes, infos, expiryDate } = req.body as {
|
||||
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 }[];
|
||||
infos?: { email: string; name: string; passport_id?: string, code: string }[];
|
||||
expiryDate: null | Date;
|
||||
entity?: string
|
||||
};
|
||||
const permission = PERMISSIONS.generateCode[type];
|
||||
|
||||
if (!permission.includes(req.session.user.type)) {
|
||||
res.status(403).json({
|
||||
ok: false,
|
||||
reason: "Your account type does not have permissions to generate a code for that type of user!",
|
||||
});
|
||||
return;
|
||||
}
|
||||
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 userCodes = await db.collection("codes").find<Code>({ creator: req.session.user.id }).toArray()
|
||||
const creatorGroupsSnapshot = await db.collection("groups").find<Group>({ admin: req.session.user.id }).toArray()
|
||||
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!" });
|
||||
|
||||
const creatorGroups = creatorGroupsSnapshot.filter((x) => x.name === "Students" || x.name === "Teachers" || x.name === "Corporate");
|
||||
const usersInGroups = creatorGroups.flatMap((x) => x.participants);
|
||||
|
||||
|
||||
if (req.session.user.type === "corporate") {
|
||||
const totalCodes = userCodes.filter((x) => !x.userId || !usersInGroups.includes(x.userId)).length + usersInGroups.length + codes.length;
|
||||
const allowedCodes = 0;
|
||||
|
||||
if (totalCodes > allowedCodes) {
|
||||
res.status(403).json({
|
||||
if (entityObj) {
|
||||
const availableCodes = await countAvailableCodes(entityObj)
|
||||
if (availableCodes < codes.length)
|
||||
return res.status(400).json({
|
||||
ok: false,
|
||||
reason: `You have or would have exceeded your amount of allowed codes, you currently are allowed to generate ${allowedCodes - userCodes.length
|
||||
} codes.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
const codePromises = codes.map(async (code, index) => {
|
||||
const codeRef = await db.collection("codes").findOne<Code>({ id: code });
|
||||
let codeInformation = {
|
||||
type,
|
||||
code,
|
||||
creator: req.session.user!.id,
|
||||
creationDate: new Date().toISOString(),
|
||||
expiryDate,
|
||||
};
|
||||
|
||||
if (infos && infos.length > index) {
|
||||
const { email, name, passport_id } = infos[index];
|
||||
const previousCode = userCodes.find((x) => x.email === email) as Code;
|
||||
|
||||
const transport = prepareMailer();
|
||||
const mailOptions = prepareMailOptions(
|
||||
{
|
||||
type,
|
||||
code: previousCode ? previousCode.code : code,
|
||||
environment: process.env.ENVIRONMENT,
|
||||
},
|
||||
[email.toLowerCase().trim()],
|
||||
"EnCoach Registration",
|
||||
"main",
|
||||
);
|
||||
|
||||
try {
|
||||
await transport.sendMail(mailOptions);
|
||||
|
||||
if (!previousCode && codeRef) {
|
||||
await db.collection("codes").updateOne(
|
||||
{ id: codeRef.id },
|
||||
{
|
||||
$set: {
|
||||
id: codeRef.id,
|
||||
...codeInformation,
|
||||
email: email.trim().toLowerCase(),
|
||||
name: name.trim(),
|
||||
...(passport_id ? { passport_id: passport_id.trim() } : {}),
|
||||
}
|
||||
},
|
||||
{ upsert: true }
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// upsert: true -> if it doesnt exist insert
|
||||
await db.collection("codes").updateOne(
|
||||
{ id: code },
|
||||
{ $set: { id: code, ...codeInformation } },
|
||||
{ upsert: true }
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Promise.all(codePromises).then((results) => {
|
||||
res.status(200).json({ ok: true, valid: results.filter((x) => x).length });
|
||||
});
|
||||
return res.status(200).json({ ok: true, valid: valid.length });
|
||||
}
|
||||
|
||||
async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
48
src/pages/api/grading/multiple.ts
Normal file
48
src/pages/api/grading/multiple.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { CorporateUser, Group } from "@/interfaces/user";
|
||||
import { Discount, Package } from "@/interfaces/paypal";
|
||||
import { v4 } from "uuid";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { CEFR_STEPS } from "@/resources/grading";
|
||||
import { getCorporateUser } from "@/resources/user";
|
||||
import { getUserCorporate } from "@/utils/groups.be";
|
||||
import { Grading, Step } from "@/interfaces";
|
||||
import { getGroupsForUser } from "@/utils/groups.be";
|
||||
import { uniq } from "lodash";
|
||||
import { getSpecificUsers, getUser } from "@/utils/users.be";
|
||||
import client from "@/lib/mongodb";
|
||||
import { getGradingSystemByEntity } from "@/utils/grading.be";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") await post(req, res);
|
||||
}
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!checkAccess(req.session.user, ["admin", "developer", "mastercorporate", "corporate"]))
|
||||
return res.status(403).json({
|
||||
ok: false,
|
||||
reason: "You do not have permission to create a new grading system",
|
||||
});
|
||||
|
||||
const body = req.body as {
|
||||
entities: string[]
|
||||
steps: Step[];
|
||||
};
|
||||
|
||||
await db.collection("grading").updateMany({ entity: { $in: body.entities } }, { $set: { steps: body.steps } }, { upsert: true });
|
||||
|
||||
res.status(200).json({ ok: true });
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
import {NextApiRequest, NextApiResponse} from "next";
|
||||
import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";
|
||||
import {app} from "@/firebase";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {Code, CorporateInformation, DemographicInformation, Group, Type} from "@/interfaces/user";
|
||||
import {addUserToGroupOnCreation} from "@/utils/registration";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { createUserWithEmailAndPassword, getAuth } from "firebase/auth";
|
||||
import { app } from "@/firebase";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { Code, CorporateInformation, DemographicInformation, Group, Type } from "@/interfaces/user";
|
||||
import { addUserToGroupOnCreation } from "@/utils/registration";
|
||||
import moment from "moment";
|
||||
import {v4} from "uuid";
|
||||
import { v4 } from "uuid";
|
||||
import client from "@/lib/mongodb";
|
||||
import { addUserToEntity, getEntityWithRoles } from "@/utils/entities.be";
|
||||
import { findBy } from "@/utils";
|
||||
|
||||
const auth = getAuth(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
@@ -29,7 +31,7 @@ const DEFAULT_LEVELS = {
|
||||
};
|
||||
|
||||
async function register(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {type} = req.body as {
|
||||
const { type } = req.body as {
|
||||
type: "individual" | "corporate";
|
||||
};
|
||||
|
||||
@@ -38,19 +40,18 @@ async function register(req: NextApiRequest, res: NextApiResponse) {
|
||||
}
|
||||
|
||||
async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {email, passport_id, password, code} = req.body as {
|
||||
const { email, passport_id, password, code } = req.body as {
|
||||
email: string;
|
||||
passport_id?: string;
|
||||
password: string;
|
||||
code?: string;
|
||||
};
|
||||
|
||||
const codeDoc = await db.collection("codes").findOne<Code>({code});
|
||||
const codeDoc = await db.collection("codes").findOne<Code>({ code });
|
||||
|
||||
if (code && code.length > 0 && !codeDoc)
|
||||
return res.status(400).json({ error: "Invalid Code!" });
|
||||
|
||||
if (code && code.length > 0 && !!codeDoc) {
|
||||
res.status(400).json({error: "Invalid Code!"});
|
||||
return;
|
||||
}
|
||||
|
||||
createUserWithEmailAndPassword(auth, email.toLowerCase(), password)
|
||||
.then(async (userCredentials) => {
|
||||
@@ -69,34 +70,39 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
||||
focus: "academic",
|
||||
type: email.endsWith("@ecrop.dev") ? "developer" : codeDoc ? codeDoc.type : "student",
|
||||
subscriptionExpirationDate: codeDoc ? codeDoc.expiryDate : moment().subtract(1, "days").toISOString(),
|
||||
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
||||
...(passport_id ? { demographicInformation: { passport_id } } : {}),
|
||||
registrationDate: new Date().toISOString(),
|
||||
status: code ? "active" : "paymentDue",
|
||||
// apparently there's an issue with the verification email system
|
||||
// therefore we will skip this requirement for now
|
||||
isVerified: true,
|
||||
entities: [],
|
||||
isVerified: !!codeDoc,
|
||||
};
|
||||
|
||||
await db.collection("users").insertOne(user);
|
||||
|
||||
if (!!codeDoc) {
|
||||
await db.collection("codes").updateOne({code: codeDoc.code}, {$set: {userId}});
|
||||
if (codeDoc.creator) await addUserToGroupOnCreation(userId, codeDoc.type, codeDoc.creator);
|
||||
await db.collection("codes").updateOne({ code: codeDoc.code }, { $set: { userId } });
|
||||
if (codeDoc.entity) {
|
||||
const inviteEntity = await getEntityWithRoles(codeDoc.entity)
|
||||
if (inviteEntity) {
|
||||
const defaultRole = findBy(inviteEntity.roles, 'isDefault', true)!
|
||||
await addUserToEntity(userId, codeDoc.entity, defaultRole.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
req.session.user = user;
|
||||
await req.session.save();
|
||||
|
||||
res.status(200).json({user});
|
||||
res.status(200).json({ user });
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error);
|
||||
res.status(401).json({error});
|
||||
res.status(401).json({ error });
|
||||
});
|
||||
}
|
||||
|
||||
async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {email, password} = req.body as {
|
||||
const { email, password } = req.body as {
|
||||
email: string;
|
||||
password: string;
|
||||
corporateInformation: CorporateInformation;
|
||||
@@ -155,10 +161,10 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
||||
req.session.user = user;
|
||||
await req.session.save();
|
||||
|
||||
res.status(200).json({user});
|
||||
res.status(200).json({ user });
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error);
|
||||
res.status(401).json({error});
|
||||
res.status(401).json({ error });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import client from "@/lib/mongodb";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {Session} from "@/hooks/useSessions";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { Session } from "@/hooks/useSessions";
|
||||
import moment from "moment";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
@@ -17,14 +17,17 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const {user} = req.query as {user?: string};
|
||||
const { user } = req.query as { user?: string };
|
||||
|
||||
const q = user ? {user: user} : {};
|
||||
const sessions = await db.collection("sessions").find<Session>(q).limit(10).toArray();
|
||||
const q = user ? { user: user } : {};
|
||||
const sessions = await db.collection("sessions").find<Session>({
|
||||
...q,
|
||||
}).limit(12).toArray();
|
||||
console.log(sessions)
|
||||
|
||||
res.status(200).json(
|
||||
sessions.filter((x) => {
|
||||
@@ -37,12 +40,12 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const session = req.body;
|
||||
|
||||
await db.collection("sessions").updateOne({id: session.id}, {$set: session}, {upsert: true});
|
||||
await db.collection("sessions").updateOne({ id: session.id }, { $set: session }, { upsert: true });
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
res.status(200).json({ ok: true });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user