我刚刚从Marionette.js转移到Angular。现在我正在创建一个应用程序,其中有一个登录屏幕和主屏幕,我有两个休息api一个用于身份验证,另一个用于检查用户是否有活动会话(使用令牌)。如果用户有活动会话,我想将他重定向到主屏幕。
如何以最佳方式在Angular中实现此功能?
谢谢, MSK
注意:我使用yeoman / generator-angular和ui-router
答案 0 :(得分:1)
'use strict';
app.factory('Auth', function Auth($http, $cookies, $q) {
this.login = //...
this.isLoggedIn = //... point to your REST services
});
.state('settings', {
url: '/settings',
authenticate: true //add this to state where user needs to be authenticated
});
app.config(function($httpProvider) {
//add interceptor to add authentication header to be verified on the server
$httpProvider.interceptors.push('authInterceptor');
})
app.factory('authInterceptor', function($cookies) {
var state;
return {
// Add authorization token to headers
request: function(config) {
config.headers = config.headers || {};
if ($cookies.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('token');
}
return config;
}
};
});
app.run(function($rootScope, $state, Auth) {
// Redirect to login if route requires authentication
$rootScope.$on('$stateChangeStart', function(event, next) {
if (next.authenticate) {
Auth.isLoggedIn(function(loggedIn) {
if (!loggedIn) {
event.preventDefault();
$state.go('login');
}
});
}
});