45 lines
1.0 KiB
JavaScript
45 lines
1.0 KiB
JavaScript
import { ref, computed } from 'vue'
|
|
import api from '../axios.js'
|
|
|
|
const user = ref(null)
|
|
const loading = ref(false)
|
|
const fetched = ref(false)
|
|
|
|
export function useAuth() {
|
|
const isAuthenticated = computed(() => user.value !== null)
|
|
|
|
const userTier = computed(() => {
|
|
if (!user.value) {
|
|
return 'guest'
|
|
}
|
|
return user.value.tier ?? 'free'
|
|
})
|
|
|
|
const isPaidTier = computed(() => {
|
|
return ['basic', 'plus', 'pro'].includes(userTier.value)
|
|
})
|
|
|
|
async function fetchUser() {
|
|
if (fetched.value) {
|
|
return
|
|
}
|
|
loading.value = true
|
|
try {
|
|
const response = await api.get('/auth/me')
|
|
user.value = response.data
|
|
} catch {
|
|
user.value = null
|
|
} finally {
|
|
loading.value = false
|
|
fetched.value = true
|
|
}
|
|
}
|
|
|
|
function clearUser() {
|
|
user.value = null
|
|
fetched.value = false
|
|
}
|
|
|
|
return { user, loading, isAuthenticated, userTier, isPaidTier, fetchUser, clearUser }
|
|
}
|