You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

104 lines
2.4 KiB

// composables/useAuth.ts
/**
* Authentication composable
*
* Wrapper around nuxt-auth-utils useUserSession() with convenience methods
*
* Usage:
* const { user, loggedIn, login, logout } = useAuth()
*/
export function useAuth() {
const { loggedIn, user, clear, fetch } = useUserSession()
/**
* Login with email and password
* Direct authentication via Cidaas API (no redirect)
*/
async function login(email: string, password: string) {
// Call login endpoint - creates session directly
const response = await $fetch<{ success: boolean; message?: string }>('/api/auth/login', {
method: 'POST',
body: { email, password },
// Don't throw on 4xx/5xx, we handle the response ourselves
ignoreResponseError: true,
})
// Check if login was successful
if (!response.success) {
// Throw error with the server's message (contains German text with umlauts)
const error: any = new Error(response.message || 'Login failed')
error.data = response
error.statusCode = 401
throw error
}
// Refresh user session
await fetch()
// Redirect to homepage or saved destination
const redirectAfterLogin = useCookie('redirect_after_login')
const destination = redirectAfterLogin.value || '/'
redirectAfterLogin.value = null // Clear cookie
navigateTo(destination)
}
/**
* Register new user
*/
async function register(data: {
email: string
password: string
firstName: string
lastName: string
}) {
try {
const result = await $fetch('/api/auth/register', {
method: 'POST',
body: data,
})
return result
} catch (error) {
console.error('Registration failed:', error)
throw error
}
}
/**
* Logout
* Clears session and redirects to homepage
*/
async function logout() {
try {
await $fetch('/api/auth/logout', { method: 'POST' })
await clear() // Clear client-side state
navigateTo('/') // Redirect to homepage
} catch (error) {
console.error('Logout failed:', error)
throw error
}
}
/**
* Refresh user data from server
*/
async function refreshUser() {
try {
await fetch() // Re-fetch session from server
} catch (error) {
console.error('Refresh user failed:', error)
}
}
return {
user,
loggedIn,
login,
register,
logout,
refreshUser,
}
}