Merge branch 'develop' into feature/ticket-system
This commit is contained in:
@@ -1,13 +1,13 @@
|
|||||||
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";
|
||||||
|
|
||||||
@@ -19,13 +19,18 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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({
|
||||||
|
isLoading,
|
||||||
|
setIsLoading,
|
||||||
|
mutateUser,
|
||||||
|
sendEmailVerification,
|
||||||
|
}: Props) {
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
@@ -36,20 +41,27 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
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!", {
|
||||||
|
toastId: "password-not-match",
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +84,9 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
mutateUser(response.data.user).then(() => sendEmailVerification(setIsLoading, onSuccess, onError));
|
mutateUser(response.data.user).then(() =>
|
||||||
|
sendEmailVerification(setIsLoading, onSuccess, onError),
|
||||||
|
);
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error.response.data);
|
console.log(error.response.data);
|
||||||
@@ -93,13 +107,30 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
};
|
};
|
||||||
|
|
||||||
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 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>
|
||||||
|
|
||||||
<div className="w-full flex gap-4">
|
<div className="flex w-full gap-4">
|
||||||
<Input
|
<Input
|
||||||
type="password"
|
type="password"
|
||||||
name="password"
|
name="password"
|
||||||
@@ -118,9 +149,9 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
/>
|
/>
|
||||||
</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"
|
||||||
@@ -140,16 +171,20 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
/>
|
/>
|
||||||
</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">
|
||||||
|
Referral *
|
||||||
|
</label>
|
||||||
<Select
|
<Select
|
||||||
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"
|
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"
|
||||||
options={[
|
options={[
|
||||||
{value: "", label: "No referral"},
|
{ value: "", label: "No referral" },
|
||||||
...users.filter((u) => u.type === "agent").map((x) => ({value: x.id, label: `${x.name} - ${x.email}`})),
|
...users
|
||||||
|
.filter((u) => u.type === "agent")
|
||||||
|
.map((x) => ({ value: x.id, label: `${x.name} - ${x.email}` })),
|
||||||
]}
|
]}
|
||||||
defaultValue={{value: "", label: "No referral"}}
|
defaultValue={{ value: "", label: "No referral" }}
|
||||||
onChange={(value) => setReferralAgent(value?.value)}
|
onChange={(value) => setReferralAgent(value?.value)}
|
||||||
styles={{
|
styles={{
|
||||||
control: (styles) => ({
|
control: (styles) => ({
|
||||||
@@ -163,24 +198,41 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
}),
|
}),
|
||||||
option: (styles, state) => ({
|
option: (styles, state) => ({
|
||||||
...styles,
|
...styles,
|
||||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
backgroundColor: state.isFocused
|
||||||
|
? "#D5D9F0"
|
||||||
|
: state.isSelected
|
||||||
|
? "#7872BF"
|
||||||
|
: "white",
|
||||||
color: state.isFocused ? "black" : styles.color,
|
color: state.isFocused ? "black" : styles.color,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</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">
|
||||||
|
Subscription Duration *
|
||||||
|
</label>
|
||||||
<Select
|
<Select
|
||||||
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"
|
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"
|
||||||
options={Object.keys(availableDurations).map((value) => ({
|
options={Object.keys(availableDurations).map((value) => ({
|
||||||
value,
|
value,
|
||||||
label: availableDurations[value as keyof typeof availableDurations].label,
|
label:
|
||||||
|
availableDurations[value as keyof typeof availableDurations]
|
||||||
|
.label,
|
||||||
}))}
|
}))}
|
||||||
defaultValue={{value: "1_month", label: availableDurations["1_month"].label}}
|
defaultValue={{
|
||||||
|
value: "1_month",
|
||||||
|
label: availableDurations["1_month"].label,
|
||||||
|
}}
|
||||||
onChange={(value) =>
|
onChange={(value) =>
|
||||||
setSubscriptionDuration(value ? availableDurations[value.value as keyof typeof availableDurations].number : 1)
|
setSubscriptionDuration(
|
||||||
|
value
|
||||||
|
? availableDurations[
|
||||||
|
value.value as keyof typeof availableDurations
|
||||||
|
].number
|
||||||
|
: 1,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
styles={{
|
styles={{
|
||||||
control: (styles) => ({
|
control: (styles) => ({
|
||||||
@@ -194,7 +246,11 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
}),
|
}),
|
||||||
option: (styles, state) => ({
|
option: (styles, state) => ({
|
||||||
...styles,
|
...styles,
|
||||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
backgroundColor: state.isFocused
|
||||||
|
? "#D5D9F0"
|
||||||
|
: state.isSelected
|
||||||
|
? "#7872BF"
|
||||||
|
: "white",
|
||||||
color: state.isFocused ? "black" : styles.color,
|
color: state.isFocused ? "black" : styles.color,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -203,11 +259,19 @@ export default function RegisterCorporate({isLoading, setIsLoading, mutateUser,
|
|||||||
</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 ||
|
||||||
|
!name ||
|
||||||
|
!password ||
|
||||||
|
!confirmPassword ||
|
||||||
|
password !== confirmPassword ||
|
||||||
|
!companyName ||
|
||||||
|
companyUsers <= 0
|
||||||
|
}
|
||||||
|
>
|
||||||
Create account
|
Create account
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
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;
|
||||||
@@ -21,7 +21,14 @@ interface Props {
|
|||||||
sendEmailVerification: typeof sendEmailVerification;
|
sendEmailVerification: typeof sendEmailVerification;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function RegisterIndividual({queryCode, defaultInformation, isLoading, setIsLoading, mutateUser, sendEmailVerification}: Props) {
|
export default function RegisterIndividual({
|
||||||
|
queryCode,
|
||||||
|
defaultInformation,
|
||||||
|
isLoading,
|
||||||
|
setIsLoading,
|
||||||
|
mutateUser,
|
||||||
|
sendEmailVerification,
|
||||||
|
}: Props) {
|
||||||
const [name, setName] = useState(defaultInformation?.name || "");
|
const [name, setName] = useState(defaultInformation?.name || "");
|
||||||
const [email, setEmail] = useState(defaultInformation?.email || "");
|
const [email, setEmail] = useState(defaultInformation?.email || "");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
@@ -29,18 +36,25 @@ export default function RegisterIndividual({queryCode, defaultInformation, isLoa
|
|||||||
const [code, setCode] = useState(queryCode || "");
|
const [code, setCode] = useState(queryCode || "");
|
||||||
const [hasCode, setHasCode] = useState<boolean>(!!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!", {
|
||||||
|
toastId: "password-not-match",
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +70,9 @@ export default function RegisterIndividual({queryCode, defaultInformation, isLoa
|
|||||||
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) => {
|
.catch((error) => {
|
||||||
console.log(error.response.data);
|
console.log(error.response.data);
|
||||||
@@ -77,12 +93,22 @@ export default function RegisterIndividual({queryCode, defaultInformation, isLoa
|
|||||||
};
|
};
|
||||||
|
|
||||||
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"
|
||||||
|
onSubmit={register}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
name="name"
|
||||||
|
onChange={(e) => setName(e)}
|
||||||
|
placeholder="Enter your name"
|
||||||
|
value={name}
|
||||||
|
required
|
||||||
|
/>
|
||||||
<Input
|
<Input
|
||||||
type="email"
|
type="email"
|
||||||
name="email"
|
name="email"
|
||||||
onChange={(e) => setEmail(e)}
|
onChange={(e) => setEmail(e.toLowerCase())}
|
||||||
placeholder="Enter email address"
|
placeholder="Enter email address"
|
||||||
value={email}
|
value={email}
|
||||||
disabled={!!defaultInformation?.email}
|
disabled={!!defaultInformation?.email}
|
||||||
@@ -105,7 +131,7 @@ export default function RegisterIndividual({queryCode, defaultInformation, isLoa
|
|||||||
required
|
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>
|
||||||
@@ -122,9 +148,18 @@ export default function RegisterIndividual({queryCode, defaultInformation, isLoa
|
|||||||
</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={
|
||||||
|
isLoading ||
|
||||||
|
!email ||
|
||||||
|
!name ||
|
||||||
|
!password ||
|
||||||
|
!confirmPassword ||
|
||||||
|
password !== confirmPassword ||
|
||||||
|
(hasCode ? !code : false)
|
||||||
|
}
|
||||||
|
>
|
||||||
Create account
|
Create account
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
// 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);
|
||||||
|
|
||||||
@@ -17,16 +25,18 @@ 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
|
||||||
|
.status(401)
|
||||||
|
.json({ ok: false, reason: "You must be logged in to generate a code!" });
|
||||||
return;
|
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"));
|
||||||
|
|
||||||
@@ -35,27 +45,41 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
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
|
||||||
|
.status(401)
|
||||||
|
.json({ ok: false, reason: "You must be logged in to generate a code!" });
|
||||||
return;
|
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
|
||||||
|
.status(403)
|
||||||
|
.json({
|
||||||
|
ok: false,
|
||||||
|
reason:
|
||||||
|
"Your account type does not have permissions to generate a code for that type of user!",
|
||||||
|
});
|
||||||
return;
|
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(
|
||||||
|
query(
|
||||||
|
collection(db, "codes"),
|
||||||
|
where("creator", "==", req.session.user.id),
|
||||||
|
),
|
||||||
|
);
|
||||||
const totalCodes = codesGeneratedByUserSnapshot.docs.length + codes.length;
|
const totalCodes = codesGeneratedByUserSnapshot.docs.length + codes.length;
|
||||||
const allowedCodes = req.session.user.corporateInformation?.companyInformation.userAmount || 0;
|
const allowedCodes =
|
||||||
|
req.session.user.corporateInformation?.companyInformation.userAmount || 0;
|
||||||
|
|
||||||
if (totalCodes > allowedCodes) {
|
if (totalCodes > allowedCodes) {
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
@@ -70,10 +94,15 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
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(
|
||||||
@@ -81,7 +110,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
type,
|
type,
|
||||||
code,
|
code,
|
||||||
},
|
},
|
||||||
[email.trim()],
|
[email.toLowerCase().trim()],
|
||||||
"EnCoach Registration",
|
"EnCoach Registration",
|
||||||
"main",
|
"main",
|
||||||
);
|
);
|
||||||
@@ -90,8 +119,13 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
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;
|
||||||
@@ -104,6 +138,6 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
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 });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,29 @@
|
|||||||
/* 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) => {
|
||||||
@@ -41,7 +43,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
props: {user: null, envVariables},
|
props: { user: null, envVariables },
|
||||||
};
|
};
|
||||||
}, sessionOptions);
|
}, sessionOptions);
|
||||||
|
|
||||||
@@ -53,7 +55,7 @@ export default function Login() {
|
|||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const {user, mutateUser} = useUser({
|
const { user, mutateUser } = useUser({
|
||||||
redirectTo: "/",
|
redirectTo: "/",
|
||||||
redirectIfFound: true,
|
redirectIfFound: true,
|
||||||
});
|
});
|
||||||
@@ -64,21 +66,32 @@ export default function Login() {
|
|||||||
|
|
||||||
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!", {
|
||||||
|
toastId: "forgot-invalid-email",
|
||||||
|
});
|
||||||
return;
|
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(
|
||||||
|
"You should receive an e-mail to reset your password!",
|
||||||
|
{ toastId: "forgot-success" },
|
||||||
|
);
|
||||||
return;
|
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>) => {
|
||||||
@@ -86,16 +99,20 @@ export default function Login() {
|
|||||||
|
|
||||||
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!", {
|
||||||
|
toastId: "login-successful",
|
||||||
|
});
|
||||||
mutateUser(response.data);
|
mutateUser(response.data);
|
||||||
})
|
})
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
if (e.response.status === 401) {
|
if (e.response.status === 401) {
|
||||||
toast.error("Wrong login credentials!", {toastId: "wrong-credentials"});
|
toast.error("Wrong login credentials!", {
|
||||||
|
toastId: "wrong-credentials",
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
toast.error("Something went wrong!", {toastId: "server-error"});
|
toast.error("Something went wrong!", { toastId: "server-error" });
|
||||||
}
|
}
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
})
|
})
|
||||||
@@ -110,53 +127,90 @@ export default function Login() {
|
|||||||
<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
|
||||||
|
src="/people-talking-tablet.png"
|
||||||
|
alt="People smiling looking at a tablet"
|
||||||
|
className="aspect-auto h-full"
|
||||||
|
/>
|
||||||
</section>
|
</section>
|
||||||
<section className="h-full w-full flex flex-col items-center justify-center gap-2">
|
<section className="flex h-full w-full flex-col items-center justify-center gap-2">
|
||||||
<div className={clsx("flex flex-col items-center", !user && "mb-4")}>
|
<div className={clsx("flex flex-col items-center", !user && "mb-4")}>
|
||||||
<img src="/logo_title.png" alt="EnCoach's Logo" className="w-36 lg:w-56" />
|
<img
|
||||||
<h1 className="font-bold text-2xl lg:text-4xl">Login to your account</h1>
|
src="/logo_title.png"
|
||||||
<p className="self-start text-sm lg:text-base font-normal text-mti-gray-cool">with your registered Email Address</p>
|
alt="EnCoach's Logo"
|
||||||
|
className="w-36 lg:w-56"
|
||||||
|
/>
|
||||||
|
<h1 className="text-2xl font-bold lg:text-4xl">
|
||||||
|
Login to your account
|
||||||
|
</h1>
|
||||||
|
<p className="text-mti-gray-cool self-start text-sm font-normal lg:text-base">
|
||||||
|
with your registered Email Address
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Divider className="max-w-xs lg:max-w-md" />
|
<Divider className="max-w-xs lg:max-w-md" />
|
||||||
{!user && (
|
{!user && (
|
||||||
<>
|
<>
|
||||||
<form className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2" onSubmit={login}>
|
<form
|
||||||
<Input type="email" name="email" onChange={(e) => setEmail(e)} placeholder="Enter email address" />
|
className="-lg:px-8 flex w-full flex-col items-center gap-6 lg:w-1/2"
|
||||||
<Input type="password" name="password" onChange={(e) => setPassword(e)} placeholder="Password" />
|
onSubmit={login}
|
||||||
<div className="flex justify-between w-full px-4">
|
>
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
name="email"
|
||||||
|
onChange={(e) => setEmail(e.toLowerCase())}
|
||||||
|
placeholder="Enter email address"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
onChange={(e) => setPassword(e)}
|
||||||
|
placeholder="Password"
|
||||||
|
/>
|
||||||
|
<div className="flex w-full justify-between px-4">
|
||||||
<div
|
<div
|
||||||
className="flex gap-3 text-mti-gray-dim text-xs cursor-pointer"
|
className="text-mti-gray-dim flex cursor-pointer gap-3 text-xs"
|
||||||
onClick={() => setRememberPassword((prev) => !prev)}>
|
onClick={() => setRememberPassword((prev) => !prev)}
|
||||||
|
>
|
||||||
<input type="checkbox" className="hidden" />
|
<input type="checkbox" className="hidden" />
|
||||||
<div
|
<div
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-4 h-4 rounded-sm flex items-center justify-center border border-mti-purple-light bg-white",
|
"border-mti-purple-light flex h-4 w-4 items-center justify-center rounded-sm border bg-white",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out",
|
||||||
rememberPassword && "!bg-mti-purple-light ",
|
rememberPassword && "!bg-mti-purple-light ",
|
||||||
)}>
|
)}
|
||||||
<BsCheck color="white" className="w-full h-full" />
|
>
|
||||||
|
<BsCheck color="white" className="h-full w-full" />
|
||||||
</div>
|
</div>
|
||||||
<span>Remember my password</span>
|
<span>Remember my password</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-mti-purple-light text-xs cursor-pointer hover:underline" onClick={forgotPassword}>
|
<span
|
||||||
|
className="text-mti-purple-light cursor-pointer text-xs hover:underline"
|
||||||
|
onClick={forgotPassword}
|
||||||
|
>
|
||||||
Forgot Password?
|
Forgot Password?
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Button className="mt-8 w-full" color="purple" disabled={isLoading}>
|
<Button
|
||||||
|
className="mt-8 w-full"
|
||||||
|
color="purple"
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
{!isLoading && "Login"}
|
{!isLoading && "Login"}
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="flex items-center justify-center">
|
<div className="flex items-center justify-center">
|
||||||
<BsArrowRepeat className="text-white animate-spin" size={25} />
|
<BsArrowRepeat
|
||||||
|
className="animate-spin text-white"
|
||||||
|
size={25}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
<span className="text-mti-gray-cool text-sm font-normal mt-8">
|
<span className="text-mti-gray-cool mt-8 text-sm font-normal">
|
||||||
Don't have an account?{" "}
|
Don't have an account?{" "}
|
||||||
<Link className="text-mti-purple-light" href="/register">
|
<Link className="text-mti-purple-light" href="/register">
|
||||||
Sign up
|
Sign up
|
||||||
@@ -164,7 +218,13 @@ export default function Login() {
|
|||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{user && !user.isVerified && <EmailVerification user={user} isLoading={isLoading} setIsLoading={setIsLoading} />}
|
{user && !user.isVerified && (
|
||||||
|
<EmailVerification
|
||||||
|
user={user}
|
||||||
|
isLoading={isLoading}
|
||||||
|
setIsLoading={setIsLoading}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
</>
|
</>
|
||||||
|
|||||||
Reference in New Issue
Block a user