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, createMuiTheme, responsiveFontSizes, MuiThemeProvider, Grid, Typography, Link, } from '@material-ui/core'; import { useHistory } from 'react-router-dom'; import { InputField } from 'components/Auth/InputField/InputField'; import { signInFormStyles } from './SignInForm.styles'; import { CredentialsType } from './CredentialsType'; const defaultValues = { username: '', password: '', }; export const SignInForm: FC = () => { const history = useHistory(); 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') { history.replace(`${AuthRoutes.dashboard}${AuthRoutes.home}`); } }); }; const classes = signInFormStyles(); return ( <> <header> <Grid item container> <Grid item xs={12} color="primary" className={classes.paddingTop}> <Typography variant="h1">SIGN IN</Typography> </Grid> </Grid> </header> <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> <Grid item container> <Grid item xs={12} color="primary" className={classes.paddingBottom}> <Typography> New here? <Link href={`${NonAuthRoutes.auth}${NonAuthRoutes.signUp}`}> Create an account. </Link> </Typography> </Grid> </Grid> </form> </> ); };