anomaly / lab-web-client

A template for building accessible, localised, high performance React front ends with a standard set of libraries. Also provides a template for development servers.
Apache License 2.0
2 stars 0 forks source link

Port `axios` interceptors as template samples #25

Open devraj opened 1 year ago

devraj commented 1 year ago

Is your feature request related to a problem? Please describe. No

Describe the solution you'd like As other applications are being developed we have quite a consice description of how axios is being used with react-query and orval, this includes the use of an interceptor to add the token every time a request is sent to the server

/**
 * Add the token before each request
 */
axios.interceptors.request.use(config => {
  if(config.headers) {
    const accessToken = window.localStorage.getItem('access_token');
    axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
  }
  return config;
}, error => {

});

and another that redirects the user to the authentication page if we receive a 401 response from the server. This is thus handled globally across the application:

/**
 * If the response is unautorised then goto the
 * login page
 */
axios.interceptors.response.use((config) => {
  return config;
}, (error) => {
  if(error.response.status === 401) {
    window.location.href = '/auth/login';
  }
  return Promise.reject(error);
});

The login action ends up writing the access_token to the localstorage:

/**
 * Call the authentication end point and on success stores
 * the access token in the query client and redirects to the
 * landing interface for the current user
 *  
 * @param queryClient 
 * @returns 
 */
export const action = (queryClient: QueryClient) => 
    async({ request } : any) => {
        const formData = await request.formData();
        const loginInfo = Object.fromEntries(formData);
        await loginForAuthToken({
            username: loginInfo.username,
            password: loginInfo.password,
    }).then((response) => {
        window.localStorage.setItem(
            'access_token',
            response.data?.access_token
        );
    }).catch((error) => {
        console.log(error);
    });

    return redirect('/admin/users');
};

The above code samples should thus be merged into index.tsx as part of the application template.

Note: that the authentication endpoints are based on what the python-server currently provides

Describe alternatives you've considered Code samples provided above

Additional context Refer to security documentation for access_tokens