Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code:

app.run(function ($rootScope, $location, Auth) {

    // Watching the value of the currentUser variable.
    $rootScope.$watch('currentUser', function(currentUser) {
      // If there is no currentUser and the page requires authorization, attempt to update it
      // This may trigger 401 errors if the user's session is invalid
      if (!currentUser && (['/', '/login', '/logout', '/signup'].indexOf($location.path()) == -1 )) {
        Auth.currentUser();
      }
    });

    // When receiving a 401 error, redirect to the login page.
    $rootScope.$on('event:auth-loginRequired', function() {
      //console.log(currentUser);
      $location.path('/login');
      return false;
    });
  });

Based on my console observations, I have noticed that the $rootScope.currentUser becomes unavailable when transitioning from the profile page to the settings page, as the Auth.currentUser() function fails due to a null value in $rootScope.currentUser.

Below is some more relevant code:

Auth.js (where the Auth.currentUser() function resides)

'use strict';

angular.module('groundup')
  .factory('Auth', function Auth($location, $rootScope, Session, User, $cookieStore) {
    $rootScope.currentUser = $cookieStore.get('user') || null;
    $cookieStore.remove('user');
    $rootScope.currentUserSignedIn;

    return {
      // various functions such as login, logout, createUser, currentUser, changePassword, and removeUser are defined here
    };
  })

After calling Auth.currentUser(), a GET request triggers the following function on the Express side:

exports.session = function (req, res) {
  console.log(req.user.user_info + " in session function");
  res.json(req.user.user_info);
};

The issue arises during the redirect to the /settings page, where $rootScope.currentUser is being monitored causing an automatic redirection to /login due to a failed call to Auth.currentUser(). Any assistance or insights would be highly appreciated. Thank you.

Answer №1

It seems that there is an issue with your Auth.currentUser() method. You may want to consider modifying it to something like the following in order to utilize the User service:

currentUser: function () {
    return User.get();
}

Your problem could also be related to a cookie storage issue. Passport attempts to save the current user in a cookie, but encounters a failure (possibly due to accessing an undefined variable) and stores a corrupted or empty user in the cookie. As a result, the first page loads correctly, but the app breaks when attempting to access the cookie.

I suggest examining the middleware.js file in the lib directory to check for any issues with cookie saving. For example, if you are trying to store the entire user object instead of just userInfo, you will need to adjust your session function to output the complete user object.

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

Transferring information between pop-up and webpage

I have developed a simple form within an ERP system that allows users to create quick support tickets. However, instead of manually inputting the client ID in the form, I want to provide them with a more user-friendly option. My idea is to include a search ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...

I am interested in obtaining the latitude and longitude of a specific city

I need to relocate the Google Map to a particular city based on user selection from a dropdown menu. I must obtain the latitude and longitude of the chosen city. Once the city is selected, I will determine its coordinates using the following code: var c ...

Error in Layout of Navigation Panel and Tabbed Pages

Working on a school project, I encountered a challenge. I found two useful solutions from the W3 website - a sticky navigation bar and the ability to include tabs on a single page for a cleaner presentation of information. However, when trying to implement ...

Steps to hide a div with jQuery when a user clicks outside of a link or the div itself:1. Create a click event

Here's a simple question - I have a link that when clicked, displays a div. If the user clicks away from the link, the div is hidden, which is good. However, I don't want the div to be hidden if the user clicks on it. I only want the div to disap ...

Tips for assigning a default value when an error occurs

Currently diving into the world of React and experimenting with rendering 10 pieces of data from a specific API. After crafting a function to iterate through the fetched information, extracting the title and image has been quite the challenge: for (let ...

Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated ...

Issues with Toggling Visibility in HTML, CSS, and Javascript

Currently, I am working on a website and following a tutorial called "Creating Slideshow using HTML, CSS, and Javascript" by W3Schools. In the project, I want to hide the thumbnail images located at the bottom and the navigation arrows initially and have t ...

Exploring the functionality of a personalized hook using the useSelector method

I have developed a custom hook and I am in the process of testing it independently. However, I am encountering an issue where I need to wrap the hook inside a Provider to proceed further. The error message I am getting is displayed below: Error: could not ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...

What is the process of integrating data retrieved from an SQL query into a Pug template using Express and MySQL?

Currently, I am in the process of developing a basic web application that will initially show a list of bus route numbers and names upon landing on the page. My tech stack includes MySQL integrated with Express and Pug. Below is the server-side code snippe ...

Tips for accurately determining the count, rather than the character length, of JSON data

After running my code, I believe it returns a JSON array. The resulting JSON array is then stored in a JavaScript variable called 'result'. When I console.log(result); in Firefox, the output shown is: [{"id":"G24","value":"Zas, S"},{"id":"G75" ...

Enhancing PHP Token Security

I developed a PHP application that has a login requirement. This application is exclusive, so no new users can create accounts. Initially, I implemented sessions to identify users, but it caused issues on tablet devices as they would lose their sessions. I ...

Moving information from Ajax to PHP

I'm experiencing an issue with sending data from AJAX to PHP on the same site, "testpage.php". The PHP script doesn't seem to be displaying the data being sent. Using jQuery/Ajax: <script src="http://code.jquery.com/jquery-latest.js" type="t ...

Invalid mime type for HTML5 mode

I have successfully set up my redirect, but now all my style sheets are being served as text/html because they are going through core.index. Strangely, I only get this error for style sheets and not for JS files. How can I fix this issue? Error: Res ...

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

What are the steps to keep a web application from closing on Android when the back button is pressed?

I am currently working on a HTML5 web application and packaging it with Cordova (phonegap) 1.7. My goal is to customize the behavior of the Android back button so that instead of closing the application by default, it navigates back using window.history.b ...

Looking for suggestions on how to bring this idea to life

I'm searching for a solution using JavaScript, jQuery, or Angular. I've created three random arrays like this: for example: (The values are randomly generated from the array ['member', 'medical', 'rx', 'disabi ...

jade, express, as well as findings from mysql

My goal is to display the results of an SQL query in Jade, which pulls data from a table of banners. Each banner has a unique id and falls under one of three types. Here is my current code : express : connection.query("SELECT * FROM banner_idx ORDER BY ...

What is the procedure for modifying the height of a button in HTML?

I wanted to add a flashing "Contact Us" button to the menu bar of my website to immediately attract people's attention when they visit. Here is the javascript code I used: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&g ...