AngularJS Login Authorization: Restricting user access to specific pages, allowing only login and registration pages to be navigated

I'm currently working on a web application using the AngularJS framework for the frontend. I need to restrict users from navigating to any page other than the login and registration pages on my site. However, my current code is blocking access to the registration page as well. Below is the snippet of my code. How can I modify it to allow users to navigate only to the login and registration pages when they are not logged in.

.run(function ($rootScope, $state, AuthService, AUTH_EVENTS) {
  $rootScope.$on('$stateChangeStart', function (event,next, nextParams, fromState) {

    if ('data' in next && 'authorizedRoles' in next.data) {
      var authorizedRoles = next.data.authorizedRoles;
      if (!AuthService.isAuthorized(authorizedRoles)) {
        event.preventDefault();
        $state.go($state.current, {}, {reload: true});
        $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
      }
    }

    if (!AuthService.isAuthenticated()) {
      if (next.name !== 'login') {
        event.preventDefault();
        $state.go('login');
      }
    }
  });

Answer №1

To achieve this functionality, you can include a boolean parameter in the data property of .state called requiresAuth. Then, check for this parameter in the .run block.

Here is some pseudo code to demonstrate this:

In the .config block

$stateProvider
  .state("register", {
        url: '/register',
        templateUrl: 'register.html',
        controller:'UserController',
        controllerAs: 'vm',
        data: {
            requiresAuth: false,
            pageTitle: 'Register'                
        }
 })
 .state("dashboard", {
        url: '/dashboard',
        templateUrl: 'dashboard.html',
        controller:'OtherController',
        controllerAs: 'vm',
        data: {
            requiresAuth: true,
            pageTitle: 'Dashboard',
            authorizedRoles: ['WHATEVER_ROLE']
        }
});

In the .run block

var stateChangeStart = $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
    if (AuthService.isAuthenticated()) {
        if (!toState.data.requiresAuth) {
            event.preventDefault();
            $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
        }
        
        if (angular.isDefined(toState.data.authorizedRoles)) {
            var roles = toState.data.authorizedRoles;
            AuthService.isAuthorized(roles).catch(function() {
                event.preventDefault();
                $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
            });
        }
    } 
    
    else if (toState.data.requiresAuth) {
        event.preventDefault();
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
    }
});

var notAuthenticated = $rootScope.$on(AUTH_EVENTS.notAuthenticated, function() {
        $log.warn('not authenticated');
        $state.go('login', null, {});
        return;
    });

var notAuthorized = $rootScope.$on(AUTH_EVENTS.notAuthorized, function() {
        $log.warn('not authorized');
        $state.go('dashboard');
        return;
    });

$rootScope.$on('$destroy', notAuthenticated);
$rootScope.$on('$destroy', notAuthorized);
$rootScope.$on('$destroy', stateChangeStart);

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

Show the current server time from ASP.NET in four distinct time zones using JScript

I am in the process of customizing a SharePoint master page by adding a unique header that showcases the current time across four different time zones. However, I am faced with the challenge of determining the appropriate server-side time to use for accura ...

What is the best approach to select and return a single directive among two nearly identical ones in AngularJS?

I'm trying to figure out how to include only one directive out of two identical ones, where one has deprecated functionality and the other one doesn't. Unfortunately, I can't remove the deprecated one by deleting the file. I vaguely recal ...

Error encountered while submitting ajax request to server

