feat: add useAuth composable with user tier detection
This commit is contained in:
@@ -3,5 +3,13 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
|
import { onMounted } from 'vue'
|
||||||
import { RouterView } from 'vue-router'
|
import { RouterView } from 'vue-router'
|
||||||
|
import { useAuth } from './composables/useAuth.js'
|
||||||
|
|
||||||
|
const { fetchUser } = useAuth()
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await fetchUser()
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
44
resources/js/composables/useAuth.js
Normal file
44
resources/js/composables/useAuth.js
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
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 }
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user