Sei sulla pagina 1di 8

Developing a permission-based auth system in AngularJS http://www.stefanoscerra.

it/permission-based-auth-system-in-angularjs/

19

{
name: "John Doe",
permissions: ['list_orders', 'read_statistics']
// ...
}

$routeProvider
requiresAuthentication permissions
permissions

1 angular
2 .module('app', [
3 'ngResource',
4 'ngRoute',
5 'AuthServices'
6 ])
7 .config(function ($routeProvider) {
8 $routeProvider
9 .when('/login', {
10 templateUrl: 'views/login.html',

1 of 8 12/25/2017, 7:54 PM
Developing a permission-based auth system in AngularJS http://www.stefanoscerra.it/permission-based-auth-system-in-angularjs/

11 controller: 'LoginCtrl'
12 })
13 .when('/home', {
14 templateUrl: 'views/home.html',
15 controller: 'HomeCtrl',
16 requiresAuthentication: true
17 })
18 .when('/sales/orders/new', {
19 templateUrl: 'views/sales/new_order.html',
20 controller: 'OrderDetailCtrl',
21 requiresAuthentication: true,
22 permissions: ["administration"]
23 })
24 .when('/sales/orders', {
25 templateUrl: 'views/sales/orders.html',
26 controller: 'OrdersCtrl',
27 requiresAuthentication: true,
28 permissions: ["administration", "list_orders"]
29 })
30 });

permission

1 <div class="sidebar" ng-show="user" ng-cloak>


2 <ul class="navigation">
3
4 <li permission="['administration']">
5 <span>Administration area</span>
6 <ul>
7 <li><a href="#/users">Users</a></li>
8 <li><a href="#/settings">Settings</a></li>
9 </ul>
10 </li>
11
12 <li permission="['administration', 'list_orders']">
13 <span>Sales</span>
14 <ul>
15 <li permission="['administration']">
16 <a href="#/sales/orders/new">New order</a>
17 </li>
18 <li permission="['administration', 'list_orders']">
19 <a href="#/sales/orders">Orders list</a>
20 </li>
21 </ul>
22 </li>
23
24 </ul>

2 of 8 12/25/2017, 7:54 PM
Developing a permission-based auth system in AngularJS http://www.stefanoscerra.it/permission-based-auth-system-in-angularjs/

Auth

1 angular.module('AuthServices', ['ngResource', 'ngStorage'])


2 .factory('Auth', function($resource, $rootScope, $sessionStorage, $q){
3
4 /**
5 * User profile resource
6 */
7 var Profile = $resource('/api/profile', {}, {
8 login: {
9 method: "POST",
10 isArray : false
11 }
12 });
13
14 var auth = {};
15
16 /**
17 * Saves the current user in the root scope
18 * Call this in the app run() method
19 */
20 auth.init = function(){
21 if (auth.isLoggedIn()){
22 $rootScope.user = auth.currentUser();
23 }
24 };
25
26 auth.login = function(username, password){
27 return $q(function(resolve, reject){
28 Profile.login({username:username, password:password}).$promise
29 .then(function(data) {
30 $sessionStorage.user = data;
31 $rootScope.user = $sessionStorage.user;
32 resolve();
33 }, function() {
34 reject();
35 });
36 });
37 };
38
39
40 auth.logout = function() {
41 delete $sessionStorage.user;
42 delete $rootScope.user;
43 };
44
45
46 auth.checkPermissionForView = function(view) {
47 if (!view.requiresAuthentication) {
48 return true;
49 }
50
51 return userHasPermissionForView(view);
52 };
53
54
55 var userHasPermissionForView = function(view){
56 if(!auth.isLoggedIn()){
57 return false;
58 }
59

3 of 8 12/25/2017, 7:54 PM
Developing a permission-based auth system in AngularJS http://www.stefanoscerra.it/permission-based-auth-system-in-angularjs/

60 if(!view.permissions || !view.permissions.length){
61 return true;
62 }
63
64 return auth.userHasPermission(view.permissions);
65 };
66
67
68 auth.userHasPermission = function(permissions){
69 if(!auth.isLoggedIn()){
70 return false;
71 }
72
73 var found = false;
74 angular.forEach(permissions, function(permission, index){
75 if ($sessionStorage.user.user_permissions.indexOf(permission) >= 0){
76 found = true;
77 return;
78 }
79 });
80
81 return found;
82 };
83
84
85 auth.currentUser = function(){
86 return $sessionStorage.user;
87 };
88
89
90 auth.isLoggedIn = function(){
91 return $sessionStorage.user != null;
92 };
93
94
95 return auth;
96 });