When I click a button, a function is triggered with the argument insertSongPlay(newSong.songID);. After logging the value of newSong.songID, which is 90 as desired, an ajax call is made: function insertSongPlay(songID) { $.ajax ({ type: " ...

Guide: Linking RCTCameraRoll to Android

I am currently attempting to utilize the CameraRoll library, however, I have encountered an obstacle. The documentation does not provide instructions on linking it for Android. It only offers guidance on how to link it for iOS. While it does mention that ...

The 'userEvent.type' function in React Testing Library is failing to update the input value in a Material UI TextField component that has

I am currently facing an issue with a material UI TextField element that is meant to track the latitude value. The requirement is for the latitude to fall within the range of -90 to 90 degrees. I have implemented a unit test as a validation measure, howeve ...

Trouble activating Bootstrap 4 checkbox through JavaScript integration

When clicking on a table row, I am able to add the class active with JavaScript. However, when trying to click on a checkbox, an error occurs. Check out the live Codepen link here Below is the custom code snippet: $('.dashboard-table-tbody tr&apo ...

Check to see if an array contains any falsy values and return accordingly

My goal is to only return the error message if any value is falsy, and never return the hooray message. I am utilizing lodash. var jawn = [ { "cheese" : true, "with" : true, "without" : true }, { "cheese" ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

Need help with jQuery UI and managing changing content?

Looking for suggestions on using a dynamic, single dialog that updates based on ajax calls. Is there a graceful method to adjust the height and width according to the new content? Currently encountering issues with an empty div being populated. Any assist ...

What are the reasons for avoiding placing CSS code directly within HTML?

Situation: My website is dynamically served, with all CSS and javascript directly embedded into the HTML document to optimize speed. Advantages: Reduces web requests Fewer files downloaded Speeds up webpage loading time Disadvantages: Potential cachin ...

retrieve data from firestore and pass it as a parameter to a function

After successfully retrieving a field from Firestore and logging the correct information, I am now trying to set the name of my code as a reusable function. Below is the original code: db.collection('users').doc('' + sender_id).get(). ...

What could be causing the nonassign error to occur in the angular-bootstrap tabset?

<tabset class="paygrade-tabs"> <tab ng-repeat="tab in rps.currentPayGrade | orderBy: 'payGrade.code' : true track by $index" ng-click="changeTab(tab)" active="activeTabId === tab.id"> <tab-heading> <span> ...

Whenever I execute the 'ng serve' command, I encounter an issue with ineffective mark-compacts close to the heap limit, resulting in an allocation failure and a JavaScript

I'm currently using Angular 9 and Node.js 12. When I input ng serve, I encounter the following problem: C:\Users\homz\my-app>ng serve 93% after chunk asset optimization SourceMapDevToolPlugin vendor.js generate SourceMap <--- ...

The controller did not have any corresponding action to fulfill the request sent from AngularJS connecting to Asp.Net WebApi

My mind is spinning. I am diving into the world of learning AnjularJS with Asp.Net Web Api. The following code snippet features an AnjularJS controller with an ajax call to a Web Api service. CustomerController = function ($http, $scope, $httpParamSeriali ...

Guide on setting up Express.js to log errors during asynchronous operations

I encountered an issue with my code that goes like this: exports.listSavedThreads = function (req, res) { SavedThread.find({}).exec().then(function (data) { wat.map(); res.render('home/listSavedThreads'); }); }; It seems that the va ...

Crafting a custom version of the $.data() function without relying on jQuery

, I am seeking guidance on how to eliminate jQuery from the code snippet below. It is my understanding that the $.data() method is employed to store data, but I am unsure of how to achieve this without using jQuery. document.querySelector('.sheet&apo ...

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? https://i.sstatic.net/y7Cs5.png Codesandbox: https: ...

Steps to define a JavaScript mixin in VueJS

Currently, I am working on a Vue project with TypeScript and in need of using a mixin from a third-party library written in JavaScript. How can I create a .d.ts file to help TypeScript recognize the functions defined in the mixin? I have attempted the fol ...

Which costs more, using an undefined ng-bind or both ng-bind and ng-show together?

Assuming that toShowVar is undefined, which of these options would be more costly? <span ng-bind="toShowVar" ng-show="toShowVar"></span> or <span ng-bind="toShowVar"></span> The latter option would clearly not display anything o ...

Combining arrays using Observables in Typescript with RxJS

Having some issues using rxjs Observable.concat function in typescript. Encountering an error "Cannot read property 'apply' of undefined" The problem appears to be limited to typescript and may be related to rxjs version 5 concat. The code seems ...