Skip to content
This repository has been archived by the owner on Oct 26, 2023. It is now read-only.

Port axios interceptors as template samples #25

Open
devraj opened this issue Feb 6, 2023 · 0 comments
Open

Port axios interceptors as template samples #25

devraj opened this issue Feb 6, 2023 · 0 comments
Assignees

Comments

@devraj
Copy link
Member

devraj commented Feb 6, 2023

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

@devraj devraj self-assigned this Feb 6, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant