fix: login validation

This commit is contained in:
Caio Cabral committed 2024-10-31 11:46:52 -04:00
1 parent fd38a9d7eb
commit 40ef5c9be4
6 files changed
+79 -151

No files matched your search

+6 -1
View File
@@ -4,7 +4,7 @@
- [ ] Validation on submit - [ ] Validation on submit
- [ ] Take validation out from the component. - [ ] Take validation out from the component.
- [x] SetNewPassword - [x] SetNewPassword
- [ ] Register - [x] Register
- [ ] Refactor on change to deal with step three specificity - [ ] Refactor on change to deal with step three specificity
- [ ] Fix Input enter not working - [ ] Fix Input enter not working
- [ ] PasswordPanel - [ ] PasswordPanel
@@ -27,3 +27,8 @@
- [x] Confirm Password Left Blank - [x] Confirm Password Left Blank
- [x] Password Change After Successful Match - [x] Password Change After Successful Match
- [x] Avoid submission in new password if password or confirm empty, and on error - [x] Avoid submission in new password if password or confirm empty, and on error
- [ ] Update validation for password on backend
//TODO Apply custom hook to SetNewPassword
// Enter on input triggers back action on steps one and two
// When user registers, we see sign up page for half a second
+63 -54
View File
@@ -130,17 +130,14 @@ const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => {
return ( return (
<> <>
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(12), sm: theme.spacing(16) }}
textAlign="center" textAlign="center"
> >
<Box> <Box>
<Typography component="h1">Log In</Typography> <Typography component="h1">Log In</Typography>
<Typography>Enter your email address</Typography> <Typography>Enter your email address</Typography>
</Box> </Box>
<Box <Box textAlign="left">
textAlign="left"
mb={theme.spacing(5)}
>
<form <form
noValidate noValidate
spellCheck={false} spellCheck={false}
@@ -219,6 +216,16 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
const navigate = useNavigate(); const navigate = useNavigate();
const inputRef = useRef(null); const inputRef = useRef(null);
console.log({ errors });
const errorsMap = {
length: "Must be at least 8 characters long",
uppercase: "Must contain at least one upper character",
lowercase: "Must contain at least one lower character",
number: "Must contain at least one number",
special: "Must contain at least one special character",
};
useEffect(() => { useEffect(() => {
if (inputRef.current) { if (inputRef.current) {
inputRef.current.focus(); inputRef.current.focus();
@@ -235,7 +242,7 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
return ( return (
<> <>
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(12), sm: theme.spacing(16) }}
position="relative" position="relative"
textAlign="center" textAlign="center"
> >
@@ -244,64 +251,66 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
<Typography>Enter your password</Typography> <Typography>Enter your password</Typography>
</Box> </Box>
<Box <Box
component="form"
noValidate
spellCheck={false}
onSubmit={onSubmit}
textAlign="left" textAlign="left"
mb={theme.spacing(5)} mb={theme.spacing(5)}
sx={{
display: "grid",
gap: { xs: theme.spacing(12), sm: theme.spacing(16) },
}}
> >
<form <Field
noValidate type="password"
spellCheck={false} id="login-password-input"
onSubmit={onSubmit} label="Password"
isRequired={true}
placeholder="••••••••••"
autoComplete="current-password"
value={form.password}
onChange={onChange}
error={errorsMap[errors.password]}
ref={inputRef}
/>
<Stack
direction="row"
justifyContent="space-between"
> >
<Field <Button
type="password" variant="outlined"
id="login-password-input" color="info"
label="Password" onClick={onBack}
isRequired={true} sx={{
placeholder="••••••••••" px: theme.spacing(5),
autoComplete="current-password" "& svg.MuiSvgIcon-root": {
value={form.password} mr: theme.spacing(3),
onChange={onChange} },
error={errors.password} }}
ref={inputRef} props={{ tabIndex: -1 }}
/> >
</form> <ArrowBackRoundedIcon />
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={onSubmit}
disabled={errors.password && true}
sx={{ width: "30%" }}
>
Continue
</Button>
</Stack>
</Box> </Box>
<Stack
direction="row"
justifyContent="space-between"
>
<Button
variant="outlined"
color="info"
onClick={onBack}
sx={{
px: theme.spacing(5),
"& svg.MuiSvgIcon-root": {
mr: theme.spacing(3),
},
}}
props={{ tabIndex: -1 }}
>
<ArrowBackRoundedIcon />
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={onSubmit}
disabled={errors.password && true}
sx={{ width: "30%" }}
>
Continue
</Button>
</Stack>
<Box <Box
textAlign="center" textAlign="center"
sx={{ sx={{
position: "absolute", position: "absolute",
top: "104%", bottom: 0,
left: "50%", left: "50%",
transform: "translateX(-50%)", transform: `translate(-50%, 150%)`,
}} }}
> >
<Typography <Typography
@@ -233,7 +233,6 @@ const Register = ({ isSuperAdmin }) => {
if (action.payload.success) { if (action.payload.success) {
const authToken = action.payload.data; const authToken = action.payload.data;
localStorage.setItem("token", authToken); localStorage.setItem("token", authToken);
/* navigate("/"); */
navigate("/monitors"); navigate("/monitors");
createToast({ createToast({
body: "Welcome! Your account was created successfully.", body: "Welcome! Your account was created successfully.",
@@ -1,11 +1,10 @@
import { useEffect, useRef /* , useState */ } from "react"; import { useEffect, useRef } from "react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { Box, Button, Stack, Typography } from "@mui/material"; import { Box, Button, Stack, Typography } from "@mui/material";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded"; import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import Field from "../../../../Components/Inputs/Field"; import Field from "../../../../Components/Inputs/Field";
import Check from "../../../../Components/Check/Check"; import Check from "../../../../Components/Check/Check";
/* import { credentials } from "../../../../Validation/validation"; */
import { useValidatePassword } from "../../hooks/useValidatePassword"; import { useValidatePassword } from "../../hooks/useValidatePassword";
StepThree.propTypes = { StepThree.propTypes = {
+1 -60
View File
@@ -1,4 +1,4 @@
import { useId, useState } from "react"; import { useId } from "react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
@@ -26,11 +26,6 @@ const SetNewPassword = () => {
const confirmPasswordId = useId(); const confirmPasswordId = useId();
const { form, errors, handleChange, feedbacks } = useValidatePassword(); const { form, errors, handleChange, feedbacks } = useValidatePassword();
// const [errors, setErrors] = useState({});
// const [form, setForm] = useState({
// password: "",
// confirm: "",
// });
const { isLoading } = useSelector((state) => state.auth); const { isLoading } = useSelector((state) => state.auth);
const { token } = useParams(); const { token } = useParams();
@@ -65,60 +60,6 @@ const SetNewPassword = () => {
} }
}; };
// const handleChange = (event) => {
// const { value, name } = event.target;
// setForm((prev) => ({ ...prev, [name]: value }));
// const validateValue = { [name]: value };
// const validateOptions = { abortEarly: false, context: { password: form.password } };
// if (name === "password" && form.confirm.length > 0) {
// validateValue.confirm = form.confirm;
// validateOptions.context = { password: value };
// } else if (name === "confirm") {
// validateValue.password = form.password;
// }
// const { error } = credentials.validate(validateValue, validateOptions);
// const errors = error?.details.map((error) => ({
// path: error.path[0],
// message: error.message,
// }));
// const errorsByPath =
// errors &&
// errors.reduce((acc, { path, message }) => {
// if (!acc[path]) {
// acc[path] = [];
// }
// acc[path].push(message);
// return acc;
// }, {});
// setErrors(() => (errorsByPath ? { ...errorsByPath } : {}));
// };
// const getFeedbackStatus = (field, criteria) => {
// const fieldErrors = errors[field];
// const isFieldEmpty = form[field].length === 0;
// const hasError = fieldErrors?.includes(criteria) || fieldErrors?.includes("empty");
// const isCorrect = !isFieldEmpty && !hasError;
// if (isCorrect) {
// return "success";
// } else if (hasError) {
// return "error";
// } else {
// return "info";
// }
// };
// const feedbacks = {
// length: getFeedbackStatus("password", "length"),
// special: getFeedbackStatus("password", "special"),
// number: getFeedbackStatus("password", "number"),
// uppercase: getFeedbackStatus("password", "uppercase"),
// lowercase: getFeedbackStatus("password", "lowercase"),
// confirm: getFeedbackStatus("confirm", "different"),
// };
return ( return (
<Stack <Stack
className="set-new-password-page auth" className="set-new-password-page auth"
+8 -33
View File
@@ -18,6 +18,9 @@ const roleValidatior = (role) => (value, helpers) => {
// Auth // Auth
//**************************************** //****************************************
const passwordPattern =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!?@#$%^&*()\-_=+[\]{};:'",.<>~`|\\/])[A-Za-z0-9!?@#$%^&*()\-_=+[\]{};:'",.<>~`|\\/]+$/;
const loginValidation = joi.object({ const loginValidation = joi.object({
email: joi email: joi
.string() .string()
@@ -30,13 +33,7 @@ const loginValidation = joi.object({
} }
return lowercasedValue; return lowercasedValue;
}), }),
password: joi password: joi.string().min(8).required().pattern(passwordPattern),
.string()
.min(8)
.required()
.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
),
}); });
const registrationBodyValidation = joi.object({ const registrationBodyValidation = joi.object({
@@ -59,13 +56,7 @@ const registrationBodyValidation = joi.object({
} }
return lowercasedValue; return lowercasedValue;
}), }),
password: joi password: joi.string().min(8).required().pattern(passwordPattern),
.string()
.min(8)
.required()
.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
),
profileImage: joi.any(), profileImage: joi.any(),
role: joi role: joi
.array() .array()
@@ -84,18 +75,8 @@ const editUserBodyValidation = joi.object({
firstName: joi.string().pattern(/^[A-Za-z]+$/), firstName: joi.string().pattern(/^[A-Za-z]+$/),
lastName: joi.string().pattern(/^[A-Za-z]+$/), lastName: joi.string().pattern(/^[A-Za-z]+$/),
profileImage: joi.any(), profileImage: joi.any(),
newPassword: joi newPassword: joi.string().min(8).pattern(passwordPattern),
.string() password: joi.string().min(8).pattern(passwordPattern),
.min(8)
.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
),
password: joi
.string()
.min(8)
.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
),
deleteProfileImage: joi.boolean(), deleteProfileImage: joi.boolean(),
role: joi.array(), role: joi.array(),
}); });
@@ -113,13 +94,7 @@ const recoveryTokenValidation = joi.object({
const newPasswordValidation = joi.object({ const newPasswordValidation = joi.object({
recoveryToken: joi.string().required(), recoveryToken: joi.string().required(),
password: joi password: joi.string().min(8).required().pattern(passwordPattern),
.string()
.min(8)
.required()
.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!?@#$%^&*()\-_=+[\]{};:'",.<>~`|\\/])[A-Za-z0-9!?@#$%^&*()\-_=+[\]{};:'",.<>~`|\\/]+$/
),
confirm: joi.string(), confirm: joi.string(),
}); });