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.
91 lines
1.8 KiB
91 lines
1.8 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
|
|
* Initiates OAuth2 flow
|
|
*/
|
|
async function login(email: string) {
|
|
try {
|
|
// Call login endpoint to get redirect URL
|
|
const { redirectUrl } = await $fetch('/api/auth/login', {
|
|
method: 'POST',
|
|
body: { email },
|
|
})
|
|
|
|
// Redirect to Cidaas
|
|
navigateTo(redirectUrl, { external: true })
|
|
} catch (error) {
|
|
console.error('Login failed:', error)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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,
|
|
}
|
|
}
|
|
|