Mohamed Maoulainine Maoulainine 2b31753265
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 39s
CI / build (push) Failing after 8s
Format / formatting (pull_request) Successful in 5s
feat: added an login page but the auth issue is still persisting, found a way to interprete the token the line is commneted in case it breaks code or needs a change
2025-04-12 03:55:30 +02:00

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 };