I am trying to retain the user information when page refresh. I used cookieStore
for this purpose. So my run module in the Angular App looks like this.
.run(['$rootScope', '$cookieStore', '$state', function($rootScope, $cookieStore, $state) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, $location){
var requireLogin = toState.data.requireLogin;
if(typeof $rootScope.user == 'undefined'){
$rootScope.user=$cookieStore.get("user");
$rootScope.sessionid=$cookieStore.get("session");
}
if(requireLogin && typeof $rootScope.user === 'undefined'){
event.preventDefault();
$state.go('login', null, {notify: false}).then(function(state) {
$rootScope.$broadcast('$stateChangeSuccess', state, null);
});
}
});
Two main things I wanted to achieve from this is,
- Have to get the
user
andsession
info from the browser's local storage, when page refresh. - If user is undefined, then it has to be redirected to the login page. It is for restricting the users to go to intermediate pages without login.
If user is undefined
, and data is not available in the local storage, the first if statement
gives error and the second if statement
doesnot work.
So when the user tries to visit any page the first time without going to login page, it is not redirecting to the login page, because the code failed in first if statement
, the second if
not working.
How can I achieve both the functionalities together?
Thank you
You can create an
authInterceptor
factory and push it ininterceptors
.This method will always check if user is logged in or not on each page and will throw user on login page if he is not authenticated
Learn more about Interceptors
With Above Mechanism, you can use
Auth
service to getuser
info in anycontroller
ordirectives
as:in template file:
Note: You need to create a proper REST API in order to get correct
user
data