From 996a93f8e04d2ff390eade12a43262b7eef7d0b2 Mon Sep 17 00:00:00 2001
From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it>
Date: Sun, 16 May 2021 15:33:45 +0200
Subject: [PATCH] Cookie fetch and set role to AuthContext.

---
 .../AuthUser/SignInForm/SignInForm.tsx        | 28 +++++++++++++++----
 1 file changed, 23 insertions(+), 5 deletions(-)

diff --git a/src/components/AuthUser/SignInForm/SignInForm.tsx b/src/components/AuthUser/SignInForm/SignInForm.tsx
index 0be901e..0482d78 100644
--- a/src/components/AuthUser/SignInForm/SignInForm.tsx
+++ b/src/components/AuthUser/SignInForm/SignInForm.tsx
@@ -1,4 +1,4 @@
-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);
         }
-- 
GitLab