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
Current authenticated Supabase user object
Extended user profile data from the database
id: string - User unique identifier
email: string - User email address
nombres: string - First names
apellidos: string - Last names
cedula: string - National ID number
parroquia: string - Parish location
barrio: string - Neighborhood
tipo: “ciudadano” | “administrador” - User role
activo: boolean - Account status
created_at: string - Creation timestamp
updated_at: string - Last update timestamp
Loading state for async operations
Error message from last failed operation
Flag to prevent concurrent user fetches
Getters
Returns true if a user is currently logged in
Returns true if current user has ‘ciudadano’ role
Returns true if current user has ‘administrador’ role
Actions
initAuth
Initializes authentication state and sets up auth state change listeners.
await authStore . initAuth ()
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
)
User profile information tipo
'ciudadano' | 'administrador'
required
User type/role
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 )
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 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'
})
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 )
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
Citizen Registration
Login & Check Role
Initialize Auth
Update Profile
< 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 >
< script setup >
import { useAuthStore } from '@/stores/auth.store'
import { computed } from 'vue'
const authStore = useAuthStore ()
async function handleLogin () {
const result = await authStore . login (
'[email protected] ' ,
'password123'
)
if ( result . success ) {
if ( authStore . isAdministrador ()) {
router . push ( '/admin/dashboard' )
} else {
router . push ( '/ciudadano/inicio' )
}
}
}
const canAccessAdmin = computed (() => {
return authStore . isAuthenticated () && authStore . isAdministrador ()
})
</ script >
< script setup >
import { useAuthStore } from '@/stores/auth.store'
import { onMounted } from 'vue'
const authStore = useAuthStore ()
onMounted ( async () => {
// Initialize auth on app startup
await authStore . initAuth ()
// Check if user is authenticated
if ( authStore . isAuthenticated ()) {
console . log ( 'User:' , authStore . usuario ?. nombres )
}
})
</ script >
< script setup >
import { useAuthStore } from '@/stores/auth.store'
const authStore = useAuthStore ()
async function updateUserProfile () {
const result = await authStore . updateProfile ({
nombres: 'Juan Carlos' ,
barrio: 'Los Esteros'
})
if ( result . success ) {
console . log ( 'Perfil actualizado' )
console . log ( 'Nuevo nombre:' , authStore . usuario ?. nombres )
}
}
</ 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.