Updated the register endpoint to use MongoDB
This commit is contained in:
@@ -4,13 +4,14 @@ import {app} from "@/firebase";
|
|||||||
import {sessionOptions} from "@/lib/session";
|
import {sessionOptions} from "@/lib/session";
|
||||||
import {withIronSessionApiRoute} from "iron-session/next";
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
import {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore";
|
import {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore";
|
||||||
import {CorporateInformation, DemographicInformation, Group, Type} from "@/interfaces/user";
|
import {Code, CorporateInformation, DemographicInformation, Group, Type} from "@/interfaces/user";
|
||||||
import {addUserToGroupOnCreation} from "@/utils/registration";
|
import {addUserToGroupOnCreation} from "@/utils/registration";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {v4} from "uuid";
|
import {v4} from "uuid";
|
||||||
|
import client from "@/lib/mongodb";
|
||||||
|
|
||||||
const auth = getAuth(app);
|
const auth = getAuth(app);
|
||||||
const db = getFirestore(app);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(register, sessionOptions);
|
export default withIronSessionApiRoute(register, sessionOptions);
|
||||||
|
|
||||||
@@ -45,24 +46,13 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
code?: string;
|
code?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const codeQuery = query(collection(db, "codes"), where("code", "==", code));
|
const codeDoc = await db.collection("codes").findOne<Code>({code});
|
||||||
const codeDocs = (await getDocs(codeQuery)).docs.filter((x) => !Object.keys(x.data()).includes("userId"));
|
|
||||||
|
|
||||||
if (code && code.length > 0 && codeDocs.length === 0) {
|
if (code && code.length > 0 && !!codeDoc) {
|
||||||
res.status(400).json({error: "Invalid Code!"});
|
res.status(400).json({error: "Invalid Code!"});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const codeData =
|
|
||||||
codeDocs.length > 0
|
|
||||||
? (codeDocs[0].data() as {
|
|
||||||
code: string;
|
|
||||||
type: Type;
|
|
||||||
creator?: string;
|
|
||||||
expiryDate: Date | null;
|
|
||||||
})
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
createUserWithEmailAndPassword(auth, email.toLowerCase(), password)
|
createUserWithEmailAndPassword(auth, email.toLowerCase(), password)
|
||||||
.then(async (userCredentials) => {
|
.then(async (userCredentials) => {
|
||||||
const userId = userCredentials.user.uid;
|
const userId = userCredentials.user.uid;
|
||||||
@@ -70,31 +60,32 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
const user = {
|
const user = {
|
||||||
...req.body,
|
...req.body,
|
||||||
|
id: userId,
|
||||||
email: email.toLowerCase(),
|
email: email.toLowerCase(),
|
||||||
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
||||||
levels: DEFAULT_LEVELS,
|
levels: DEFAULT_LEVELS,
|
||||||
bio: "",
|
bio: "",
|
||||||
isFirstLogin: codeData ? codeData.type === "student" : true,
|
isFirstLogin: codeDoc ? codeDoc.type === "student" : true,
|
||||||
profilePicture: "/defaultAvatar.png",
|
profilePicture: "/defaultAvatar.png",
|
||||||
focus: "academic",
|
focus: "academic",
|
||||||
type: email.endsWith("@ecrop.dev") ? "developer" : codeData ? codeData.type : "student",
|
type: email.endsWith("@ecrop.dev") ? "developer" : codeDoc ? codeDoc.type : "student",
|
||||||
subscriptionExpirationDate: codeData ? codeData.expiryDate : moment().subtract(1, "days").toISOString(),
|
subscriptionExpirationDate: codeDoc ? codeDoc.expiryDate : moment().subtract(1, "days").toISOString(),
|
||||||
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
||||||
registrationDate: new Date().toISOString(),
|
registrationDate: new Date().toISOString(),
|
||||||
status: code ? "active" : "paymentDue",
|
status: code ? "active" : "paymentDue",
|
||||||
};
|
};
|
||||||
|
|
||||||
await setDoc(doc(db, "users", userId), user);
|
await db.collection("users").insertOne(user);
|
||||||
|
|
||||||
if (codeDocs.length > 0 && codeData) {
|
if (!!codeDoc) {
|
||||||
await setDoc(codeDocs[0].ref, {userId: userId}, {merge: true});
|
await db.collection("codes").updateOne({code: codeDoc.code}, {$set: {userId}});
|
||||||
if (codeData.creator) await addUserToGroupOnCreation(userId, codeData.type, codeData.creator);
|
if (codeDoc.creator) await addUserToGroupOnCreation(userId, codeDoc.type, codeDoc.creator);
|
||||||
}
|
}
|
||||||
|
|
||||||
req.session.user = {...user, id: userId};
|
req.session.user = user;
|
||||||
await req.session.save();
|
await req.session.save();
|
||||||
|
|
||||||
res.status(200).json({user: {...user, id: userId}});
|
res.status(200).json({user});
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
@@ -116,6 +107,7 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
const user = {
|
const user = {
|
||||||
...req.body,
|
...req.body,
|
||||||
|
id: userId,
|
||||||
email: email.toLowerCase(),
|
email: email.toLowerCase(),
|
||||||
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
||||||
levels: DEFAULT_LEVELS,
|
levels: DEFAULT_LEVELS,
|
||||||
@@ -152,15 +144,13 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
disableEditing: true,
|
disableEditing: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
await setDoc(doc(db, "users", userId), user);
|
await db.collection("users").insertOne(user);
|
||||||
await setDoc(doc(db, "groups", defaultTeachersGroup.id), defaultTeachersGroup);
|
await db.collection("groups").insertMany([defaultCorporateGroup, defaultStudentsGroup, defaultTeachersGroup]);
|
||||||
await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
|
|
||||||
await setDoc(doc(db, "groups", defaultCorporateGroup.id), defaultCorporateGroup);
|
|
||||||
|
|
||||||
req.session.user = {...user, id: userId};
|
req.session.user = user;
|
||||||
await req.session.save();
|
await req.session.save();
|
||||||
|
|
||||||
res.status(200).json({user: {...user, id: userId}});
|
res.status(200).json({user});
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
|
|||||||
@@ -2,30 +2,28 @@ import {collection, doc, getDoc, getDocs, getFirestore, query, setDoc, where} fr
|
|||||||
import {app} from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import {Group, Type, User} from "@/interfaces/user";
|
import {Group, Type, User} from "@/interfaces/user";
|
||||||
import {uuidv4} from "@firebase/util";
|
import {uuidv4} from "@firebase/util";
|
||||||
|
import client from "@/lib/mongodb";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export const addUserToGroupOnCreation = async (userId: string, type: Type, creatorId: string) => {
|
export const addUserToGroupOnCreation = async (userId: string, type: Type, creatorId: string) => {
|
||||||
const creatorDoc = await getDoc(doc(db, "users", creatorId));
|
const creator = await db.collection("users").findOne<User>({id: creatorId});
|
||||||
if (!creatorDoc.exists()) return false;
|
if (!creator) return false;
|
||||||
|
|
||||||
const creator = {...creatorDoc.data(), id: creatorDoc.id} as User;
|
const creatorGroup = await db.collection("groups").findOne<Group>({admin: creator.id, name: type === "student" ? "Students" : "Teachers"});
|
||||||
|
|
||||||
const creatorGroupsDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", creator.id)));
|
if (!!creatorGroup) {
|
||||||
const typeGroup = creatorGroupsDocs.docs.find((x) => (x.data() as Group).name === (type === "student" ? "Students" : "Teachers"));
|
await db.collection("groups").updateOne({id: creatorGroup.id}, {$set: {participants: [...creatorGroup.participants, userId]}});
|
||||||
|
|
||||||
if (typeGroup && typeGroup.exists()) {
|
|
||||||
await setDoc(typeGroup.ref, {participants: [...typeGroup.data().participants, userId]}, {merge: true});
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupId = uuidv4();
|
const groupId = uuidv4();
|
||||||
await setDoc(doc(db, "groups", groupId), {
|
await db.collection("groups").insertOne({
|
||||||
admin: creatorId,
|
admin: creatorId,
|
||||||
name: type === "student" ? "Students" : "Teachers",
|
name: type === "student" ? "Students" : "Teachers",
|
||||||
id: groupId,
|
id: groupId,
|
||||||
participants: [userId],
|
participants: [userId],
|
||||||
disableEditing: true,
|
disableEditing: true,
|
||||||
} as Group);
|
});
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user