Continued updating the code to work with entities better

This commit is contained in:
Tiago Ribeiro
2024-10-07 15:49:58 +01:00
parent b5200c88fc
commit 1ef4efcacf
36 changed files with 2489 additions and 3012 deletions

View File

@@ -1,6 +1,6 @@
import type {NextApiRequest, NextApiResponse} from "next";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import type { NextApiRequest, NextApiResponse } from "next";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { FirebaseScrypt } from 'firebase-scrypt';
import { firebaseAuthScryptParams } from "@/firebase";
import crypto from 'crypto';
@@ -9,53 +9,58 @@ import axios from "axios";
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") return post(req, res);
if (req.method === "POST") return post(req, res);
return res.status(404).json({ok: false});
return res.status(404).json({ ok: false });
}
async function post(req: NextApiRequest, res: NextApiResponse) {
const maker = req.session.user;
if (!maker) {
return res.status(401).json({ok: false, reason: "You must be logged in to make user!"});
}
const maker = req.session.user;
if (!maker) {
return res.status(401).json({ ok: false, reason: "You must be logged in to make user!" });
}
const scrypt = new FirebaseScrypt(firebaseAuthScryptParams)
const scrypt = new FirebaseScrypt(firebaseAuthScryptParams)
const users = req.body.users as {
email: string;
name: string;
type: string;
passport_id: string;
groupName?: string;
corporate?: string;
studentID?: string;
expiryDate?: string;
demographicInformation: {
country?: string;
passport_id?: string;
phone: string;
};
passwordHash: string | undefined;
passwordSalt: string | undefined;
}[];
const users = req.body.users as {
email: string;
name: string;
type: string;
passport_id: string;
groupName?: string;
corporate?: string;
studentID?: string;
expiryDate?: string;
demographicInformation: {
country?: string;
passport_id?: string;
phone: string;
};
entity?: string
entities: { id: string, role: string }[]
passwordHash: string | undefined;
passwordSalt: string | undefined;
}[];
const usersWithPasswordHashes = await Promise.all(users.map(async (user) => {
const currentUser = { ...user };
const salt = crypto.randomBytes(16).toString('base64');
const hash = await scrypt.hash(user.passport_id, salt);
currentUser.email = currentUser.email.toLowerCase();
currentUser.passwordHash = hash;
currentUser.passwordSalt = salt;
return currentUser;
}));
const backendRequest = await axios.post(`${process.env.BACKEND_URL}/batch_users`, { makerID: maker.id, users: usersWithPasswordHashes }, {
headers: {
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
},
});
const usersWithPasswordHashes = await Promise.all(users.map(async (user) => {
const currentUser = { ...user };
const salt = crypto.randomBytes(16).toString('base64');
const hash = await scrypt.hash(user.passport_id, salt);
return res.status(backendRequest.status).json(backendRequest.data)
currentUser.entities = [{ id: currentUser.entity!, role: "90ce8f08-08c8-41e4-9848-f1500ddc3930" }]
delete currentUser.entity
currentUser.email = currentUser.email.toLowerCase();
currentUser.passwordHash = hash;
currentUser.passwordSalt = salt;
return currentUser;
}));
const backendRequest = await axios.post(`${process.env.BACKEND_URL}/batch_users`, { makerID: maker.id, users: usersWithPasswordHashes }, {
headers: {
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
},
});
return res.status(backendRequest.status).json(backendRequest.data)
}

View File

@@ -0,0 +1,32 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { getEntities, getEntitiesWithRoles } from "@/utils/entities.be";
import { Entity, WithEntities, WithEntity, WithLabeledEntities } from "@/interfaces/entity";
import { v4 } from "uuid";
import { mapBy } from "@/utils";
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
import { Group, User } from "@/interfaces/user";
import { getGroups, getGroupsByEntities } from "@/utils/groups.be";
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") return await get(req, res);
}
async function get(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
res.status(401).json({ ok: false });
return;
}
const user = req.session.user;
const groups: WithEntity<Group>[] = ["admin", "developer"].includes(user.type)
? await getGroups()
: await getGroupsByEntities(mapBy(user.entities || [], 'id'))
res.status(200).json(groups);
}

