useAuth
A composable that provides authentication functionality through a wrapper around Nuxt's Sanctum authentication. It offers methods for user login, logout, checking authentication status, and managing user data and tokens.
Usage
ts
import { useAuth } from '#imports'
// Check if user is authenticated
const { loggedIn } = useAuth()
if (loggedIn.value) {
// User is logged in
}
// Access user information
const { user } = useAuth()
console.log(user.value) // Current user object
// Login a user
const { login } = useAuth()
await login({
email: 'user@example.com',
password: 'password'
})
// Logout a user
const { logout } = useAuth()
await logout()
Type Signature
ts
function useAuth(): {
login: (credentials: any) => Promise<void>;
logout: () => Promise<void>;
loggedIn: ComputedRef<boolean>;
fetchUser: () => Promise<void>;
user: ComputedRef<any>;
setUserToken: (token: string) => Promise<void>;
getUserToken: () => Promise<string | null>;
}
Return Value
Property | Type | Description |
---|---|---|
login | (credentials: any) => Promise<void> | Method to authenticate a user with provided credentials |
logout | () => Promise<void> | Method to sign out the current user |
loggedIn | ComputedRef<boolean> | Whether a user is currently authenticated |
fetchUser | () => Promise<void> | Method to fetch the latest user data from the server |
user | ComputedRef<any> | The currently authenticated user object |
setUserToken | (token: string) => Promise<void> | Method to set the authentication token |
getUserToken | () => Promise<string | null> | Method to retrieve the current authentication token |
Examples
Basic Authentication
vue
<script setup>
import { ref } from 'vue'
import { useAuth } from '#imports'
const { login, loggedIn } = useAuth()
const email = ref('')
const password = ref('')
const loading = ref(false)
const error = ref(null)
async function submitLogin() {
loading.value = true
error.value = null
try {
await login({
email: email.value,
password: password.value
})
// Login successful - navigation is usually handled automatically
} catch (err) {
error.value = 'Invalid login credentials'
} finally {
loading.value = false
}
}
</script>
<template>
<div v-if="!loggedIn">
<form @submit.prevent="submitLogin">
<div v-if="error" class="error">{{ error }}</div>
<v-text-field
v-model="email"
label="Email"
type="email"
required
/>
<v-text-field
v-model="password"
label="Password"
type="password"
required
/>
<v-btn
type="submit"
:loading="loading"
color="primary"
>
Login
</v-btn>
</form>
</div>
<div v-else>
You are already logged in.
</div>
</template>
Accessing User Data
vue
<script setup>
import { useAuth } from '#imports'
const { user, loggedIn, logout } = useAuth()
async function handleLogout() {
await logout()
// Redirect or show login form
}
</script>
<template>
<div v-if="loggedIn">
<v-card>
<v-card-title>User Profile</v-card-title>
<v-card-text>
<p><strong>Name:</strong> {{ user.name }}</p>
<p><strong>Email:</strong> {{ user.email }}</p>
<p><strong>Role:</strong> {{ user.role?.name || 'No role assigned' }}</p>
</v-card-text>
<v-card-actions>
<v-btn @click="handleLogout">Logout</v-btn>
</v-card-actions>
</v-card>
</div>
</template>
Token Management
ts
import { useAuth } from '#imports'
// Use case: After receiving a token from an external source
async function processExternalToken(token) {
const { setUserToken, fetchUser } = useAuth()
// Set the token
await setUserToken(token)
// Fetch the user data with the new token
await fetchUser()
}
// Use case: Getting the current token for external API calls
async function makeExternalApiCall() {
const { getUserToken } = useAuth()
const token = await getUserToken()
// Use token in external API call
const response = await fetch('https://external-api.example.com/data', {
headers: {
'Authorization': `Bearer ${token}`
}
})
return response.json()
}