Add global auth middleware and refresh token handling
This commit is contained in:
29
app/middleware/auth.global.js
Normal file
29
app/middleware/auth.global.js
Normal 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;
|
||||
});
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user