Creating a route provider tailored to specific user roles

I have a rather straightforward requirement.

There are 3 different User Roles:

  1. CATUSER
  2. LICUSER
  3. ALLUSER
    • The User Role value is stored in the $rootScope.userRole variable.
    • The User Role is predefined before the AngularJS application starts as the AngularJS app gets called from a PHP script where the User Role is set.

Upon starting the AngularJS app, I need to configure specific Routes based on the User Role:

$rootScope.userRole == "CATUSER"

if ($rootScope.userRole == "CATUSER") {

    $routeProvider
        .when("/catheter", {
            title: "Catheter Expiration Code Generator",
            templateUrl: "app/catheter/catheter.html",
            controller: "CatheterController",
            controllerAs: "vm"
        })
        .when("/support", {
            title: "Support",
            templateUrl: "app/support/support.html",
            controller: "SupportController",
            controllerAs: "vm"
        })
        .otherwise({
            redirectTo: "/catheter"
        });

}

$rootScope.userRole == "LICUSER"

if ($rootScope.userRole == "LICUSER") {

    $routeProvider
        .when("/license", {
            title: "License Generator",
            templateUrl: "app/license/license.html",
            controller: "LicenseController",
            controllerAs: "vm"
        })
        .when("/support", {
            title: "Support",
            templateUrl: "app/support/support.html",
            controller: "SupportController",
            controllerAs: "vm"
        })
        .otherwise({
            redirectTo: "/license"
        });

}

$rootScope.userRole == "ALLUSER"

if ($rootScope.userRole == "LICUSER") {

   $routeProvider
        .when("/license", {
            title: "License Generator",
            templateUrl: "app/license/license.html",
            controller: "LicenseController",
            controllerAs: "vm"
        })
        .when("/catheter", {
            title: "Catheter Expiration Code Generator",
            templateUrl: "app/catheter/catheter.html",
            controller: "CatheterController",
            controllerAs: "vm"
        })
        .when("/support", {
            title: "Support",
            templateUrl: "app/support/support.html",
            controller: "SupportController",
            controllerAs: "vm"
        })
        .otherwise({
            redirectTo: "/license"
        });

}

It's important to note that I prefer not to utilize UI Router for this task.

Answer №1

In the past, I have utilized UI Router for this specific purpose. Here is a sample code snippet to help you get started:

angular
.module('app', [

])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
    $stateProvider
    .state('license', {
        url: 'url',
        templateUrl: './preview.html',
        controller: 'LicenseController',
        data: {
            requiredAuth: true,
            role: ['CATUSER', 'LICUSER'],
            permission : ['read', 'write', 'etc etc']
        }
    })
    $urlRouterProvider.otherwise(subdomain1 + 'error');
})
.run(['$rootScope', '$state', function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        // Check if user is authenticated
        var isAuthenticationRequired = toState.data
              && toState.data.requiredAuth
              && !AuthService.isAuthenticated() // Use local storage lookup method here
        ;
        // Check if user is authorized
        var isAuthorizationRequired = toState.data
              && (toState.data.role && AuthService.IsInRole(toState.data.role))
              && (toState.data.permission && AuthService.IsInPermission(toState.data.permission))
        ;
        if (isAuthenticationRequired) {
            event.preventDefault();
            $state.go('auth.login');
        } else if (isAuthorizationRequired) {
            event.preventDefault();
            $state.go('auth.denied');
        }
    });
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, error) {
        cfpLoadingBar.complete();
    });
    $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
        cfpLoadingBar.complete();
    });
}]);

The License route defined above has properties such as data, which specifies that authentication is required and authorization is granted for roles like LICUSER and CATUSER. Additional permissions such as read and write can also be added and checked. If the user is both authenticated and authorized, the requested state will load; otherwise, they will be redirected to either the login or denied page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

The comparison between dynamically adding elements through Javascript and hiding them using CSS

