Files
encoach_frontend/src/pages/api/batch_users.ts
Carlos-Mesquita 61e07dae95 ENCOA-308
2025-01-05 19:04:08 +00:00

71 lines
2.3 KiB
TypeScript

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';
import axios from "axios";
import { getEntityWithRoles } from "@/utils/entities.be";
import { findBy } from "@/utils";
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") return post(req, res);
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 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;
};
entity: { id: string, label: 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);
const entity = await getEntityWithRoles(currentUser.entity!.id)
const defaultRole = findBy(entity?.roles || [], "isDefault", true)
currentUser.entities = [{ id: entity?.id || "", role: defaultRole?.id || "" }]
currentUser.email = currentUser.email.toLowerCase();
currentUser.passwordHash = hash;
currentUser.passwordSalt = salt;
return currentUser;
}));
const backendRequest = await axios.post(`${process.env.BACKEND_URL}/user/import`, { makerID: maker.id, users: usersWithPasswordHashes }, {
headers: {
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
},
});
return res.status(backendRequest.status).json(backendRequest.data)
}