You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.8 KiB
58 lines
1.8 KiB
import $ from 'jquery'; |
|
|
|
const authorization = async () => { |
|
const storage = localStorage; |
|
|
|
let haslogin = false; |
|
// 用户名 |
|
let username = storage.getItem('username_blog'); |
|
// 过期时间 |
|
const expired_time = Number(storage.getItem("expired_time")); |
|
// 当前时间 |
|
const current = new Date().getTime(); |
|
// 刷新令牌 |
|
const refreshToken = storage.getItem("refresh_blog"); |
|
// 未过期 |
|
if (expired_time > current) { |
|
haslogin = true; |
|
// console.log('authorization success'); |
|
} |
|
// 初始tokeng过期,则由刷新令牌申请新的token |
|
else if (refreshToken !== null) { |
|
try { |
|
$.ajax({ |
|
url: "http://127.0.0.1:6789/api/token/refresh/", |
|
type: "POST", |
|
async: false, |
|
data: { |
|
refresh: refreshToken, |
|
}, |
|
success(resp) { |
|
const nextExpiredTime = new Date().getTime() + 24*3600*1000; |
|
storage.setItem("access_blog", resp.access); |
|
storage.removeItem("refresh_blog"); // 移除刷新令牌 |
|
console.log( |
|
"令牌刷新时间: ", |
|
new Date().toLocaleString() |
|
); |
|
storage.setItem("expired_time", nextExpiredTime); |
|
haslogin = true; |
|
}, |
|
}); |
|
}catch(err){ |
|
storage.clear(); |
|
haslogin = false; |
|
// console.log('authorization err'); |
|
} |
|
|
|
} else { |
|
storage.clear(); // 清除所有有效信息 |
|
haslogin = false; |
|
// console.log('authorization exp'); |
|
} |
|
|
|
console.log('authorization done'); |
|
return [haslogin, username]; |
|
} |
|
|
|
export default authorization; |