简体   繁体   中英

Redirect users to login screen on page load if not authenticated (Nuxt-firebase)

I'm trying to setup navigation guards in my Nuxt app to redirect users to the login screen if they are not authenticated via Firebase Authentication. When the user attempts to navigate my router middleware is redirecting them successfully, but on page load they are not being redirected.

I did realize that the middleware is not even being fired on page load. I found a recommendation to try a plugin to handle the redirect on page load, but it is not working. Calling router.push from within the plugin does not redirect the user.

Here are a few notes on my setup. This is being deployed to firebase hosting directly as a SPA with no SSR. It's using the Nuxt-Firebase module with Firebase Authentication service.

// nuxt.config.js

  target: "server", // server here works when I deploy to firebase, but I also tried static
  ssr: false,
  middleware: ["auth"],
  plugins: [
    "~/plugins/auth.js",
  ],
  modules: [
    [
      "@nuxtjs/firebase",
      {
        services: {
          auth: {
            initialize: {
              onAuthStateChangedMutation:
                "authData/ON_AUTH_STATE_CHANGED_MUTATION",
              onAuthStateChangedAction: "authData/ON_AUTH_STATE_CHANGED_ACTION",
              subscribeManually: false,
            },
          },
        },
      },
    ],
  ],
};

Here's a sample plugin I thought might solve this, but calling handleLoggedOut appears to do nothing on page load.

// --- plugin to redirect user --- /plugins/auth.js   ---
export default function (context, inject) {
  const auth = {
    handleLoggedOut: () => {
      console.log("logout handled");
      context.redirect("/login");
    },
  };
  inject("auth", auth);
}

// --- store actions --- /store/authData.js  ---
  actions: {
    async ON_AUTH_STATE_CHANGED_ACTION(
      { commit, state, dispatch },
      { authUser, claims }
    ) {
      if (authUser) {
         // logged in
      }
      else {
         // attempting to redirect here does not work
         this.$auth.handleLoggedOut()
      }
   }

I'm new to Nuxt and I can't seem to find an example that solves my issue.

Any help would be greatly appreciated, thank you!

Code seems fine, But you can just use the this.$fire.auth.signOut() and you can remove the auth plugin.

Example:

// --- store actions --- /store/authData.js ---

actions: {
    async signOut({ commit }, payload) {
        try {
           await this.$fire.auth.signOut();
           // This is just a guard to avoid navigation guard error (NavigationDuplicated), 
           // you can remove the if block
           if (!payload) {
              this.$router.push('/login')
           }
           commit(ON_AUTH_STATE_CHANGED_MUTATION, { authUser: null})
        } catch(err) {
           console.log(err)
        }

    },
async ON_AUTH_STATE_CHANGED_ACTION(
      { commit, state, dispatch },
      { authUser, claims }
    ) {
      if (authUser) {
         // logged in
      }
      else {
         // attempting to redirect here does not work
         return dispatch('signOut')
      }
   }

}

The solution for redirecting users to the login on page load was to put this in my auth middleware:

export default function ({ redirect, store, route }) {
  // https://nuxtjs.org/docs/internals-glossary/context#redirect
  if (!store || !store.getters || !store.getters["authData/isLoggedIn"]) {
    window.onNuxtReady(() => {
      window.$nuxt.$router.push("/login");
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM