import { defineStore } from "pinia"; import keycloakService from '@/services/keycloak'; import type Keycloak from "keycloak-js"; export const useAuthStore = defineStore("storeAuth", { state: () => { return { testv: true, authenticated: false, user: { token: "", refreshToken: "", username: "", }, } }, persist: true, getters: {}, actions: { // Initialize Keycloak OAuth async initOauth(keycloak: Keycloak, clearData = true) { if(clearData) { await this.clearUserData(); } this.authenticated = !!keycloak.authenticated; // the !! removes undefined if (this.authenticated && keycloak.token && keycloak.idTokenParsed && keycloak.refreshToken){ this.user.username = keycloak.idTokenParsed.given_name; this.user.token = keycloak.token; this.user.refreshToken = keycloak.refreshToken; } }, async login(){ try { const keycloak = await keycloakService.callLogin(); if (keycloak) await this.initOauth(keycloak); } catch (error) { console.log(error) } }, async signup() { try { const keycloak = await keycloakService.callSignup(); if (keycloak) await this.initOauth(keycloak); } catch (error) { console.log(error) } }, // Logout user async logout() { try { await keycloakService.CallLogout(import.meta.env.VITE_APP_URL + "/test"); await this.clearUserData(); } catch (error) { console.error(error); } }, // Refresh user's token async refreshUserToken() { try { const keycloak = await keycloakService.CallTokenRefresh(); if (keycloak) await this.initOauth(keycloak, false); } catch (error) { console.error(error); } }, test() { this.testv = !this.testv; }, // Clear user's store data clearUserData() { this.authenticated = false; this.user = { token: "", refreshToken: "", username: "", }; } } });