Files
FEDEO/frontend/stores/auth.ts
florianfederspiel 998d725528 Fixed Login
Allowed Workflows to be public #22
2026-01-06 21:12:51 +01:00

201 lines
6.4 KiB
TypeScript

import { defineStore } from "pinia"
import router from "#app/plugins/router";
import {Preferences} from "@capacitor/preferences";
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,
activeTenantData: null as any,
loading: true as boolean,
notLoggedIn: true,
}),
actions: {
async persist(token) {
console.log("On Web")
useCookie("token").value = token // persistieren
},
async initStore() {
console.log("Auth initStore")
// 1. Check: Haben wir überhaupt ein Token?
const token = useCookie("token").value
/*if (!token) {
// Kein Token -> Wir sind fertig, User ist Gast.
this.user = null
this.loading = false
return
}*/
// 2. Token existiert -> Versuche User zu laden
await this.fetchMe(token)
// Wenn fetchMe fertig ist (egal ob Erfolg oder Fehler), ladebalken weg
// Optional: Wenn eingeloggt, leite zur Home, falls gewünscht
if(this.activeTenant > 0) {
this.loading = false
// Hier vorsichtig sein: Nicht navigieren, wenn der User auf eine Deep-Link URL will!
// navigateTo("/") <-- Das würde ich hier evtl. sogar weglassen und der Middleware überlassen
}
},
async init(token=null) {
console.log("Auth init")
await this.fetchMe(token)
const tempStore = useTempStore()
if(this.profile?.temp_config) tempStore.setStoredTempConfig(this.profile.temp_config)
if(this.activeTenant > 0) {
this.loading = false
navigateTo("/")
}
},
async login(email: string, password: string) {
try {
console.log("Auth login")
const { token } = await useNuxtApp().$api("/auth/login", {
method: "POST",
body: { email, password }
})
console.log("Token: " + token)
// 1. WICHTIG: Token sofort ins Cookie schreiben, damit es persistiert wird
const tokenCookie = useCookie("token")
tokenCookie.value = token
// 2. User Daten laden
await this.fetchMe(token)
console.log(this.user)
// 3. WICHTIG: Jetzt explizit weiterleiten!
// Prüfen, ob der User geladen wurde
if (this.user) {
// Falls Passwort-Änderung erzwungen wird (passend zu deiner Middleware)
if (this.user.must_change_password) {
return navigateTo("/password-change")
}
// Normaler Login -> Dashboard
return navigateTo("/")
}
} catch (e) {
console.log("login error:" + e)
// Hier könnte man noch eine Fehlermeldung im UI anzeigen
}
},
async logout() {
console.log("Auth logout")
try {
await useNuxtApp().$api("/auth/logout", { method: "POST" })
} catch (e) {
console.error("Logout API fehlgeschlagen (egal):", e)
}
// State resetten
this.resetState()
// Token löschen
useCookie("token").value = null
// Nur beim expliziten Logout navigieren wir
navigateTo("/login")
},
resetState() {
this.user = null
this.permissions = []
this.profile = null
this.activeTenant = null
this.tenants = []
this.activeTenantData = null
},
async fetchMe(jwt= null) {
console.log("Auth fetchMe")
const tempStore = useTempStore()
// Token aus Argument oder Cookie holen
const tokenToUse = jwt || useCookie("token").value
try {
const me = await useNuxtApp().$api("/api/me", {
headers: {
Authorization: `Bearer ${tokenToUse}`,
context: { jwt: tokenToUse }
}
})
// ... (Deine Logik für tenants, sorting etc. bleibt gleich) ...
console.log(me)
this.user = me.user
this.permissions = me.permissions
this.tenants = me.tenants
this.tenants.sort(function (a, b) {
if (a.id < b.id) return -1
if (a.id > b.id) return 1
})
this.profile = me.profile
if(this.profile?.temp_config) tempStore.setStoredTempConfig(this.profile.temp_config)
if(me.activeTenant > 0) {
this.activeTenant = me.activeTenant
this.activeTenantData = me.tenants.find(i => i.id === me.activeTenant)
}
console.log(this)
} catch (err: any) {
// WICHTIG: Hier NICHT this.logout() aufrufen, weil das navigiert!
console.log("fetchMe failed (Invalid Token or Network)", err)
// Stattdessen nur den State sauber machen und Token löschen
this.resetState()
useCookie("token").value = null
// Wir werfen den Fehler nicht weiter, damit initStore normal durchläuft
}
},
async switchTenant(tenant_id: string) {
console.log("Auth switchTenant")
this.loading = true
const res = await useNuxtApp().$api("/api/tenant/switch", {
method: "POST",
body: { tenant_id }
})
console.log(res)
const {token} = res
useCookie("token").value = token // persistieren
await this.init(token)
},
hasPermission(key: string) {
return this.permissions.includes(key)
}
}
})