Skip to main content

Overview

The useAuthStore manages authentication state, user sessions, and profile data. It integrates with Supabase Auth and handles both citizen (ciudadano) and administrator (administrador) user types.

State Properties

user
User | null
Current authenticated Supabase user object
usuario
Usuario | null
Extended user profile data from the database
loading
boolean
Loading state for async operations
error
string | null
Error message from last failed operation
fetchingUser
boolean
Flag to prevent concurrent user fetches

Getters

isAuthenticated
() => boolean
Returns true if a user is currently logged in
isCiudadano
() => boolean
Returns true if current user has ‘ciudadano’ role
isAdministrador
() => boolean
Returns true if current user has ‘administrador’ role

Actions

initAuth

Initializes authentication state and sets up auth state change listeners.
await authStore.initAuth()
return
Promise<void>
Resolves when initialization is complete
Features:
  • Retrieves current session
  • Fetches user profile data
  • Listens for auth state changes (SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED)
  • Handles automatic token refresh
  • Prevents duplicate user fetches

register

Registers a new user account.
const result = await authStore.register(
  email,
  password,
  userData
)
email
string
required
User’s email address
password
string
required
User’s password
userData
object
required
User profile information
return
Promise<{ success: boolean; error?: string }>
Result object indicating success or failure
Behavior:
  • Creates account in Supabase Auth
  • Creates corresponding record in usuarios or administradores table based on type
  • Sends verification email with redirect to /login?verified=true

login

Authenticates a user with email and password.
const result = await authStore.login(email, password)
email
string
required
User’s email address
password
string
required
User’s password
rememberMe
boolean
default:"true"
Maintained for compatibility (Supabase handles persistence automatically)
return
Promise<{ success: boolean; error?: string }>
Result object indicating success or failure
Behavior:
  • Authenticates with Supabase
  • Fetches user profile from usuarios or administradores table
  • Updates store state with user data

logout

Signs out the current user.
const result = await authStore.logout()
return
Promise<{ success: boolean; warning?: string }>
Always returns success: true after clearing local state
Behavior:
  • Clears local state immediately
  • Signs out from Supabase with 5-second timeout
  • Returns success even if timeout occurs (local state is cleared)

resetPassword

Sends password reset email to user.
const result = await authStore.resetPassword(email)
email
string
required
Email address to send reset link to
return
Promise<{ success: boolean; error?: string }>
Result object indicating success or failure
Behavior:
  • Sends reset email via Supabase Auth
  • Redirects to /reset-password when user clicks link

updateProfile

Updates the current user’s profile information.
const result = await authStore.updateProfile({
  nombres: 'Juan',
  apellidos: 'Pérez'
})
updates
Partial<Usuario>
required
Object with profile fields to update
return
Promise<{ success: boolean; error?: string }>
Result object indicating success or failure
Behavior:
  • Updates record in usuarios table
  • Refetches user data after successful update

fetchUsuario (Internal)

Fetches user profile data from database. Used internally by other actions.
const usuario = await authStore.fetchUsuario(userId)
userId
string
required
Supabase user ID
return
Promise<Usuario | null>
User profile data or null if not found
Features:
  • Prevents concurrent fetches with fetchingUser flag
  • 10-second timeout protection
  • Falls back to administradores table if not found in usuarios
  • Returns null if user doesn’t exist in either table

Usage Examples

<script setup>
import { useAuthStore } from '@/stores/auth.store'

const authStore = useAuthStore()

async function handleRegister() {
  const result = await authStore.register(
    '[email protected]',
    'password123',
    {
      nombres: 'Juan',
      apellidos: 'Pérez',
      cedula: '1234567890',
      parroquia: 'Manta',
      barrio: 'Centro',
      tipo: 'ciudadano'
    }
  )
  
  if (result.success) {
    console.log('Cuenta creada exitosamente')
  } else {
    console.error('Error:', result.error)
  }
}
</script>

Notes

The store automatically handles token refresh and maintains session state across page reloads.
The fetchUsuario action includes timeout protection and prevents concurrent fetches to avoid performance issues.
Use isAuthenticated(), isCiudadano(), and isAdministrador() getters for route guards and conditional rendering.

Build docs developers (and LLMs) love