View File

@@ -0,0 +1,47 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { getEntities, getEntitiesWithRoles } from "@/utils/entities.be";
import { Entity, WithEntities, WithLabeledEntities } from "@/interfaces/entity";
import { v4 } from "uuid";
import { mapBy } from "@/utils";
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
import { User } from "@/interfaces/user";
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") return await get(req, res);
}
async function get(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
res.status(401).json({ ok: false });
return;
}
const user = req.session.user;
const { type } = req.query as { type: string }
const entities = await getEntitiesWithRoles(mapBy(user.entities || [], 'id'))
const filter = !type ? undefined : { type }
const users = ["admin", "developer"].includes(user.type)
? await getUsers(filter)
: await getEntitiesUsers(mapBy(entities, 'id') as string[], filter)
const usersWithEntities: WithLabeledEntities<User>[] = users.map((u) => {
return {
...u, entities: (u.entities || []).map((e) => {
const entity = entities.find((x) => x.id === e.id)
if (!entity) return e
const role = entity.roles.find((x) => x.id === e.role)
return { id: e.id, label: entity.label, role: e.role, roleLabel: role?.label }
})
}
})
res.status(200).json(usersWithEntities);
}

View File

@@ -1,28 +1,28 @@
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {v4} from "uuid";
import {CorporateUser, Group, Type, User} from "@/interfaces/user";
import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";
import type { NextApiRequest, NextApiResponse } from "next";
import { app } from "@/firebase";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { v4 } from "uuid";
import { CorporateUser, Group, Type, User } from "@/interfaces/user";
import { createUserWithEmailAndPassword, getAuth } from "firebase/auth";
import ShortUniqueId from "short-unique-id";
import {getGroup, getGroups, getUserCorporate, getUserGroups, getUserNamedGroup} from "@/utils/groups.be";
import {uniq} from "lodash";
import {getSpecificUsers, getUser} from "@/utils/users.be";
import { getGroup, getGroups, getUserCorporate, getUserGroups, getUserNamedGroup } from "@/utils/groups.be";
import { uniq } from "lodash";
import { getSpecificUsers, getUser } from "@/utils/users.be";
import client from "@/lib/mongodb";
const DEFAULT_DESIRED_LEVELS = {
reading: 9,
listening: 9,
writing: 9,
speaking: 9,
reading: 9,
listening: 9,
writing: 9,
speaking: 9,
};
const DEFAULT_LEVELS = {
reading: 0,
listening: 0,
writing: 0,
speaking: 0,
reading: 0,
listening: 0,
writing: 0,
speaking: 0,
};
const auth = getAuth(app);
@@ -30,198 +30,97 @@ const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
const getUsersOfType = async (admin: string, type: Type) => {
const groups = await getUserGroups(admin);
const participants = groups.flatMap((x) => x.participants);
const users = await getSpecificUsers(participants);
return users.filter((x) => x?.type === type).map((x) => x?.id);
};
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") return post(req, res);
if (req.method === "POST") return post(req, res);
return res.status(404).json({ok: false});
return res.status(404).json({ ok: false });
}
async function post(req: NextApiRequest, res: NextApiResponse) {
const maker = req.session.user;
if (!maker) {
return res.status(401).json({ok: false, reason: "You must be logged in to make user!"});
}
const maker = req.session.user;
if (!maker) {
return res.status(401).json({ ok: false, reason: "You must be logged in to make user!" });
}
const corporateCorporate = await getUserCorporate(maker.id);
const { email, passport_id, password, type, groupID, entity, expiryDate, corporate } = req.body as {
email: string;
password?: string;
passport_id: string;
type: string;
entity: string;
groupID?: string;
corporate?: string;
expiryDate: null | Date;
};
const {email, passport_id, password, type, groupID, expiryDate, corporate} = req.body as {
email: string;
password?: string;
passport_id: string;
type: string;
groupID?: string;
corporate?: string;
expiryDate: null | Date;
};
// cleaning data
delete req.body.passport_id;
delete req.body.groupID;
delete req.body.expiryDate;
delete req.body.password;
delete req.body.corporate;
// cleaning data
delete req.body.passport_id;
delete req.body.groupID;
delete req.body.expiryDate;
delete req.body.password;
delete req.body.corporate;
delete req.body.entity
await createUserWithEmailAndPassword(auth, email.toLowerCase(), !!password ? password : passport_id)
.then(async (userCredentials) => {
const userId = userCredentials.user.uid;
await createUserWithEmailAndPassword(auth, email.toLowerCase(), !!password ? password : passport_id)
.then(async (userCredentials) => {
const userId = userCredentials.user.uid;
const profilePicture = !corporateCorporate ? "/defaultAvatar.png" : corporateCorporate.profilePicture;
const user = {
...req.body,
bio: "",
id: userId,
type: type,
focus: "academic",
status: "active",
desiredLevels: DEFAULT_DESIRED_LEVELS,
profilePicture: "/defaultAvatar.png",
levels: DEFAULT_LEVELS,
isFirstLogin: false,
isVerified: true,
registrationDate: new Date(),
entities: [{ id: entity, role: "90ce8f08-08c8-41e4-9848-f1500ddc3930" }],
subscriptionExpirationDate: expiryDate || null,
...((maker.type === "corporate" || maker.type === "mastercorporate") && type === "corporate"
? {
corporateInformation: {
companyInformation: {
name: maker.corporateInformation?.companyInformation?.name || "N/A",
userAmount: 0,
},
},
}
: {}),
};
const user = {
...req.body,
bio: "",
id: userId,
type: type,
focus: "academic",
status: "active",
desiredLevels: DEFAULT_DESIRED_LEVELS,
profilePicture,
levels: DEFAULT_LEVELS,
isFirstLogin: false,
isVerified: true,
registrationDate: new Date(),
subscriptionExpirationDate: expiryDate || null,
...((maker.type === "corporate" || maker.type === "mastercorporate") && type === "corporate"
? {
corporateInformation: {
companyInformation: {
name: maker.corporateInformation?.companyInformation?.name || "N/A",
userAmount: 0,
},
},
}
: {}),
};
const uid = new ShortUniqueId();
const code = uid.randomUUID(6);
const uid = new ShortUniqueId();
const code = uid.randomUUID(6);
await db.collection("users").insertOne(user);
await db.collection("codes").insertOne({
code,
creator: maker.id,
expiryDate,
type,
creationDate: new Date(),
userId,
email: email.toLowerCase(),
name: req.body.name,
...(!!passport_id ? { passport_id } : {}),
});
await db.collection("users").insertOne(user);
await db.collection("codes").insertOne({
code,
creator: maker.id,
expiryDate,
type,
creationDate: new Date(),
userId,
email: email.toLowerCase(),
name: req.body.name,
...(!!passport_id ? {passport_id} : {}),
});
if (!!groupID) {
const group = await getGroup(groupID);
if (!!group) await db.collection("groups").updateOne({ id: group.id }, { $set: { participants: [...group.participants, userId] } });
}
if (type === "corporate") {
const students = maker.type === "corporate" ? await getUsersOfType(maker.id, "student") : [];
const teachers = maker.type === "corporate" ? await getUsersOfType(maker.id, "teacher") : [];
console.log(`Returning - ${email}`);
return res.status(200).json({ ok: true });
})
.catch((error) => {
if (error.code.includes("email-already-in-use")) return res.status(403).json({ error, message: "E-mail is already in the platform." });
const defaultTeachersGroup: Group = {
admin: userId,
id: v4(),
name: "Teachers",
participants: teachers,
disableEditing: true,
};
const defaultStudentsGroup: Group = {
admin: userId,
id: v4(),
name: "Students",
participants: students,
disableEditing: true,
};
await db.collection("groups").insertMany([defaultStudentsGroup, defaultTeachersGroup]);
}
if (!!corporate) {
const corporateUser = await db.collection("users").findOne<CorporateUser>({email: corporate.trim().toLowerCase()});
if (!!corporateUser) {
await db.collection("codes").updateOne({code}, {$set: {creator: corporateUser.id}});
const typeGroup = await db
.collection("groups")
.findOne<Group>({creator: corporateUser.id, name: type === "student" ? "Students" : "Teachers"});
if (!!typeGroup) {
if (!typeGroup.participants.includes(userId)) {
await db.collection("groups").updateOne({id: typeGroup.id}, {$set: {participants: [...typeGroup.participants, userId]}});
}
} else {
const defaultGroup: Group = {
admin: corporateUser.id,
id: v4(),
name: type === "student" ? "Students" : "Teachers",
participants: [userId],
disableEditing: true,
};
await db.collection("groups").insertOne(defaultGroup);
}
}
}
if (maker.type === "corporate") {
await db.collection("codes").updateOne({code}, {$set: {creator: maker.id}});
const typeGroup = await getUserNamedGroup(maker.id, type === "student" ? "Students" : "Teachers");
if (!!typeGroup) {
if (!typeGroup.participants.includes(userId)) {
await db.collection("groups").updateOne({id: typeGroup.id}, {$set: {participants: [...typeGroup.participants, userId]}});
}
} else {
const defaultGroup: Group = {
admin: maker.id,
id: v4(),
name: type === "student" ? "Students" : "Teachers",
participants: [userId],
disableEditing: true,
};
await db.collection("groups").insertOne(defaultGroup);
}
}
if (!!corporateCorporate && corporateCorporate.type === "mastercorporate" && type === "corporate") {
const corporateGroup = await getUserNamedGroup(corporateCorporate.id, "Corporate");
if (!!corporateGroup) {
if (!corporateGroup.participants.includes(userId)) {
await db
.collection("groups")
.updateOne({id: corporateGroup.id}, {$set: {participants: [...corporateGroup.participants, userId]}});
}
} else {
const defaultGroup: Group = {
admin: corporateCorporate.id,
id: v4(),
name: "Corporate",
participants: [userId],
disableEditing: true,
};
await db.collection("groups").insertOne(defaultGroup);
}
}
if (!!groupID) {
const group = await getGroup(groupID);
if (!!group) await db.collection("groups").updateOne({id: group.id}, {$set: {participants: [...group.participants, userId]}});
}
console.log(`Returning - ${email}`);
return res.status(200).json({ok: true});
})
.catch((error) => {
if (error.code.includes("email-already-in-use")) return res.status(403).json({error, message: "E-mail is already in the platform."});
console.log(`Failing - ${email}`);
console.log(error);
return res.status(401).json({error});
});
console.log(`Failing - ${email}`);
console.log(error);
return res.status(401).json({ error });
});
}

