var token = getToken();
var username = "****";
var password = "****";
if (token === null){
context.promise = getNewToken().then((data) => {
context.query.token = data.token;
saveToken(data.token, data.expires)
})
}else{
context.promise = new Promise(function(resolve) {
context.query.token = token;
resolve()
})
}
function getNewToken(){
return new Promise(function(resolve) {
var api = context.utils.axios.post('http://'+context.hostname+'/api/admin/login', {
user_name:username,
password:password
});
api.then(function(result) {
var data = result.data.data
var token = data.token;
var expires = data.expire;
resolve({
token,expires
});
});
});
}
function saveToken(token, expires){
var expiredTime = (new Date()).getTime() + (expires * 1000);
storage.setItem('admin_token', expiredTime + '@#@' + token);
}
function getToken(){
var con = storage.getItem('admin_token');
if (!con) {
return null;
}
let [expiredTime, token] = con.split("@#@")
if (!token){
return null;
}
var leftTime = expiredTime - (10 * 1000) - (new Date()).getTime()
console.log("token 距離過期還剩:" + (leftTime / 1000) + "秒")
if (leftTime <= 0){
return null;
}
return token;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結