我已經做到了這一點通過創建一個名爲MyAuthentication角度服務呈現方法
爲了得到適當的分離我有一個單獨的用戶代理,它使我的用戶HTTP請求。
angular.module('myNgApplication').service('MyAuthentication', function ($rootScope, $cookies, $log, UserProxy) {
var self = this;
self.user = null ;
(function(){
UserProxy.retrieveSession().then(function(authResponse){
self.user = authResponse
}, function() {
self.user = null
})
}).call(this)
this.isLoggedIn = function() {
return self.user != null ;
}
this.login = function (email, password) {
return UserProxy.login(email, password).then(function(authResponse){
self.user = authResponse
return self.user
})
}
this.logout = function() {
return UserProxy.logout().then(function(response){
self.user = null ;
return response
})
}
// this is never used externally. because the HTTP request to gte the user may be in progress when this is called and therefore self.user is null
this.getUser = function() {
return self.user
}
this.bootstrapUser = function(callback){
if(self.isLoggedIn()){
callback(self.user)
}
else {
$rootScope.$watch(self.getUser, function(newUser, oldUser) {
if(newUser != oldUser) {
callback(self.user)
}
});
}
}
})
用戶對象在內存中停留的整個時間...然後授權可能是這個樣子:
angular.module('myNgApplication').service('MyEntitlments', function (MyAuthentication) {
this.isEntitled = function(feature) {
return MyAuthentication.bootstrapUser(function(user){
// check users role and feature
return true || false
})
}
})
,我仍然使用Passport的服務器上。
好的,所以這不是存儲在cookie或localstorage?但是如果用戶關閉瀏覽器並返回頁面會發生什麼 - 他必須再次登錄,對吧? – uglycode
好吧,是的。你不能兩面都有。您可以做的另一件事是添加一個cookie來標識服務器上的會話。用戶cookie中唯一的東西是會話ID。 MyAuthentication服務中的自我調用功能試圖檢索會話...所以你可以在那裏工作。 – akaphenom
現實情況是,您將需要存儲本地的東西,或者要求它們在關閉瀏覽器時重新登錄。如果你存儲了本地的東西,那麼你最好儘可能少地存儲。 – akaphenom