Updated the login and register to transform the e-mail to lowercase

This commit is contained in:
Tiago Ribeiro
2024-01-29 09:51:11 +00:00
parent cf1cb6f270
commit a862e59574
4 changed files with 716 additions and 523 deletions

View File

@@ -1,215 +1,279 @@
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import {User} from "@/interfaces/user"; import { User } from "@/interfaces/user";
import {sendEmailVerification} from "@/utils/email"; import { sendEmailVerification } from "@/utils/email";
import axios from "axios"; import axios from "axios";
import {Divider} from "primereact/divider"; import { Divider } from "primereact/divider";
import {useState} from "react"; import { useState } from "react";
import {toast} from "react-toastify"; import { toast } from "react-toastify";
import {KeyedMutator} from "swr"; import { KeyedMutator } from "swr";
import Select from "react-select"; import Select from "react-select";
import moment from "moment"; import moment from "moment";
interface Props { interface Props {
isLoading: boolean; isLoading: boolean;
setIsLoading: (isLoading: boolean) => void; setIsLoading: (isLoading: boolean) => void;
mutateUser: KeyedMutator<User>; mutateUser: KeyedMutator<User>;
sendEmailVerification: typeof sendEmailVerification; sendEmailVerification: typeof sendEmailVerification;
} }
const availableDurations = { const availableDurations = {
"1_month": {label: "1 Month", number: 1}, "1_month": { label: "1 Month", number: 1 },
"3_months": {label: "3 Months", number: 3}, "3_months": { label: "3 Months", number: 3 },
"6_months": {label: "6 Months", number: 6}, "6_months": { label: "6 Months", number: 6 },
"12_months": {label: "12 Months", number: 12}, "12_months": { label: "12 Months", number: 12 },
}; };
export default function RegisterCorporate({isLoading, setIsLoading, mutateUser, sendEmailVerification}: Props) { export default function RegisterCorporate({
const [name, setName] = useState(""); isLoading,
const [email, setEmail] = useState(""); setIsLoading,
const [password, setPassword] = useState(""); mutateUser,
const [confirmPassword, setConfirmPassword] = useState(""); sendEmailVerification,
const [referralAgent, setReferralAgent] = useState<string | undefined>(); }: Props) {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [referralAgent, setReferralAgent] = useState<string | undefined>();
const [companyName, setCompanyName] = useState(""); const [companyName, setCompanyName] = useState("");
const [companyUsers, setCompanyUsers] = useState(0); const [companyUsers, setCompanyUsers] = useState(0);
const [subscriptionDuration, setSubscriptionDuration] = useState(1); const [subscriptionDuration, setSubscriptionDuration] = useState(1);
const {users} = useUsers(); const { users } = useUsers();
const onSuccess = () => toast.success("An e-mail has been sent, please make sure to check your spam folder!"); const onSuccess = () =>
toast.success(
"An e-mail has been sent, please make sure to check your spam folder!",
);
const onError = (e: Error) => { const onError = (e: Error) => {
console.error(e); console.error(e);
toast.error("Something went wrong, please logout and re-login.", {toastId: "send-verify-error"}); toast.error("Something went wrong, please logout and re-login.", {
}; toastId: "send-verify-error",
});
};
const register = (e: any) => { const register = (e: any) => {
e.preventDefault(); e.preventDefault();
if (confirmPassword !== password) { if (confirmPassword !== password) {
toast.error("Your passwords do not match!", {toastId: "password-not-match"}); toast.error("Your passwords do not match!", {
return; toastId: "password-not-match",
} });
return;
}
setIsLoading(true); setIsLoading(true);
axios axios
.post("/api/register", { .post("/api/register", {
name, name,
email, email,
password, password,
type: "corporate", type: "corporate",
profilePicture: "/defaultAvatar.png", profilePicture: "/defaultAvatar.png",
subscriptionExpirationDate: moment().subtract(1, "days").toISOString(), subscriptionExpirationDate: moment().subtract(1, "days").toISOString(),
corporateInformation: { corporateInformation: {
companyInformation: { companyInformation: {
name: companyName, name: companyName,
userAmount: companyUsers, userAmount: companyUsers,
}, },
monthlyDuration: subscriptionDuration, monthlyDuration: subscriptionDuration,
referralAgent, referralAgent,
}, },
}) })
.then((response) => { .then((response) => {
mutateUser(response.data.user).then(() => sendEmailVerification(setIsLoading, onSuccess, onError)); mutateUser(response.data.user).then(() =>
}) sendEmailVerification(setIsLoading, onSuccess, onError),
.catch((error) => { );
console.log(error.response.data); })
.catch((error) => {
console.log(error.response.data);
if (error.response.status === 401) { if (error.response.status === 401) {
toast.error("There is already a user with that e-mail!"); toast.error("There is already a user with that e-mail!");
return; return;
} }
if (error.response.status === 400) { if (error.response.status === 400) {
toast.error("The provided code is invalid!"); toast.error("The provided code is invalid!");
return; return;
} }
toast.error("There was something wrong, please try again!"); toast.error("There was something wrong, please try again!");
}) })
.finally(() => setIsLoading(false)); .finally(() => setIsLoading(false));
}; };
return ( return (
<form className="flex flex-col items-center gap-4 w-full" onSubmit={register}> <form
<div className="w-full flex gap-4"> className="flex w-full flex-col items-center gap-4"
<Input type="text" name="name" onChange={(e) => setName(e)} placeholder="Enter your name" defaultValue={name} required /> onSubmit={register}
<Input type="email" name="email" onChange={(e) => setEmail(e)} placeholder="Enter email address" defaultValue={email} required /> >
</div> <div className="flex w-full gap-4">
<Input
type="text"
name="name"
onChange={(e) => setName(e)}
placeholder="Enter your name"
defaultValue={name}
required
/>
<Input
type="email"
name="email"
onChange={(e) => setEmail(e.toLowerCase())}
placeholder="Enter email address"
defaultValue={email}
required
/>
</div>
<div className="w-full flex gap-4"> <div className="flex w-full gap-4">
<Input <Input
type="password" type="password"
name="password" name="password"
onChange={(e) => setPassword(e)} onChange={(e) => setPassword(e)}
placeholder="Enter your password" placeholder="Enter your password"
defaultValue={password} defaultValue={password}
required required
/> />
<Input <Input
type="password" type="password"
name="confirmPassword" name="confirmPassword"
onChange={(e) => setConfirmPassword(e)} onChange={(e) => setConfirmPassword(e)}
placeholder="Confirm your password" placeholder="Confirm your password"
defaultValue={confirmPassword} defaultValue={confirmPassword}
required required
/> />
</div> </div>
<Divider className="w-full !my-2" /> <Divider className="!my-2 w-full" />
<div className="w-full flex gap-4"> <div className="flex w-full gap-4">
<Input <Input
type="text" type="text"
name="companyName" name="companyName"
onChange={(e) => setCompanyName(e)} onChange={(e) => setCompanyName(e)}
placeholder="Corporate name" placeholder="Corporate name"
label="Corporate name" label="Corporate name"
defaultValue={companyName} defaultValue={companyName}
required required
/> />
<Input <Input
type="number" type="number"
name="companyUsers" name="companyUsers"
onChange={(e) => setCompanyUsers(parseInt(e))} onChange={(e) => setCompanyUsers(parseInt(e))}
label="Number of users" label="Number of users"
defaultValue={companyUsers} defaultValue={companyUsers}
required required
/> />
</div> </div>
<div className="w-full flex gap-4"> <div className="flex w-full gap-4">
<div className="flex flex-col gap-3 w-full"> <div className="flex w-full flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Referral *</label> <label className="text-mti-gray-dim text-base font-normal">
<Select Referral *
className="px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed bg-white rounded-full border border-mti-gray-platinum focus:outline-none" </label>
options={[ <Select
{value: "", label: "No referral"}, className="placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim border-mti-gray-platinum w-full rounded-full border bg-white px-4 py-4 text-sm font-normal focus:outline-none disabled:cursor-not-allowed"
...users.filter((u) => u.type === "agent").map((x) => ({value: x.id, label: `${x.name} - ${x.email}`})), options={[
]} { value: "", label: "No referral" },
defaultValue={{value: "", label: "No referral"}} ...users
onChange={(value) => setReferralAgent(value?.value)} .filter((u) => u.type === "agent")
styles={{ .map((x) => ({ value: x.id, label: `${x.name} - ${x.email}` })),
control: (styles) => ({ ]}
...styles, defaultValue={{ value: "", label: "No referral" }}
paddingLeft: "4px", onChange={(value) => setReferralAgent(value?.value)}
border: "none", styles={{
outline: "none", control: (styles) => ({
":focus": { ...styles,
outline: "none", paddingLeft: "4px",
}, border: "none",
}), outline: "none",
option: (styles, state) => ({ ":focus": {
...styles, outline: "none",
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white", },
color: state.isFocused ? "black" : styles.color, }),
}), option: (styles, state) => ({
}} ...styles,
/> backgroundColor: state.isFocused
</div> ? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color,
}),
}}
/>
</div>
<div className="flex flex-col gap-3 w-full"> <div className="flex w-full flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Subscription Duration *</label> <label className="text-mti-gray-dim text-base font-normal">
<Select Subscription Duration *
className="px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed bg-white rounded-full border border-mti-gray-platinum focus:outline-none" </label>
options={Object.keys(availableDurations).map((value) => ({ <Select
value, className="placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim border-mti-gray-platinum w-full rounded-full border bg-white px-4 py-4 text-sm font-normal focus:outline-none disabled:cursor-not-allowed"
label: availableDurations[value as keyof typeof availableDurations].label, options={Object.keys(availableDurations).map((value) => ({
}))} value,
defaultValue={{value: "1_month", label: availableDurations["1_month"].label}} label:
onChange={(value) => availableDurations[value as keyof typeof availableDurations]
setSubscriptionDuration(value ? availableDurations[value.value as keyof typeof availableDurations].number : 1) .label,
} }))}
styles={{ defaultValue={{
control: (styles) => ({ value: "1_month",
...styles, label: availableDurations["1_month"].label,
paddingLeft: "4px", }}
border: "none", onChange={(value) =>
outline: "none", setSubscriptionDuration(
":focus": { value
outline: "none", ? availableDurations[
}, value.value as keyof typeof availableDurations
}), ].number
option: (styles, state) => ({ : 1,
...styles, )
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white", }
color: state.isFocused ? "black" : styles.color, styles={{
}), control: (styles) => ({
}} ...styles,
/> paddingLeft: "4px",
</div> border: "none",
</div> outline: "none",
":focus": {
outline: "none",
},
}),
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused
? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color,
}),
}}
/>
</div>
</div>
<Button <Button
className="lg:mt-8 w-full" className="w-full lg:mt-8"
color="purple" color="purple"
disabled={ disabled={
isLoading || !email || !name || !password || !confirmPassword || password !== confirmPassword || !companyName || companyUsers <= 0 isLoading ||
}> !email ||
Create account !name ||
</Button> !password ||
</form> !confirmPassword ||
); password !== confirmPassword ||
!companyName ||
companyUsers <= 0
}
>
Create account
</Button>
</form>
);
} }

