88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
import { defineStore } from "pinia";
|
|
import keycloakService from "@/services/keycloak";
|
|
import type Keycloak from "keycloak-js";
|
|
|
|
const useAuthStore = defineStore("storeAuth", {
|
|
state: () => {
|
|
return {
|
|
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 + "/login" //redirect to login page instead of 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);
|
|
}
|
|
},
|
|
// Clear user's store data
|
|
clearUserData() {
|
|
this.authenticated = false;
|
|
this.user = {
|
|
token: "",
|
|
refreshToken: "",
|
|
username: "",
|
|
};
|
|
},
|
|
},
|
|
});
|
|
|
|
type AuthStore = ReturnType<typeof useAuthStore>;
|
|
|
|
export { useAuthStore, type AuthStore };
|