Skip to content
Snippets Groups Projects

Move back cookie fetch to SignInForm. Role fetched and saved into a Context. Small refactorings.

Merged Defendi Alberto requested to merge feature/role into dev
1 file
+ 23
5
Compare changes
  • Side-by-side
  • Inline
import React, { FC, useContext } from 'react';
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';
@@ -8,9 +8,29 @@ 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]);
console.log(isCookieFetched);
const history = useHistory();
const { role, setRole } = useContext(AuthContext);
const { setRole } = useContext(AuthContext);
interface FormData {
username: string;
@@ -33,7 +53,7 @@ export const SignInForm: FC = () => {
{
username: values.username,
password: values.password,
csrfmiddlewaretoken: sessionStorage.getItem('X-CSRFTOKEN'),
csrfmiddlewaretoken: isCookieFetched,
},
{
headers: {
@@ -42,7 +62,6 @@ export const SignInForm: FC = () => {
},
)
.then((response) => {
console.log(response);
if (response.data.status === 'fail') {
setError('username', {
type: 'server',
@@ -53,7 +72,6 @@ export const SignInForm: FC = () => {
message: 'Something went wrong with password',
});
} else if (response.data.status === 'success') {
localStorage.setItem('ROLE', response.data.role);
setRole(response.data.role);
history.replace(AuthRoutes.dashboard);
}
Loading