View File

@@ -1,132 +1,167 @@
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox"; import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import {User} from "@/interfaces/user"; import { User } from "@/interfaces/user";
import {sendEmailVerification} from "@/utils/email"; import { sendEmailVerification } from "@/utils/email";
import axios from "axios"; import axios from "axios";
import {useEffect, useState} from "react"; import { useEffect, useState } from "react";
import {toast} from "react-toastify"; import { toast } from "react-toastify";
import {KeyedMutator} from "swr"; import { KeyedMutator } from "swr";
interface Props { interface Props {
queryCode?: string; queryCode?: string;
defaultInformation?: { defaultInformation?: {
email: string; email: string;
name: string; name: string;
passport_id?: string; passport_id?: string;
}; };
isLoading: boolean; isLoading: boolean;
setIsLoading: (isLoading: boolean) => void; setIsLoading: (isLoading: boolean) => void;
mutateUser: KeyedMutator<User>; mutateUser: KeyedMutator<User>;
sendEmailVerification: typeof sendEmailVerification; sendEmailVerification: typeof sendEmailVerification;
} }
export default function RegisterIndividual({queryCode, defaultInformation, isLoading, setIsLoading, mutateUser, sendEmailVerification}: Props) { export default function RegisterIndividual({
const [name, setName] = useState(defaultInformation?.name || ""); queryCode,
const [email, setEmail] = useState(defaultInformation?.email || ""); defaultInformation,
const [password, setPassword] = useState(""); isLoading,
const [confirmPassword, setConfirmPassword] = useState(""); setIsLoading,
const [code, setCode] = useState(queryCode || ""); mutateUser,
const [hasCode, setHasCode] = useState<boolean>(!!queryCode); sendEmailVerification,
}: Props) {
const [name, setName] = useState(defaultInformation?.name || "");
const [email, setEmail] = useState(defaultInformation?.email || "");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [code, setCode] = useState(queryCode || "");
const [hasCode, setHasCode] = useState<boolean>(!!queryCode);
const onSuccess = () => toast.success("An e-mail has been sent, please make sure to check your spam folder!"); const onSuccess = () =>
toast.success(
"An e-mail has been sent, please make sure to check your spam folder!",
);
const onError = (e: Error) => { const onError = (e: Error) => {
console.error(e); console.error(e);
toast.error("Something went wrong, please logout and re-login.", {toastId: "send-verify-error"}); toast.error("Something went wrong, please logout and re-login.", {
}; toastId: "send-verify-error",
});
};
const register = (e: any) => { const register = (e: any) => {
e.preventDefault(); e.preventDefault();
if (confirmPassword !== password) { if (confirmPassword !== password) {
toast.error("Your passwords do not match!", {toastId: "password-not-match"}); toast.error("Your passwords do not match!", {
return; toastId: "password-not-match",
} });
return;
}
setIsLoading(true); setIsLoading(true);
axios axios
.post("/api/register", { .post("/api/register", {
name, name,
email, email,
password, password,
type: "individual", type: "individual",
code, code,
passport_id: defaultInformation?.passport_id, passport_id: defaultInformation?.passport_id,
profilePicture: "/defaultAvatar.png", profilePicture: "/defaultAvatar.png",
}) })
.then((response) => { .then((response) => {
mutateUser(response.data.user).then(() => sendEmailVerification(setIsLoading, onSuccess, onError)); mutateUser(response.data.user).then(() =>
}) sendEmailVerification(setIsLoading, onSuccess, onError),
.catch((error) => { );
console.log(error.response.data); })
.catch((error) => {
console.log(error.response.data);
if (error.response.status === 401) { if (error.response.status === 401) {
toast.error("There is already a user with that e-mail!"); toast.error("There is already a user with that e-mail!");
return; return;
} }
if (error.response.status === 400) { if (error.response.status === 400) {
toast.error("The provided code is invalid!"); toast.error("The provided code is invalid!");
return; return;
} }
toast.error("There was something wrong, please try again!"); toast.error("There was something wrong, please try again!");
}) })
.finally(() => setIsLoading(false)); .finally(() => setIsLoading(false));
}; };
return ( return (
<form className="flex flex-col items-center gap-6 w-full" onSubmit={register}> <form
<Input type="text" name="name" onChange={(e) => setName(e)} placeholder="Enter your name" value={name} required /> className="flex w-full flex-col items-center gap-6"
<Input onSubmit={register}
type="email" >
name="email" <Input
onChange={(e) => setEmail(e)} type="text"
placeholder="Enter email address" name="name"
value={email} onChange={(e) => setName(e)}
disabled={!!defaultInformation?.email} placeholder="Enter your name"
required value={name}
/> required
<Input />
type="password" <Input
name="password" type="email"
onChange={(e) => setPassword(e)} name="email"
placeholder="Enter your password" onChange={(e) => setEmail(e.toLowerCase())}
defaultValue={password} placeholder="Enter email address"
required value={email}
/> disabled={!!defaultInformation?.email}
<Input required
type="password" />
name="confirmPassword" <Input
onChange={(e) => setConfirmPassword(e)} type="password"
placeholder="Confirm your password" name="password"
defaultValue={confirmPassword} onChange={(e) => setPassword(e)}
required placeholder="Enter your password"
/> defaultValue={password}
required
/>
<Input
type="password"
name="confirmPassword"
onChange={(e) => setConfirmPassword(e)}
placeholder="Confirm your password"
defaultValue={confirmPassword}
required
/>
<div className="flex flex-col gap-4 w-full items-start"> <div className="flex w-full flex-col items-start gap-4">
<Checkbox isChecked={hasCode} onChange={setHasCode}> <Checkbox isChecked={hasCode} onChange={setHasCode}>
I have a code I have a code
</Checkbox> </Checkbox>
{hasCode && ( {hasCode && (
<Input <Input
type="text" type="text"
name="code" name="code"
onChange={(e) => setCode(e)} onChange={(e) => setCode(e)}
placeholder="Enter your registration code (optional)" placeholder="Enter your registration code (optional)"
defaultValue={code} defaultValue={code}
required required
/> />
)} )}
</div> </div>
<Button <Button
className="lg:mt-8 w-full" className="w-full lg:mt-8"
color="purple" color="purple"
disabled={isLoading || !email || !name || !password || !confirmPassword || password !== confirmPassword || (hasCode ? !code : false)}> disabled={
Create account isLoading ||
</Button> !email ||
</form> !name ||
); !password ||
!confirmPassword ||
password !== confirmPassword ||
(hasCode ? !code : false)
}
>
Create account
</Button>
</form>
);
} }

