Created
April 5, 2021 09:38
-
-
Save dingyaguang117/4e1af131c4ea2674de4e4ce0877c439e to your computer and use it in GitHub Desktop.
Yearning Token 过期刷 新油猴脚本
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Yearning 自动刷新 Token | |
// @description 自动刷新 Yearning Token, 测试于 Yearning 2.1.6 | |
// @author Yaguang Ding | |
// @namespace https://yearning.yourcompany.com/ | |
// @version 0.1 | |
// @include https://yearning.yourcompany.com/* | |
// @content self | |
// @require tampermonkey://vendor/jquery.js | |
// @grant GM_notification | |
// @run-at document-start | |
// ==/UserScript== | |
// 因为 Yearning 只有在刷新页面的时候才会从 SessionStorage 里面读取 jwt, | |
// 所以当我们的脚本重新登陆之后,即使设置了 SessionStorage 也不会生效, | |
// 因此需要通过 Hack XHR 的 setRequestHeader 方法,实现更新 Token 的目的 | |
// https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/setRequestHeader | |
let originSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader; | |
XMLHttpRequest.prototype.setRequestHeader = function (key, value) { | |
// console.log('setRequestHeader', key, value, this); | |
if(key == 'Authorization') { | |
if (value != sessionStorage.jwt) { | |
value = sessionStorage.jwt; | |
} | |
} | |
return originSetRequestHeader.apply(this, [key, value]); | |
}; | |
function login() { | |
var username = sessionStorage.user; | |
var password = localStorage.password; | |
if(!password) { | |
password = prompt("当前登录已失效,请重新登录, 请输入密码:"); | |
if(!password) { | |
return; | |
} | |
} | |
$.ajax({ | |
method: 'POST', | |
url: '/ldap', | |
data: { | |
username: username, | |
password: password, | |
} | |
}).done(function(data) { | |
sessionStorage.jwt = 'Bearer ' + data.token; | |
localStorage.password = password; | |
GM_notification({ | |
text: "过期 Token 已经自动刷新!" | |
}) | |
}).fail(function(e) { | |
if(e.status == 401) { | |
localStorage.password = ''; | |
alert('密码错误'); | |
} else { | |
alert('登录失败:' + e.status); | |
} | |
}); | |
} | |
function check_token() { | |
$.ajax({ | |
method: 'GET', | |
url: '/api/v2/dash/count', | |
headers: { | |
Authorization: sessionStorage.jwt | |
} | |
}).done(function() { | |
console.log('token 有效') | |
}).fail(function(e) { | |
if(e.status == 400 || e.status == 401) { | |
if(confirm('Token 似乎已经过期,是否刷新 Token ?')) { | |
login(); | |
} | |
} | |
}); | |
} | |
// 每次切换到当前页面的时候,检查 Token 是否过期 | |
window.addEventListener('visibilitychange', function(e) { | |
if(document.visibilityState == 'visible'){ | |
check_token() | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment