改进 刷新策略

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