Files
Checkmate/Client/src/Pages/Auth/Register/Register.jsx
T

676 lines
19 KiB
React
Raw Normal View History

2024-08-10 17:13:31 -04:00
import PropTypes from "prop-types";
2024-08-10 18:57:30 -04:00
import { useState, useEffect, useRef } from "react";
2024-06-06 13:10:13 -07:00
import { useNavigate } from "react-router-dom";
2024-07-15 18:47:23 -04:00
import { useTheme } from "@emotion/react";
2024-08-10 17:13:31 -04:00
import { Box, Stack, Typography } from "@mui/material";
2024-07-19 10:05:18 -07:00
import { useDispatch } from "react-redux";
import { credentials } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils";
2024-07-19 10:24:01 -07:00
import { register } from "../../../Features/Auth/authSlice";
import { useParams } from "react-router-dom";
2024-08-10 17:13:31 -04:00
import background from "../../../assets/Images/background_pattern_decorative.png";
import Logo from "../../../assets/icons/bwu-icon.svg?react";
import Mail from "../../../assets/icons/mail.svg?react";
2024-08-10 17:46:35 -04:00
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
2024-08-10 17:13:31 -04:00
import Check from "../../../Components/Check/Check";
import Button from "../../../Components/Button";
import Field from "../../../Components/Inputs/Field";
2024-08-18 17:42:49 -07:00
import { networkService } from "../../../main";
2024-08-10 17:13:31 -04:00
import "../index.css";
import { logger } from "../../../Utils/Logger";
2024-08-10 17:13:31 -04:00
2024-08-10 19:02:21 -04:00
/**
* Displays the initial landing page.
*
* @param {Object} props
2024-08-26 10:00:34 -07:00
* @param {boolean} props.isSuperAdmin - Whether the user is creating and admin account
2024-08-10 19:02:21 -04:00
* @param {Function} props.onContinue - Callback function to handle "Continue with Email" button click.
* @returns {JSX.Element}
*/
2024-08-26 10:00:34 -07:00
const LandingPage = ({ isSuperAdmin, onSignup }) => {
2024-08-10 17:13:31 -04:00
const theme = useTheme();
return (
<>
<Stack
gap={{ xs: theme.gap.ml, sm: theme.gap.large }}
alignItems="center"
textAlign="center"
>
2024-08-10 17:13:31 -04:00
<Box>
<Typography component="h1">Sign Up</Typography>
<Typography>
2024-08-26 10:00:34 -07:00
Create your {isSuperAdmin ? "Super admin " : ""}account to get
started.
2024-08-10 17:13:31 -04:00
</Typography>
</Box>
<Box width="100%">
<Button
level="secondary"
label="Sign up with Email"
img={<Mail />}
2024-08-10 17:46:35 -04:00
onClick={onSignup}
2024-08-10 17:13:31 -04:00
sx={{
width: "100%",
"& svg": {
mr: theme.gap.small,
},
}}
/>
</Box>
<Box maxWidth={400}>
<Typography className="tos-p">
By signing up, you agree to our{" "}
2024-08-21 10:58:40 -07:00
<Typography
component="span"
onClick={() => {
window.open(
"https://bluewavelabs.ca/terms-of-service-open-source",
2024-08-22 12:35:38 -04:00
"_blank",
"noreferrer"
2024-08-21 10:58:40 -07:00
);
}}
>
Terms of Service
</Typography>{" "}
and{" "}
<Typography
component="span"
onClick={() => {
2024-08-22 12:35:38 -04:00
window.open(
"https://bluewavelabs.ca/privacy-policy-open-source",
"_blank",
"noreferrer"
);
2024-08-21 10:58:40 -07:00
}}
>
Privacy Policy.
</Typography>
2024-08-10 17:13:31 -04:00
</Typography>
</Box>
</Stack>
</>
);
};
2024-06-06 13:10:13 -07:00
LandingPage.propTypes = {
2024-08-26 10:00:34 -07:00
isSuperAdmin: PropTypes.bool,
onSignup: PropTypes.func,
};
2024-08-10 19:02:21 -04:00
/**
* Renders the first step of the sign up process.
*
* @param {Object} props
* @param {Object} props.form - Form state object.
* @param {Object} props.errors - Object containing form validation errors.
* @param {Function} props.onSubmit - Callback function to handle form submission.
* @param {Function} props.onChange - Callback function to handle form input changes.
* @param {Function} props.onBack - Callback function to handle "Back" button click.
* @returns {JSX.Element}
*/
2024-08-10 17:46:35 -04:00
const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => {
const theme = useTheme();
2024-08-10 18:57:30 -04:00
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
2024-08-10 17:46:35 -04:00
return (
<>
<Stack gap={{ xs: theme.gap.ml, sm: theme.gap.large }} textAlign="center">
2024-08-10 17:46:35 -04:00
<Box>
<Typography component="h1">Sign Up</Typography>
<Typography>Enter your personal details</Typography>
</Box>
<Box textAlign="left">
<form noValidate spellCheck={false} onSubmit={onSubmit}>
<Field
id="register-firstname-input"
label="Name"
isRequired={true}
placeholder="Jordan"
autoComplete="given-name"
value={form.firstName}
onChange={onChange}
error={errors.firstName}
2024-08-10 18:57:30 -04:00
ref={inputRef}
2024-08-10 17:46:35 -04:00
/>
2024-08-10 18:54:17 -04:00
</form>
<form noValidate spellCheck={false} onSubmit={onSubmit}>
<Field
id="register-lastname-input"
label="Surname"
isRequired={true}
placeholder="Ellis"
autoComplete="family-name"
value={form.lastName}
onChange={onChange}
error={errors.lastName}
/>
2024-08-10 17:46:35 -04:00
</form>
</Box>
<Stack direction="row" justifyContent="space-between">
<Button
level="secondary"
label="Back"
animate="slideLeft"
img={<ArrowBackRoundedIcon />}
onClick={onBack}
sx={{
px: theme.gap.ml,
"& svg.MuiSvgIcon-root": {
mr: theme.gap.xs,
},
}}
props={{ tabIndex: -1 }}
/>
<Button
level="primary"
label="Continue"
onClick={onSubmit}
disabled={(errors.firstName || errors.lastName) && true}
sx={{ width: "30%" }}
/>
</Stack>
</Stack>
</>
);
};
StepOne.propTypes = {
form: PropTypes.object,
errors: PropTypes.object,
onSubmit: PropTypes.func,
onChange: PropTypes.func,
onBack: PropTypes.func,
};
2024-08-10 19:02:21 -04:00
/**
* Renders the second step of the sign up process.
*
* @param {Object} props
* @param {Object} props.form - Form state object.
* @param {Object} props.errors - Object containing form validation errors.
* @param {Function} props.onSubmit - Callback function to handle form submission.
* @param {Function} props.onChange - Callback function to handle form input changes.
* @param {Function} props.onBack - Callback function to handle "Back" button click.
* @returns {JSX.Element}
*/
2024-08-10 18:07:04 -04:00
const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
const theme = useTheme();
2024-08-10 18:57:30 -04:00
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
2024-08-10 18:07:04 -04:00
return (
<>
<Stack gap={{ xs: theme.gap.ml, sm: theme.gap.large }} textAlign="center">
2024-08-10 18:07:04 -04:00
<Box>
<Typography component="h1">Sign Up</Typography>
<Typography>Enter your email address</Typography>
</Box>
<Box textAlign="left">
<form noValidate spellCheck={false} onSubmit={onSubmit}>
<Field
type="email"
id="register-email-input"
label="Email"
isRequired={true}
placeholder="jordan.ellis@domain.com"
autoComplete="email"
value={form.email}
onInput={(e) => (e.target.value = e.target.value.toLowerCase())}
2024-08-10 18:07:04 -04:00
onChange={onChange}
error={errors.email}
2024-08-10 18:57:30 -04:00
ref={inputRef}
2024-08-10 18:07:04 -04:00
/>
</form>
</Box>
<Stack direction="row" justifyContent="space-between">
<Button
level="secondary"
label="Back"
animate="slideLeft"
img={<ArrowBackRoundedIcon />}
onClick={onBack}
sx={{
px: theme.gap.ml,
"& svg.MuiSvgIcon-root": {
mr: theme.gap.xs,
},
}}
props={{ tabIndex: -1 }}
/>
<Button
level="primary"
label="Continue"
onClick={onSubmit}
disabled={errors.email && true}
sx={{ width: "30%" }}
/>
</Stack>
</Stack>
</>
);
};
StepTwo.propTypes = {
form: PropTypes.object,
errors: PropTypes.object,
onSubmit: PropTypes.func,
onChange: PropTypes.func,
onBack: PropTypes.func,
};
2024-08-10 19:02:21 -04:00
/**
* Renders the third step of the sign up process.
*
* @param {Object} props
* @param {Object} props.form - Form state object.
* @param {Object} props.errors - Object containing form validation errors.
* @param {Function} props.onSubmit - Callback function to handle form submission.
* @param {Function} props.onChange - Callback function to handle form input changes.
* @param {Function} props.onBack - Callback function to handle "Back" button click.
* @returns {JSX.Element}
*/
2024-08-10 18:54:17 -04:00
const StepThree = ({ form, errors, onSubmit, onChange, onBack }) => {
const theme = useTheme();
2024-08-10 18:57:30 -04:00
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
2024-08-10 18:54:17 -04:00
return (
<>
<Stack gap={{ xs: theme.gap.ml, sm: theme.gap.large }} textAlign="center">
2024-08-10 18:54:17 -04:00
<Box>
<Typography component="h1">Sign Up</Typography>
<Typography>Create your password</Typography>
</Box>
<Box textAlign="left">
<form noValidate spellCheck={false} onSubmit={onSubmit}>
<Field
type="password"
id="register-password-input"
label="Password"
isRequired={true}
placeholder="Create a password"
autoComplete="current-password"
value={form.password}
onChange={onChange}
error={errors.password}
2024-08-10 18:57:30 -04:00
ref={inputRef}
2024-08-10 18:54:17 -04:00
/>
</form>
<form noValidate spellCheck={false} onSubmit={onSubmit}>
<Field
type="password"
id="register-confirm-input"
label="Confirm password"
isRequired={true}
placeholder="Confirm your password"
autoComplete="current-password"
value={form.confirm}
onChange={onChange}
error={errors.confirm}
/>
2024-08-10 18:54:17 -04:00
</form>
<Stack
gap={theme.gap.small}
mb={{ xs: theme.gap.ml, sm: theme.gap.large }}
>
2024-08-10 18:54:17 -04:00
<Check
text={
<>
<Typography component="span">Must be at least</Typography> 8
characters long
</>
}
2024-08-10 18:54:17 -04:00
variant={
errors?.password === "Password is required"
? "error"
: form.password === ""
? "info"
: form.password.length < 8
? "error"
: "success"
}
/>
<Check
text={
<>
<Typography component="span">Must contain</Typography> one
special character and a number
</>
}
2024-08-10 18:54:17 -04:00
variant={
errors?.password === "Password is required"
? "error"
: form.password === ""
? "info"
: !/^(?=.*[!@#$%^&*(),.?":{}|])(?=.*\d).+$/.test(
form.password
)
? "error"
: "success"
}
/>
<Check
text={
<>
<Typography component="span">
Must contain at least
</Typography>{" "}
one upper and lower character
</>
}
2024-08-10 18:54:17 -04:00
variant={
errors?.password === "Password is required"
? "error"
: form.password === ""
? "info"
: !/^(?=.*[A-Z])(?=.*[a-z]).+$/.test(form.password)
? "error"
: "success"
}
/>
</Stack>
</Box>
<Stack direction="row" justifyContent="space-between">
<Button
level="secondary"
label="Back"
animate="slideLeft"
img={<ArrowBackRoundedIcon />}
onClick={onBack}
sx={{
px: theme.gap.ml,
"& svg.MuiSvgIcon-root": {
mr: theme.gap.xs,
},
}}
props={{ tabIndex: -1 }}
/>
<Button
level="primary"
label="Continue"
onClick={onSubmit}
disabled={errors.email && true}
sx={{ width: "30%" }}
/>
</Stack>
</Stack>
</>
);
};
StepThree.propTypes = {
form: PropTypes.object,
errors: PropTypes.object,
onSubmit: PropTypes.func,
onChange: PropTypes.func,
onBack: PropTypes.func,
};
2024-08-26 10:00:34 -07:00
const Register = ({ isSuperAdmin }) => {
2024-06-07 16:17:10 -07:00
const dispatch = useDispatch();
2024-06-06 13:10:13 -07:00
const navigate = useNavigate();
const { token } = useParams();
2024-07-15 18:47:23 -04:00
const theme = useTheme();
// TODO If possible, change the IDs of these fields to match the backend
2024-06-06 11:41:34 -07:00
const idMap = {
2024-07-22 12:40:44 -04:00
"register-firstname-input": "firstName",
"register-lastname-input": "lastName",
2024-06-06 11:41:34 -07:00
"register-email-input": "email",
"register-password-input": "password",
2024-07-15 18:47:23 -04:00
"register-confirm-input": "confirm",
2024-06-06 11:41:34 -07:00
};
const [form, setForm] = useState({
2024-07-22 12:40:44 -04:00
firstName: "",
lastName: "",
2024-06-06 11:41:34 -07:00
email: "",
password: "",
2024-07-15 18:47:23 -04:00
confirm: "",
role: [],
2024-06-06 11:41:34 -07:00
});
2024-07-15 18:47:23 -04:00
const [errors, setErrors] = useState({});
2024-08-10 17:46:35 -04:00
const [step, setStep] = useState(0);
2024-06-06 11:41:34 -07:00
useEffect(() => {
const fetchInvite = async () => {
if (token !== undefined) {
try {
2024-08-18 17:42:49 -07:00
const res = await networkService.verifyInvitationToken(token);
const { role, email } = res.data.data;
setForm({ ...form, email, role });
} catch (error) {
logger.error(error);
}
}
};
fetchInvite();
}, [token, form]);
2024-08-10 19:02:21 -04:00
/**
* Validates the form data against the validation schema.
*
* @param {Object} data - The form data to validate.
* @param {Object} [options] - Optional settings for validation.
* @returns {Object | undefined} - Returns the validation error object if there are validation errors; otherwise, `undefined`.
*/
2024-08-10 18:07:04 -04:00
const validateForm = (data, options = {}) => {
const { error } = credentials.validate(data, {
abortEarly: false,
...options,
});
return error;
};
2024-08-10 19:02:21 -04:00
/**
* Handles validation errors by setting the state with error messages and displaying a toast notification.
*
* @param {Object} error - The validation error object returned from the validation schema.
*/
2024-08-10 18:07:04 -04:00
const handleError = (error) => {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
createToast({ body: error.details[0].message || "Error validating data." });
};
const handleStepOne = async (e) => {
2024-07-15 18:47:23 -04:00
e.preventDefault();
let error = validateForm({
firstName: form.firstName,
lastName: form.lastName,
});
2024-08-10 18:07:04 -04:00
if (error) {
handleError(error);
return;
}
setStep(2);
};
const handleStepTwo = async (e) => {
e.preventDefault();
let error;
error = validateForm({ email: form.email });
if (error) {
handleError(error);
return;
2024-08-10 18:07:04 -04:00
}
2024-08-10 17:46:35 -04:00
setStep(3);
};
// Final step
// Attempts account registration
const handleStepThree = async (e) => {
e.preventDefault();
2024-08-26 10:00:34 -07:00
let registerForm = {
...form,
role: isSuperAdmin ? ["superadmin"] : form.role,
};
let error = validateForm(registerForm, {
context: { password: form.password },
});
2024-08-10 18:07:04 -04:00
if (error) {
handleError(error);
return;
}
delete registerForm.confirm;
const action = await dispatch(register(registerForm));
if (action.payload.success) {
const token = action.payload.data;
localStorage.setItem("token", token);
navigate("/");
createToast({
body: "Welcome! Your account was created successfully.",
});
} else {
if (action.payload) {
// dispatch errors
2024-07-12 14:00:16 -04:00
createToast({
body: action.payload.msg,
2024-07-12 14:00:16 -04:00
});
} else {
// unknown errors
createToast({
body: "Unknown error.",
});
}
2024-06-06 13:10:13 -07:00
}
};
2024-07-15 18:47:23 -04:00
const handleChange = (event) => {
const { value, id } = event.target;
const name = idMap[id];
setForm((prev) => ({
...prev,
[name]: value,
}));
const { error } = credentials.validate(
{ [name]: value },
{ abortEarly: false, context: { password: form.password } }
);
setErrors((prev) => {
const prevErrors = { ...prev };
if (error) prevErrors[name] = error.details[0].message;
else delete prevErrors[name];
return prevErrors;
});
};
2024-05-24 18:32:40 +03:30
return (
2024-08-10 17:13:31 -04:00
<Stack className="register-page auth" overflow="hidden">
<Box
2024-07-17 17:44:29 -04:00
className="background-pattern-svg"
sx={{ backgroundImage: `url(${background})` }}
2024-07-17 17:44:29 -04:00
/>
2024-08-10 17:13:31 -04:00
<Stack
direction="row"
alignItems="center"
px={theme.gap.large}
gap={theme.gap.small}
>
<Logo style={{ borderRadius: theme.shape.borderRadius }} />
<Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography>
</Stack>
<Stack
width="100%"
maxWidth={600}
flex={1}
justifyContent="center"
px={{ xs: theme.gap.large, lg: theme.gap.xl }}
pb={theme.gap.xl}
2024-08-10 17:13:31 -04:00
mx="auto"
sx={{
"& > .MuiStack-root": {
border: 1,
borderRadius: theme.shape.borderRadius,
borderColor: theme.palette.otherColors.graishWhite,
backgroundColor: theme.palette.otherColors.white,
padding: {
xs: theme.gap.large,
sm: theme.gap.xl,
},
},
}}
>
2024-08-10 17:46:35 -04:00
{step === 0 ? (
2024-08-26 10:00:34 -07:00
<LandingPage
isSuperAdmin={isSuperAdmin}
onSignup={() => setStep(1)}
/>
2024-08-10 17:46:35 -04:00
) : step === 1 ? (
<StepOne
form={form}
errors={errors}
onSubmit={handleStepOne}
2024-08-10 17:46:35 -04:00
onChange={handleChange}
onBack={() => setStep(0)}
/>
2024-08-10 18:07:04 -04:00
) : step === 2 ? (
<StepTwo
form={form}
errors={errors}
onSubmit={handleStepTwo}
2024-08-10 18:07:04 -04:00
onChange={handleChange}
onBack={() => setStep(1)}
/>
2024-08-10 18:54:17 -04:00
) : step === 3 ? (
<StepThree
form={form}
errors={errors}
onSubmit={handleStepThree}
2024-08-10 18:54:17 -04:00
onChange={handleChange}
onBack={() => setStep(2)}
/>
2024-08-10 17:46:35 -04:00
) : (
""
)}
2024-08-10 17:13:31 -04:00
</Stack>
<Box textAlign="center" p={theme.gap.large}>
<Typography display="inline-block">
Already have an account? —
</Typography>
<Typography
component="span"
ml={theme.gap.xs}
onClick={() => {
navigate("/login");
}}
sx={{ userSelect: "none" }}
>
Log In
</Typography>
</Box>
</Stack>
2024-05-24 18:32:40 +03:30
);
};
Register.propTypes = {
2024-08-26 10:00:34 -07:00
isSuperAdmin: PropTypes.bool,
};
export default Register;