I have created admin dashboard for one client. Project is created using Vue.js with Nuxt.js. Backend is Directus and it was created by my colleague.
Problem is that auth middleware is not working as I need. When I log in, I save AUTH_TOKEN and REFRESH_TOKEN in cookies. Then, I am firing up one API call, if response.message is: 'Token expired', I send new API call with REFRESH_TOKEN to refresh. Then, from response I save new REFRESH_TOKEN and new AUTH_TOKEN to cookies again and if response is not 200, I redirect user to /login.
Here is my code (/middleware/authenticated.js):
import authService from '../services/authService';
export default function ({ $cookies, redirect, store, $toast, $router }) {
const access_token = $cookies.get('access_token');
const refresh_token = $cookies.get('refresh_token');
if (!access_token) {
$cookies.remove('access_token');
$cookies.remove('refresh_token');
store.commit('RESET_USER');
return redirect('/login');
}
if(access_token){
store.commit('SET_USER');
setInterval(function(){
try{
authService.retrieveCurrentUser({headers: {
"Content-type": "application/json",
"Authorization": `Bearer ${access_token}`,
}})
.then(() => {
console.log('ok');
})
.catch ((error) => {
console.log('prvy catch error', error);
if(error.response.data.errors[0].message == 'Token expired.'){
const config = {
"refresh_token": refresh_token
}
authService.refreshToken(config)
.then((response) => {
$cookies.set('access_token', response.data.data.access_token);
$cookies.set('refresh_token', response.data.data.refresh_token);
store.commit('SET_USER');
return redirect();
})
.catch((err) => {
console.log('druhy catch error', err);
$cookies.remove('access_token');
$cookies.remove('refresh_token');
store.commit('RESET_USER');
$toast.error('Platnosť vášho prihlásenia vypršala, prihláste sa prosím znova.', { timeout: 5000 });
clearInterval(this);
return redirect('/login');
})
}
})
}
catch (err){
console.log('treti catch error', err);
$cookies.remove('access_token');
$cookies.remove('refresh_token');
store.commit('RESET_USER');
$toast.error('Platnosť vášho prihlásenia vypršala, prihláste sa prosím znova.', { timeout: 5000 });
clearInterval(this);
return redirect('/login');
}
}, 300000)
}
};
Here is authService:
import api from '@/services/api';
export default {
login (credentials){
return api().post('/auth/login', credentials);
},
refreshToken(config) {
return api().post('/auth/refresh', config);
},
logout (refresh_token){
return api().post('/auth/logout', refresh_token);
},
retrieveCurrentUser(refresh_token){
return api().get('/users/me', refresh_token);
}
};
And this is how I call middleware inside page:
middleware: 'authenticated',
Also I need that setInterval because I want to check if token is still valid every 5 minutes.
When I use this code, I am receiving automatic log outs, or spamming of that toast notification.