View File

@@ -1,109 +1,143 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import {app} from "@/firebase"; import { app } from "@/firebase";
import {getFirestore, setDoc, doc, query, collection, where, getDocs} from "firebase/firestore"; import {
import {withIronSessionApiRoute} from "iron-session/next"; getFirestore,
import {sessionOptions} from "@/lib/session"; setDoc,
import {Type} from "@/interfaces/user"; doc,
import {PERMISSIONS} from "@/constants/userPermissions"; query,
import {uuidv4} from "@firebase/util"; collection,
import {prepareMailer, prepareMailOptions} from "@/email"; where,
getDocs,
} from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { Type } from "@/interfaces/user";
import { PERMISSIONS } from "@/constants/userPermissions";
import { uuidv4 } from "@firebase/util";
import { prepareMailer, prepareMailOptions } from "@/email";
const db = getFirestore(app); const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions); export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) { async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") return get(req, res); if (req.method === "GET") return get(req, res);
if (req.method === "POST") return post(req, res); if (req.method === "POST") return post(req, res);
return res.status(404).json({ok: false}); return res.status(404).json({ ok: false });
} }
async function get(req: NextApiRequest, res: NextApiResponse) { async function get(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ok: false, reason: "You must be logged in to generate a code!"}); res
return; .status(401)
} .json({ ok: false, reason: "You must be logged in to generate a code!" });
return;
}
const {creator} = req.query as {creator?: string}; const { creator } = req.query as { creator?: string };
const q = query(collection(db, "codes"), where("creator", "==", creator)); const q = query(collection(db, "codes"), where("creator", "==", creator));
const snapshot = await getDocs(creator ? q : collection(db, "codes")); const snapshot = await getDocs(creator ? q : collection(db, "codes"));
res.status(200).json(snapshot.docs.map((doc) => doc.data())); res.status(200).json(snapshot.docs.map((doc) => doc.data()));
} }
async function post(req: NextApiRequest, res: NextApiResponse) { async function post(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ok: false, reason: "You must be logged in to generate a code!"}); res
return; .status(401)
} .json({ ok: false, reason: "You must be logged in to generate a code!" });
return;
}
const {type, codes, infos, expiryDate} = req.body as { const { type, codes, infos, expiryDate } = req.body as {
type: Type; type: Type;
codes: string[]; codes: string[];
infos?: {email: string; name: string; passport_id?: string}[]; infos?: { email: string; name: string; passport_id?: string }[];
expiryDate: null | Date; expiryDate: null | Date;
}; };
const permission = PERMISSIONS.generateCode[type]; const permission = PERMISSIONS.generateCode[type];
if (!permission.includes(req.session.user.type)) { if (!permission.includes(req.session.user.type)) {
res.status(403).json({ok: false, reason: "Your account type does not have permissions to generate a code for that type of user!"}); res
return; .status(403)
} .json({
ok: false,
reason:
"Your account type does not have permissions to generate a code for that type of user!",
});
return;
}
if (req.session.user.type === "corporate") { if (req.session.user.type === "corporate") {
const codesGeneratedByUserSnapshot = await getDocs(query(collection(db, "codes"), where("creator", "==", req.session.user.id))); const codesGeneratedByUserSnapshot = await getDocs(
const totalCodes = codesGeneratedByUserSnapshot.docs.length + codes.length; query(
const allowedCodes = req.session.user.corporateInformation?.companyInformation.userAmount || 0; collection(db, "codes"),
where("creator", "==", req.session.user.id),
),
);
const totalCodes = codesGeneratedByUserSnapshot.docs.length + codes.length;
const allowedCodes =
req.session.user.corporateInformation?.companyInformation.userAmount || 0;
if (totalCodes > allowedCodes) { if (totalCodes > allowedCodes) {
res.status(403).json({ res.status(403).json({
ok: false, ok: false,
reason: `You have or would have exceeded your amount of allowed codes, you currently are allowed to generate ${ reason: `You have or would have exceeded your amount of allowed codes, you currently are allowed to generate ${
allowedCodes - codesGeneratedByUserSnapshot.docs.length allowedCodes - codesGeneratedByUserSnapshot.docs.length
} codes.`, } codes.`,
}); });
return; return;
} }
} }
const codePromises = codes.map(async (code, index) => { const codePromises = codes.map(async (code, index) => {
const codeRef = doc(db, "codes", code); const codeRef = doc(db, "codes", code);
const codeInformation = {type, code, creator: req.session.user!.id, expiryDate}; const codeInformation = {
type,
code,
creator: req.session.user!.id,
expiryDate,
};
if (infos && infos.length > index) { if (infos && infos.length > index) {
const {email, name, passport_id} = infos[index]; const { email, name, passport_id } = infos[index];
const transport = prepareMailer(); const transport = prepareMailer();
const mailOptions = prepareMailOptions( const mailOptions = prepareMailOptions(
{ {
type, type,
code, code,
}, },
[email.trim()], [email.toLowerCase().trim()],
"EnCoach Registration", "EnCoach Registration",
"main", "main",
); );
try { try {
await transport.sendMail(mailOptions); await transport.sendMail(mailOptions);
await setDoc( await setDoc(
codeRef, codeRef,
{...codeInformation, email: email.trim(), name: name.trim(), ...(passport_id ? {passport_id: passport_id.trim()} : {})}, {
{merge: true}, ...codeInformation,
); email: email.trim().toLowerCase(),
name: name.trim(),
...(passport_id ? { passport_id: passport_id.trim() } : {}),
},
{ merge: true },
);
return true; return true;
} catch (e) { } catch (e) {
return false; return false;
} }
} else { } else {
await setDoc(codeRef, codeInformation); await setDoc(codeRef, codeInformation);
} }
}); });
Promise.all(codePromises).then((results) => { Promise.all(codePromises).then((results) => {
res.status(200).json({ok: true, valid: results.filter((x) => x).length}); res.status(200).json({ ok: true, valid: results.filter((x) => x).length });
}); });
} }

