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() {
    console.log('[auth] fetchMe start')
    loading.value = true
    try {
      user.value = await getMe()
      console.log('[auth] fetchMe success', user.value)
    } catch (err) {
      console.log('[auth] fetchMe error', err.message)
      if (err.message?.includes('401')) {
        user.value = null
      }
      // Swallow non-401 errors (network, 5xx) so the app stays usable
      // and doesn't flash the login screen on transient failures.
    } finally {
      loading.value = false
      console.log('[auth] fetchMe loading=false')
    }
  }

  async function fetchStatus() {
    console.log('[auth] fetchStatus start')
    try {
      const res = await fetch('/auth/status')
      console.log('[auth] fetchStatus response', res.status, res.ok)
      if (res.ok) {
        const data = await res.json()
        console.log('[auth] fetchStatus data', data)
        authConfigured.value = !!data.configured
        console.log('[auth] fetchStatus authConfigured set to', authConfigured.value)
      } else {
        console.log('[auth] fetchStatus not ok')
        authConfigured.value = false
      }
    } catch (err) {
      console.log('[auth] fetchStatus error', err)
      authConfigured.value = false
    }
  }

  function login() {
    const isAndroid = navigator.userAgent.includes('NaviAndroid')
    const params = new URLSearchParams()
    if (isAndroid) {
      params.set('platform', 'android')
    }
    const qs = params.toString()
    window.location.href = '/auth/login' + (qs ? '?' + qs : '')
  }

  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,
  }
})