AngularJS Authorization

In this article we'll talk about quickly and "painless" access control in AngularJS. We also touch some standard routing tools provided by AngularJS kernel and will write a simple application with authorization. This article is based on Доверяй, но проверяй with several important changes. So, Angular offers us $routeProvider authorization mean from ngRoute module.

Routing scheme:

    • /add - add object
    • /view - view object
    • /login - authorization page

User roles:

    • admin - superuser
    • user - regular user
    • guest - unregistered user

app.js

var app = angular.module('bookWorldApp', 
['ngRoute', 'authorizationModule', 
'securityModule'])
  .config(function($routeProvider){
    $routeProvider

      .when('/add', {
          templateUrl: 'view/add.html',
          controller: 'addCtrl'   
      })
     .when('/view', {
          templateUrl: 'view/view.html',
          controller: 'viewCtrl'
      })
      .when('/login', {
        templateUrl: 'view/login.html',
        controller: 'loginCtrl'
      })
      .otherwise({
        redirectTo: '/login'
      });
  });

authorizationModule.js

var authorizationModule = 
angular.module('authorizationModule', []);

authorizationModule.controller('loginCtrl', 
['$scope', 'userService', '$userProvider', '$http', '$location', 
function($scope,userService, $userProvider, $http, $location){
	$scope.user;
	var Guest = {Login: "Guest", Roles: [2]};
	if (typeof $scope.user === "undefined") {
		//if session token exist
		if ( (typeof $.cookie("token") !== "undefined") 
               && ($.cookie("token") !== "null") )  {
			userService.getUserByToken($.cookie("token"))
			.then(function (u) {
				$scope.user = u.data;
				$userProvider.setUser(u.data);
			});
		}
		else
			$scope.user = Guest;
   }
	$userProvider.setUser($scope.user);
	

  $scope.exit = function() {
      $userProvider.setUser({Login: "Guest", Roles: [2]});
      $.cookie("token", "null");
      $scope.goTo('/login');
    }

$scope.isUserLogIn = function(){
  if ( $.cookie("token") != "null" )
    return true;
  return false;
}

$scope.loginClick = function(user) {
	if (typeof user.login !== "undefined")
		userService.loginUser(user);
}	

}]);

authorizationModule.factory('$userProvider', 
['userService', function(userService){

	var Guest = {Login: "Guest", Roles: [2]};
	var user;
	if (typeof user === "undefined") {
		//if session token exist
		if ( (typeof $.cookie("token") !== "undefined") 
                && ($.cookie("token") !== "null") )  {
			userService.getUserByToken($.cookie("token"))
			.then(function (u) {
				user = u.data;
			});
		}
		else
			user = Guest;
      }

var rolesEnum = {
    Admin: 0,
    User: 1,
    Guest: 2
  };
  
  var setUser = function(u){
    user = u;
  }
  
  var getUser = function(){
    return user;
  }
   
  return {
    getUser: getUser,
    setUser: setUser,
    rolesEnum: rolesEnum
  }
}]);

securityModule.js

angular.module('securityModule', ['authorizationModule'])
.factory('$pagesSecurityService', ['$userProvider', '$location',
    function ($userProvider, $location) {

        var checkAuthorize = function(path) {
            if ($userProvider.getUser() == null) {
                $location.path('/login');
            }
            switch (path) {
              case '/add':
                  return checkPageSecurity({
                      UserRoles: $userProvider.getUser().Roles,
                      AvailableRoles: [
                          $userProvider.rolesEnum.Admin
                      ]
                  });
              case '/view':
                  return checkPageSecurity({
                      UserRoles: $userProvider.getUser().Roles,
                      AvailableRoles: [
                          $userProvider.rolesEnum.Admin, 
                          $userProvider.rolesEnum.User
                      ]
                  });
              case '/galler':
                  return checkPageSecurity({
                      UserRoles: $userProvider.getUser().Roles,
                      AvailableRoles: [
                          $userProvider.rolesEnum.Admin, 
                          $userProvider.rolesEnum.User
                      ]
                  });
   
            default:
                return true;
            }
        };

        var checkPageSecurity = function (config) {
            var authorize = false;
            for (var i in config.UserRoles) {
                if ($.inArray(config.UserRoles[i], 
                config.AvailableRoles) == -1) {
                    authorize = false;
                } else {
                    authorize = true;
                    break;
                }
            }
            return authorize;
        };

        return {
            checkAuthorize: checkAuthorize,
        };
    }]);