-
Defendi Alberto authoredDefendi Alberto authored
SignInForm.tsx 3.10 KiB
import React, { FC, useContext } from 'react';
import axios from 'axios';
import { useCookie } from 'hooks/useCookie';
import { AuthRoutes, NonAuthRoutes } from 'api/routes';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Button } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
import { AuthContext } from 'components/Auth/AuthContext';
import { InputField } from 'components/Auth/InputField/InputField';
import { useStyles } from './useStyles';
import { CredentialsType } from './CredentialsType';
const defaultValues = {
username: '',
password: '',
};
export const SignInForm: FC = () => {
const history = useHistory();
const { setRole, setIsAuth } = useContext(AuthContext);
const cookie = useCookie();
const { control, errors, setError, handleSubmit } = useForm<CredentialsType>({
defaultValues,
});
const onSubmit: SubmitHandler<CredentialsType> = (
values: CredentialsType,
) => {
axios
.post(
'/api/web/login',
{
username: values.username,
password: values.password,
csrfmiddlewaretoken: cookie,
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
if (response.data.status === 'fail') {
setError('username', {
type: 'server',
message: 'Something went wrong with username',
});
setError('password', {
type: 'server',
message: 'Something went wrong with password',
});
} else if (response.data.status === 'role-choice-needed') {
history.replace(`${NonAuthRoutes.auth}${AuthRoutes.choseRole}`);
} else if (response.data.status === 'success') {
setRole(response.data.role);
setIsAuth(true);
history.replace(`${AuthRoutes.dashboard}${AuthRoutes.home}`);
}
});
};
const classes = useStyles();
return (
<>
<form
className={classes.form}
onSubmit={handleSubmit(onSubmit)}
data-testid="Form"
>
<InputField
name="username"
control={control}
rules={{
required: {
value: true,
message: 'Username is not valid',
},
}}
label="username"
type="username"
error={!!errors.username}
errorMessage="Insert username"
/>
<InputField
name="password"
type="password"
control={control}
rules={{
minLength: 8,
maxLength: 60,
required: {
value: true,
message: 'Insert valid password',
},
}}
label="Password"
error={!!errors.password}
errorMessage="Insert valid password"
/>
<Button
data-testid="Submit"
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</form>
</>
);
};