File: /var/www/vhosts/app.ett-dev.2amigos.us/docroot/src/views/auth/RegisterView.js
import React, {useEffect, useRef, useState} from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import * as Yup from 'yup';
import { Formik } from 'formik';
import {
Box,
Button,
Container,
FormHelperText,
Link,
TextField,
Typography,
makeStyles,
CircularProgress
} from '@material-ui/core';
import { Alert, AlertTitle } from '@material-ui/lab';
import Page from 'src/components/Page';
import api from 'src/utils/api';
import { useSnackbar } from 'notistack';
import { GoogleReCaptcha, useGoogleReCaptcha } from 'react-google-recaptcha-v3';
import {validateLogin} from "../../utils/EmitValidation";
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: theme.palette.background.dark,
height: '100%',
paddingBottom: theme.spacing(3),
paddingTop: theme.spacing(3)
}
}));
const RegisterView = () => {
const [token, setToken] = useState("");
const [hasRegistered, setRegistered] = useState(false);
const classes = useStyles();
const { enqueueSnackbar } = useSnackbar();
const navigate = useNavigate();
const { executeRecaptcha } = useGoogleReCaptcha();
const formikFormRef = useRef();
const onSignUp = (user_data, navigate, formikFormRef) => {
if(user_data.password === user_data.confirm_password){
let { name, email, password, confirm_password } = user_data
const register_params = {
name,
email,
password,
"password-confirmation": confirm_password,
recaptcha: token,
}
executeRecaptcha("register").then(function (token){
api.postAuth('register', {...register_params, "recaptcha": token}, false).then((resRegister) => {
if(resRegister.ok) setRegistered(true)
else if(resRegister.errors){
const error_array = Object.keys(resRegister.errors).map(function(key) {
return {"type" : key, "data" : resRegister.errors[key] }
})
formikFormRef.current.setErrors({ server_error: error_array })
formikFormRef.current.setSubmitting(false)
}else{
formikFormRef.current.setErrors({ catch_error: "Something went wrong please try again" })
formikFormRef.current.setSubmitting(false)
}
}).catch((error) => {
formikFormRef.current.setErrors({ catch_error: error.message })
formikFormRef.current.setSubmitting(false)
})
});
}else{
formikFormRef.current.setErrors({ email: false, password: "Both passwords do not match", confirm_password: "Both passwords do not match" });
formikFormRef.current.setSubmitting(false)
}
}
useEffect(() => {
const access_token = validateLogin();
if(access_token){
navigate('/app/dashboard', { replace: true });
}
}, []);
const handleVerify = React.useCallback((token) => {
setToken(token)
}, []);
return (
<Page className={classes.root} title="Register">
<Box
display="flex"
flexDirection="column"
height="100%"
justifyContent="center"
>
<Container maxWidth="sm">
{!hasRegistered ?
<Formik
innerRef={formikFormRef}
initialValues={{
name: '',
email: '',
password: '',
confirm_password: ''
}}
validationSchema={
Yup.object().shape({
name: Yup.string().min(3, 'Full name must be at least 3 characters').max(70, 'Full name must be at most 70 characters').required('Full name is required'),
email: Yup.string().email('Must be a valid email').max(255).required('Email is required'),
password: Yup.string().min(8, 'Password must be at least 8 characters').max(32, 'Password must be at most 32 characters').required('Password is required'),
confirm_password: Yup.string().required('Password confirmation is required'),
})
}
onSubmit={(user_data) => onSignUp(user_data, navigate, formikFormRef)}
>
{({ errors, handleBlur, handleChange, handleSubmit, isSubmitting, touched, values
}) => (
<form onSubmit={handleSubmit}>
<Box mb={3}>
<Typography color="textPrimary" align="center" variant="h2" >
Create new account
</Typography>
<Typography color="textSecondary" gutterBottom variant="body2" align="center">
Use your email to create new account
</Typography>
</Box>
<TextField
error={Boolean(touched.name && errors.name)}
fullWidth
helperText={touched.name && errors.name}
label="Full name"
margin="normal"
name="name"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstName}
variant="outlined"
/>
<TextField
error={Boolean(touched.email && errors.email)}
fullWidth
helperText={touched.email && errors.email}
label="Email address"
margin="normal"
name="email"
onBlur={handleBlur}
onChange={handleChange}
type="email"
value={values.email}
variant="outlined"
/>
<TextField
error={Boolean(touched.password && errors.password)}
fullWidth
helperText={touched.password && errors.password}
label="Password"
margin="normal"
name="password"
onBlur={handleBlur}
onChange={handleChange}
type="password"
value={values.password}
variant="outlined"
/>
<TextField
error={Boolean(touched.confirm_password && errors.confirm_password)}
fullWidth
helperText={touched.confirm_password && errors.confirm_password}
label="Confirm password"
margin="normal"
name="confirm_password"
onBlur={handleBlur}
onChange={handleChange}
type="password"
value={values.confirm_password}
variant="outlined"
/>
{Boolean(errors.catch_error) && (<FormHelperText error>{errors.catch_error}</FormHelperText>)}
{Boolean(errors.server_error) && (
errors.server_error.map((errors_d, i) => {
return(
<FormHelperText key={i} error>{errors_d.data}</FormHelperText>
)
})
)}
<GoogleReCaptcha onVerify={handleVerify} />
<Box my={2} display="flex" justifyContent="center">
{
!isSubmitting ?
<Button color="primary" disabled={isSubmitting} fullWidth size="large" type="submit" variant="contained">
Sign up now
</Button>
:
<CircularProgress />
}
</Box>
<Typography color="textSecondary" variant="body1">
Have an account?{' '}
<Link component={RouterLink} to="/login" variant="h6">
Sign in
</Link>
</Typography>
</form>
)}
</Formik>
:
<Alert severity="success" onClose={() => {setRegistered(false)}}>
<AlertTitle>Thank you for registering!</AlertTitle>
Please verify your email to complete the process
</Alert>
}
</Container>
</Box>
</Page>
);
};
export default RegisterView;