84 lines
2.5 KiB
TypeScript
84 lines
2.5 KiB
TypeScript
import { defineStore } from "pinia"
|
|
|
|
export const useAuthStore = defineStore("auth", {
|
|
state: () => ({
|
|
user: null as null | { user_id: string; email: string; tenant_id?: string; role?: string },
|
|
profile: null as null | any,
|
|
tenants: [] as { tenant_id: string; role: string; tenants: { id: string; name: string } }[],
|
|
permissions: [] as string[],
|
|
activeTenant: null as any,
|
|
loading: true as boolean,
|
|
}),
|
|
|
|
actions: {
|
|
async init(token) {
|
|
await this.fetchMe(token)
|
|
},
|
|
|
|
async login(email: string, password: string) {
|
|
const { token } = await useNuxtApp().$api("/auth/login", {
|
|
method: "POST",
|
|
body: { email, password }
|
|
})
|
|
useCookie("token").value = token // persistieren
|
|
await this.fetchMe(token)
|
|
},
|
|
|
|
async logout() {
|
|
try {
|
|
await useNuxtApp().$api("/auth/logout", { method: "POST" })
|
|
} catch (e) {
|
|
console.error("Logout fehlgeschlagen:", e)
|
|
}
|
|
this.user = null
|
|
this.permissions = []
|
|
this.profile = null
|
|
this.activeTenant = null
|
|
this.tenants = []
|
|
useCookie("token").value = null
|
|
navigateTo("/login")
|
|
},
|
|
|
|
async fetchMe(jwt= null) {
|
|
try {
|
|
const me = await useNuxtApp().$api("/api/me", {
|
|
headers: { Authorization: `Bearer ${jwt}`,
|
|
context: {
|
|
jwt
|
|
}}
|
|
})
|
|
console.log(me)
|
|
this.user = me.user
|
|
this.permissions = me.permissions
|
|
this.tenants = me.tenants
|
|
this.profile = me.profile
|
|
|
|
if(me.activeTenant) {
|
|
this.activeTenant = me.activeTenant
|
|
this.loading = false
|
|
|
|
} else {
|
|
|
|
}
|
|
|
|
|
|
} catch (err: any) {
|
|
if (err?.response?.status === 401) this.logout()
|
|
}
|
|
},
|
|
|
|
async switchTenant(tenant_id: string) {
|
|
this.loading = true
|
|
const { token } = await useNuxtApp().$api("/api/tenant/switch", {
|
|
method: "POST",
|
|
body: { tenant_id }
|
|
})
|
|
useCookie("token").value = token
|
|
await this.init(token)
|
|
},
|
|
|
|
hasPermission(key: string) {
|
|
return this.permissions.includes(key)
|
|
}
|
|
}
|
|
}) |