Skip to content

Commit

Permalink
Redirect to login when 401 or 403
Browse files Browse the repository at this point in the history
  • Loading branch information
wmazoni authored and ciandt-wmazoni committed Dec 29, 2023
1 parent 9503a8e commit cd6b898
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
7 changes: 4 additions & 3 deletions frontend/src/Routes.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';
import { Router, Switch, Route, Redirect } from 'react-router-dom';
import Home from 'pages/Home';
import Navbar from 'components/Navbar';
import Catalog from 'pages/Catalog';
import Admin from 'pages/Admin';
import ProductDetails from 'pages/ProductDetails';
import Auth from 'pages/Admin/Auth';
import history from 'util/history';

const Routes = () => (
<BrowserRouter>
<Router history={history}>
<Navbar />
<Switch>
<Route path="/" exact>
Expand All @@ -28,7 +29,7 @@ const Routes = () => (
<Admin />
</Route>
</Switch>
</BrowserRouter>
</Router>
);

export default Routes;
3 changes: 3 additions & 0 deletions frontend/src/util/history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createBrowserHistory } from 'history'

export default createBrowserHistory()
19 changes: 18 additions & 1 deletion frontend/src/util/requests.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import qs from 'qs'
import axios, { AxiosRequestConfig } from 'axios'
import history from './history'

type LoginResponse = {
"access_token": string,
Expand Down Expand Up @@ -46,4 +47,20 @@ export const requestBackend = (config: AxiosRequestConfig) => {
Authorization: "Bearer " + getAuthData().access_token
} : config.headers;
return axios({...config, baseURL: BASE_URL, headers})
}
}

// Add a request interceptor
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
if (error.response.status === 401 || error.response.status === 403) {
history.push('/admin/auth')
}
return Promise.reject(error);
});

0 comments on commit cd6b898

Please sign in to comment.