简体   繁体   中英

Get user on initial page load - Nuxt middleware

I'm using Firebase Auth in my Nuxt app and having some trouble with protected routes. I have the nuxt middleware enabled that handles redirection based on whether or not a user a logged in on page navigation.

My issue is, if you visit a protected route from the address bar and you were previously logged out, you'll be given access to the route. However if you try to visit another protected route from that route you'll be redirected. I am using Vuex to handle the user logged in state.

How can I get the middleware to kick in on a 'cold start' for a protected route.

Middleware: router-auth.js

export default function({ store, redirect, route }) {
    const user = JSON.parse(store.state.Authentication.user)
    console.log(user);
    user !== null && route.name === '/' ? redirect('/dashboard') : ''
    //user === null && route.name !== '/' ? redirect('/dashboard') : ''
  }

Plugin: auth.js

import firebase from "firebase/app";
import "firebase/auth";

export default function ({store, router}) {
  firebase.auth().onAuthStateChanged((user) => {
      if(user){
        store.dispatch('Authentication/SET_USER',JSON.stringify(user))
      }else{
        store.dispatch('Authentication/SET_USER', null)
      }
  })
}

Vuex: Authentication.js

export const state = () => ({
    user: ''
});

export const getters = {
    user: state => {
      return state.user;
    },
  
  }

export const mutations = {
    SET_USER: (state, payload) => {
        state.user = payload;
    },
}

export const actions = {
    SET_USER({ commit }, payload) {
        commit('SET_USER', payload)
    },
}

You can return an error func call in middleware:

export default function({ store, redirect, route, error }) {
  const accessDenied = true // ... your access route logic goes here
  if (accessDenied) {
    return error({
      message: 'access denied',
      statusCode: 403
    })
  }
}

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