Leveraging $cookies and $stateChangeStart to verify if the sessionID surpasses the maximum callstack limit

I'm encountering an issue and seeking some guidance. In my Angular application, I want to intercept every state change and redirect the user back to the login page if they are not authenticated. I am storing their encrypted sessionID in a cookie, checking if the cookie is undefined, and then directing the user accordingly. I plan to utilize the toState and toParams arguments in the future for user roles, but for now, let's focus on the current task.

Any advice or feedback would be greatly appreciated. Thank you in advance!

.run(($rootScope, $state, $cookies) => {
    $rootScope.$on('$stateChangeStart', (evt, toState, toParams) => {
        if(!$cookies.get('SessionID')){
            evt.preventDefault();
            $state.go('login');
        }
    })
})

Answer №1

If you find yourself executing this code on every state change, be cautious as it may result in an infinite loop. To address this issue and implement a more organized approach, consider the following code snippet:

.run(($rootScope, $state, $cookies) => {
      $rootScope.$on('$stateChangeStart', (evt, toState, toParams) => {
            if(!$cookies.get('SessionID'))
               {
                if (toState.name !== "login") {
                evt.preventDefault();
                $state.go('login');
               }
            }
        })
  })

This initial code snippet will set you on the right path. However, as you progress, you may realize the need to grant access to certain states without relying on cookies or authentication. One efficient way to handle this is by defining a custom property for each state. For instance, when configuring your states, include something similar to the following:

.state('home', {url: '/home', templateUrl: 'views/home.html', authRequired: false}) 
.state('someSecureUrl', {url: '/someSecure.url', templateUrl: 'views/someSecureUrl.html', authRequired: true}) 

Subsequently, adjust the above code like so:

.run(($rootScope, $state, $cookies) => {
          $rootScope.$on('$stateChangeStart', (evt, toState, toParams) => {
                if(!$cookies.get('SessionID')  && toState.authRequired)
                   {
                    evt.preventDefault();
                    $state.go('login');
                }
            })
      })

Alternatively, consider implementing a resolve function within your states for a more streamlined solution.

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 A-Frame VR: Understanding the Distinction between Cursor and Raycaster

I'm in the process of developing a WebVR project that allows users to interact with the environment by 'clicking' on entities. Can you explain the distinction between using the cursor fuse attribute and the raycaster for interaction? ...

Ensure that two text boxes are checked to confirm they are not empty and do not contain the value 0

I have a custom function that retrieves hours, rates, and tax deductions, then calculates them and displays the result. The function is currently functioning properly. var newtax= new Number(dep[i]); taxrate = newtax*100; var h=eval(document.paycheck.h ...

jQuery Ajax Redirect Form

I am currently developing an HTML application with a form. Upon clicking the submit button, I initiate a server-side call using jquery.ajax(). However, when the server returns an exception, such as a Status Code 500, I need to display an error message on t ...

Exploring the contents of this JSON array

I'm trying to fetch data from this link: <script type="text/javascript"> $.getJSON('http://api01.notaion.com/?item&id=120001462', function(data) { }); </script> I am uncertain whether I need to use a callback=?, a ...

Error Encountered: Duplicate Key Found in Repeater while using an Array called 'name'. The issue is resolved when using a different name

Here's the issue: when the variable is named 'name', the error 'dupes Duplicate Key in Repeater' appears! But why does this happen? Here's the code snippet: app.js var galleryModule = angular.module ("gallery",[]); var name ...

Can you explain the function of a digest attribute?

As a beginner in the world of NextJS, I am currently working on getting my first project ready for production. However, I encountered the following error: Application error: a client-side exception has occurred (see the browser console for more information ...

Angular service containing a data object variable that can be updated through an asynchronous AJAX request

Use Case: I have a requirement to create an Angular service that will return a data object stored inside the service. This data object should be updated once through an AJAX call. Initially, the service should return an empty object until the data is fetc ...

Array specifically designed for replacing strings, but it only works with the final element

Here is a snippet of code I am working with: $(document).on('click','.submitMessage,.submitStdMessage', function(e){ prevContent=$('textarea').val(); alert(prevContent); variables = { '{nom}' ...

Encountering the error message "Issue: [$rootScope:inprog] $apply already in progress" while trying to choose an option from a dropdown menu after upgrading from version 1.2 to version 1.6

Since upgrading our AngularJS application from v1.2.9 to v1.6.9, I have encountered a problem where clicking on a dropdown option triggers an error in the developer console. The error message reads: 'Error: [$rootScope:inprog] $apply already in pro ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Working with string interpolation in SQLite3 and Nodejs

Just starting out with this and I'm running into an issue with trying to insert a variable into my sqlite3 query. I keep getting the error { [Error: SQLITE_ERROR: no such column: shmee] errno: 1, code: 'SQLITE_ERROR' } where "shmee" is actua ...

Addressing React Native Rendering Problems

I'm currently working on a weather application and facing some challenges with rendering the forecast. I'm uncertain whether it's related to the styling. I've tested the API call through the browser and encountered no errors in Android ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

Is there a way to duplicate an image a specified number of times depending on a given output value?

As a beginner in coding, I am looking to learn how to dynamically insert multiple images based on input and output values. Currently, my code for basic addition looks like this: <form oninput="x.value=parseInt(a.value)+parseInt(b.value)"> <inpu ...

How can I manually set a date in Angular bootstrap datepicker?

Using the Angularjs Bootstrap datepicker has been a great experience, but I encountered a problem when attempting to select the date using JavaScript. How can I ensure that the selected date in the datepicker matches the date read from a specific object, s ...

Encountering a "MissingSchemaError" while attempting to populate the database with mongoose-seeder

I am facing an issue while trying to populate a database using mongoose-seeder. Despite setting up the schema correctly, I keep encountering a MissingSchemaError which has left me puzzled. Here is a snippet from the file where I define the schema: const m ...

Dynamically Add Routes in ExpressJS During Runtime

I am interested in creating routes dynamically at runtime, but I'm not entirely sure how to do it. Currently, I have the following code snippet: var app = express(); function CreateRoute(route){ app.use(route, require('./routes/customchat.js&ap ...

Tips on how to retrieve an Observable Array instead of a subscription?

Is there a way to modify this forkJoin function so that it returns an observable array instead of a subscription? connect(): Observable<any[]> { this.userId = this.authService.userId; this.habits$ = this.habitService.fetchAllById(this.userId); this.s ...

The OnsenUi getCurrentPage() function returns an empty object

As I work on creating a hybrid mobile app using Onsen UI, I've encountered an issue regarding navigation and data transfer between two pages. My starting point is index.html, which consists of a main.html ons-template along with ons-navigation and ons ...

Implementing Vue components dynamically within a v-for loop based on specific conditions

My JS array is structured like this: [{type:'text', data: 'some text'},{type: 'image', data: 'link/to/image'}] Each value of type corresponds to a different Vue component (<text-block>, <image-block>). ...