Solved a bug where users could change their e-mail to another user's email

This commit is contained in:
Tiago Ribeiro
2024-03-26 16:13:39 +00:00
parent bf6c805487
commit 259ed03ee4
4 changed files with 244 additions and 238 deletions

View File

@@ -1,4 +1,4 @@
export type Error = "E001" | "E002"; export type Error = "E001" | "E002" | "E003";
export interface ErrorMessage { export interface ErrorMessage {
error: Error; error: Error;
message: string; message: string;
@@ -7,4 +7,5 @@ export interface ErrorMessage {
export const errorMessages: {[key in Error]: string} = { export const errorMessages: {[key in Error]: string} = {
E001: "Wrong password!", E001: "Wrong password!",
E002: "Invalid e-mail", E002: "Invalid e-mail",
E003: "E-mail already in use!",
}; };

View File

@@ -1,24 +1,13 @@
import { NextApiRequest, NextApiResponse } from "next"; import {NextApiRequest, NextApiResponse} from "next";
import { createUserWithEmailAndPassword, getAuth } from "firebase/auth"; import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";
import { app } from "@/firebase"; 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 { import {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore";
getFirestore, import {CorporateInformation, DemographicInformation, Group, Type} from "@/interfaces/user";
doc, import {addUserToGroupOnCreation} from "@/utils/registration";
setDoc,
query,
collection,
where,
getDocs,
} from "firebase/firestore";
import {
CorporateInformation,
DemographicInformation,
Type,
} from "@/interfaces/user";
import { addUserToGroupOnCreation } from "@/utils/registration";
import moment from "moment"; import moment from "moment";
import {v4} from "uuid";
const auth = getAuth(app); const auth = getAuth(app);
const db = getFirestore(app); const db = getFirestore(app);
@@ -26,140 +15,145 @@ const db = getFirestore(app);
export default withIronSessionApiRoute(register, sessionOptions); export default withIronSessionApiRoute(register, sessionOptions);
const DEFAULT_DESIRED_LEVELS = { const DEFAULT_DESIRED_LEVELS = {
reading: 9, reading: 9,
listening: 9, listening: 9,
writing: 9, writing: 9,
speaking: 9, speaking: 9,
}; };
const DEFAULT_LEVELS = { const DEFAULT_LEVELS = {
reading: 0, reading: 0,
listening: 0, listening: 0,
writing: 0, writing: 0,
speaking: 0, speaking: 0,
}; };
async function register(req: NextApiRequest, res: NextApiResponse) { async function register(req: NextApiRequest, res: NextApiResponse) {
const { type } = req.body as { const {type} = req.body as {
type: "individual" | "corporate"; type: "individual" | "corporate";
}; };
if (type === "individual") return registerIndividual(req, res); if (type === "individual") return registerIndividual(req, res);
if (type === "corporate") return registerCorporate(req, res); if (type === "corporate") return registerCorporate(req, res);
} }
async function registerIndividual(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; email: string;
passport_id?: string; passport_id?: string;
password: string; password: string;
code?: string; code?: string;
}; };
const codeQuery = query(collection(db, "codes"), where("code", "==", code)); const codeQuery = query(collection(db, "codes"), where("code", "==", code));
const codeDocs = (await getDocs(codeQuery)).docs.filter( const codeDocs = (await getDocs(codeQuery)).docs.filter((x) => !Object.keys(x.data()).includes("userId"));
(x) => !Object.keys(x.data()).includes("userId"),
);
if (code && code.length > 0 && codeDocs.length === 0) { if (code && code.length > 0 && codeDocs.length === 0) {
res.status(400).json({ error: "Invalid Code!" }); res.status(400).json({error: "Invalid Code!"});
return; return;
} }
const codeData = const codeData =
codeDocs.length > 0 codeDocs.length > 0
? (codeDocs[0].data() as { ? (codeDocs[0].data() as {
code: string; code: string;
type: Type; type: Type;
creator?: string; creator?: string;
expiryDate: Date | null; expiryDate: Date | null;
}) })
: undefined; : 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;
delete req.body.password; delete req.body.password;
const user = { const user = {
...req.body, ...req.body,
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: codeData ? codeData.type === "student" : true,
focus: "academic", focus: "academic",
type: email.endsWith("@ecrop.dev") type: email.endsWith("@ecrop.dev") ? "developer" : codeData ? codeData.type : "student",
? "developer" subscriptionExpirationDate: codeData ? codeData.expiryDate : moment().subtract(1, "days").toISOString(),
: codeData ...(passport_id ? {demographicInformation: {passport_id}} : {}),
? codeData.type registrationDate: new Date().toISOString(),
: "student", status: code ? "active" : "paymentDue",
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) { if (codeDocs.length > 0 && codeData) {
await setDoc(codeDocs[0].ref, { userId: userId }, { merge: true }); await setDoc(codeDocs[0].ref, {userId: userId}, {merge: true});
if (codeData.creator) if (codeData.creator) await addUserToGroupOnCreation(userId, codeData.type, codeData.creator);
await addUserToGroupOnCreation( }
userId,
codeData.type,
codeData.creator,
);
}
req.session.user = { ...user, id: userId }; req.session.user = {...user, id: userId};
await req.session.save(); await req.session.save();
res.status(200).json({ user: { ...user, id: userId } }); res.status(200).json({user: {...user, id: userId}});
}) })
.catch((error) => { .catch((error) => {
console.log(error); console.log(error);
res.status(401).json({ error }); res.status(401).json({error});
}); });
} }
async function registerCorporate(req: NextApiRequest, res: NextApiResponse) { async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
const { email, password } = req.body as { const {email, password} = req.body as {
email: string; email: string;
password: string; password: string;
corporateInformation: CorporateInformation; corporateInformation: CorporateInformation;
}; };
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;
delete req.body.password; delete req.body.password;
const user = { const user = {
...req.body, ...req.body,
email: email.toLowerCase(), email: email.toLowerCase(),
desiredLevels: DEFAULT_DESIRED_LEVELS, desiredLevels: DEFAULT_DESIRED_LEVELS,
levels: DEFAULT_LEVELS, levels: DEFAULT_LEVELS,
bio: "", bio: "",
isFirstLogin: false, isFirstLogin: false,
focus: "academic", focus: "academic",
type: "corporate", type: "corporate",
subscriptionExpirationDate: req.body.subscriptionExpirationDate || null, subscriptionExpirationDate: req.body.subscriptionExpirationDate || null,
status: "paymentDue", status: "paymentDue",
registrationDate: new Date().toISOString(), registrationDate: new Date().toISOString(),
}; };
await setDoc(doc(db, "users", userId), user); const defaultTeachersGroup: Group = {
admin: userId,
id: v4(),
name: "Teachers",
participants: [],
disableEditing: true,
};
req.session.user = { ...user, id: userId }; const defaultStudentsGroup: Group = {
await req.session.save(); admin: userId,
id: v4(),
name: "Students",
participants: [],
disableEditing: true,
};
res.status(200).json({ user: { ...user, id: userId } }); await setDoc(doc(db, "users", userId), user);
}) await setDoc(doc(db, "groups", defaultTeachersGroup.id), defaultTeachersGroup);
.catch((error) => { await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
console.log(error);
res.status(401).json({ error }); 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});
});
} }

