Add global auth middleware and refresh token handling

This commit is contained in:
2025-08-08 19:52:43 +02:00
parent 43016fa5a9
commit 65e0c583cf
3 changed files with 39 additions and 9 deletions

View File

@@ -0,0 +1,29 @@
// file: ~/middleware/authentication.global.ts
export default defineNuxtRouteMiddleware(async (to) => {
const { status, refresh } = useAuth();
const deleteCookies = () => {
const atoken = useCookie("authls.atoken");
atoken.value = null;
const rtoken = useCookie("authls.rtoken");
rtoken.value = null;
};
// Return immediately if user is already authenticated and protected page
if (status.value === "authenticated" && to.meta.auth === true) {
console.log("case 1");
return;
}
if (status.value !== "authenticated" && to.meta.auth === true) {
try {
console.log("case 2");
await refresh();
} catch {
console.log("case 3");
deleteCookies();
}
return;
}
deleteCookies();
return;
});

View File

@@ -10,11 +10,12 @@
<div class="mt-3">My Application's Home Page</div>
<div>
{{ norrisStore.response }}
</div>
<div>
{{ data }}
{{ status }}
</div>
<div>
<v-btn color="primary" @click="refresh">Refresca token</v-btn>
</div>
</v-container>
</template>
@@ -25,10 +26,9 @@ definePageMeta({
import { ref, onMounted } from "vue";
import { useChuckNorris } from "~/stores/chuck";
const norrisStore = useChuckNorris();
const { data, status } = useAuth();
const { data, status, refresh } = useAuth();
onMounted(async () => {
await norrisStore.getData();
console.log(norrisStore.response);
});
</script>