英文:
Authentication using Nuxt.js and Firebase middleware
问题
- 我有一个 Nuxt Js 3 + Firebase 项目。在这个项目中,要求登录以访问管理员面板。
- 我下面写的代码部分正常运行。
然而,正如您在 GIF 中所看到的,当我在未登录的情况下转到 /admin/dashboard 页面时,页面会出现几秒钟,也就是说,它会渲染并将其发送到登录页面。
我想要的 是首先检查是否已登录,如果没有登录,不要跳转到 /admin/dashboard 页面,而是保持在登录页面。
英文:
- I have a Nuxt Js 3 + Firebase project. In this project, login is required to access the admin panel.
- The code sections I wrote below are working properly.
However, as you can see in the Gif, when I go to the /admin/dashboard page without logging in, the page comes for a few seconds, that is, it renders and sends it to the login page.
What I want is to first check if you are logged in, if you are not logged in, it does not go to /admin/dashboard and stays on the login page.
//middleware/isAuth.js
import { auth } from "~~/firebase/config";
export default defineNuxtRouteMiddleware(async (to, from) => {
await auth.onAuthStateChanged(async (user) => {
if (user == null && to.name != "admin") {
return await navigateTo("/admin");
} else if (user && to.name == "admin") {
return navigateTo("/admin/dashboard");
} else if (user && to.name != "admin") {
return navigateTo(from.fullPath);
}
});
});
答案1
得分: 1
我用一个小技巧解决了这个问题,没有使用中间件。
// layouts/admin/default.vue
英文:
I solved this problem without using middleware with a little trick
// layouts/admin/default.vue
<template>
<div v-if="loading">loading</div>
<div v-else>
....
</div>
<template>
<script setup>
import { useAuthStore } from "~~/stores/authStore";
import { auth } from "@/firebase/config";
const currentUser = ref(false);
const loading = ref(true);
const router = useRouter();
const authStore = useAuthStore();
auth.onAuthStateChanged(async () => {
loading.value = true;
currentUser.value = await auth.currentUser;
if (currentUser.value) {
await authStore.setCurrentUser(currentUser.value);
router.push("/admin/dashboard");
} else {
router.push("/admin");
}
loading.value = false;
});
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论