I am contemplating the advantages and disadvantages of adding elements to a page and setting display:none versus creating a function that dynamically generates the elements and appends them where needed. In my current situation, I am implementing a reply ...

SyntaxError was not caught and an unexpected token export occurred at line 2371 in the popper.js file

I'm a beginner with bootstrap and jquery, and I'm attempting to utilize the datatables feature for sorting. However, when I run my code, I encounter the following error in the console: uncaught SyntaxError: Unexpected token export at popper.js:2 ...

What could be causing my YouTube code to malfunction with certain playlists?

Check out the first jsfiddle playlist here The Alum Songs Playlist is working perfectly, but unfortunately, the same code is not functioning for another playlist ID. View the second jsfiddle playlist here The Medical Animated Playlist is currently not w ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

The visibility of content that flickers on the webpage should be hidden with the display: none property during loading

Currently working on a new toy website, but encountering some unexpected behavior. On the homepage HTML file, there are two separate sets of <body> tags: <body class = "intro">...</body> <body class = "home">...</body& ...

The Ajax request is not being triggered when using a different form submit method

Being a tech enthusiast, I have developed a handy function: function blur_slide_visit_count(){ $.ajax({ type: 'POST', url: 'add_save_slide_visitor_count.php', async: false, data: { fillvalue: fieldAr ...

Having Difficulty Configuring Async Request Outcome

I'm struggling to access the outcome of an asynchronous request made to an rss feed. After reading a post on How do I return the response from an asynchronous call?, which recommended using Promises, I tried implementing one. However, even though the ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

Is it possible to incorporate npm modules into a browser and utilize them locally on a personal computer?

This is my first time working with npm modules and node.js, so I find it quite challenging. I have a JavaScript code with multiple data points and I need to find the closest city to each of them. In response to another question on Stack Overflow (Reverse ...

Cross domain Ajax POST requests using CodeIgniter and AjaxBy utilizing CodeIgn

Initially, I would like to clarify ... I own two domains: www.one.com and www.two.com The first domain www.one.com has a form input below <div class="hidden cswrap2"> <h3>Edit Data Mustahik</h3> <div class="cscontent"> ...

Live Node.js and Next.js apps experiencing issues with functioning websockets

Within my nodejs backend at https://backend.example.com, the following code resides in my server.js file: const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 7500 }, () => { console.log('S ...

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

Creating an array using Vue.js

When I initialize a Vue data array like this [0: Object, 2: Object];, the console log in Vue shows the array as [0: Object, 1: undefined 2: Object];. This causes issues when iterating through with 'v-for="cell in row.cells"' as it results in tryi ...

The Chrome debugger will pause execution at a function without needing a DOM break point

Greetings! I am currently working on an angular js application. One issue that I have encountered is when I run the application and open the debugger by hitting F12, I notice that for every page it continuously calls a certain function and seems to stop th ...

Can a variable containing HTML code be iterated through with a loop?

I am currently working on setting up a select button that will receive options from an ajax call. The ajax call is functioning properly. However, I am facing a challenge when trying to create a variable containing the HTML. I am unsure of how to iterate a ...

What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2? Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, ...

How does a web crawler determine which elements to click on when navigating a webpage?

Recently, I developed a crawler application that is able to access a given webpage and extract the HTTP Requests before storing them in an excel sheet. Currently, I have implemented click events for some buttons using jQuery. Now, I am faced with the chal ...

Can an in-progress NPM package be tested using NPX?

I am currently developing an NPM package that is designed to be used exclusively through npx *, similar to packages like create-nuxt-app. Is there a method to test my package using npx *? Essentially, I want to run my bin script without actually installin ...

Is there a way in Angular to activate the contenteditable feature through a controller?

I have a collection of items, and the currently selected one is displayed in more detail on another section of the screen. The detailed section allows users to modify specific parts of the chosen item using contenteditable. When a user adds a new item to ...