permission Auth

1 angular.module('app')
2 .directive('permission', ['Auth', function(Auth) {
3 return {
4 restrict: 'A',
5 scope: {
6 permission: '='
7 },
8
9 link: function (scope, elem, attrs) {
10 scope.$watch(Auth.isLoggedIn, function() {
11 if (Auth.userHasPermission(scope.permission)) {
12 elem.show();
13 } else {
14 elem.hide();
15 }
16 });
17 }
18 }
19 }]);

4 of 8 12/25/2017, 7:54 PM
Developing a permission-based auth system in AngularJS http://www.stefanoscerra.it/permission-based-auth-system-in-angularjs/

1 angular.module('app')
2 .controller('OrdersCtrl', function ($scope, Auth, Sales) {
3
4 if (Auth.userHasPermission(["administration"])){
5 // some evil logic here
6 var userName = Auth.currentUser().name;
7 // ...
8 }
9
10 });

Auth
user

1 <div ng-show="user" ng-cloak>


2 <span>{{user.full_name}}</span> <a ng-click="logout()">Logout</a>
3 </div>

run

1 angular.module('app', [
2 'ngResource',
3 'ngRoute',
4 'AuthServices'
5 ])
6 .run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
7 Auth.init();
8
9 $rootScope.$on('$routeChangeStart', function (event, next) {
10 if (!Auth.checkPermissionForView(next)){
11 event.preventDefault();
12 $location.path("/login");
13 }
14 });
15 }]);

Auth.init

Auth

1 angular.module('app').controller('LoginCtrl', function($scope, $location, Auth) {


2

5 of 8 12/25/2017, 7:54 PM
Developing a permission-based auth system in AngularJS http://www.stefanoscerra.it/permission-based-auth-system-in-angularjs/

3 $scope.email = "";
4 $scope.password = "";
5 $scope.failed = false;
6
7 $scope.login = function() {
8 Auth.login($scope.email, $scope.password)
9 .then(function() {
10 $location.path("/home");
11 }, function() {
12 $scope.failed = true;
13 });
14 };
15
16 });

1 angular.module('app')
2 .controller('MainCtrl', function ($scope, $rootScope, $location, Auth) {
3
4 $rootScope.logout = function(){
5 Auth.logout();
6 $location.path("/login");
7 };
8
9 });

Like 17 Tweet Share 19

6 of 8 12/25/2017, 7:54 PM
Developing a permission-based auth system in AngularJS http://www.stefanoscerra.it/permission-based-auth-system-in-angularjs/

13 Comments Stefano Scerra's blog 1 Login

Recommend 1 Share Sort by Best

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Michael Bennett • 7 months ago


Should line 22 of the AuthServices be auth.currentUser()? I was getting an error on page refresh
on line 22 until I made it auth.currentUser(). Thanks for the code.
1 • Reply • Share ›

Stefano Scerra Mod Michael Bennett • 7 months ago


Yes, you're right, fixed it. Thank you
• Reply • Share ›

leeu1911 • 5 months ago


As your Angular app expects this:

{
name: "John Doe",
permissions: ['list_orders', 'read_statistics']
// ...
}

Shouldn't line 75 of the AuthServices be:


if ($sessionStorage.user.permissions.indexOf(permission) >= 0){

Thanks for the nice tutorial anw.


• Reply • Share ›

apmeena • 10 months ago


Can I use the same thing with $stateProvider? Thanks.
• Reply • Share ›

Christian Böhm • a year ago


Excellent blog! Really usefull in order to start with. Let me add one extra idea about this... instead
of hardcoding the allowed permissions in the html, it would be better to get them from the
controller, so that if is not so easy for the user to see which is the expected permission key and
change it.
• Reply • Share ›

7 of 8 12/25/2017, 7:54 PM
Developing a permission-based auth system in AngularJS http://www.stefanoscerra.it/permission-based-auth-system-in-angularjs/

8 of 8 12/25/2017, 7:54 PM

Potrebbero piacerti anche