Created
October 1, 2015 14:14
-
-
Save BoLaMN/f4061e6530754c3a5aa1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module | |
.factory('LoopBackAuth', function() { | |
var props = ['accessTokenId', 'currentUserId', 'currentUserData', 'rememberMe']; | |
var propsPrefix = '$LoopBack$'; | |
function LoopBackAuth() { | |
var self = this; | |
this.rememberMe = undefined; | |
this.currentUserData = null; | |
props.forEach(function(name) { | |
self[name] = load(name); | |
}); | |
} | |
LoopBackAuth.prototype.save = function() { | |
var self = this; | |
var storage = this.rememberMe ? localStorage : sessionStorage; | |
props.forEach(function(name) { | |
save(storage, name, self[name]); | |
}); | |
}; | |
LoopBackAuth.prototype.setUser = function(accessTokenId, userId, userData, rememberMe) { | |
this.accessTokenId = accessTokenId; | |
this.currentUserId = userId; | |
this.currentUserData = userData; | |
this.rememberMe = rememberMe; | |
} | |
LoopBackAuth.prototype.clearUser = function() { | |
this.accessTokenId = null; | |
this.currentUserId = null; | |
this.currentUserData = null; | |
} | |
LoopBackAuth.prototype.clearStorage = function() { | |
props.forEach(function(name) { | |
save(sessionStorage, name, null); | |
save(localStorage, name, null); | |
}); | |
}; | |
return new LoopBackAuth(); | |
// Note: LocalStorage converts the value to string | |
// We are using empty string as a marker for null/undefined values. | |
function save(storage, name, value) { | |
var key = propsPrefix + name; | |
if (value == null) value = ''; | |
storage[key] = angular.toJson(value); | |
} | |
function load(name) { | |
var key = propsPrefix + name; | |
return angular.fromJson(localStorage[key] || sessionStorage[key] || null); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment