Skip to content

Commit

Permalink
axios interceptor jwt refreshing logic simple refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
reszkojr committed Oct 18, 2023
1 parent 9b5812c commit e7845cf
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 33 deletions.
32 changes: 15 additions & 17 deletions src/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
config.headers['Authorization'] = `Bearer ${token}`;
config.headers['Accept'] = 'application/json';
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
return config;
},
Expand All @@ -18,6 +20,9 @@ api.interceptors.request.use(
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response.config.url.includes('/auth/login') || error.response.config.url.includes('/auth/register')) {
return Promise.reject(error);
}
const originalRequest = error.config;

// If the error status is 401 and there is no originalRequest._retry flag,
Expand All @@ -26,22 +31,15 @@ api.interceptors.response.use(
originalRequest._retry = true;
}

try {
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) return;
const response = await api.post('/auth/token/refresh', { refresh: refreshToken });
const token = response.data.access;

localStorage.setItem('token', token);

originalRequest.headers.Authorization = `Bearer ${token}`;
return axios(originalRequest);
} catch (error: unknown) {
if (axios.isAxiosError(error) && error.response?.status === 401) {
localStorage.removeItem('refreshToken');
localStorage.removeItem('token');
}
}
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) return;

const response = await api.post('/auth/token/refresh', { refresh: refreshToken });
const token = response.data.access;

localStorage.setItem('token', token);

return axios(originalRequest);
}
);

Expand Down
20 changes: 6 additions & 14 deletions src/context/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,7 @@ export const AuthProvider = ({ children }: Props) => {

const register = async (userData: RegistrationUserData) => {
try {
const response = await AuthService.handleRegister(userData);

if (response.status !== 201) {
return {
message: 'Something wrong happened.',
error: true,
status: 400,
};
}

// Login user after registration
const { email, password } = userData;
login({ email, password });
await AuthService.handleRegister(userData);

return {
message: 'Your account was successfully created!',
Expand All @@ -87,8 +75,12 @@ export const AuthProvider = ({ children }: Props) => {
status: 400,
};
}
return {
message: ['An error ocurred. We are sorry for the inconvenience.'],
error: true,
status: 400,
};
}
return {} as ResponseData;
};

const logout = () => {
Expand Down
2 changes: 0 additions & 2 deletions src/services/AuthService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ class AuthService {

public handleLogin = async (userData: LoginUserData) => {
const response = await api.post('/auth/token/', userData, { headers: AuthService.jsonHeaders });
const { access } = response.data;
api.defaults.headers.common['Authorization'] = 'Bearer ' + access;
return response;
};

Expand Down

0 comments on commit e7845cf

Please sign in to comment.