Files
SIB/frontend/src/stores/auth.ts

65 lines
2.1 KiB
TypeScript
Raw Normal View History

2026-02-21 09:53:31 -05:00
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { supabase } from '@/supabase'
2026-02-21 09:53:31 -05:00
export const useAuthStore = defineStore('auth', () => {
const userSession = ref<any>(null)
const userProfile = ref<any>(null)
const isAuthenticated = computed(() => !!userSession.value)
// We check the custom Postgres role we put in our `users` table
const role = computed(() => userProfile.value?.role || userSession.value?.user?.user_metadata?.role)
const userName = computed(() => userProfile.value?.full_name || userSession.value?.user?.user_metadata?.full_name)
2026-02-21 09:53:31 -05:00
const isAdmin = computed(() => role.value?.toUpperCase() === 'ADMIN')
const isDriver = computed(() => role.value?.toUpperCase() === 'DRIVER')
const isPromoter = computed(() => role.value?.toUpperCase() === 'PROMOTER')
const isPassenger = computed(() => !role.value || role.value?.toUpperCase() === 'PASSENGER')
/** Listens for Supabase Auth state changes */
supabase.auth.onAuthStateChange(async (_event, session) => {
userSession.value = session
if (session?.user) {
// Immediately fetch their role from standard Public table if present
const { data } = await supabase
.from('users')
.select('*')
.eq('id', session.user.id)
.single()
if (data) userProfile.value = data
} else {
userProfile.value = null
}
})
async function login(email: string, pass: string) {
// Use standard Supabase signIn
const { error } = await supabase.auth.signInWithPassword({ email, password: pass })
if (error) throw new Error(error.message)
2026-02-21 09:53:31 -05:00
}
async function logout() {
await supabase.auth.signOut()
userSession.value = null
userProfile.value = null
2026-02-21 09:53:31 -05:00
window.location.href = '/'
}
return {
userSession,
userProfile,
2026-02-21 09:53:31 -05:00
role,
userName,
isAuthenticated,
isAdmin,
isDriver,
isPromoter,
isPassenger,
login,
logout
}
})