Checking Login on every view

I am building an app where user must be loggedin/signup from the beginning. The one must be loggedin to see a single view , I have to put below code on every view

var post = JSON.parse(window.localStorage['chanmeds_cridentials'] || '{}'); if ( post.username !== undefined && post.loggedin !== undefined ){ $scope.alreadyloggedin = true; } else { $scope.alreadyloggedin = false; //$state.go("app.playlists"); //$location.path("app.playlists"); }

One, I have repeat code again and again on every controller and second , either $state.go(“app.playlists”); or $location.path(“app.playlists”); (which I commented in above code) nothing redirecting to login page well, while testing on my mac. some kind of error I am not aware of , so instead of auto redirect to login view (which is playlists for now ) , I have to do trick below on every view :


You are not logged in. Login here.

Add a Base state and controller around your whole app --> in that controller you can listen on $stateChangeStart event

There you can check if user is loggedin --> if not do not allow to go to this state (if it is not the login state)

angular.module('myApp').controller('BaseCtrl', function ($scope, $state) {
    $scope.$on('$stateChangeStart', function (event, toState) {
        var post = JSON.parse(window.localStorage['chanmeds_cridentials'] || '{}'),
              isLoggedin = post.username !== undefined && post.loggedin !== undefined;

        if ( === 'YOURLOGINSTARE' && isLoggedin) {
            event.preventDefault(); // stop current routing
        } else if ( !== 'YOURLOGINSTARE' && !isLoggedin) {
            event.preventDefault(); // stop current routing
            // reset history and clear your localstorage
1 Like

maybe you forgot to inject $state / $location in your respective controller !
$state for $state.go OR $location to $location.path

1 Like

Do I have to ? so instead of
controller(‘AppCtrl’, function($scope, $http)
it should be like
controller(‘AppCtrl’, function($scope, $http, $state, $location) ?

yes right ! any one which you using ! injecting both wont hurt either ! inject $state and use $state.go only

1 Like

Awesome brah ! it worked.

Great… ! cheers (y)

However, last thing remain, do i have to paste the code in every view ? I guess, there should be any function or service stuff instead of pasting same codes.

yes , you can maintain the same code in a single service and call the service function from the controller ! which will require injecting the service name in the controller ! google angular services or google sharing data between controllers using service

1 Like