使用Nuxt.js和Firebase中间件进行身份验证

huangapple go评论60阅读模式
英文:

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.

使用Nuxt.js和Firebase中间件进行身份验证

//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