H
H
helixly2016-11-11 08:19:33
Laravel
helixly, 2016-11-11 08:19:33

How to make vue.js authorization check delay?

There is a SPA application on Vue.js + Laravel. All authorization logic resides directly in Laravel. When using Vue-router, there was a need to check if the user is logged in or not. Actually there is a small Auth class that does this.

export default {
  user: {
    authenticated : false
  },
  check: function(context) {
    context.$http.get('/api/v1/user').then((response) => {
                if (response.body.user != null) {
                    this.user.authenticated = true
                }
      }, (response) =>{
      	 сonsole.log(response)
      });
   }
}


The component itself has a beforeRouteEnter method that fires when you go to the given url

beforeRouteEnter (to, from, next) {
    next(vm =>{
      Auth.check(vm);
        if (!Auth.user.authenticated) {
          next({path:'/login'});
        }
    })
  }


The next function, which actually navigates to the given url, accepts a callback with a Vue instance.
Then, in the next function itself, you can call it again to go to another url if something went wrong.
In general, everything works only if the page is already loaded by the browser. If you try to immediately go to the key page, then a redirect to /login occurs, even if the user is authorized, since the request to the api has not yet completed, and the code continues to be executed. Any ideas how to overcome this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
helixly, 2016-11-11
@helixly

Thought it out at all. I underestimated the power of promises. Who cares, you need to return the promise

check: function(context) {
   return context.$http.get('/api/v1/user').then((response) => {
                if (response.body.user != null) {
                    this.user.authenticated = true
                }
      }, (response) =>{
      	 сonsole.log(response)
      });
   }

Then
beforeRouteEnter (to, from, next) {
    Auth.check().then( ( ) => {
        if(!Auth.user.authenticated)
           next({ path: '/login' })
        else
           next()
    })
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question