View File

@@ -1,172 +1,232 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import {User} from "@/interfaces/user"; import { User } from "@/interfaces/user";
import {toast, ToastContainer} from "react-toastify"; import { toast, ToastContainer } from "react-toastify";
import axios from "axios"; import axios from "axios";
import {FormEvent, useEffect, useState} from "react"; import { FormEvent, useEffect, useState } from "react";
import Head from "next/head"; import Head from "next/head";
import useUser from "@/hooks/useUser"; import useUser from "@/hooks/useUser";
import {Divider} from "primereact/divider"; import { Divider } from "primereact/divider";
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import {BsArrowRepeat, BsCheck} from "react-icons/bs"; import { BsArrowRepeat, BsCheck } from "react-icons/bs";
import Link from "next/link"; import Link from "next/link";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import clsx from "clsx"; import clsx from "clsx";
import {useRouter} from "next/router"; import { useRouter } from "next/router";
import EmailVerification from "./(auth)/EmailVerification"; import EmailVerification from "./(auth)/EmailVerification";
import {withIronSessionSsr} from "iron-session/next"; import { withIronSessionSsr } from "iron-session/next";
import {sessionOptions} from "@/lib/session"; import { sessionOptions } from "@/lib/session";
const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/g); const EMAIL_REGEX = new RegExp(
/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/g,
);
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
const user = req.session.user; const user = req.session.user;
const envVariables: {[key: string]: string} = {}; const envVariables: { [key: string]: string } = {};
Object.keys(process.env) Object.keys(process.env)
.filter((x) => x.startsWith("NEXT_PUBLIC")) .filter((x) => x.startsWith("NEXT_PUBLIC"))
.forEach((x: string) => { .forEach((x: string) => {
envVariables[x] = process.env[x]!; envVariables[x] = process.env[x]!;
}); });
if (user && user.isVerified) { if (user && user.isVerified) {
res.setHeader("location", "/"); res.setHeader("location", "/");
res.statusCode = 302; res.statusCode = 302;
res.end(); res.end();
return { return {
props: { props: {
user: null, user: null,
envVariables, envVariables,
}, },
}; };
} }
return { return {
props: {user: null, envVariables}, props: { user: null, envVariables },
}; };
}, sessionOptions); }, sessionOptions);
export default function Login() { export default function Login() {
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [rememberPassword, setRememberPassword] = useState(false); const [rememberPassword, setRememberPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const router = useRouter(); const router = useRouter();
const {user, mutateUser} = useUser({ const { user, mutateUser } = useUser({
redirectTo: "/", redirectTo: "/",
redirectIfFound: true, redirectIfFound: true,
}); });
useEffect(() => { useEffect(() => {
if (user && user.isVerified) router.push("/"); if (user && user.isVerified) router.push("/");
}, [router, user]); }, [router, user]);
const forgotPassword = () => { const forgotPassword = () => {
if (!email || email.length < 0 || !EMAIL_REGEX.test(email)) { if (!email || email.length < 0 || !EMAIL_REGEX.test(email)) {
toast.error("Please enter your e-mail to reset your password!", {toastId: "forgot-invalid-email"}); toast.error("Please enter your e-mail to reset your password!", {
return; toastId: "forgot-invalid-email",
} });
return;
}
axios axios
.post<{ok: boolean}>("/api/reset", {email}) .post<{ ok: boolean }>("/api/reset", { email })
.then((response) => { .then((response) => {
if (response.data.ok) { if (response.data.ok) {
toast.success("You should receive an e-mail to reset your password!", {toastId: "forgot-success"}); toast.success(
return; "You should receive an e-mail to reset your password!",
} { toastId: "forgot-success" },
);
return;
}
toast.error("That e-mail address is not connected to an account!", {toastId: "forgot-error"}); toast.error("That e-mail address is not connected to an account!", {
}) toastId: "forgot-error",
.catch(() => toast.error("That e-mail address is not connected to an account!", {toastId: "forgot-error"})); });
}; })
.catch(() =>
toast.error("That e-mail address is not connected to an account!", {
toastId: "forgot-error",
}),
);
};
const login = (e: FormEvent<HTMLFormElement>) => { const login = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
setIsLoading(true); setIsLoading(true);
axios axios
.post<User>("/api/login", {email, password}) .post<User>("/api/login", { email, password })
.then((response) => { .then((response) => {
toast.success("You have been logged in!", {toastId: "login-successful"}); toast.success("You have been logged in!", {
mutateUser(response.data); toastId: "login-successful",
}) });
.catch((e) => { mutateUser(response.data);
if (e.response.status === 401) { })
toast.error("Wrong login credentials!", {toastId: "wrong-credentials"}); .catch((e) => {
} else { if (e.response.status === 401) {
toast.error("Something went wrong!", {toastId: "server-error"}); toast.error("Wrong login credentials!", {
} toastId: "wrong-credentials",
setIsLoading(false); });
}) } else {
.finally(() => setIsLoading(false)); toast.error("Something went wrong!", { toastId: "server-error" });
}; }
setIsLoading(false);
})
.finally(() => setIsLoading(false));
};
return ( return (
<> <>
<Head> <Head>
<title>Login | EnCoach</title> <title>Login | EnCoach</title>
<meta name="description" content="Generated by create next app" /> <meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
</Head> </Head>
<main className="w-full h-[100vh] flex bg-white text-black"> <main className="flex h-[100vh] w-full bg-white text-black">
<ToastContainer /> <ToastContainer />
<section className="h-full w-fit min-w-fit relative hidden lg:flex"> <section className="relative hidden h-full w-fit min-w-fit lg:flex">
<div className="absolute h-full w-full bg-mti-rose-light z-10 bg-opacity-50" /> <div className="bg-mti-rose-light absolute z-10 h-full w-full bg-opacity-50" />
<img src="/people-talking-tablet.png" alt="People smiling looking at a tablet" className="h-full aspect-auto" /> <img
</section> src="/people-talking-tablet.png"
<section className="h-full w-full flex flex-col items-center justify-center gap-2"> alt="People smiling looking at a tablet"
<div className={clsx("flex flex-col items-center", !user && "mb-4")}> className="aspect-auto h-full"
<img src="/logo_title.png" alt="EnCoach's Logo" className="w-36 lg:w-56" /> />
<h1 className="font-bold text-2xl lg:text-4xl">Login to your account</h1> </section>
<p className="self-start text-sm lg:text-base font-normal text-mti-gray-cool">with your registered Email Address</p> <section className="flex h-full w-full flex-col items-center justify-center gap-2">
</div> <div className={clsx("flex flex-col items-center", !user && "mb-4")}>
<Divider className="max-w-xs lg:max-w-md" /> <img
{!user && ( src="/logo_title.png"
<> alt="EnCoach's Logo"
<form className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2" onSubmit={login}> className="w-36 lg:w-56"
<Input type="email" name="email" onChange={(e) => setEmail(e)} placeholder="Enter email address" /> />
<Input type="password" name="password" onChange={(e) => setPassword(e)} placeholder="Password" /> <h1 className="text-2xl font-bold lg:text-4xl">
<div className="flex justify-between w-full px-4"> Login to your account
<div </h1>
className="flex gap-3 text-mti-gray-dim text-xs cursor-pointer" <p className="text-mti-gray-cool self-start text-sm font-normal lg:text-base">
onClick={() => setRememberPassword((prev) => !prev)}> with your registered Email Address
<input type="checkbox" className="hidden" /> </p>
<div </div>
className={clsx( <Divider className="max-w-xs lg:max-w-md" />
"w-4 h-4 rounded-sm flex items-center justify-center border border-mti-purple-light bg-white", {!user && (
"transition duration-300 ease-in-out", <>
rememberPassword && "!bg-mti-purple-light ", <form
)}> className="-lg:px-8 flex w-full flex-col items-center gap-6 lg:w-1/2"
<BsCheck color="white" className="w-full h-full" /> onSubmit={login}
</div> >
<span>Remember my password</span> <Input
</div> type="email"
<span className="text-mti-purple-light text-xs cursor-pointer hover:underline" onClick={forgotPassword}> name="email"
Forgot Password? onChange={(e) => setEmail(e.toLowerCase())}
</span> placeholder="Enter email address"
</div> />
<Button className="mt-8 w-full" color="purple" disabled={isLoading}> <Input
{!isLoading && "Login"} type="password"
{isLoading && ( name="password"
<div className="flex items-center justify-center"> onChange={(e) => setPassword(e)}
<BsArrowRepeat className="text-white animate-spin" size={25} /> placeholder="Password"
</div> />
)} <div className="flex w-full justify-between px-4">
</Button> <div
</form> className="text-mti-gray-dim flex cursor-pointer gap-3 text-xs"
<span className="text-mti-gray-cool text-sm font-normal mt-8"> onClick={() => setRememberPassword((prev) => !prev)}
Don&apos;t have an account?{" "} >
<Link className="text-mti-purple-light" href="/register"> <input type="checkbox" className="hidden" />
Sign up <div
</Link> className={clsx(
</span> "border-mti-purple-light flex h-4 w-4 items-center justify-center rounded-sm border bg-white",
</> "transition duration-300 ease-in-out",
)} rememberPassword && "!bg-mti-purple-light ",
{user && !user.isVerified && <EmailVerification user={user} isLoading={isLoading} setIsLoading={setIsLoading} />} )}
</section> >
</main> <BsCheck color="white" className="h-full w-full" />
</> </div>
); <span>Remember my password</span>
</div>
<span
className="text-mti-purple-light cursor-pointer text-xs hover:underline"
onClick={forgotPassword}
>
Forgot Password?
</span>
</div>
<Button
className="mt-8 w-full"
color="purple"
disabled={isLoading}
>
{!isLoading && "Login"}
{isLoading && (
<div className="flex items-center justify-center">
<BsArrowRepeat
className="animate-spin text-white"
size={25}
/>
</div>
)}
</Button>
</form>
<span className="text-mti-gray-cool mt-8 text-sm font-normal">
Don&apos;t have an account?{" "}
<Link className="text-mti-purple-light" href="/register">
Sign up
</Link>
</span>
</>
)}
{user && !user.isVerified && (
<EmailVerification
user={user}
isLoading={isLoading}
setIsLoading={setIsLoading}
/>
)}
</section>
</main>
</>
);
} }