Skip to content

Instantly share code, notes, and snippets.

@BoLaMN
Created October 1, 2015 14:14
Show Gist options
  • Save BoLaMN/f4061e6530754c3a5aa1 to your computer and use it in GitHub Desktop.
Save BoLaMN/f4061e6530754c3a5aa1 to your computer and use it in GitHub Desktop.
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