我有一个angularjs应用程序,它使用$ transitions来检查用户是否在某些$状态更改之前进行了身份验证。我使用passport.js来执行身份验证策略。如果未发生身份验证或未通过AuthisLoggedIn()检查,我希望用户恢复为“登录”状态。州。我遇到的问题是默认状态' /'似乎总是在我的身份验证承诺之前加载,Auth.getCurrentUserAsync()执行完毕导致一堆问题。如何强制在等待此身份验证检查时未加载任何状态,然后将用户发送到我的“登录”状态。如果他们在未经过身份验证的所有情况下都会说明。我的代码如下
app.js
clientApp.run(['$transitions', '$state', '$http', 'Auth', '$rootScope',
function($transitions, $state, $http, Auth, $rootScope) {
$http.defaults.xsrfHeaderName = 'X-CSRFToken'
$http.defaults.xsrfCookieName = 'csrftoken'
$rootScope.baseApiUrl='/app/api'
//verify the user
$transitions.onStart(
{
to: function(state) {
if (typeof state.authenticate !== 'undefined' && state.authenticate === false) {
return // this state does not require authentication
}
if (!Auth.isLoggedIn()) {
Auth.getCurrentUserAsync().then(
function() {
if (!Auth.isLoggedIn()) {
$state.go('login')
}
}
)
}
}
})
}])
clientApp.config(['$urlRouterProvider', '$stateProvider', '$locationProvider',
function($urlRouterProvider, $stateProvider, $locationProvider) {
$urlRouterProvider
.otherwise('/')
$stateProvider
.state('main', {
url: '/',
component: 'main',
authenticate: true
})
.state('login', {
url: '/login',
template: loginTemplate,
controller: 'LoginCtrl',
controllerAs: 'Login',
authenticate: false,
params: {
loginMessage: "",
loginErrorMessage: "",
username: "",
password: undefined,
errors: []
},
})
$locationProvider.html5Mode(true)
}])
auth.js
import angular from 'angular'
angular
.module('app.factories.auth', [])
.factory('Auth',
['$http', '$q', '$rootScope',
function Auth($http, $q, $rootScope) {
function _isLoggedIn() {
if (Object.keys(authObj.user).length !== 0) {
return true
} else {
return false
}
}
function _login(user) {
const deferred = $q.defer()
$http.post($rootScope.baseApiUrl + '/user/login', {
username: user.username,
password: user.password
})
.then(
function(response) {
if (response.status === 200) {
authObj.user = response.data.user
deferred.resolve(response)
} else {
authObj.user = {}
deferred.reject(response)
}
},
function(err) {
authObj.user = {}
deferred.reject(err)
}
)
return deferred.promise
}
function _getCurrentUserAsync() {
return $http.get($rootScope.baseApiUrl + '/user/status')
.then(
function(response) {
console.log('response', response)
if (response.data.status) {
authObj.user = response.data.user
} else {
authObj.user = {}
}
},
function() {
authObj.user = {}
})
}
const authObj = {
isLoggedIn: _isLoggedIn,
getCurrentUserAsync: _getCurrentUserAsync,
login: _login,
user: {}
}
return authObj
}
])