refactor: use middleware to handle redirection

This commit is contained in:
Anthony Fu 2022-11-15 21:54:13 +08:00
parent a17d3276d3
commit 0dac7b9785
3 changed files with 15 additions and 13 deletions

8
middleware/auth.ts Normal file
View file

@ -0,0 +1,8 @@
export default defineNuxtRouteMiddleware((from) => {
const token = useCookie('nuxtodon-token')
if (!token.value)
return navigateTo('/public')
else if (from.path === '/')
return navigateTo('/home')
})

View file

@ -1,8 +1,7 @@
<script setup lang="ts">
const token = useCookie('nuxtodon-token')
const router = useRouter()
if (!token.value)
router.replace('/public')
definePageMeta({
middleware: 'auth',
})
const masto = await useMasto()
const paginator = masto.timelines.getHomeIterable()
@ -17,7 +16,7 @@ const paginator = masto.timelines.getHomeIterable()
<div color-gray i-ri:equalizer-fill mr-1 h-6 />
</template>
<slot>
<TimelinePaginator :timelines="paginator" />
<TimelinePaginator :paginator="paginator" />
</slot>
</MainContent>
</template>

View file

@ -1,12 +1,7 @@
<script setup lang="ts">
const token = useCookie('nuxtodon-token')
const router = useRouter()
// TODO: move to middleware
if (!token.value)
router.replace('/public')
else
router.replace('/home')
definePageMeta({
middleware: 'auth',
})
</script>
<template>