-2

I put in place a simple login system in my angular application similar to the one at http://demos.angularcode.com/angularcode-authentication-app/#/login

The problem that I'm facing now is that if I try to access a page when I'm not logged in, it first displays the restricted page for a second before redirecting to login.

You can see this behaviour if you try to go directly to the page http://demos.angularcode.com/angularcode-authentication-app/#/dashboard

The earliest I can do the authentification check is in my module declaration:

angular.module('myApp', [])
.run(function() {
   //check auth + redirect
}

Is there a way to not display the restricted page first before redirecting to login?


EDIT

I use $urlRouterProvider and $stateProvider to manage routes.

For example the home page:

app.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise("/home");
    $stateProvider
        .state('home', {
            url : '/home',
            templateUrl : 'views/home.html'
        })
gyc
  • 4,300
  • 5
  • 32
  • 54

3 Answers3

1

You can 'catch' the state change start event, and check if the user may or may not be redirected to the requested page:

app.run(function ($rootScope, $state) {

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
        // run logic to check if login is required
        if (requireLogin && !userIsLoggedIn) {
            event.preventDefault(); // stop redirecting
            $state.go("login");
        } else {
            // allowed to go to requested state
            // .. do nothing, user will go to state
        }
    });

});
devqon
  • 13,818
  • 2
  • 30
  • 45
0
angular.module('myApp', [])
.run(function() {
  //Firstly Display Restricted page then after some time show the login page
}

Use this system $timeout. Show your restricted page and then call the login page from the same function after whatever time gap you want.

Check the documentation here for implementation. https://docs.angularjs.org/api/ng/service/$timeout

Check this Example - Pic is changed after some time

http://jsfiddle.net/thomporter/vqVrX/

You can check other jsfiddles as well to understand the concept.

Gandalf the White
  • 2,415
  • 2
  • 18
  • 39
0

Bind a variable to rootScope in order to check if user is logged in or not like $rootScope.isLoggedIn, and set it false by default.

Then add

ng-show="isLoggedIn"

attribute to home.html container.

I think it will fix your problem.

Ibrahim Mumcu
  • 243
  • 2
  • 11