Controlling ever-changing routes using AngularJS

My AngularJS app (Angular v1) has a secure login system in place. Users who are not authenticated can only access the login page, forgotten password page, and cookie policy.

I am utilizing ngRoute as shown below:

    $routeProvider
    .when('/login:param', {
        templateUrl: 'app/login/login.html',
        controller: 'loginCtrl',
        controllerAs: 'vm'
    })

    /* ... other routes ... */

    .otherwise({
        redirectTo: '/login'
    });

Now, my goal is to redirect logged-in users directly to the dashboard without allowing access to the "public routes" (routes accessible without authentication), and redirect non-logged-in users to the login page.

To achieve this, I have implemented a check within the Angular run function and using the $locationChangeStart event listener:

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        if (routeClean($location.path()) && AuthenticationService.isLoggedIn()) {
            $location.url(DASHBOARD);
        } else {
            $location.url(LOGIN);
        }
    });

Here, DASHBOARD and LOGIN constants define the routes to /dashboard and /login respectively.

Before proceeding further, I have a couple of questions:

  • Is run the right place for this check? (though it works, maybe there's a better location)
  • What is the best practice for achieving this functionality?

The AuthenticationService service handles user authentication, while routeClean function checks if a route is included in an array:

    var routeClean = function (route) {
        for (var i = 0; i < CLEAN_ROUTES.length; i++) {
            var pattern = new RegExp(CLEAN_ROUTES[i]);
            var bool = pattern.test(route);
            if (bool)
                return true;
        }
        return false;
    };

Where CLEAN_ROUTES contains all the "public routes".

    CLEAN_ROUTES = [
        '/login',
        '/forgotten-password',
        '/verify-code',
        '/reset-password',
        '/cookie-policy'
    ]

Lastly, some final questions:

  • Is there a more efficient way to check for "public routes" in Angular?
  • If, for example, I need to display different login templates based on user roles like:

    /login?user=client
    /login?user=seller
    /login?user=editor
    /login?user=admin
    

Can ngRoute dynamically handle this differentiation?

Essentially, when logging out and being redirected to the general login page defined by the LOGIN constant (/login), is there a way to identify seller, client, etc., and redirect them to the appropriate login page/template?

Answer №1

I believe that utilizing $httpProvider.interceptors is the optimal approach.

When working with ngRoute, you have the option to use -

$routeProvider -> 'route' -> resolve property

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

Having trouble converting JSON object to regular object?

I'm trying to change a JSON object into a regular object by using this method... var slaobj = eval('('+s+')'); However, it doesn't appear to be working correctly (the `.length' is returning as undefined). What m ...

Installing a package from a private repository using a different package name with npm

I'm looking to incorporate a module from a private GitHub repository into my project. To achieve this, I will execute the command npm install git+https://[API-KEY]:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b737c6e607 ...

Exploring Methods for Retrieving the Height of a Div Element in Ionic

Currently, I'm in the process of building a mobile app using Ionic. Before diving into details, let me explain what my goal is. One particular design challenge I am facing involves coding an image with a fixed height at the bottom right corner of a ...

Issues with link behavior when using Angular UI-Router

I am just starting to learn AngularJS and I'm trying to figure out how to pass a parameter using anchor tags within the $stateProvider code. I've been attempting to do so, but it doesn't seem to be working. Can someone guide me on the correc ...

Tips on triggering another action before a loop completes, involving AJAX

I've been struggling with this issue for quite some time now and I'm out of ideas. Can anyone offer assistance, please? All I want is to reload the current page after adding items to the cart. I've tried various methods like using count, pr ...

Transferring arrays through curl command to interact with MongoDB

Here is my mongoDB schema used for storing data: const mongoose = require("mongoose"); const subSchema = require("../../src/models/Course"); const All_CoursesSchema = new mongoose.Schema({ Student_name: { type: String, required: true ...

Exploring Vue JS: Decoupling variables in separate files and effective ways of accessing them

In my Vue project, I am looking to create a dedicated .js file to store multiple variables that can be easily accessed by other components. I am seeking advice on the most efficient method to achieve this and would greatly appreciate any examples provide ...

The noclose feature in Twitter Bootstrap is malfunctioning when placed within a div

I have a PHP page named a.php that contains the following code: <ul class="dropdown-menu noclose"> This code functions correctly, preventing the drop-down menu from closing until the user clicks outside the box. However, when I load the entire a.p ...

Combining php with jquery

This message contains a successful integration of PHP code within jQuery using the AJAX method. However, there are errors encountered which may be due to my lack of experience in jQuery. Uncaught ReferenceError: save_customer is not defined Uncaught Synt ...

Invalid preflight response (redirect) error

I am a beginner in utilizing Laravel and Lumen frameworks for my projects. Currently, I am working on my first project using Lumen and attempting to create an API call from Angular. Below is the Angular code snippet: app.controller('ListCtrl', ...

Is it possible for me to automatically send the user's email and username through code without requiring any information from them while using the tawk.to chat widget?

I need assistance with automatically sending the user's email and name when they open a chat window. I have tried various methods to pre-fill the form data but it still appears empty. Please let me know if there is something I am missing. Thank you ta ...

Unexpected failure when using FormData in Ajax callback for large files

I have a file upload control where I can upload various types of files. After getting the file, I store it in a FormData object and make an ajax call to my controller. Everything works well with images and small .mp3 files. However, when I try to upload .m ...

Is there a hover function in jQuery that works with both mouseenter and mouseout events?

I've been facing a slight issue with a list of items using the <li> element. I have a plugin running that dynamically adds a data-tag ID to the data-* attribute of these items. As a result, all items are dynamically added and another function I ...

How can one pass req.validationErrors() from the backend to the frontend with Express Validator?

Hello and thank you for taking the time to read this. I am currently trying to implement express-validator in my project. It's working well as it blocks posts if, for example, the name input is empty. However, I'm struggling to display the error ...

Update an item's precise orientation in relation to the global axis

Update: Included a jsfiddle for clarification: JSFiddle I am working with an object (a cube) in a scene and my objective is to provide it with 3 angles that represent its orientation in the real world. These angles are measured against the X, Y, and Z ax ...

Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled. On a specific page (localhost/admin/networks), I can click on an item from a database-ge ...

``To increase a value within an array object in MongoDB with the use of nodejs, what steps should be

Within my node.js application, I have a MongoDB post model that includes an array of comments. Each comment has a "likes" field representing the number of likes it has received. I want to increment this value for each comment individually. How can I achiev ...

Developing dynamic progress indicators in Django - A guide

I'm in the process of figuring out how to create a real-time progress bar for updating. The idea is that the server will update the user periodically on the current progress. Fortunately, I am familiar with making an Ajax call using Django and jQuery ...

Tips on eliminating certain text from a hyperlink

I need assistance with removing the text  Title from my link while preserving the image. <tr id="group0"> <td colspan="100" nowrap="" class="ms-gb"> <a href="javascript:" onclick="javascript:ExpCollGroup('28-1_', ...

Generating HTML using a filter

I have been working on creating a filter that will render HTML tags. Here is the code for my filter: filters: { limitStrLength: function (value, maxLength) { if (value && value.length > maxLength) { let partialVal = value.substr(0, ...