import {defineStore} from 'pinia'
import Keycloak from 'keycloak-js'
export const useKeycloakStore = defineStore('Keycloak', {
state: () => {
const keycloak = null
return {
keycloak
}
},
persist: true,
getters: {
token: (state) => {return state.keycloak?.token},
username:(state)=>state.keycloak?.tokenParsed?.preferred_username,
email:(state)=>state.keycloak?.tokenParsed?.email
},
actions: {
//创建定时器
createRefreshTokenTimer(keycloak) {
setInterval(() => {
keycloak.updateToken(60).then((refreshed) => {
if (refreshed) {
console.log("Token 已更新:" + new Date() + '\n' + keycloak.token)
} else {
// 这里只是检查Token是否更新了,所以发现没更新的话,什么都不用做
}
}).catch(() => {
console.error("更新Keycloak Token失败!")
})
}, 6000)
},
code
//初始化Keycloak对象
async initializeKeycloak() {
const my_promise = new Promise((resolve, reject) => {
const keycloak = new Keycloak({
url: "http://192.168.1.8:8080/",
realm: "sinno",
clientId: "sinno_pd_manager",
});
keycloak.init({
onLoad: "login-required",
checkLoginIframe: false, // otherwise it would reload the window every so seconds
enableLogging: true,
pkceMethod: 'S256',
flow: 'standard',
}).then(async (authenticated) => {
if (authenticated) {
//将 Promise 的状态由"未完成"改为"成功"
this.keycloak = keycloak //把注册的keycloak存到store里
resolve(首次登录,Keycloak授权成功!\nToken:\n${this.keycloak.token});
await this.createRefreshTokenTimer(this.keycloak);
} else {
//将 Promise 的状态由"未完成"改为"失败",
reject(new Error(Keycloak授权失败!${authenticated}))
}
})
//上面在调用keycloak.init后根据状态设定了promise的最终状态,下面同理,根据promise的状态进行下一步处理
}).then(async (success_msg) => {
console.log(success_msg)
//添加定时器
// await this.createRefreshTokenTimer(this.keycloak);
}).catch((error) => {
console.error("首次登录,Keycloak授权失败!", error)
})
console.log("初始化已结束!")
code
},
login() {
this.keycloak.login()
},
logout() {
this.keycloak.logout()
},
},
})改成这样不行吗嘛