View File

@@ -12,7 +12,7 @@ import moment from "moment";
import ShortUniqueId from "short-unique-id"; import ShortUniqueId from "short-unique-id";
import {Payment} from "@/interfaces/paypal"; import {Payment} from "@/interfaces/paypal";
import {toFixedNumber} from "@/utils/number"; import {toFixedNumber} from "@/utils/number";
import { propagateStatusChange } from '@/utils/propagate.user.changes'; import {propagateStatusChange} from "@/utils/propagate.user.changes";
const db = getFirestore(app); const db = getFirestore(app);
const auth = getAuth(app); const auth = getAuth(app);
@@ -85,7 +85,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const user = await setDoc(userRef, updatedUser, {merge: true}); const user = await setDoc(userRef, updatedUser, {merge: true});
await managePaymentRecords(updatedUser, updatedUser.id); await managePaymentRecords(updatedUser, updatedUser.id);
if(updatedUser.status) { if (updatedUser.status) {
// there's no await as this does not affect the user // there's no await as this does not affect the user
propagateStatusChange(queryId, updatedUser.status); propagateStatusChange(queryId, updatedUser.status);
} }
@@ -117,6 +117,12 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
if (updatedUser.email !== req.session.user.email && updatedUser.password) { if (updatedUser.email !== req.session.user.email && updatedUser.password) {
try { try {
const usersWithSameEmail = await getDocs(query(collection(db, "users"), where("email", "==", updatedUser.email.toLowerCase())));
if (usersWithSameEmail.docs.length > 0) {
res.status(400).json({error: "E003", message: errorMessages.E003});
return;
}
const credential = await signInWithEmailAndPassword(auth, req.session.user.email, updatedUser.password); const credential = await signInWithEmailAndPassword(auth, req.session.user.email, updatedUser.password);
await updateEmail(credential.user, updatedUser.email); await updateEmail(credential.user, updatedUser.email);
@@ -142,7 +148,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
} }
} }
if(updatedUser.status) { if (updatedUser.status) {
// there's no await as this does not affect the user // there's no await as this does not affect the user
propagateStatusChange(req.session.user.id, updatedUser.status); propagateStatusChange(req.session.user.id, updatedUser.status);
} }

