Exploring cookie evaluation in AngularJS routes and templates

I am in the process of implementing a login system using cookies to ensure that a user stays logged in even after leaving the application. While I have successfully set the cookie, I am unsure of how to utilize it to restrict access to the login screen for users who are already logged in.

I believe the most effective approach would be to handle this within the routes. Here is a snippet of my current file:

var routes = angular.module('we365', ['rcForm', 'ngCookie', 'ngCookies']);
routes.config(function ($routeProvider) {

    $routeProvider
    .when('/login', {

        templateUrl: 'views/login.html',
        controller: 'loginCtrl'

    })

    .when('/', {// get digest view

        templateUrl: 'views/getDigest.html',
        controller: 'GetDigestCtrl'

    })

    .when('/artifact/:artifact_id', {// single artifact view

        templateUrl: 'views/artifact.html',
        controller: 'artifactCtrl'

    })

    .otherwise({

        redirectTo: '/'

    });

});

Additionally, I am looking to remove the 'login' button from the parent view to prevent users from accessing it. Here is the current view structure:

<div class="container">
    <div class="page-header col col-lg-12">
        <h1>Welcome!</h1>
        <a href="/#/login/" class="btn btn-sm btn-primary button-login">Login</a>
        <a href="/#/" class="btn btn-sm btn-primary button-getDigest">Load Digest Data</a>
    </div>
</div>

Answer №1

There are a multitude of strategies, but I have two personal favorites:

1) Monitoring changes in the route

angular.module('MyApp', [])
.run(function($rootScope, myLoginService) {
$rootScope.$on('$routeChangeStart', function () {
  if (!myLoginService.isLoggedIn()) {
    $location.path('/login');
  }
});

You can replace the isLoggedIn function with a mapping service that verifies if the user has the necessary privileges to access the desired route; if authorized (either through a cookie or token stored in localStorage), the route proceeds. Otherwise, an error is displayed or the user is redirected as needed. In my implementation, the myLoginService checks for a localStorage entry.

2) Inclusion of a token in server requests; handling failed requests and user redirection

This method is more applicable to CRUD applications rather than routing, but the principle remains straightforward: a user A can carry out N actions only if they possess the required privileges. If an unauthorized action (or group of actions) is attempted, the request is intercepted and queued until the user authenticates with an account that has the necessary permissions.

.factory('securityInterceptor', ['$injector', 'securityRetryQueue', function($injector, queue) {
  return function(promise) {
    // Intercept failed requests
    return promise.then(null, function(originalResponse) {
      if(originalResponse.status === 401) {
        // Unauthorized request - add to retry queue
        promise = queue.pushRetryFn('unauthorized-server', function retryRequest() {
          return $injector.get('$http')(originalResponse.config);
        });
      }
      return promise;
    });
  };
}]);

Once again, this approach is geared towards data requests rather than routing. The concept was inspired by the AngularJS sample app, which can be found here. For further examples, I recommend exploring the repository.

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

What is the best way to attach an event listener to a div so that clicking on it increases the width and height of the div by 20%?

I've started working on it and decided to use the same dimensions (100px by 100px) as a previous question. Right now, I'm sticking with just Javascript, but I might incorporate jQuery down the line. One big issue is that in the line (this.style.w ...

Using VeeValidate with v-menu

Has anyone been able to successfully apply veevalidate to vuetify's v-menu component? I've tried using the validation-provider container with other HTML inputs and it works fine, but when I try to integrate it with v-menu, it doesn't seem t ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

Issues with fundamental JavaScript client-side code

As a newcomer to the world of javascript and jQuery, I am diving into my first experiment with javascript. My initial focus has been on changing questions by clicking next or previous buttons. The goal is to create a dynamic quiz webpage that updates quest ...

customizable options in user interface navigation version 1.0

The latest release of UI-Router1.0.0-alpha.1 by Christopher Thielen introduced dynamic parameters. From what I understand, when a parameter is set to be dynamic, changing it from the controller should also update the URL. However, despite trying various me ...

Encountering difficulties when trying to display a nested object with two levels of depth using

I am currently developing an application where I need to display a nested object with two levels using the map method. The data structure is as follows: const categories = [ { catName: "Education", subCategory: [ { subCatName: "Col ...

Instantly summing up two numbers with javascript

In my web development work using Visual Studio 2008, I encountered an interesting challenge. On a webpage, I have three textboxes labeled "Price," "Quantity," and "Amount." The task at hand is to calculate the value of "Amount" by multiplying the values ...

The jQuery draggable feature ceases to function after it has been dropped

I have a scenario with two divs, each housing a list of quantities and items. These items are draggable, and the div containing them is droppable. The condition here is if an item with the same name exists in the div, it cannot be dropped on that div again ...

What benefits come from employing jQuery for data storage techniques?

After learning more about jQuery data storage, I have a question. Is there any advantage to using either of these methods: $('#editCity').data('href', "xx"); var a = $('#editCity').data('href'); or $('#edit ...

What are the steps for incorporating a YouTube playlist into a website?

I'm in the process of creating a website and I'd like to incorporate a YouTube video playlist that looks similar to this example - http://www.youtube.com/user/icicibank/home. I plan to use HTML5, JavaScript, and the YouTube API. Can you provide g ...

The node server.js encountered an error - Module not found

After attempting to start my node server using the following command: node server.js An error was thrown: internal/modules/cjs/loader.js:905 throw err; ^ Error: Cannot find module 'fcc-express-bground' Does anyone have any solutions? ...

Tips for choosing one specific element among multiple elements in cheerio nodejs

Currently, I'm attempting to extract links from a webpage. However, the issue I'm encountering is that I need to extract href from anchor tags, but they contain multiple tags with no class within them. The structure appears as follows. <div c ...

What is the method for loading a subcategory based on the category by invoking a jQuery function within the <td> element of a JavaScript function that adds rows dynamically?

Whenever I click the add row button, the category dropdown list successfully loads. However, when I select an option from this category list, the subcategory does not load any list. The Javascript function responsible for adding rows dynamically is as fol ...

The form action seems to be unresponsive when utilized within a vue-bootstrap form

I'm utilizing a form submission service called formsubmit.co, which allows forms to receive input data via email without the need to develop a backend for storing and transmitting data. Formsubmit handles all the storage and sending processes. Accordi ...

A guide to assigning multiple classes to an element in Vue.js depending on the props!

Take a look at my code to grasp the issue. <template> <div class="header" :class="flat ? 'flat' : null" :class="app ? 'app' : null"> </div> </template> <script> export default ...

Steps to minimize the Bootstrap expanded menu on devices such as iPhone, iPad, Smartphones, tablets, etc. by simply tapping outside of the menu

Hello there! I'm currently working on a website project using Bootstrap framework v2.0.1. One interesting challenge I'm facing is related to the navigation menu behavior on different devices such as iPhones, iPads, tablets, and smartphones. When ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

personalizing material-ui component styles – set select component color to be pure white

I am looking to implement a dropdown menu using material-ui components (refer to https://material-ui.com/components/selects/). To do so, I have extracted the specific component from the example: Component return <div> <FormControl variant="outli ...

Creating animated effects through Javascript and CSS triggered by user events

As a beginner in javascript and CSS, I am experimenting with creating a simple animation that adjusts the transparency of an image when triggered by an event. However, I am facing an issue where the animation only works every other time the function is cal ...

Incorporating words into the core of a pie chart: Highcharts

Is there a way to display the total value in the center of a pie chart? I've attempted some methods but haven't been successful. The goal is to show the sum of all y values. Input export const data = [ { y: 15, name: "Category 1&q ...