Handling User Roles and Permissions in AngularJS

Loading

Managing user roles and permissions is crucial in AngularJS applications to control access to routes, UI elements, and API requests. This guide will cover:

✔ Setting up user roles in AngularJS
✔ Restricting routes based on roles
✔ Hiding or showing UI elements dynamically
✔ Enforcing backend security


1. Understanding User Roles and Permissions

A role-based access control (RBAC) system assigns users roles such as:

  • Admin – Full access to all features
  • Editor – Can edit content but cannot manage users
  • Viewer – Read-only access

Permissions define what each role can or cannot do.


2. Implementing Role-Based Access Control (RBAC)

A. Storing User Roles Securely

Store user roles securely in encrypted cookies or local storage.

Example: Assigning Roles When a User Logs In

app.service('AuthService', ['$http', '$q', function($http, $q) {
var userRole = null;

this.login = function(credentials) {
return $http.post('/api/login', credentials).then(function(response) {
userRole = response.data.role; // e.g., 'Admin', 'Editor', 'Viewer'
localStorage.setItem('userRole', userRole);
return response.data;
});
};

this.getRole = function() {
return localStorage.getItem('userRole') || 'Guest';
};

this.logout = function() {
userRole = null;
localStorage.removeItem('userRole');
};
}]);

B. Restricting Routes Based on Roles

Use $routeProvider to restrict certain views based on user roles.

Example: Protecting Routes

app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'DashboardController',
data: { roles: ['Admin', 'Editor'] } // Allowed roles
})
.when('/admin', {
templateUrl: 'admin.html',
controller: 'AdminController',
data: { roles: ['Admin'] } // Only Admin can access
})
.otherwise({ redirectTo: '/login' });
}]);

app.run(['$rootScope', 'AuthService', '$location', function($rootScope, AuthService, $location) {
$rootScope.$on('$routeChangeStart', function(event, next) {
var userRole = AuthService.getRole();
if (next.data && next.data.roles && next.data.roles.indexOf(userRole) === -1) {
event.preventDefault();
$location.path('/unauthorized'); // Redirect unauthorized users
}
});
}]);

How It Works:
✔ If the user role is not in the allowed roles, they are redirected to /unauthorized.


C. Showing or Hiding UI Elements Dynamically

Use ng-if or ng-show to show/hide UI elements based on roles.

Example: Hide Buttons Based on User Role

<button ng-if="userRole === 'Admin'" ng-click="deleteUser()">Delete User</button>

Example: Using a Directive for Role-Based UI Control

app.directive('hasRole', ['AuthService', function(AuthService) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var allowedRoles = attrs.hasRole.split(',');
var userRole = AuthService.getRole();

if (allowedRoles.indexOf(userRole) === -1) {
element.remove(); // Hide if the user role is not allowed
}
}
};
}]);

Example: Use the Directive in HTML

<button has-role="Admin,Editor">Manage Users</button>

How It Works:
✔ The directive checks if the user has one of the allowed roles.
✔ If not, the element is removed from the DOM.


3. Enforcing Security in the Backend

While front-end checks improve UX, they cannot fully protect against unauthorized access. Always enforce role-based access on the backend.

Example: Securing API Endpoints

app.post('/api/admin-action', verifyToken, (req, res) => {
if (req.user.role !== 'Admin') {
return res.status(403).send('Forbidden: Access Denied');
}
// Proceed with admin action
});

Leave a Reply

Your email address will not be published. Required fields are marked *