2016-10-05 215 views
0

在我的vue.js應用程序中,我有一個登錄系統。我main.js看起來是這樣的:Laravel&Vue.js身份驗證

import Vue from 'vue'; 
import NProgress from 'nprogress'; 
import Resource from 'vue-resource'; 
import Router from 'vue-router'; 
import App from './App.vue'; 
import Login from './components/Authentication/Login.vue'; 
import auth from './Services/Authentication/Auth'; 


Vue.use(Router); 
Vue.use(Resource); 

auth.checkAuth(); 

export var router = new Router({ 
    history: true 
}); 

router.map({ 
    '/': { 
     name: 'Login', 
     component: Login, 
     guest: true 
    } 
}); 

router.beforeEach((transition) => {  
    if (transition.to.auth && !auth.user.authenticated) { 
     transition.redirect('/login'); 
    } else if (transition.to.guest && auth.user.authenticated) { 
     transition.redirect('/'); 
    } else { 
     transition.next(); 
    } 
}); 

Vue.http.interceptors.push((request, next) => {  
    NProgress.start(); 
    const token = auth.getToken(); 
    request.headers['Authorization'] = 'Bearer ' + token; 
    request.headers['X-CSRF-TOKEN'] = document.querySelector('meta[name="token"]').content; 

    request.respondWith(request.body); 

    next((response) => { 
     NProgress.done(); 

     if (response.status == 404) { 
      router.go('/'); 
     } else if (response.status == 401 && response.data.refreshed_token) { 
      // If you received 401 "Unauthorized" response 
      // with a refreshed_token in the payload, 
      // this means you've got to refresh your token 
      auth.setToken(response.data.refreshed_token); 
     } 

     return response; 
    }); 
}); 

所以在每次請求我檢查用戶auth.checkAuth();該功能看起來像這樣(Auth.js)

checkAuth() { 
    var token || localStorage.getItem('jwt-token'); 

    if (!token) { 
     return false; 
    } 

    Vue.http.get('/api/me') 
     .then(({data}) => { 
     this.user.id = data.id; 
     this.user.name = data.name; 
     this.user.email = data.email; 
     this.user.role = data.role; 
     this.user.authenticated = true; 
     }, ({data}) => { 
      router.go('/'); 
     }); 
    } 

所以我的問題是,在我的router.beforeEach - >auth.user.authenticated我檢查用戶被認證。但是因爲auth.checkAuth();的承諾沒有退回,所以auth.user.authenticated總是假的!

我該如何解決這個問題?

會很有幫助!

+0

任何人!請! – Jamie

回答

1

對於未來的用戶有同樣的問題

Vue.http.interceptors.push((request, next) => { 
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken); 
    next((response) => { 
     if(response.status == 401) {//or add any error code you want here 
      //Do another request for some endpoint here to get a fresh token and override your token variable 
     } 
    }); 
});