简体   繁体   中英

Nuxt.js middleware redirect based on role

On login I want to redirect to different page based on role using the nuxt.js middleware.

This is my notAuthenticated middleware

export default function({ store, redirect }) {
  // If the user is authenticated redirect to home page
  if (store.state.auth) {
    debugger
    if (store.state.auth.role === 'admin') {
      return redirect('/admin')
    } else {
      return redirect('/')
    }
  }
}

Problem is it does not redirect to /admin and I don't know how to debug it. Debugger is not working here.

Seems middleware didn't redirect me after login, so I had to use the router and redirect based on the role after the login has completed.

EDIT: As asked I'm adding also the code solution.

In my login function, after logging in I check the role of the user (which in my case was saved in the JWT token).

login(data) {
      const self = this
      this.$axios.post('/auth/login', data).then(function(response) {
        const tkData = self.parseJwt(response.data.Token)
        const auth = {
          accessToken: response.data.Token,
          email: tkData.email,
          role: tkData.role
        }
        self.$store.commit('setAuth', auth)
        Cookie.set('auth', auth)
        if (tkData.role === 'admin') {
          self.$router.push('/admin')
        } else {
          self.$router.push('/')
        }
      })
    }

PS: You can check out my code and test it in my GitHub

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