改进 刷新策略

This commit is contained in:
iVampireSP.com 2023-12-06 09:10:39 +08:00
parent 70569ee1bb
commit 0fded66d7e
No known key found for this signature in database
GPG Key ID: 2F7B001CA27A8132

View File

@ -1,63 +1,68 @@
import {defineStore} from 'pinia' import { defineStore } from "pinia";
import axios from "axios"; import axios from "axios";
import {useConfigStore} from "./config"; import { useConfigStore } from "./config";
const useUserStore = defineStore('user', { const useUserStore = defineStore("user", {
persist: true, persist: true,
state: () => ({ state: () => ({
refresh_token: null as null | string, refresh_token: null as null | string,
jwt_token: null as null | string, jwt_token: null as null | string,
expired_at: null as null | Date, expired_at: null as null | Date,
}), }),
getters: { getters: {
isLoggedIn(): boolean { isLoggedIn(): boolean {
return this.jwt_token !== null return this.jwt_token !== null;
}
}, },
actions: { },
login(refresh_token: string, jwt_token: string) { actions: {
this.refresh_token = refresh_token login(refresh_token: string, jwt_token: string) {
this.jwt_token = jwt_token this.refresh_token = refresh_token;
}, this.jwt_token = jwt_token;
setExpired(expires_in: number) { },
// get date(current + seconds) setExpired(expires_in: number) {
this.expired_at = new Date(Date.now() + expires_in * 1000) // get date(current + seconds)
}, this.expired_at = new Date(Date.now() + expires_in * 1000);
logout() { },
console.log("logout") logout() {
this.refresh_token = null console.log("logout");
this.jwt_token = null this.refresh_token = null;
}, this.jwt_token = null;
refresh() { },
let config = useConfigStore() refresh() {
let config = useConfigStore();
axios.post(config.getRefreshUrl(), { axios
refresh_token: this.refresh_token .post(config.getRefreshUrl(), {
}).then(r => { refresh_token: this.refresh_token,
this.jwt_token = r.data.token })
}).catch(e => { .then((r) => {
console.error(e) this.jwt_token = r.data.token;
this.logout() this.setExpired(r.data.expires_in);
}) })
}, .catch((e) => {
get_token() { console.error(e);
return this.jwt_token this.logout();
} });
} },
}) get_token() {
return this.jwt_token;
},
},
});
setInterval(() => { setInterval(() => {
// check expired // check expired
const currentDate = new Date() const currentDate = new Date();
const userStore = useUserStore() const userStore = useUserStore();
const expiredAt = new Date(userStore.expired_at || 0);
// if has expired
if (userStore.expired_at !== null && expiredAt < currentDate) {
if (userStore.jwt_token !== null && userStore.refresh_token !== null) {
userStore.refresh();
}
}
}, 1000);
export { useUserStore };
})
export {
useUserStore
}