View File

@@ -64,6 +64,8 @@ interface Props {
mutateUser: Function; mutateUser: Function;
} }
const DoubleColumnRow = ({children}: {children: ReactNode}) => <div className="flex flex-col md:flex-row gap-8 w-full">{children}</div>;
function UserProfile({user, mutateUser}: Props) { function UserProfile({user, mutateUser}: Props) {
const [bio, setBio] = useState(user.bio || ""); const [bio, setBio] = useState(user.bio || "");
const [name, setName] = useState(user.name || ""); const [name, setName] = useState(user.name || "");
@@ -150,106 +152,45 @@ function UserProfile({user, mutateUser}: Props) {
} }
} }
const request = await axios.post("/api/users/update", { axios
bio, .post("/api/users/update", {
name, bio,
email, name,
password, email,
newPassword, password,
profilePicture, newPassword,
desiredLevels, profilePicture,
preferredGender, desiredLevels,
preferredTopics, preferredGender,
demographicInformation: { preferredTopics,
phone, demographicInformation: {
country, phone,
employment: user?.type === "corporate" ? undefined : employment, country,
position: user?.type === "corporate" ? position : undefined, employment: user?.type === "corporate" ? undefined : employment,
gender, position: user?.type === "corporate" ? position : undefined,
passport_id, gender,
timezone, passport_id,
}, timezone,
...(user.type === "corporate" ? {corporateInformation} : {}), },
}); ...(user.type === "corporate" ? {corporateInformation} : {}),
if (request.status === 200) { })
toast.success("Your profile has been updated!"); .then((response) => {
mutateUser((request.data as {user: User}).user); if (response.status === 200) {
setIsLoading(false); toast.success("Your profile has been updated!");
return; mutateUser((response.data as {user: User}).user);
} setIsLoading(false);
return;
toast.error((request.data as ErrorMessage).message); }
setIsLoading(false); })
.catch((error) => {
console.log(error);
toast.error((error.response.data as ErrorMessage).message);
})
.finally(() => {
setIsLoading(false);
});
}; };
const DoubleColumnRow = ({children}: {children: ReactNode}) => <div className="flex flex-col md:flex-row gap-8 w-full">{children}</div>;
const PasswordInput = () => (
<DoubleColumnRow>
<Input
label="Current Password"
type="password"
name="password"
onChange={(e) => setPassword(e)}
placeholder="Enter your password"
required
/>
<Input
label="New Password"
type="password"
name="newPassword"
onChange={(e) => setNewPassword(e)}
placeholder="Enter your new password (optional)"
/>
</DoubleColumnRow>
);
const NameInput = () => (
<Input label="Name" type="text" name="name" onChange={(e) => setName(e)} placeholder="Enter your name" defaultValue={name} required />
);
const AgentInformationInput = () => (
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 w-full">
<Input
label="Corporate Name"
type="text"
name="companyName"
onChange={() => null}
placeholder="Enter corporate name"
defaultValue={companyName}
disabled
/>
<Input
label="Commercial Registration"
type="text"
name="commercialRegistration"
onChange={() => null}
placeholder="Enter commercial registration"
defaultValue={commercialRegistration}
disabled
/>
</div>
);
const CountryInput = () => (
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Country *</label>
<CountrySelect value={country} onChange={setCountry} />
</div>
);
const PhoneInput = () => (
<Input
type="tel"
name="phone"
label="Phone number"
onChange={(e) => setPhone(e)}
placeholder="Enter phone number"
defaultValue={phone}
required
/>
);
const ExpirationDate = () => ( const ExpirationDate = () => (
<div className="flex flex-col gap-3 w-full"> <div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Expiry Date (click to purchase)</label> <label className="font-normal text-base text-mti-gray-dim">Expiry Date (click to purchase)</label>
@@ -276,7 +217,7 @@ function UserProfile({user, mutateUser}: Props) {
</div> </div>
); );
const manualDownloadLink = ['student', 'teacher', 'corporate'].includes(user.type) ? `/manuals/${user.type}.pdf` : ''; const manualDownloadLink = ["student", "teacher", "corporate"].includes(user.type) ? `/manuals/${user.type}.pdf` : "";
return ( return (
<Layout user={user}> <Layout user={user}>
@@ -288,7 +229,15 @@ function UserProfile({user, mutateUser}: Props) {
<form className="flex flex-col items-center gap-6 w-full"> <form className="flex flex-col items-center gap-6 w-full">
<DoubleColumnRow> <DoubleColumnRow>
{user.type !== "corporate" ? ( {user.type !== "corporate" ? (
<NameInput /> <Input
label="Name"
type="text"
name="name"
onChange={(e) => setName(e)}
placeholder="Enter your name"
defaultValue={name}
required
/>
) : ( ) : (
<Input <Input
label="Company name" label="Company name"
@@ -316,12 +265,60 @@ function UserProfile({user, mutateUser}: Props) {
required required
/> />
</DoubleColumnRow> </DoubleColumnRow>
<PasswordInput /> <DoubleColumnRow>
{user.type === "agent" && <AgentInformationInput />} <Input
label="Current Password"
type="password"
name="password"
onChange={(e) => setPassword(e)}
placeholder="Enter your password"
required
/>
<Input
label="New Password"
type="password"
name="newPassword"
onChange={(e) => setNewPassword(e)}
placeholder="Enter your new password (optional)"
/>
</DoubleColumnRow>
{user.type === "agent" && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 w-full">
<Input
label="Corporate Name"
type="text"
name="companyName"
onChange={() => null}
placeholder="Enter corporate name"
defaultValue={companyName}
disabled
/>
<Input
label="Commercial Registration"
type="text"
name="commercialRegistration"
onChange={() => null}
placeholder="Enter commercial registration"
defaultValue={commercialRegistration}
disabled
/>
</div>
)}
<DoubleColumnRow> <DoubleColumnRow>
<CountryInput /> <div className="flex flex-col gap-3 w-full">
<PhoneInput /> <label className="font-normal text-base text-mti-gray-dim">Country *</label>
<CountrySelect value={country} onChange={setCountry} />
</div>
<Input
type="tel"
name="phone"
label="Phone number"
onChange={(e) => setPhone(e)}
placeholder="Enter phone number"
defaultValue={phone}
required
/>
</DoubleColumnRow> </DoubleColumnRow>
{user.type === "student" ? ( {user.type === "student" ? (
@@ -426,7 +423,15 @@ function UserProfile({user, mutateUser}: Props) {
<> <>
<Divider /> <Divider />
<DoubleColumnRow> <DoubleColumnRow>
<NameInput /> <Input
label="Name"
type="text"
name="name"
onChange={(e) => setName(e)}
placeholder="Enter your name"
defaultValue={name}
required
/>
<Input <Input
name="position" name="position"
onChange={setPosition} onChange={setPosition}