Enhance your AngularJS application with advanced security features and implement a local storage

I have implemented an AngularJS application that utilizes angular ui-router for routing.

Despite my efforts to enhance security, I encountered some challenges:

  1. To manage user authentication, I store tokens and user roles in local storage, redirecting users based on their roles. However, the watch service I implemented on local storage does not retain the previous value upon refresh, causing my checks to fail.

  2. If a user changes the token in local storage and then refreshes the site, I am unable to detect this change.

  3. In such cases, unauthorized users can access templates but are unable to fetch data due to backend security measures. It is crucial to restrict access to templates as well.

I am seeking assistance in enhancing client-side security in Angular to address these issues.

Answer №1

It seems like you want to ensure that users with the required permissions can only view certain templates. My approach involves checking the user's permissions before allowing access to different pages. I specify the necessary permission for each state, and if the user lacks the permission, they will be redirected to a designated page.

// Current user permissions
var currentPermissions = {
  "User.Read": true,
  "User.Create": false
}

// AngularJS module with ui-router
var app = angular.module('myApp', ['ui.router']);

app.config(function($stateProvider) {

    $stateProvider.state('page1', {
            url: "/page1",
            data: { permission: "User.Read" },
            template: "Page 1"
        })
        .state('page2', {
            url: "/page2",
            data: { permission: "User.Read" },
            template: "Page 2"
        })
        .state('page3', {
            url: "/page3",
            data: { permission: "User.Create" },
            template: "Page 3"
        })
        .state("noAccess", {
            url: "/noAccess",
            template: "Access Denied"
        });
});

app.run(function($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {

        // Check if user has correct permission
        if (toState.data && !currentPermissions[toState.data.permission]) {
            event.preventDefault();
            $state.go('noAccess'); // Redirect if user does not have permission
        }
    });
});

You can view this in action here: https://jsfiddle.net/Darin_Cardin/mwg33rm4/

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

Exploring Three.js raycasting in a non-full screen scenario

I've encountered some challenges with raycasting in three.js recently. The div element I'm using is not fullscreen, which I believe is causing issues with the raycast positioning that I'm struggling to resolve. let mouseVector = new THR ...

Why does the lazy loading feature keep moving the background image around?

While trying to incorporate lazy loading on my website, I encountered an issue where the image position would change after it was fully loaded and made visible. I experimented with rearranging the order in which my JavaScript and CSS files were called, bu ...

Choose all the HTML content that falls within two specific tags

Similar Question: jquery - How to select all content between two tags Let's say there is a sample HTML code as follows: <div> <span> <a>Link</a> </span> <p id="start">Foo</p> <!-- lots of random HTML ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

Adjusting the NVM Node version with a Bash script

I'm currently working on creating aliases in my .bash_profile file with specific functionalities: xx projname => cd ~/folder_1/projname and ensure nvm uses node version 6 if it's not already using that version yy projname => cd ~/f ...

iOS devices do not support the add/removeClass function

This code functions properly on desktop browsers, but encounters issues when used on iPhones. Furthermore, the script mentioned below seems to be causing problems specifically on iPhone devices. var $event = ($ua.match(/(iPod|iPhone|iPad)/i)) ? "touchstar ...

Align the Bootstrap Nav Bar in the Center

<!-- Unique Header --> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-togg ...

HTML code with embedded messages

I am interested in creating a straightforward message forum system. My goal is to organize messages in a nested structure (answering questions). For my website, I want it to be in Hebrew (dir="rtl"). I am considering generating <ol> elements dynam ...

When you click on the Admin Panel Side menu, the page refreshes instead of expanding the menu item

I have encountered a strange problem with the AdminLTE admin panel template that I am using in my Angular 11 application. Everything is loading fine with the menu items, but when I click on an item, instead of expanding the group, the page refreshes. Here ...

Is there a way to direct to a specific URL upon clicking a button using PHP?

In my PHP code called registerprocess.php, it executes after clicking a submit button on another page named userregistration.php. If a user tries to register with an email that already exists in the database, I want registerprocess.php to redirect back to ...

After a period of time since the server has been initialized, the function req.isAuthenticated() no

In my Node.js routes.js file, I have a function implemented to check if a request is isAuthenticated before serving it: function isLoggedIn(req, res, next) { if (req.isAuthenticated()) { console.log('Session Expiry '+req.session.cook ...

AngularJS application, when making a CORS GET request, is not transmitting HTTP headers

My issue lies in the fact that when making HTTP GET requests in AngularJS, the headers are not being sent. Strangely enough, for HTTP POST requests, the headers are properly set. These requests are made over CORS. Despite scouring numerous posts on StackO ...

Exploring the differences between $scope binding and $broadcast in managing an application timer

I'm a bit puzzled about the most effective way to bind the time value of a Timer service to multiple directives. There are two methods outlined below, and I'm uncertain about which one is considered best practice or if there are any performance b ...

Changing the color of an open Bootstrap 4 accordion panel when the page loads

I am looking to emphasize the panel that the user has opened. If a user clicks the button in the card header, the background turns red, which is working smoothly as demonstrated in the code snippet. In certain scenarios, the first panel is open by default ...

Add a specific CSS class to a div element depending on the status of a checkbox

Is there a way to dynamically append data based on the selected items in a checkbox table? I want to be able to add multiple or single items by clicking the add button. The key is to avoid appending duplicate data that already exists in the view. Any sugge ...

When the user clicks on the page, show the data fetched from MySQL and echoed in

I am facing an issue with a table containing a loan_id. When fetching the information, everything appears to be in order. However, I need to be able to click on the loan_id number and have it display results based on the corresponding id number. <?php ...

Establish a value for the attribute of an HTML tag

Can anyone assist me with setting the attribute value for the following HTML tag using Selenium WebDriver? For example, I need to change 50% to 70% either via JavaScript with WebDriver or a simple WebDriver script. I have tried several options but this pa ...

Error message: Unable to locate module without the '.js' extension at the end of the import file path

It seems like the solution is not difficult, just something obvious. I am working on a simple TypeScript project. There are no modules involved, only TypeScript for compilation. The TS files compile into JS files in the dist folder, which are then connect ...

Is there a convenient feature in WebStorm for quickly inserting a lambda function in TypeScript that matches the current argument's signature while coding?

While working with promise chains in TypeScript, I often find myself dealing with a syntax tax that can become cumbersome. It would be great to have a way to automate this process, especially when using WebStorm. My ideal situation would involve having an ...

Deploying Node.js on Heroku

After deploying a test app using node.js on Heroku, I checked the Heroku log file and it seems like everything is running smoothly. 2017-02-09T12:25:56.034718+00:00 heroku[web.1]: Starting process with command `npm start` 2017-02-09T12:25:58.77986 ...