Currently, I am developing a Single Page Application (SPA) that interacts with a REST server on the backend.
The objective is to create a user interface that is consistent across all roles.
For example: On a product page, a guest can view the product and comments, a registered user can comment using a text box. An administrator has the ability to edit both comments and the product itself, all within the same SPA view.
Essentially, there are DOM elements that should be displayed for some users but not others.
To manage access control in my application, I have implemented a factory that checks if the user has the necessary privileges to access certain pages. This factory also updates the rootScope with the user's access level.
Within the compile function of the xLimitAccess directive, I validate the current user's access level to determine whether they can view the content within the directive before removing it.
Issue: The challenge lies in accessing the $rootScope from the compile function as it does not exist yet. If attempted in the link function, it is already too late to remove the element from the DOM.
Below is an example of HTML code:
<div class="product">...</div>
<div class="manageProduct" x-limit-access x-access-level="admin">...</div>
<div class="comment" x-limit-access x-access-level="user, admin">...</div>
<div class="comment" x-limit-access x-access-level="admin">...</div>
Javascript code snippet:
var app = angular.module('home', []);
app.config(function($routeProvider){
$routeProvider.
when('/',
{
templateUrl: 'views/home.html',
controller: 'homeCtrl',
resolve: {auth : 'authUser'} //This page is only accessible to logged-in users
}).
when('/login',
{
templateUrl: 'views/login.html',
controller: 'loginCtrl',
resolve: {}
}).
when('/logout',
{
templateUrl: 'views/logout.html',
controller: 'logoutCtrl',
resolve: {auth : 'authUser'} //This page is only accessible to logged-in users
}).
when('/register',
{
templateUrl: 'views/register.html',
controller: 'registerController',
resolve: {}
}).
when('/admin',
{
templateUrl: 'views/admin/home.html',
controller: 'registerController',
resolve: {auth: 'authAdmin'}
}).
otherwise({ redirectTo: '/'});
}).
run(function($rootScope, $location, $http, authUser){
$rootScope.$on("$routeChangeError", function(event, current, previous, rejection){
if(rejection.status == 401)
$location.path('/login');
})
$http.get('/users/me', {withCredentials: true}).
success(function(data, status, headers, config){
$rootScope.roles = data.roles;
}).
error(function(data, status, headers, config){
});
});
app.factory('authUser', function($http){
return $http.head('/users/me', {withCredentials: true});
});
app.directive('xLimitAccess', function(){
return{
restrict: 'A',
prioriry: 100000,
scope: {
xAccessLevel: '='
}
compile: function(element,$rootScope){//this is essentially the problem
if(scope.xAccessLevel != $rootScope.roles)
element.children().remove();
elemnet.remove();
}
}
})