Check user token validity when receiving a 401 && set jwt expiration date

This commit is contained in:
cyril lopez 2018-01-11 15:59:00 +01:00
parent 99316e42d5
commit c9a07da1e8
2 changed files with 32 additions and 2 deletions

View File

@ -18,11 +18,15 @@ function parseJSON(response) {
*
* @return {object|undefined} Returns either the response, or throws an error
*/
function checkStatus(response) {
function checkStatus(response, checkToken = true) {
if (response.status >= 200 && response.status < 300) {
return response;
}
if (response.status === 401 && auth.getToken() && checkToken) {
return checkTokenValidity(response);
}
return parseJSON(response).then(responseFormatted => {
const error = new Error(response.statusText);
error.response = response;
@ -31,6 +35,30 @@ function checkStatus(response) {
});
}
function checkTokenValidity(response) {
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${auth.getToken()}`,
},
};
if (auth.getToken()) {
return fetch(`${strapi.backendURL}/user/me`, options)
.then(resp => {
if (response.status === 401) {
const { origin } = window.location;
window.location = `${origin}/admin/plugins/users-permissions/auth/login`;
auth.clearAppStorage();
}
return checkStatus(response, false);
});
}
}
/**
* Format query params
*

View File

@ -39,7 +39,9 @@ module.exports = {
issue: (payload) => {
return jwt.sign(
_.clone(payload.toJSON ? payload.toJSON() : payload),
process.env.JWT_SECRET || _.get(strapi.plugins['users-permissions'], 'config.jwtSecret') || 'oursecret'
process.env.JWT_SECRET || _.get(strapi.plugins['users-permissions'], 'config.jwtSecret') || 'oursecret', {
expiresIn: '30d'
}
);
},