53 lines
1.2 KiB
JavaScript
53 lines
1.2 KiB
JavaScript
import { computed, ref } from "vue";
|
|
import { defineStore } from "pinia";
|
|
|
|
const AUTH_STORAGE_KEY = "fms-auth";
|
|
|
|
try {
|
|
// Retain a session created before persistence moved from sessionStorage.
|
|
const session = sessionStorage.getItem(AUTH_STORAGE_KEY);
|
|
if (session && !localStorage.getItem(AUTH_STORAGE_KEY)) {
|
|
localStorage.setItem(AUTH_STORAGE_KEY, session);
|
|
}
|
|
} catch {
|
|
// Storage can be unavailable in restricted browser contexts.
|
|
}
|
|
|
|
export const useAuthStore = defineStore(
|
|
"auth",
|
|
() => {
|
|
const token = ref("");
|
|
const orgId = ref("");
|
|
const user = ref(null);
|
|
const isAuthenticated = computed(() => Boolean(token.value));
|
|
|
|
function setSession(session, organizationId) {
|
|
token.value = session.token ?? session.access_token ?? "";
|
|
orgId.value = session.orgid ?? organizationId;
|
|
user.value = session.user ?? session.user_info ?? null;
|
|
}
|
|
|
|
function clearSession() {
|
|
token.value = "";
|
|
orgId.value = "";
|
|
user.value = null;
|
|
}
|
|
|
|
return {
|
|
token,
|
|
orgId,
|
|
user,
|
|
isAuthenticated,
|
|
setSession,
|
|
clearSession,
|
|
};
|
|
},
|
|
{
|
|
persist: {
|
|
key: AUTH_STORAGE_KEY,
|
|
storage: localStorage,
|
|
pick: ["token", "orgId", "user"],
|
|
},
|
|
},
|
|
);
|