Extract shared auth logic and validation rules to shared/auth.ts Introduce utility functions for HTTP errors and user input parsing Standardize error messages and date formatting across the app
53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import { needsUserOnboarding, type AuthUser } from '~~/shared/auth'
|
|
|
|
export function useAuth() {
|
|
const user = useState<AuthUser | null>('auth:user', () => null)
|
|
const loaded = useState<boolean>('auth:loaded', () => false)
|
|
const loading = useState<boolean>('auth:loading', () => false)
|
|
const apiClient = useApiClient()
|
|
|
|
const isAuthenticated = computed(() => Boolean(user.value))
|
|
const isSuperAdmin = computed(() => user.value?.role === 'super_admin')
|
|
const needsOnboarding = computed(() => needsUserOnboarding(user.value))
|
|
|
|
async function fetchSession(force = false) {
|
|
if (loaded.value && !force) {
|
|
return user.value
|
|
}
|
|
|
|
loading.value = true
|
|
|
|
try {
|
|
const response = await apiClient<{ user: AuthUser | null }>('/api/auth/me')
|
|
user.value = response.user
|
|
loaded.value = true
|
|
return user.value
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
function setUser(nextUser: AuthUser | null) {
|
|
user.value = nextUser
|
|
loaded.value = true
|
|
}
|
|
|
|
function clearUser() {
|
|
user.value = null
|
|
loaded.value = true
|
|
}
|
|
|
|
return {
|
|
user,
|
|
loaded,
|
|
loading,
|
|
isAuthenticated,
|
|
isSuperAdmin,
|
|
needsOnboarding,
|
|
fetchSession,
|
|
refreshSession: () => fetchSession(true),
|
|
setUser,
|
|
clearUser
|
|
}
|
|
}
|