Solved a bug where users could change their e-mail to another user's email
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
export type Error = "E001" | "E002";
|
||||
export type Error = "E001" | "E002" | "E003";
|
||||
export interface ErrorMessage {
|
||||
error: Error;
|
||||
message: string;
|
||||
@@ -7,4 +7,5 @@ export interface ErrorMessage {
|
||||
export const errorMessages: {[key in Error]: string} = {
|
||||
E001: "Wrong password!",
|
||||
E002: "Invalid e-mail",
|
||||
E003: "E-mail already in use!",
|
||||
};
|
||||
|
||||
@@ -3,22 +3,11 @@ 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 {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore";
|
||||
import {CorporateInformation, DemographicInformation, Group, Type} from "@/interfaces/user";
|
||||
import {addUserToGroupOnCreation} from "@/utils/registration";
|
||||
import moment from "moment";
|
||||
import {v4} from "uuid";
|
||||
|
||||
const auth = getAuth(app);
|
||||
const db = getFirestore(app);
|
||||
@@ -57,9 +46,7 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
||||
};
|
||||
|
||||
const codeQuery = query(collection(db, "codes"), where("code", "==", code));
|
||||
const codeDocs = (await getDocs(codeQuery)).docs.filter(
|
||||
(x) => !Object.keys(x.data()).includes("userId"),
|
||||
);
|
||||
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!"});
|
||||
@@ -89,14 +76,8 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
||||
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(),
|
||||
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",
|
||||
@@ -106,12 +87,7 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
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 (codeData.creator) await addUserToGroupOnCreation(userId, codeData.type, codeData.creator);
|
||||
}
|
||||
|
||||
req.session.user = {...user, id: userId};
|
||||
@@ -151,7 +127,25 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
||||
registrationDate: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const defaultTeachersGroup: Group = {
|
||||
admin: userId,
|
||||
id: v4(),
|
||||
name: "Teachers",
|
||||
participants: [],
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
const defaultStudentsGroup: Group = {
|
||||
admin: userId,
|
||||
id: v4(),
|
||||
name: "Students",
|
||||
participants: [],
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
await setDoc(doc(db, "users", userId), user);
|
||||
await setDoc(doc(db, "groups", defaultTeachersGroup.id), defaultTeachersGroup);
|
||||
await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
|
||||
|
||||
req.session.user = {...user, id: userId};
|
||||
await req.session.save();
|
||||
|
||||
@@ -12,7 +12,7 @@ import moment from "moment";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import {Payment} from "@/interfaces/paypal";
|
||||
import {toFixedNumber} from "@/utils/number";
|
||||
import { propagateStatusChange } from '@/utils/propagate.user.changes';
|
||||
import {propagateStatusChange} from "@/utils/propagate.user.changes";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const auth = getAuth(app);
|
||||
@@ -117,6 +117,12 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
if (updatedUser.email !== req.session.user.email && updatedUser.password) {
|
||||
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);
|
||||
await updateEmail(credential.user, updatedUser.email);
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ interface Props {
|
||||
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) {
|
||||
const [bio, setBio] = useState(user.bio || "");
|
||||
const [name, setName] = useState(user.name || "");
|
||||
@@ -150,7 +152,8 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
const request = await axios.post("/api/users/update", {
|
||||
axios
|
||||
.post("/api/users/update", {
|
||||
bio,
|
||||
name,
|
||||
email,
|
||||
@@ -170,86 +173,24 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
timezone,
|
||||
},
|
||||
...(user.type === "corporate" ? {corporateInformation} : {}),
|
||||
});
|
||||
if (request.status === 200) {
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.status === 200) {
|
||||
toast.success("Your profile has been updated!");
|
||||
mutateUser((request.data as {user: User}).user);
|
||||
mutateUser((response.data as {user: User}).user);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error((request.data as ErrorMessage).message);
|
||||
})
|
||||
.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 = () => (
|
||||
<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>
|
||||
@@ -276,7 +217,7 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
</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 (
|
||||
<Layout user={user}>
|
||||
@@ -288,7 +229,15 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
<form className="flex flex-col items-center gap-6 w-full">
|
||||
<DoubleColumnRow>
|
||||
{user.type !== "corporate" ? (
|
||||
<NameInput />
|
||||
<Input
|
||||
label="Name"
|
||||
type="text"
|
||||
name="name"
|
||||
onChange={(e) => setName(e)}
|
||||
placeholder="Enter your name"
|
||||
defaultValue={name}
|
||||
required
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
label="Company name"
|
||||
@@ -316,12 +265,60 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
required
|
||||
/>
|
||||
</DoubleColumnRow>
|
||||
<PasswordInput />
|
||||
{user.type === "agent" && <AgentInformationInput />}
|
||||
<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>
|
||||
{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>
|
||||
<CountryInput />
|
||||
<PhoneInput />
|
||||
<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>
|
||||
<Input
|
||||
type="tel"
|
||||
name="phone"
|
||||
label="Phone number"
|
||||
onChange={(e) => setPhone(e)}
|
||||
placeholder="Enter phone number"
|
||||
defaultValue={phone}
|
||||
required
|
||||
/>
|
||||
</DoubleColumnRow>
|
||||
|
||||
{user.type === "student" ? (
|
||||
@@ -426,7 +423,15 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
<>
|
||||
<Divider />
|
||||
<DoubleColumnRow>
|
||||
<NameInput />
|
||||
<Input
|
||||
label="Name"
|
||||
type="text"
|
||||
name="name"
|
||||
onChange={(e) => setName(e)}
|
||||
placeholder="Enter your name"
|
||||
defaultValue={name}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
name="position"
|
||||
onChange={setPosition}
|
||||
|
||||
Reference in New Issue
Block a user