mirror of
https://github.com/strapi/strapi.git
synced 2025-12-24 13:43:41 +00:00
Check user token validity when receiving a 401 && set jwt expiration date
This commit is contained in:
parent
99316e42d5
commit
c9a07da1e8
@ -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
|
||||
*
|
||||
|
||||
@ -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'
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user