🔥 Reset password now working
This commit is contained in:
@@ -20,12 +20,14 @@ import EditEventsPage from "./pages/EditEventsPage";
|
||||
import DefaultLayout from "./layouts/default";
|
||||
import AdministratorLayout from "./layouts/administrator";
|
||||
import UsersManagement from "./pages/UsersManagement";
|
||||
import ResetPasswordPage from "./pages/ResetPasswordPage";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Routes>
|
||||
{/* User Routes */}
|
||||
<Route path="/" element={<DefaultLayout />}>
|
||||
<Route path="/">
|
||||
<Route element={<DefaultLayout />}>
|
||||
{/* General Routes */}
|
||||
<Route index element={<HomePage />} />
|
||||
<Route element={<SignUpPage />} path="signup" />
|
||||
@@ -57,6 +59,8 @@ function App() {
|
||||
<Route element={<EditPostPage />} path="edit/:id" />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route element={<ResetPasswordPage />} path="reset-password/:token" />
|
||||
</Route>
|
||||
|
||||
{/* Admin Routes */}
|
||||
<Route path="/admin" element={<AdministratorLayout />}>
|
||||
|
||||
@@ -36,9 +36,6 @@ export default function NavigationBar() {
|
||||
);
|
||||
setUserInformation(value);
|
||||
})
|
||||
.catch(() => {
|
||||
navigate("/signin");
|
||||
})
|
||||
.finally(() => {
|
||||
setDoneLoading(true);
|
||||
});
|
||||
|
||||
@@ -45,7 +45,7 @@ export default function SignInModule() {
|
||||
if (value.accountType == 2) {
|
||||
navigate("/admin");
|
||||
} else {
|
||||
navigate("/springboard");
|
||||
window.location.reload();
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
@@ -18,7 +18,7 @@ import { Form, Formik } from "formik";
|
||||
import NextUIFormikInput from "./NextUIFormikInput";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import UserProfilePicture from "./UserProfilePicture";
|
||||
import { popErrorToast } from "../utilities";
|
||||
import { popErrorToast, popToast } from "../utilities";
|
||||
import instance from "../security/http";
|
||||
|
||||
export default function UpdateAccountModule() {
|
||||
@@ -105,6 +105,25 @@ export default function UpdateAccountModule() {
|
||||
});
|
||||
};
|
||||
|
||||
const sendResetPasswordEmail = () => {
|
||||
instance
|
||||
.put(
|
||||
`${
|
||||
config.serverAddress
|
||||
}/users/request-reset-password/${encodeURIComponent(
|
||||
userInformation.email
|
||||
)}`
|
||||
)
|
||||
.then(() => {
|
||||
console.log("Email sent successfully");
|
||||
popToast("Email sent to your mailbox!", 1);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Failed to send email:", error);
|
||||
popErrorToast("Failed to send email: " + error);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{userInformation && (
|
||||
@@ -221,16 +240,7 @@ export default function UpdateAccountModule() {
|
||||
color="danger"
|
||||
variant="light"
|
||||
onPress={() => {
|
||||
instance
|
||||
.put(
|
||||
`${config.serverAddress}/connections/send-reset-password-email/${userInformation.id}`
|
||||
)
|
||||
.then(() => {
|
||||
console.log("Email sent successfully");
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Failed to send email:", error);
|
||||
});
|
||||
sendResetPasswordEmail();
|
||||
}}
|
||||
>
|
||||
Reset your password
|
||||
|
||||
142
client/src/pages/ResetPasswordPage.tsx
Normal file
142
client/src/pages/ResetPasswordPage.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import instance from "../security/http";
|
||||
import config from "../config";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, Card, CircularProgress } from "@nextui-org/react";
|
||||
import EcoconnectFullLogo from "../components/EcoconnectFullLogo";
|
||||
import NextUIFormikInput from "../components/NextUIFormikInput";
|
||||
import { Formik, Form } from "formik";
|
||||
import * as Yup from "yup";
|
||||
import axios from "axios";
|
||||
import { popErrorToast, popToast } from "../utilities";
|
||||
|
||||
const validationSchema = Yup.object({
|
||||
password: Yup.string()
|
||||
.trim()
|
||||
.max(69, "Password must be at most 69 characters")
|
||||
.matches(
|
||||
/^(?=.*[a-zA-Z])(?=.*[0-9]).{1,}$/,
|
||||
"Password must contain both letters and numbers"
|
||||
)
|
||||
.required("Password is required"),
|
||||
confirmPassword: Yup.string()
|
||||
.oneOf([Yup.ref("password"), undefined], "Passwords must match")
|
||||
.required("Confirm Password is required"),
|
||||
});
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
const { token } = useParams();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [validationResult, setValidationResult] = useState<boolean>(false);
|
||||
const [pageLoading, setPageLoading] = useState<boolean>(true);
|
||||
|
||||
const validateToken = () => {
|
||||
instance
|
||||
.get(`${config.serverAddress}/users/reset-password/${token}`)
|
||||
.then(() => {
|
||||
setValidationResult(true);
|
||||
})
|
||||
.catch(() => {
|
||||
setValidationResult(false);
|
||||
})
|
||||
.finally(() => {
|
||||
setPageLoading(false);
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
validateToken();
|
||||
}, []);
|
||||
|
||||
const handleSubmit = (values: any): void => {
|
||||
console.log("submitting");
|
||||
instance
|
||||
.post(`${config.serverAddress}/users/reset-password`, {
|
||||
token,
|
||||
password: values.password,
|
||||
})
|
||||
.then(() => {
|
||||
popToast("Success!", 1);
|
||||
navigate("/signin");
|
||||
})
|
||||
.catch((error) => {
|
||||
popErrorToast(error);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="absolute inset-0 p-8 w-full h-full flex flex-col justify-center">
|
||||
<div className="flex flex-row justify-center">
|
||||
{pageLoading && (
|
||||
<div>
|
||||
<CircularProgress label="Loading..." />
|
||||
</div>
|
||||
)}
|
||||
{!pageLoading && (
|
||||
<div className="flex flex-col gap-8 *:mx-auto">
|
||||
<Card className="max-w-[600px] w-full mx-auto">
|
||||
{validationResult && (
|
||||
<div className="flex flex-col gap-8 p-12 text-left">
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-3xl font-bold">Password Reset</p>
|
||||
<p>Enter a new password below.</p>
|
||||
</div>
|
||||
<Formik
|
||||
initialValues={{ password: "", confirmPassword: "" }}
|
||||
validationSchema={validationSchema}
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
{({ isValid, dirty }) => (
|
||||
<Form className="flex flex-col gap-8">
|
||||
<NextUIFormikInput
|
||||
label="New Password"
|
||||
name="password"
|
||||
type="password"
|
||||
placeholder="Enter new password"
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
<NextUIFormikInput
|
||||
label="Confirm Password"
|
||||
name="confirmPassword"
|
||||
type="password"
|
||||
placeholder="Confirm new password"
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
color="primary"
|
||||
size="lg"
|
||||
isDisabled={!isValid || !dirty}
|
||||
>
|
||||
Confirm
|
||||
</Button>
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
</div>
|
||||
)}
|
||||
{!validationResult && (
|
||||
<div className="flex flex-col gap-8 p-12 *:mr-auto text-left">
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-3xl font-bold">
|
||||
Reset portal has been closed.
|
||||
</p>
|
||||
<p>Please request for a password reset again.</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
<div className="flex flex-row gap-4">
|
||||
<EcoconnectFullLogo />
|
||||
<p>·</p>
|
||||
<p className="opacity-50">
|
||||
© Copyright {new Date().getFullYear()}. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -49,9 +49,13 @@ async function sendEmail(recipientEmail, title, content) {
|
||||
}
|
||||
}
|
||||
|
||||
async function sendPasswordResetEmail(email, firstName) {
|
||||
const ecoconnectEmailLogoUrl =
|
||||
"https://onedrive.live.com/download?resid=FDC8D8692E9A43C0%21425747&authkey=%21ADT2uhKbMIG4iqw&width=1310&height=212";
|
||||
|
||||
async function sendPasswordResetEmail(email, firstName, resetToken) {
|
||||
let dateTimeNow = new Date().toLocaleString();
|
||||
let emailContent = `
|
||||
<!doctype html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
@@ -191,28 +195,54 @@ async function sendPasswordResetEmail(email, firstName) {
|
||||
.h-3 {
|
||||
height: 1.5rem;
|
||||
}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body style="background-color: white;">
|
||||
<div class="m-8 flex flex-col rounded-xl border-2 border-red-200 shadow-lg">
|
||||
<div class="flex flex-col gap-4 p-8 *:mr-auto">
|
||||
<img src="https://onedrive.live.com/download?resid=FDC8D8692E9A43C0%21425747&authkey=%21ADT2uhKbMIG4iqw&width=1310&height=212" alt="ecoconnect logo" class="w-44" />
|
||||
<h1 class="text-3xl font-bold text-red-900">Greetings, ${firstName}!</h1>
|
||||
<p>We have received your request to reset the password.<br />Click the button below to do so.</p>
|
||||
<a href="https://example.com/reset-password" class="rounded-xl border-2 border-red-300 bg-red-500 px-4 py-3 text-white shadow-md w-max no-underline">RESET PASSWORD</a>
|
||||
<p class="text-sm opacity-50">If you have not made a request to reset the password, feel free to ignore this email.</p>
|
||||
<p>Best regards,<br/><span class="font-bold text-red-900">ecoconnect administrators</span></p>
|
||||
<img src="${ecoconnectEmailLogoUrl}" alt="ecoconnect logo" class="w-44" />
|
||||
<h1 class="text-3xl font-bold text-red-900">
|
||||
Greetings, ${firstName}!
|
||||
</h1>
|
||||
<p>
|
||||
We have received your request to reset the password.<br />Click the
|
||||
button below to do so.
|
||||
</p>
|
||||
<div class="flex flex-col">
|
||||
<a
|
||||
href="http://localhost:5173/reset-password/${resetToken}"
|
||||
class="rounded-xl border-2 border-red-300 bg-red-500 px-4 py-3 text-white font-bold shadow-md w-max no-underline"
|
||||
>RESET PASSWORD</a
|
||||
>
|
||||
<p class="text-sm">This reset portal is opened on ${dateTimeNow}, for 60 minutes.</p>
|
||||
<p class="text-sm opacity-50">
|
||||
If you have not made a request to reset the password, feel free to
|
||||
ignore this email.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-col justify-center h-20 w-full rounded-b-xl bg-red-500 text-white">
|
||||
|
||||
<p>
|
||||
Best regards,<br /><span class="font-bold text-red-900"
|
||||
>ecoconnect administrators</span
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-col justify-center h-20 w-full rounded-b-xl bg-red-500 text-white"
|
||||
>
|
||||
<div class="mx-auto flex w-max flex-row gap-2 *:my-auto">
|
||||
<img src="https://onedrive.live.com/download?resid=FDC8D8692E9A43C0%21425747&authkey=%21ADT2uhKbMIG4iqw&width=1310&height=212" alt="ecoconnect logo" class=" h-3 py-2 px-3 bg-white rounded-xl" />
|
||||
<img
|
||||
src="${ecoconnectEmailLogoUrl}"
|
||||
alt="ecoconnect logo"
|
||||
class="h-3 py-2 px-3 bg-white rounded-xl"
|
||||
/>
|
||||
<p>· Connecting neighbourhoods together</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
`;
|
||||
await sendEmail(
|
||||
email,
|
||||
|
||||
@@ -43,13 +43,21 @@ module.exports = (sequelize) => {
|
||||
accountType: {
|
||||
type: DataTypes.TINYINT(2),
|
||||
allowNull: false,
|
||||
defaultValue: 0
|
||||
defaultValue: 0,
|
||||
},
|
||||
isArchived: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
resetPasswordToken: {
|
||||
type: DataTypes.STRING(64),
|
||||
allowNull: true,
|
||||
},
|
||||
resetPasswordExpireTime: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
tableName: "users",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const express = require("express");
|
||||
const yup = require("yup");
|
||||
const { Op } = require("sequelize");
|
||||
const { Op, Sequelize } = require("sequelize");
|
||||
const { User } = require("../models");
|
||||
const { validateToken } = require("../middlewares/auth");
|
||||
const argon2 = require("argon2");
|
||||
@@ -8,6 +8,10 @@ const router = express.Router();
|
||||
const { sign } = require("jsonwebtoken");
|
||||
const multer = require("multer");
|
||||
const sharp = require("sharp");
|
||||
const { sendPasswordResetEmail } = require("../connections/mailersend");
|
||||
const {
|
||||
generatePasswordResetToken,
|
||||
} = require("../security/generatePasswordResetToken");
|
||||
|
||||
require("dotenv").config();
|
||||
|
||||
@@ -333,4 +337,113 @@ router.put(
|
||||
}
|
||||
);
|
||||
|
||||
router.put("/request-reset-password/:email", async (req, res) => {
|
||||
let email = req.params.email;
|
||||
|
||||
try {
|
||||
console.log(email);
|
||||
let user = await User.findOne({
|
||||
where: { email: email },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
res.sendStatus(404);
|
||||
return;
|
||||
}
|
||||
|
||||
if (user.isArchived) {
|
||||
res.status(400).json({
|
||||
message: `ERR_ACC_IS_ARCHIVED`,
|
||||
});
|
||||
} else {
|
||||
const token = await generatePasswordResetToken();
|
||||
let num = await User.update(
|
||||
{
|
||||
resetPasswordToken: token,
|
||||
resetPasswordExpireTime: Date.now() + 3600000,
|
||||
},
|
||||
{
|
||||
where: { id: user.id },
|
||||
}
|
||||
);
|
||||
|
||||
if (num == 1) {
|
||||
res.json({
|
||||
message: "User was updated successfully.",
|
||||
});
|
||||
} else {
|
||||
res.status(400).json({
|
||||
message: `Something went wrong setting token for user with id ${id}.`,
|
||||
});
|
||||
}
|
||||
await sendPasswordResetEmail(user.email, user.firstName, token);
|
||||
|
||||
res.status(200).json({ message: "Email sent successfully" });
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
// Silence.
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/reset-password", async (req, res) => {
|
||||
let token = req.body.token;
|
||||
let newPassword = req.body.password;
|
||||
|
||||
try {
|
||||
resetPassword(token, newPassword).then(() => {
|
||||
res.sendStatus(200);
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({ errors: err.errors });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/reset-password/:token", async (req, res) => {
|
||||
let token = req.params.token;
|
||||
try {
|
||||
let user = await validateResetPasswordToken(token);
|
||||
|
||||
if (!user) {
|
||||
console.log("no");
|
||||
res.sendStatus(404);
|
||||
return;
|
||||
} else {
|
||||
console.log("yes");
|
||||
res.sendStatus(200);
|
||||
}
|
||||
} catch {
|
||||
res.status(401);
|
||||
}
|
||||
});
|
||||
|
||||
async function validateResetPasswordToken(token) {
|
||||
const user = await User.findOne({
|
||||
where: {
|
||||
resetPasswordToken: token,
|
||||
resetPasswordExpireTime: { [Sequelize.Op.gt]: Date.now() },
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return undefined;
|
||||
} else {
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
async function resetPassword(token, newPassword) {
|
||||
const user = await validateResetPasswordToken(token);
|
||||
|
||||
if (!user) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const hashedPassword = await argon2.hash(newPassword);
|
||||
user.password = hashedPassword;
|
||||
user.resetPasswordToken = null;
|
||||
user.resetPasswordExpires = null;
|
||||
await user.save();
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
|
||||
16
server/security/generatePasswordResetToken.js
Normal file
16
server/security/generatePasswordResetToken.js
Normal file
@@ -0,0 +1,16 @@
|
||||
const crypto = require("crypto");
|
||||
|
||||
function generatePasswordResetToken() {
|
||||
return new Promise((resolve, reject) => {
|
||||
crypto.randomBytes(32, (err, buffer) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
const token = buffer.toString("hex");
|
||||
resolve(token);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { generatePasswordResetToken };
|
||||
Reference in New Issue
Block a user