Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update data provider headers dynamically in hasura react admin?

I'm trying to do an application that needs authentication using react-admin and the hasura data provider, i need to change the headers of the after the login success. Right now, the headers are only updated when i reload the page, otherwise, this error are throwed:

{"path":"$","error":"Malformed Authorization header","code":"invalid-headers"}

This is my current code of the app.js:

import React, { useEffect } from 'react';

import { Admin, Resource,  } from 'react-admin';
import Dashboard from './Dashboard';
import hasuraDataProvider from 'ra-data-hasura';
import authProvider from './authProvider';
import {Cookies} from "react-cookie";
import { AssociadoList, AssociadoShow } from "./Associado";
import portugueseMessages from 'ra-language-portuguese';
import LoginPage from "./Login";
import "./App.scss";
const ucookies = new Cookies();

const messages = {
  'pt': portugueseMessages,
};
const i18nProvider = locale => messages[locale];
const dataProvider = () => {
  const dataProvider = hasuraDataProvider(process.env.REACT_APP_HASURA_URL, { "content-type": "application/json", "Authorization": "Bearer " +  ucookies.get("authToken")});
  return dataProvider;
}
function App() {
  return (
    <Admin
      dataProvider={dataProvider()}
      authProvider={authProvider}
      dashboard={Dashboard}
      loginPage={LoginPage}
      locale="pt" i18nProvider={i18nProvider}
    >
      <Resource name="adear.associado" list={AssociadoList} options={{ label: 'Associado' }} show={AssociadoShow} />
    </Admin>
  );
}

export default App;

And this is the code of authprovider:

import { AUTH_LOGIN, AUTH_LOGOUT, AUTH_ERROR, AUTH_CHECK } from 'react-admin';
import graphql from './graphqlClient';
import Cookies from 'universal-cookie';
import { GraphQLClient } from 'graphql-request';
const cookies = new Cookies();

const LOGIN = `
    mutation($username:String!, $password:String!){
        login(username: $username, password: $password){
            token
        }
    }
`;
const ME = `
    query {
        me {
            username
        }
    }
`;

export default (type, params) => {

    if (type === AUTH_LOGIN) {
        const { username, password } = params;
        return graphql.request(LOGIN, { username, password }).then(data => {
            const token = data.login.token;

            cookies.set("authToken", token, { path: "/", sameSite: "strict" });
            localStorage.setItem("loggedIn", true);
            //localStorage.setItem("reloaded", false);

        });
    }
    if (type === AUTH_LOGOUT) {
        cookies.set("authToken", "", { path: "/", sameSite: "strict" });
        localStorage.setItem("loggedIn", false);
        localStorage.removeItem("reloaded");
        return Promise.resolve();
    }
    if (type === AUTH_ERROR) {
        const graphqlauth = new GraphQLClient(process.env.REACT_APP_HASURA_ENDPOINT, {
            headers: {
                authorization: 'Bearer ' + cookies.get('authToken'),
            },
        })
        return graphqlauth.request(ME).then(data => { return (data.me.username) ? Promise.resolve() : Promise.reject(); }).catch(e => {
            cookies.set("authToken", "", { path: "/", sameSite: "strict" });
            localStorage.setItem("loggedIn", false);

        });

    }
    if (type === AUTH_CHECK) { 
        const graphqlauth = new GraphQLClient(process.env.REACT_APP_HASURA_ENDPOINT, {
            headers: {
                authorization: 'Bearer ' + cookies.get('authToken'),
            },
        })
        return graphqlauth.request(ME).then(data => { return (data.me.username) ? Promise.resolve() : Promise.reject(); });
        //return cookies.get('authToken') &&  cookies.get('authToken') !== "" ? Promise.resolve() : Promise.reject();
    }
    return Promise.resolve();
};

When i reload the page, the error doesn't occour. I've tried to use states, but seems imposisble to change the headers.

like image 282
Mihael Zamin Avatar asked Aug 12 '19 00:08

Mihael Zamin


1 Answers

A newer version (0.0.7) of ra-data-hasura data provider adds support for httpClient to pass in dynamic headers.

It uses react-admin's fetchUtils.fetchJson() as HTTP client. Hence to add custom headers to your requests, you just need to wrap the fetchUtils.fetchJson() call inside your own function:

const httpClient = (url, options = {}) => {
  if (!options.headers) {
      options.headers = new Headers({ Accept: 'application/json' });
  }
  // add your own headers here
  options.headers.set('Authorization', 'Bearer xxxxx');
  return fetchUtils.fetchJson(url, options);
};
const dataProvider = hasuraDataProvider('http://localhost:8080', httpClient);
like image 86
praveenweb Avatar answered Nov 05 '22 06:11

praveenweb