Skip to content
Snippets Groups Projects
SignInForm.tsx 3.35 KiB
Newer Older
import React, { FC, useContext, useEffect, useState } from 'react';
Defendi Alberto's avatar
Defendi Alberto committed
import axios from 'axios';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Button } from '@material-ui/core';
Defendi Alberto's avatar
Defendi Alberto committed
import { InputField } from 'components/AuthUser/InputField/InputField';
Defendi Alberto's avatar
Defendi Alberto committed
import { useHistory } from 'react-router-dom';
Defendi Alberto's avatar
Defendi Alberto committed
import { AuthRoutes } from 'api/routes';
Defendi Alberto's avatar
Defendi Alberto committed
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]);
Defendi Alberto's avatar
Defendi Alberto committed
  const history = useHistory();
  const { setRole } = useContext(AuthContext);
  type FormData = {
    username: string;
Defendi Alberto's avatar
Defendi Alberto committed
    password: string;
Defendi Alberto's avatar
Defendi Alberto committed

  const defaultValues: FormData = {
    username: '',
Defendi Alberto's avatar
Defendi Alberto committed
    password: '',
  };

  const { control, errors, setError, handleSubmit } = useForm<FormData>({
    defaultValues,
  });

  const onSubmit: SubmitHandler<FormData> = (values: FormData) => {
Defendi Alberto's avatar
Defendi Alberto committed
    axios
      .post(
        '/api/web/login',
        {
          username: values.username,
Defendi Alberto's avatar
Defendi Alberto committed
          password: values.password,
          csrfmiddlewaretoken: isCookieFetched,
Defendi Alberto's avatar
Defendi Alberto committed
        {
          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') {
Defendi Alberto's avatar
Defendi Alberto committed
          setRole(response.data.role);
          history.replace(AuthRoutes.dashboard);
        }
Defendi Alberto's avatar
Defendi Alberto committed
      });
Defendi Alberto's avatar
Defendi Alberto committed
  const classes = useStyles();
  return (
    <>
      <form
        className={classes.form}
        onSubmit={handleSubmit(onSubmit)}
        data-testid="Form"
Defendi Alberto's avatar
Defendi Alberto committed
      >
          name="username"
          control={control}
Defendi Alberto's avatar
Defendi Alberto committed
          rules={{
            required: {
              value: true,
              message: 'Username is not valid',
Defendi Alberto's avatar
Defendi Alberto committed
            },
          }}
          label="username"
          error={!!errors.username}
          errorMessage="Insert username"
Defendi Alberto's avatar
Defendi Alberto committed
        <InputField
Defendi Alberto's avatar
Defendi Alberto committed
          name="password"
Defendi Alberto's avatar
Defendi Alberto committed
          control={control}
          rules={{
            minLength: 8,
            maxLength: 60,
Defendi Alberto's avatar
Defendi Alberto committed
            required: {
              value: true,
Defendi Alberto's avatar
Defendi Alberto committed
              message: 'Insert valid password',
Defendi Alberto's avatar
Defendi Alberto committed
            },
Defendi Alberto's avatar
Defendi Alberto committed
          label="Password"
Defendi Alberto's avatar
Defendi Alberto committed
          error={!!errors.password}
Defendi Alberto's avatar
Defendi Alberto committed
          errorMessage="Insert valid password"
        <Button
Defendi Alberto's avatar
Defendi Alberto committed
          data-testid="Submit"
          type="submit"
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
        >
          Sign In
        </Button>
      </form>
    </>
Defendi Alberto's avatar
Defendi Alberto committed
  );
};