AngularJS using State Provider

the $stateChangeStart event handling redirect to log-on state - if needed

by Yashwanth M

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootswatch/3.0.3/flatly/bootstrap.min.css">
<div ng-app="loginApp" class="container">
  <div class="page-header">
    <h1>AngularJS using State Provider</h1>
  </div>
  
  <a ui-sref="root.main" href="#/main">main state</a> <i>just authenticated</i><br />
  <a ui-sref="root.other" href="#/other">other state</a> <i>also for authenticated</i> <hr />
  <a ui-sref="root.public" href="#/public">public</a> <i>can see anybody</i><hr />
  <a ui-sref="root.login" href="#/login">login</a><hr />
  <div ui-view=""> </div>

<!-- Templates -->

<script type="text/ng-template" id="tpl.login.html">
<div>
  IsAuthenticated: <input type="checkbox" ng-model="auth.isLoggedIn" />
</div>
</script>
</div>

SCSS

// https://code.angularjs.org/1.2.1/angular-route.js
// http://jsfiddle.net/yaprak/789Ks/1/
// https://jsfiddle.net/awolf2904/Lmsumk2v/

// https://rawgit.com/angular-ui/ui-router/0.2.10/release/angular-ui-router.js
// https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js

// $routeProvider, $stateProvider - http://jsfiddle.net/mao8kx0L/5/

JavaScript

'use strict';

var myApp = angular.module('loginApp', ['ui.router','AppCtrls']);
var ctrls = angular.module("AppCtrls", []);

ctrls.controller( "UserCtrl", function($scope, User) {
    console.log("UserCtrl loaded.");
    $scope.user = User;
});

myApp.config(function($stateProvider, $urlRouterProvider)
{
  $stateProvider
    // available for anybody
    .state('public',{
        url : '/public',
        template : '<div>public</div>',
    })
    // just for authenticated
    .state('some',{
        url : '/some',
        template : '<div>some</div>',
        data : {requiresLogin : true },
    })
    // just for authenticated
    .state('other',{
        url : '/other',
        template : '<div>other</div>',
        data : {requiresLogin : true },
    })
    // the log-on screen
    .state('login',{
        url : '/login',
        templateUrl : 'tpl.login.html',
        controller : 'UserCtrl',
    })
    
  $urlRouterProvider.otherwise("/login");
})
.factory('User',function() { return { isLoggedIn : false, }; });
myApp.run(['$rootScope', '$state', 'User', function($rootScope, $state, User) {
  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {

    var isAuthenticationRequired =  toState.data 
          && toState.data.requiresLogin 
          && !User.isLoggedIn;

    if(isAuthenticationRequired)
    {
      event.preventDefault();
      $state.go('login');
    }
  });
}])