jeudi 1 février 2018

Pattern for redirecting on unauthorized vuex actions

Navigation guards are perfect for redirecting unauthorized users to a login page, but what about redirecting unauthorized vuex actions to a login page?

I can do this easily enough in the vue method where I'm calling the action like so:

  if (!this.isLoggedIn) {
    this.$router.push({ name: 'login', query: { comeBack: true } })
    $(`.modal`).modal('hide')
    return
  }

But then I'm inserting these 5 lines of code for every component method that requires authorization.

  1. I can reject it in an vuex action if I pass in the $router instance in the dispatch payload, but (a) I'm still using the same 5 lines for all auth required actions and (b) I'm passing up the router instance in order to change routes, which seems hacky

  2. I can add these five lines to a utility file, but now I'm handling the $route instance in utility file.

  3. I can use a global mixin and call it once before the action call, and again if the server returns a 401. But this also seems odd.

So what's the pattern that people are using to redirect on methods/actions?

Aucun commentaire:

Enregistrer un commentaire