user2085143
user2085143

Reputation: 4232

Angular - Protected Pages

When it comes to pages that only a user who is logged should be able to view, I have a function like this in the controller on that page;

if ( user is not logged in ) {

    $state.go('someState')

} else {

    // prepare the page as normal

}

Considering I need to write something like this on each page I want to authenticate, I feel maybe there is a more elegant solution.

Should I perform this in the app.run instead? Something like

  var protectedPages = a list of protected pages

  if ( protectedPages && user is not logged in ) {

        $state.go('someState')

    } else {

        // prepare the page as normal

    }

or is there a more standard approach which is entirely different?

Upvotes: 1

Views: 112

Answers (1)

Poyraz Yilmaz
Poyraz Yilmaz

Reputation: 5857

General and I believe best approach for these kind of situation is setting a page change event and define logic there...

But for defining logic you need to know about some properties for next state so you can add some data for each state like requiresLogin. These properties are completely custom so you can define whatever you want.

Lets define some state which is requiresLogin

$stateProvider
        .state('exampleState', {
            url: '/example',
            controller: 'ExampleController as vm',
            templateUrl: 'example.html',
            data: {
                requiresLogin: true,
                someOtherCustomProperty: 'It can be anything'
            }
        })

as you see exampleState has requiresLogin property now in config block we can get this data and allow user to go exampleState or redirect him to some other state.

$rootScope.$on('$stateChangeStart', function (event, toState) {
        // if next state requires login and user is not loged in
        if (toState.data.requiresLogin && userNotLogedIn) {
            // prevent default behaviour and implement your logic here
            event.preventDefault();

            // TODO

            // as an example you can redirect user to login state
            $state.go('login');
        }
    });

That's it. All you have to do is put that logic in config block as it should check every state change...

Upvotes: 2

Related Questions