Continued updating the e-mail verification and I think I managed to get it working

This commit is contained in:
Tiago Ribeiro
2023-09-26 11:28:10 +01:00
parent 3491efb494
commit 8fb1d8e886
8 changed files with 922 additions and 97 deletions

View File

@@ -1,5 +1,4 @@
/* eslint-disable @next/next/no-img-element */
import {User} from "@/interfaces/user";
import {toast, ToastContainer} from "react-toastify";
import axios from "axios";
import {FormEvent, useEffect, useState} from "react";
@@ -7,10 +6,9 @@ import Head from "next/head";
import useUser from "@/hooks/useUser";
import {Divider} from "primereact/divider";
import Button from "@/components/Low/Button";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {BsArrowRepeat} from "react-icons/bs";
import Link from "next/link";
import Input from "@/components/Low/Input";
import clsx from "clsx";
import {useRouter} from "next/router";
export function getServerSideProps({query, res}: {query: {oobCode: string; mode: string; apiKey?: string; continueUrl?: string}; res: any}) {
@@ -23,6 +21,8 @@ export function getServerSideProps({query, res}: {query: {oobCode: string; mode:
};
}
console.log(query.continueUrl);
return {
props: {
code: query.oobCode,
@@ -36,7 +36,6 @@ export function getServerSideProps({query, res}: {query: {oobCode: string; mode:
export default function Reset({code, mode, apiKey, continueUrl}: {code: string; mode: string; apiKey?: string; continueUrl?: string}) {
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [email, setEmail] = useState<string>();
const router = useRouter();
@@ -45,35 +44,33 @@ export default function Reset({code, mode, apiKey, continueUrl}: {code: string;
redirectIfFound: true,
});
const verifyEmail = (e: any) => {
e.preventDefault();
useEffect(() => {
if (mode === "signIn") {
axios
.post<{ok: boolean}>("/api/reset/verify", {
email: continueUrl?.replace("https://encoach.com/", ""),
})
.then((response) => {
if (response.data.ok) {
toast.success("Your account has been verified!", {toastId: "verify-successful"});
setTimeout(() => {
router.push("/");
}, 1000);
return;
}
setIsLoading(true);
axios
.post<{ok: boolean}>("/api/reset/verify", {
link: `https://encoach.com/action?apiKey=${apiKey}&mode=${mode}&oobCode=${code}&continueUrl=${continueUrl}`,
email: email?.trim(),
})
.then((response) => {
if (response.data.ok) {
toast.success("Your account has been verified!", {toastId: "verify-successful"});
setTimeout(() => {
router.push("/");
}, 1000);
return;
}
toast.error("Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!", {
toastId: "verify-error",
toast.error("Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!", {
toastId: "verify-error",
});
})
.catch(() => {
toast.error("Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!", {
toastId: "verify-error",
});
setIsLoading(false);
});
})
.catch(() => {
toast.error("Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!", {
toastId: "verify-error",
});
setIsLoading(false);
});
};
}
});
const login = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
@@ -148,29 +145,12 @@ export default function Reset({code, mode, apiKey, continueUrl}: {code: string;
<p className="self-start text-sm lg:text-base font-normal text-mti-gray-cool">to your registered Email Address</p>
</div>
<Divider className="max-w-xs lg:max-w-md" />
<form className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2" onSubmit={verifyEmail}>
{isLoading && (
<span className="text-center">
Your e-mail is currently being verified, please wait a second. <br /> <br />
Once it has been verified, you will be redirected to the home page.
</span>
)}
{!isLoading && (
<>
<span>Please enter your e-mail to verify it</span>
<Input
name="email"
type="email"
defaultValue={email}
required
label="E-mail address"
placeholder="Enter your e-mail address"
onChange={setEmail}
/>
<Button className="w-full">Submit</Button>
</>
)}
</form>
<div className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2">
<span className="text-center">
Your e-mail is currently being verified, please wait a second. <br /> <br />
Once it has been verified, you will be redirected to the home page.
</span>
</div>
</section>
)}
</main>

View File

@@ -1,6 +1,7 @@
import {NextApiRequest, NextApiResponse} from "next";
import {getAuth, sendSignInLinkToEmail, User} from "firebase/auth";
import {app} from "@/firebase";
import {getAuth, sendEmailVerification, sendSignInLinkToEmail, User} from "firebase/auth";
import {getAuth as getAdminAuth, UserRecord} from "firebase-admin/auth";
import {app, adminApp} from "@/firebase";
import {sessionOptions} from "@/lib/session";
import {withIronSessionApiRoute} from "iron-session/next";
@@ -11,7 +12,7 @@ export default withIronSessionApiRoute(sendVerification, sessionOptions);
async function sendVerification(req: NextApiRequest, res: NextApiResponse) {
if (req.session.user) {
sendSignInLinkToEmail(auth, req.session.user.email, {
url: "https://encoach.com/",
url: `https://encoach.com/${req.session.user.email}`,
handleCodeInApp: true,
})
.then(() => res.status(200).json({ok: true}))

View File

@@ -1,32 +1,26 @@
import {NextApiRequest, NextApiResponse} from "next";
import {getAuth, signInWithEmailLink} from "firebase/auth";
import {app} from "@/firebase";
import {getAuth} from "firebase-admin/auth";
import {adminApp, app} from "@/firebase";
import {sessionOptions} from "@/lib/session";
import {withIronSessionApiRoute} from "iron-session/next";
import {doc, getFirestore, setDoc} from "firebase/firestore";
const auth = getAuth(app);
const auth = getAuth(adminApp);
const db = getFirestore(app);
export default withIronSessionApiRoute(verify, sessionOptions);
async function verify(req: NextApiRequest, res: NextApiResponse) {
const {link, email} = req.body as {link: string; email: string};
const {email} = req.body as {email: string};
console.log("HERE FOR WHEN VERIFY: ", {link, email});
const user = await auth.getUserByEmail(email);
if (!user) {
res.status(404).json({ok: false});
return;
}
signInWithEmailLink(auth, email, link)
.then(async () => {
const userRef = doc(db, "users", req.session.user!.id);
await setDoc(userRef, {isVerified: true}, {merge: true});
const userRef = doc(db, "users", user.uid);
await setDoc(userRef, {isVerified: true}, {merge: true});
req.session.user = {...req.session.user!, isVerified: true};
await req.session.save();
res.status(200).json({ok: true});
})
.catch((e) => {
console.log("HERE FOR WHEN FAIL VERIFY: ", e);
res.status(404).json({ok: false});
});
res.status(200).json({ok: true});
}

View File

@@ -1,14 +1,14 @@
import {PERMISSIONS} from "@/constants/userPermissions";
import {app} from "@/firebase";
import {app, adminApp} from "@/firebase";
import {User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {getAuth} from "firebase/auth";
import {deleteDoc, doc, getDoc, getFirestore} from "firebase/firestore";
import {getAuth} from "firebase-admin/auth";
import {withIronSessionApiRoute} from "iron-session/next";
import {NextApiRequest, NextApiResponse} from "next";
const auth = getAuth(app);
const db = getFirestore(app);
const auth = getAuth(adminApp);
export default withIronSessionApiRoute(user, sessionOptions);
@@ -49,9 +49,10 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
return;
}
await auth.deleteUser(id);
await deleteDoc(doc(db, "users", id));
res.json({...user, id: req.session.user.id});
res.json({ok: true});
}
async function get(req: NextApiRequest, res: NextApiResponse) {