Can we address certain data before the $stateChangeStart event is triggered?

I have been working on creating a custom Role-Permissions system that I want to set up during the initial root state resolve:

 $stateProvider
  .state('common', {
    resolve:{
      user: function(AclService, UserService) {
        UserService.getCurrent().then((currentUser) => {
          AclService.initialize(currentUser);
        });
      }
    }
  })

and verify permissions every time there is a $stateChangeStart:

$rootScope.$on('$stateChangeStart', ($event, toState) => AclService.interceptStateChange($event, toState));

However, I encountered an issue where the first $stateChangeStart event was triggered before the resolve took place, hence the permissions were not initialized yet.

What steps would you recommend in addressing this specific situation?

Answer №1

Incorporating this logic within the run function of your application is a viable approach. Below is a condensed example demonstrating how to preload authentication data.

(function() {

    "use strict";

    angular
        .module("myModule", [ //dependencies here...]);

    angular
        .module("myModule")
        .run(run);

    run.$inject = ["$rootScope", "$state", "authService"];

function run($rootScope, $state, authService) {

    authService.fillAuthData(); //loading auth data upfront...

    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {

        var isPublic = (toState.data && toState.data.isPublic && toState.data.isPublic === true);
        var requiredRole = (toState.data && toState.data.requiredRole) ? toState.data.requiredRole : null;
        var authorized = isPublic || authService.isUserInRole(requiredRole);

        if (authService.authentication.isAuth || isPublic) {

            //redirect user to unauthorized page if they lack necessary permissions for the requested page
            if (!authorized) {
                event.preventDefault();
                $state.go("unauthorized");
                return;
            }

        } else {

            event.preventDefault();
            $state.go("login");
            return;
        }
    });
}

})();

An example state definition could appear as follows:

.state("someState", {
    url: "/someState",
    templateUrl: "my/folder/file.html",
    data: {
        pageTitle: "Some Page",
        isPublic: false,
        requiredRole: "Admin"
    }
})

Answer №2

Avoid incorporating authentication logic within state resolves. A more effective approach is to create a listener for the $stateChangeStart event within the angular.run function:

angular.module('yourModule', [])
    .run(['$rootScope', 'principal', '$state', function ($rootScope, principal, $state) {
        var firstOpen = true;
        $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
            if (!principal.isAuthenticated() && firstOpen) {
                firstOpen = false;
                event.preventDefault();
                principal.checkAuthentication().then(function() {
                    $state.go(toState, toParams);
                });
            } else if (principal.isAuthenticated() && toState.name === 'login') {
                event.preventDefault();
                // You can add custom actions here, such as redirecting to the main 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

How do the scopes of a controller and a directive's controller differ from each other?

Can you explain the difference between a controller and a directive's controller in terms of scope? I'm struggling to grasp the distinction and whether it's necessary to create controllers within the DDO for my directives. In the code snipp ...

I am looking to optimize my WordPress posts to load in increments as the user scrolls down the page, similar to how Facebook does

I am looking to implement a feature on my WordPress post where the content loads a few at a time as the user scrolls, similar to Facebook. Specifically, I would like my webpage to automatically load 10 posts and then continue loading 10 more as the user re ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

Deploying CSS/JS files in Magento 2 is a crucial

Hello, I recently set up magento2 with the sample data included. After attempting to deploy static css/JS using the command php bin/magento setup:static-content:deploy, I didn't receive any errors but the issue persists. Additionally, I am unable to l ...

The ngMessage feature in Angular bootstrap ui tabs seems to be malfunctioning specifically within the initial tab

Encountered a peculiar issue with ngMessage While using angular ui bootstrap tabs, the validation is not functioning correctly in the first tab This is the code snippet js angular .module('app', ['ngMessages','ui.boots ...

Establishing a default selection for a react dropdown menu filled with data retrieved from an API request

class Select extends React.PureComponent { constructor(props) { super(props) this.state = { value: this.props.initialValue } this.handleChange = this.handleChange.bind(this) } handleChange(e) { e.persist() ...

Ways to designate a parent element in Vue Draggable when the element is lacking a child

I'm currently incorporating vue-draggable into my project from the following GitHub repository: https://github.com/SortableJS/Vue.Draggable Below is my ElementsList component: <div> <draggable v-model="newElement" :move ...

Top tips for handling HTML data in JSON format

I'm looking to fetch HTML content via JSON and I'm wondering if my current method is the most efficient... Here's a sample of what I'm doing: jsonRequest = [ { "id": "123", "template": '<div class=\"container\"&g ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

What is the method to access the controller value within a metadata tag?

One of the challenges I am facing is how to access a variable from a controller and use it in a metadata tag using AngularJS. Below is my approach: First, let's define the variable in the controller: app.controller('homeCtlr', function($sc ...

Is it possible to launch a React application with a specific Redux state preloaded?

Is there a way to skip navigating through a bulky frontend application in order to reach the specific component I want to modify? I'm curious if it's feasible to save the redux store and refresh my application after every code alteration using t ...

Preserving the information of a different language

What is the best method for saving a text in a foreign language with emoticons into an SQL database and then displaying it on AngularJS? The backend language being utilized is PHP, while the frontend is AngularJS. The database being used is MySQL. ...

Using an array.map inside a stateless component with React.createElement: the type provided is invalid

There is a component called BasicDetail in my code with the following structure: import React from "react"; import { Grid, Form } from "semantic-ui-react"; const BasicDetail = ({DetailData}) => { return( <div> <Grid.Ro ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

A guide on selecting the best UI container based on API data in React using TypeScript

I have been developing a control panel that showcases various videos and posts sourced from an API. One div displays video posts with thumbnails and text, while another shows text-based posts. Below is the code for both: <div className=""> &l ...

Nextjs version 13 encountered hydration failure due to discrepancies between the initial UI and the server-rendered content

I am currently utilizing the latest version 13.1.0. I have implemented a ContextProvider that allows switching between light and dark themes. 'use client'; import { Theme, ThemeContext } from '@store/theme'; import { ReactNode, useState ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

Tips for sending a Json array to a servlet

[DUPICATE] Here is the JSON code I am using for my POST request: var data_create = JSON.stringify($("#form_create_delegate").serializeArray()); alert("data_create content" + data_create); // console.log(data_create) $.ajax({ ...

Ensuring a boolean outcome from a promise function within AngularJS

When working with angularjs, I am attempting to determine whether the value isInternal is true or false based on a promise function. However, instead of getting the expected result, I am receiving another promise (Promise {$$state: Object} $$state : Object ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...