Reputation: 959
Currently I am using $window.sessionStorage.token, so if user refresh the Page it maintains its session without losing any data. But now I want to open in different tab, but it is asking me to login again. After doing some research I found out that I have to use the localStorage.
Problem Question -
1) How would I share session between tabs using local Storage? 2) Is there another approach to this problem?
I have checked most of the post out there and does not give good understanding. If anyone can help with understanding this with basic example would be great and much appreciated.
Upvotes: 0
Views: 2804
Reputation: 1341
You need a service to inject each controller or the $rootScope for unified access. I am doing the same thing with an angular app. Here is my version to get you started. Authutils service you see used in he code is an implementation of Stanford Javascript Crypto Library at http://bitwiseshiftleft.github.io/sjcl/ to add a layer of security to the stored resources since they are easily visible with browser debugging tools:
angular.module('myApp').service('Dataservice', [
'Authutils',
function Dataservice(Authutils) {
var _test = [1, 2, 3];
var hasStorage = function() {
if (Modernizr.localstorage) {
return true;
} else {
return false;
}
};
var _get = function(key, make, init_data) {
var out = [];
var create = typeof make !== "undefined" ? make : false;
var data = typeof init_data !== "undefined" ? init_data : false;
if (hasStorage()) {
var sval = localStorage.getItem(key);
if (!!sval) {
try {
sval = Authutils.decrypt(sval);
out = JSON.parse(sval);
} catch (e) {
}
} else {
if (create) {
if (data) {
data = Authutils.encrypt(data);
_set(key, data);
} else {
_set(key, []);
}
}
}
}
return out;
};
var _set = function(key, value) {
if (hasStorage()) {
var subject = JSON.stringify(value);
localStorage.setItem(key, Authutils.encrypt(subject));
return true;
}
return false;
};
var _drop = function(key) {
if (hasStorage()) {
localStorage.removeItem(key);
return true;
}
return false;
};
var _nuke = function() {
if (hasStorage()) {
localStorage.clear();
return true;
}
return false;
};
var _push = function(key, value) {
var out = [];
if (hasStorage()) {
var current = JSON.parse(localStorage.getItem(key));
if (!!current) {
current.push(value);
_set(key, current);
}
}
return out;
};
return {
get: function(key, make, init_data) {
return _get(key, make, init_data);
},
set: function(key, value) {
_set(key, value);
},
push: function(key, value) {
_push(key, value);
},
trash: function(key) {
_cut(key);
},
nuke: function() {
_nuke();
},
test: function() {
return _test;
}
};
}
]);
Upvotes: 1