View File

@@ -7,7 +7,8 @@ import {withIronSessionApiRoute} from "iron-session/next";
import {NextApiRequest, NextApiResponse} from "next";
import {getPermissions, getPermissionDocs} from "@/utils/permissions.be";
import client from "@/lib/mongodb";
import {getGroupsForUser, getParticipantGroups} from "@/utils/groups.be";
import {getGroupsForUser, getParticipantGroups, removeParticipantFromGroup} from "@/utils/groups.be";
import { mapBy } from "@/utils";
const auth = getAuth(adminApp);
const db = client.db(process.env.MONGODB_DB);
@@ -41,20 +42,6 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
return;
}
if (user.type === "corporate" && (targetUser.type === "student" || targetUser.type === "teacher")) {
const groups = await getGroupsForUser(user.id, targetUser.id);
await Promise.all([
...groups
.filter((x) => x.admin === user.id)
.map(
async (x) =>
await db.collection("groups").updateOne({id: x.id}, {$set: {participants: x.participants.filter((y: string) => y !== id)}}),
),
]);
return;
}
await auth.deleteUser(id);
await db.collection("users").deleteOne({id: targetUser.id});
await db.collection("codes").deleteMany({userId: targetUser.id});
@@ -62,11 +49,10 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
await db.collection("stats").deleteMany({user: targetUser.id});
const groups = await getParticipantGroups(targetUser.id);
await Promise.all(
groups.map(
async (x) => await db.collection("groups").updateOne({id: x.id}, {$set: {participants: x.participants.filter((y: string) => y !== id)}}),
),
);
await Promise.all(
groups
.map(async (g) => await removeParticipantFromGroup(g.id, targetUser.id)),
);
res.json({ok: true});
}