From 800d04da37f25354bf6e28cb0ee0b4eca830efc2 Mon Sep 17 00:00:00 2001 From: Tiago Ribeiro Date: Mon, 29 Jan 2024 09:53:47 +0000 Subject: [PATCH] Updated the login and register to transform the e-mail to lowercase --- src/pages/(admin)/BatchCodeGenerator.tsx | 2 +- src/pages/api/login.ts | 50 ++--- src/pages/api/register.ts | 223 +++++++++++++---------- 3 files changed, 155 insertions(+), 120 deletions(-) diff --git a/src/pages/(admin)/BatchCodeGenerator.tsx b/src/pages/(admin)/BatchCodeGenerator.tsx index 7c8d2f76..ec3e6426 100644 --- a/src/pages/(admin)/BatchCodeGenerator.tsx +++ b/src/pages/(admin)/BatchCodeGenerator.tsx @@ -76,7 +76,7 @@ export default function BatchCodeGenerator({ user }: { user: User }) { ] = row as string[]; return EMAIL_REGEX.test(email.toString().trim()) ? { - email: email.toString().trim(), + email: email.toString().trim().toLowerCase(), name: `${firstName ?? ""} ${lastName ?? ""}`.trim(), passport_id: passport_id?.toString().trim() || undefined, } diff --git a/src/pages/api/login.ts b/src/pages/api/login.ts index eaee7022..6276dc51 100644 --- a/src/pages/api/login.ts +++ b/src/pages/api/login.ts @@ -1,10 +1,10 @@ -import {NextApiRequest, NextApiResponse} from "next"; -import {getAuth, signInWithEmailAndPassword} from "firebase/auth"; -import {app} from "@/firebase"; -import {sessionOptions} from "@/lib/session"; -import {withIronSessionApiRoute} from "iron-session/next"; -import {User} from "@/interfaces/user"; -import {getFirestore, getDoc, doc} from "firebase/firestore"; +import { NextApiRequest, NextApiResponse } from "next"; +import { getAuth, signInWithEmailAndPassword } from "firebase/auth"; +import { app } from "@/firebase"; +import { sessionOptions } from "@/lib/session"; +import { withIronSessionApiRoute } from "iron-session/next"; +import { User } from "@/interfaces/user"; +import { getFirestore, getDoc, doc } from "firebase/firestore"; const auth = getAuth(app); const db = getFirestore(app); @@ -12,27 +12,27 @@ const db = getFirestore(app); export default withIronSessionApiRoute(login, sessionOptions); async function login(req: NextApiRequest, res: NextApiResponse) { - const {email, password} = req.body as {email: string; password: string}; + const { email, password } = req.body as { email: string; password: string }; - signInWithEmailAndPassword(auth, email, password) - .then(async (userCredentials) => { - const userId = userCredentials.user.uid; + signInWithEmailAndPassword(auth, email.toLowerCase(), password) + .then(async (userCredentials) => { + const userId = userCredentials.user.uid; - const docUser = await getDoc(doc(db, "users", userId)); - if (!docUser.exists()) { - res.status(401).json({error: 401, message: "User does not exist!"}); - return; - } + const docUser = await getDoc(doc(db, "users", userId)); + if (!docUser.exists()) { + res.status(401).json({ error: 401, message: "User does not exist!" }); + return; + } - const user = docUser.data() as User; + const user = docUser.data() as User; - req.session.user = {...user, id: userId}; - await req.session.save(); + req.session.user = { ...user, id: userId }; + await req.session.save(); - res.status(200).json({user: {...user, id: userId}}); - }) - .catch((error) => { - console.log(error); - res.status(401).json({error}); - }); + res.status(200).json({ user: { ...user, id: userId } }); + }) + .catch((error) => { + console.log(error); + res.status(401).json({ error }); + }); } diff --git a/src/pages/api/register.ts b/src/pages/api/register.ts index ec609d50..80a2da9a 100644 --- a/src/pages/api/register.ts +++ b/src/pages/api/register.ts @@ -1,11 +1,23 @@ -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 {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore"; -import {CorporateInformation, DemographicInformation, 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 { + getFirestore, + doc, + setDoc, + query, + collection, + where, + getDocs, +} from "firebase/firestore"; +import { + CorporateInformation, + DemographicInformation, + Type, +} from "@/interfaces/user"; +import { addUserToGroupOnCreation } from "@/utils/registration"; import moment from "moment"; const auth = getAuth(app); @@ -14,117 +26,140 @@ const db = getFirestore(app); export default withIronSessionApiRoute(register, sessionOptions); 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, }; async function register(req: NextApiRequest, res: NextApiResponse) { - const {type} = req.body as { - type: "individual" | "corporate"; - }; + const { type } = req.body as { + type: "individual" | "corporate"; + }; - if (type === "individual") return registerIndividual(req, res); - if (type === "corporate") return registerCorporate(req, res); + if (type === "individual") return registerIndividual(req, res); + if (type === "corporate") return registerCorporate(req, res); } async function registerIndividual(req: NextApiRequest, res: NextApiResponse) { - const {email, passport_id, password, code} = req.body as { - email: string; - passport_id?: string; - password: string; - code?: string; - }; + const { email, passport_id, password, code } = req.body as { + email: string; + passport_id?: string; + password: string; + code?: string; + }; - const codeQuery = query(collection(db, "codes"), where("code", "==", code)); - const codeDocs = (await getDocs(codeQuery)).docs.filter((x) => !Object.keys(x.data()).includes("userId")); + const codeQuery = query(collection(db, "codes"), where("code", "==", code)); + const codeDocs = (await getDocs(codeQuery)).docs.filter( + (x) => !Object.keys(x.data()).includes("userId"), + ); - if (code && code.length > 0 && codeDocs.length === 0) { - res.status(400).json({error: "Invalid Code!"}); - return; - } + if (code && code.length > 0 && codeDocs.length === 0) { + res.status(400).json({ error: "Invalid Code!" }); + return; + } - const codeData = codeDocs.length > 0 ? (codeDocs[0].data() as {code: string; type: Type; creator?: string; expiryDate: Date | null}) : undefined; + const codeData = + codeDocs.length > 0 + ? (codeDocs[0].data() as { + code: string; + type: Type; + creator?: string; + expiryDate: Date | null; + }) + : undefined; - createUserWithEmailAndPassword(auth, email, password) - .then(async (userCredentials) => { - const userId = userCredentials.user.uid; - delete req.body.password; + createUserWithEmailAndPassword(auth, email.toLowerCase(), password) + .then(async (userCredentials) => { + const userId = userCredentials.user.uid; + delete req.body.password; - const user = { - ...req.body, - desiredLevels: DEFAULT_DESIRED_LEVELS, - levels: DEFAULT_LEVELS, - bio: "", - isFirstLogin: codeData ? codeData.type === "student" : true, - focus: "academic", - type: email.endsWith("@ecrop.dev") ? "developer" : codeData ? codeData.type : "student", - subscriptionExpirationDate: codeData ? codeData.expiryDate : moment().subtract(1, "days").toISOString(), - ...(passport_id ? {demographicInformation: {passport_id}} : {}), - registrationDate: new Date().toISOString(), - status: code ? "active" : "paymentDue", - }; + const user = { + ...req.body, + email: email.toLowerCase(), + desiredLevels: DEFAULT_DESIRED_LEVELS, + levels: DEFAULT_LEVELS, + bio: "", + isFirstLogin: codeData ? codeData.type === "student" : true, + focus: "academic", + type: email.endsWith("@ecrop.dev") + ? "developer" + : codeData + ? codeData.type + : "student", + subscriptionExpirationDate: codeData + ? codeData.expiryDate + : moment().subtract(1, "days").toISOString(), + ...(passport_id ? { demographicInformation: { passport_id } } : {}), + registrationDate: new Date().toISOString(), + status: code ? "active" : "paymentDue", + }; - await setDoc(doc(db, "users", userId), user); + await setDoc(doc(db, "users", userId), user); - if (codeDocs.length > 0 && codeData) { - await setDoc(codeDocs[0].ref, {userId: userId}, {merge: true}); - if (codeData.creator) await addUserToGroupOnCreation(userId, codeData.type, codeData.creator); - } + if (codeDocs.length > 0 && codeData) { + await setDoc(codeDocs[0].ref, { userId: userId }, { merge: true }); + if (codeData.creator) + await addUserToGroupOnCreation( + userId, + codeData.type, + codeData.creator, + ); + } - req.session.user = {...user, id: userId}; - await req.session.save(); + req.session.user = { ...user, id: userId }; + await req.session.save(); - res.status(200).json({user: {...user, id: userId}}); - }) - .catch((error) => { - console.log(error); - res.status(401).json({error}); - }); + res.status(200).json({ user: { ...user, id: userId } }); + }) + .catch((error) => { + console.log(error); + res.status(401).json({ error }); + }); } async function registerCorporate(req: NextApiRequest, res: NextApiResponse) { - const {email, password} = req.body as { - email: string; - password: string; - corporateInformation: CorporateInformation; - }; + const { email, password } = req.body as { + email: string; + password: string; + corporateInformation: CorporateInformation; + }; - createUserWithEmailAndPassword(auth, email, password) - .then(async (userCredentials) => { - const userId = userCredentials.user.uid; - delete req.body.password; + createUserWithEmailAndPassword(auth, email.toLowerCase(), password) + .then(async (userCredentials) => { + const userId = userCredentials.user.uid; + delete req.body.password; - const user = { - ...req.body, - desiredLevels: DEFAULT_DESIRED_LEVELS, - levels: DEFAULT_LEVELS, - bio: "", - isFirstLogin: false, - focus: "academic", - type: "corporate", - subscriptionExpirationDate: req.body.subscriptionExpirationDate || null, - status: "paymentDue", - registrationDate: new Date().toISOString(), - }; + const user = { + ...req.body, + email: email.toLowerCase(), + desiredLevels: DEFAULT_DESIRED_LEVELS, + levels: DEFAULT_LEVELS, + bio: "", + isFirstLogin: false, + focus: "academic", + type: "corporate", + subscriptionExpirationDate: req.body.subscriptionExpirationDate || null, + status: "paymentDue", + registrationDate: new Date().toISOString(), + }; - await setDoc(doc(db, "users", userId), user); + await setDoc(doc(db, "users", userId), user); - req.session.user = {...user, id: userId}; - await req.session.save(); + req.session.user = { ...user, id: userId }; + await req.session.save(); - res.status(200).json({user: {...user, id: userId}}); - }) - .catch((error) => { - console.log(error); - res.status(401).json({error}); - }); + res.status(200).json({ user: { ...user, id: userId } }); + }) + .catch((error) => { + console.log(error); + res.status(401).json({ error }); + }); }