import React, { FC, useContext, useEffect, useState } from 'react'; import axios from 'axios'; import { SubmitHandler, useForm } from 'react-hook-form'; import { Button } from '@material-ui/core'; import { InputField } from 'components/AuthUser/InputField/InputField'; import { useHistory } from 'react-router-dom'; import { AuthRoutes } from 'api/routes'; import { AuthContext } from 'components/AuthUser/AuthContext'; import { useStyles } from './useStyles'; const configDjangoCookieName = (): void => { axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.withCredentials = true; }; export const SignInForm: FC = () => { const [isCookieFetched, setisCookieFetched] = useState<string>(''); configDjangoCookieName(); useEffect(() => { const fetchCookie = async (): Promise<unknown> => { const response = await axios('/api/web/csrf'); setisCookieFetched(response.data.token); return null; }; if (!isCookieFetched) fetchCookie(); }, [isCookieFetched]); const history = useHistory(); const { setRole } = useContext(AuthContext); type FormData = { username: string; password: string; }; const defaultValues: FormData = { username: '', password: '', }; const { control, errors, setError, handleSubmit } = useForm<FormData>({ defaultValues, }); const onSubmit: SubmitHandler<FormData> = (values: FormData) => { axios .post( '/api/web/login', { username: values.username, password: values.password, csrfmiddlewaretoken: isCookieFetched, }, { 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 === 'success') { setRole(response.data.role); history.replace(AuthRoutes.dashboard); } }); }; 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" error={!!errors.username} errorMessage="Insert username" /> <InputField name="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> </> ); };