79 lines
1.7 KiB
JavaScript
79 lines
1.7 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
|
|
}
|
|
|
|
async function logout() {
|
|
try {
|
|
await api.post('/auth/logout')
|
|
} finally {
|
|
clearUser()
|
|
}
|
|
}
|
|
|
|
async function updateProfile(data) {
|
|
const response = await api.put('/user/profile', data)
|
|
user.value = response.data
|
|
}
|
|
|
|
async function updatePassword(data) {
|
|
await api.put('/user/password', data)
|
|
}
|
|
|
|
async function deleteAccount(password) {
|
|
await api.delete('/user', { data: { password } })
|
|
clearUser()
|
|
}
|
|
|
|
return {
|
|
user,
|
|
loading,
|
|
isAuthenticated,
|
|
userTier,
|
|
isPaidTier,
|
|
fetchUser,
|
|
clearUser,
|
|
logout,
|
|
updateProfile,
|
|
updatePassword,
|
|
deleteAccount,
|
|
}
|
|
}
|