Newer
Older
navi-1 / webclient / src / stores / auth.js
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { getMe, logout as apiLogout } from '@/api'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const loading = ref(false)
  const authConfigured = ref(false)

  const isAuthenticated = computed(() => user.value !== null)
  const isAdmin = computed(() => user.value?.role === 'admin')

  function hasPermission(permission) {
    if (!user.value) return false
    if (user.value.role === 'admin') return true
    return (user.value.permissions || []).includes(permission)
  }

  async function fetchMe() {
    loading.value = true
    try {
      user.value = await getMe()
    } catch (err) {
      if (err.message?.includes('401')) {
        user.value = null
      }
      throw err
    } finally {
      loading.value = false
    }
  }

  async function fetchStatus() {
    const res = await fetch('/auth/status')
    if (res.ok) {
      const data = await res.json()
      authConfigured.value = !!data.configured
    }
  }

  function login() {
    window.location.href = '/auth/login'
  }

  async function logout() {
    try {
      await apiLogout()
    } catch {
      // ignore
    }
    user.value = null
    window.location.reload()
  }

  return {
    user,
    loading,
    authConfigured,
    isAuthenticated,
    isAdmin,
    hasPermission,
    fetchMe,
    fetchStatus,
    login,
    logout,
  }
})