Connected set new password to backend

This commit is contained in:
Alex Holliday committed 2024-06-11 14:18:20 -07:00
1 parent d1427010c2
commit a8af106606
5 files changed
+105 -19

No files matched your search

+17 -10
View File
@@ -12,6 +12,7 @@ import axios from "axios";
const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;
const ForgotPassword = () => { const ForgotPassword = () => {
const [isLoading, setIsLoading] = useState(false); // Used to disable the button while loading so user doesn't submit multiple times
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [form, setForm] = useState({ const [form, setForm] = useState({
email: "", email: "",
@@ -39,16 +40,21 @@ const ForgotPassword = () => {
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
const { error } = recoveryValidation.validate(form); //TODO show loading spinner
if (error === undefined) { setIsLoading(true);
try { try {
const res = await axios.post(`${BASE_URL}/auth/recovery/request`, form); const { error } = recoveryValidation.validate(form);
console.log(res); if (error !== undefined) {
} catch (error) { throw error;
console.log(error);
} }
} else { const res = await axios.post(`${BASE_URL}/auth/recovery/request`, form);
// TODO properly display success
alert(JSON.stringify(res.data));
} catch (error) {
//TODO display error (Toast?)
alert(error); alert(error);
} finally {
setIsLoading(false);
} }
}; };
return ( return (
@@ -72,13 +78,14 @@ const ForgotPassword = () => {
<div className="forgot-password-body"> <div className="forgot-password-body">
<EmailTextField <EmailTextField
onChange={handleInput} onChange={handleInput}
error={errors.email ? true : false} error={errors.email !== undefined ? true : false}
helperText={errors.email ? errors.email : ""} helperText={errors.email !== undefined ? errors.email : ""}
placeholder="Enter your email" placeholder="Enter your email"
id="forgot-password-email-input" id="forgot-password-email-input"
/> />
<div className="forgot-password-v-gap-medium"></div> <div className="forgot-password-v-gap-medium"></div>
<Button <Button
disabled={errors.email !== undefined || isLoading === true}
onClick={handleSubmit} onClick={handleSubmit}
level="primary" level="primary"
label="Reset password" label="Reset password"
+66 -5
View File
@@ -1,14 +1,69 @@
import BackgroundPattern from "../../Components/BackgroundPattern/BackgroundPattern"; import BackgroundPattern from "../../Components/BackgroundPattern/BackgroundPattern";
import "./index.css"; import "./index.css";
import React from "react";
import LockIcon from "../../assets/Images/lock-icon.png"; import LockIcon from "../../assets/Images/lock-icon.png";
import PasswordTextField from "../../Components/TextFields/Password/PasswordTextField"; import PasswordTextField from "../../Components/TextFields/Password/PasswordTextField";
import Check from "../../Components/Check/Check"; import Check from "../../Components/Check/Check";
import Button from "../../Components/Button"; import Button from "../../Components/Button";
import LeftArrow from "../../assets/Images/arrow-left.png"; import LeftArrow from "../../assets/Images/arrow-left.png";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { newPasswordValidation } from "../../Validation/validation";
import axios from "axios";
const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;
import { useNavigate } from "react-router-dom";
const SetNewPassword = () => { const SetNewPassword = () => {
const navigate = useNavigate();
const [errors, setErrors] = useState({});
const [form, setForm] = useState({});
const [isLoading, setIsLoading] = useState(false);
const idMap = {
"register-password-input": "password",
"confirm-password-input": "confirm",
};
const handleInput = (e) => {
const fieldName = idMap[e.target.id];
setForm({ ...form, [fieldName]: e.target.value });
console.log(errors);
};
const handleSubmit = async () => {
// TODO show loading spinner
setIsLoading(true);
try {
await axios.post(`${BASE_URL}/auth/recovery/validate`, {
recoveryToken: token,
});
await axios.post(`${BASE_URL}/auth/recovery/reset`, {
...form,
recoveryToken: token,
});
navigate("/login");
} catch (error) {
// TODO display error (Toast?)
alert(error);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
const { error } = newPasswordValidation.validate(form, {
abortEarly: false,
});
if (error) {
const validationErrors = error.details.reduce((acc, err) => {
return { ...acc, [err.path[0]]: err.message };
}, {});
setErrors(validationErrors);
} else {
setErrors({});
}
}, [form]);
const { token } = useParams(); const { token } = useParams();
return ( return (
<div className="set-new-password-page"> <div className="set-new-password-page">
@@ -31,16 +86,20 @@ const SetNewPassword = () => {
<div className="set-new-password-form-content"> <div className="set-new-password-form-content">
<PasswordTextField <PasswordTextField
label="Password" label="Password"
error={false} onChange={handleInput}
error={errors.password !== undefined ? true : false}
helperText={errors.password !== undefined ? errors.password : ""}
placeholder="••••••••" placeholder="••••••••"
id="register-password-input" id="register-password-input"
/> />
<div className="set-new-password-form-gap-medium"></div> <div className="set-new-password-form-gap-medium"></div>
<PasswordTextField <PasswordTextField
label="Confirm password" label="Confirm password"
error={false} onChange={handleInput}
error={errors.confirm !== undefined ? true : false}
helperText={errors.confirm !== undefined ? errors.confirm : ""}
placeholder="••••••••" placeholder="••••••••"
id="register-password-input" id="confirm-password-input"
/> />
<div className="set-new-password-form-gap-medium"></div> <div className="set-new-password-form-gap-medium"></div>
<div className="set-new-password-form-checks"> <div className="set-new-password-form-checks">
@@ -50,8 +109,10 @@ const SetNewPassword = () => {
</div> </div>
<div className="set-new-password-form-gap-medium"></div> <div className="set-new-password-form-gap-medium"></div>
<Button <Button
disabled={Object.keys(errors).length !== 0 || isLoading === true}
onClick={handleSubmit}
level="primary" level="primary"
label="Reset passwprd" label="Reset password"
sx={{ sx={{
width: "100%", width: "100%",
fontSize: "13px", fontSize: "13px",
+18 -1
View File
@@ -51,4 +51,21 @@ const recoveryValidation = joi.object({
}), }),
}); });
export { registerValidation, loginValidation, recoveryValidation }; const newPasswordValidation = joi.object({
password: joi.string().min(8).required().messages({
"string.min": "Password must be at least 8 characters",
"string.empty": "Password is required",
}),
confirm: joi.string().valid(joi.ref("password")).min(8).required().messages({
"string.min": "Password must be at least 8 characters",
"string.empty": "Password is required",
"any.only": "Passwords do not match",
}),
});
export {
registerValidation,
loginValidation,
recoveryValidation,
newPasswordValidation,
};
+1 -1
View File
@@ -167,7 +167,7 @@ const recoveryRequestController = async (req, res, next) => {
await sendEmail( await sendEmail(
[req.body.email], [req.body.email],
"Uptime Monitor Password Recovery", "Uptime Monitor Password Recovery",
`<a href='${process.env.CLIENT_HOST}/set-new-password/${recoveryToken.token}'>Click here to reset your password</a>`, `<a clicktracking="off" href='${process.env.CLIENT_HOST}/set-new-password/${recoveryToken.token}'>Click here to reset your password</a>`,
`Recovery token: ${recoveryToken.token}` `Recovery token: ${recoveryToken.token}`
); );
return res.status(200).json({ return res.status(200).json({
+3 -2
View File
@@ -131,7 +131,6 @@ const validateRecoveryToken = async (req, res) => {
const resetPassword = async (req, res) => { const resetPassword = async (req, res) => {
try { try {
const newPassword = req.body.password; const newPassword = req.body.password;
// Validate token again // Validate token again
const recoveryToken = await validateRecoveryToken(req, res); const recoveryToken = await validateRecoveryToken(req, res);
const user = await UserModel.findOne({ email: recoveryToken.email }); const user = await UserModel.findOne({ email: recoveryToken.email });
@@ -148,7 +147,9 @@ const resetPassword = async (req, res) => {
} else { } else {
throw new Error("User not found"); throw new Error("User not found");
} }
} catch (error) {} } catch (error) {
throw error;
}
}; };
//**************************************** //****************************************