Unusual behavior noticed with AngularJs authentication service

Updated: code in JavaScript

I took the authentication (session) service from angular-app, and made significant modifications to it:

  angular.module('auth', [])
    .factory('session', ['$location', '$http', '$q', ($location, $http, $q) ->

      service =

        requestCurrentUser: ->
          if service.isAuthenticated()
            $q.when service.currentUser
          else
            $http.get('/user').then (response) ->
              console.log(response.data)
              service.currentUser = response.data
              service.currentUser

        currentUser: null

        isAuthenticated: ->
          not service.currentUser?

      service
    ])

This is how the app looks like:

  BookReader = angular.module('BookReader', ['ngRoute', 'home', 'main', 'books', 'auth'])

  BookReader
    .config(['$routeProvider', '$httpProvider', '$locationProvider', ($routeProvider, $httpProvider, $locationProvider) ->
      $routeProvider
        .when '/',
          templateUrl: 'assets/tour.html'
          controller: 'MainCtrl'
        .when '/home',
          templateUrl: 'assets/main.html'
          controller: 'HomeCtrl'
        .when '/books',
          templateUrl: 'assets/books.html'
          controller: 'BooksCtrl'
    ])
    .run(['session', (session) ->
      session.requestCurrentUser()
    ])

When the application starts, the currentUser is requested. Then, we have the Controllers:

angular.module('main', ['ngCookies'])
  .controller('MainCtrl', ['$scope', '$http', '$cookies', '$location', 'session', '$log',
    ($scope, $http, $cookies, $location, session, $log) ->
      $log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
      $location.path '/home' if session.isAuthenticated()
  ])


angular.module('home', ['ngCookies'])
  .controller('HomeCtrl', ['$scope', '$http', '$cookies', 'session', '$location', '$log'
    ($scope, $http, $cookies, session, $location, $log) ->
      $log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
      $location.path '/' unless session.isAuthenticated()
  ])

The issue is that isAuthenticated() always returns false, even when currentUser is not null. When logged in, $log.info shows

currentUser: [object Object] ; isAuth: false
, not only on initial load, but during navigation as well. When logged out, it shows
currentUser: null ; isAuth: false
. It seems that currentUser is always null within the service. How can I properly define it to be able to change its value?

Answer №1

To track changes, consider using a watch function:

$scope.$watch(function() {
   return session.isLoggedIn();
 },
 function() {
   $log.debug "User: " + session.user + " ; isLogged: " + session.isLoggedIn()
 }
);

Answer №2

modify isAuthenticated to

isAuthenticated: ->
      service.currentUser?

even though this is asynchronous, it is recommended to utilize resolve in the router.

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

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

Stopping a function that is currently running on a website using Javascript

I have a script on my website that triggers a rain feature when a user clicks on a button. However, I am struggling to figure out how to allow the user to deactivate this feature. I've tried various methods such as using break, return, and timeouts, b ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...

What is the method for breaking a statement within an if statement on Blogger when both the IF and ELSE conditions are met?

I'm making some adjustments to the labels on my blog to ensure that each post has at least two labels. The concept is that if a post has LABEL 1, it will load one script, otherwise it will load another. However, I've encountered a situation wher ...

Enable AngularJS to automatically redirect to the login page when a user is not authenticated,

EDIT: I need to mention that my experience with AngularJs is only a week, so if you have any suggestions unrelated to the question itself, please feel free to share them in the comments section. Alright, here's the situation. I have authentication Co ...

Tips for identifying a pair of numbers (with varying ranges) in which one number must be present at all times

I am currently trying to understand the regex I have implemented in Angular 2 using Typescript: /[0-5]?[0-9]?/ Surprisingly, this regular expression works flawlessly to match any valid minute from 1 to 59, even though it seems like an empty string would ...

Issue with Vue directive bind not functioning after element refresh

My approach involves utilizing vue.js to create forms, where all fields are structured within a JavaScript objects array. Here is an example of the structure I use: { type: "input", mask: "date", default: "2018/04/14" }, { type: "input", ...

How to use image blob in Angular JS?

Working with API endpoints that require authentication for image retrieval. Utilizing a service called authenticatedHttp as an abstraction over $http to manage authentication tokens successfully. Successfully receiving response, converting blob to object ...

Having trouble establishing a connection with localhost at port 4445 using Nightwatch and Selenium

I am encountering an issue while trying to execute my Nightwatch script in Javascript. The error message I am receiving is: \ Connecting to localhost on port 4445... ‼ Error connecting to localhost on port 4445. × failed E ...

Exploring the functionality of Protractor testing in combination with Angular 2, focusing

I am currently developing an Angular 2 application and I require some information regarding unit testing with Protractor. Previously, in Angular 1, we were able to check for things like: element(by.css('[ng-click="myFunction()"]')) in our test ...

Incorporating code execution during promise completion

I'm currently working on an express application that involves a generator function which takes approximately 5 minutes to process a large amount of data. Unfortunately, I am unable to optimize this function any further. Express has a built-in ti ...

Event handler assigned to a group of constantly changing elements

Here is my JavaScript code: $(document).ready(function(){ $('#data1').change(function(){ title = $('#title1').val(); url = $('#url1').val(); $.post('library/edit.php',{title:title, url:ur ...

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Using jQuery to create a checkbox that functions like a radio button

In my code, I have a bunch of checkbox elements placed in different containers as demonstrated below: $("input:checkbox").click(function() { var url = "http://example.com/results?&" var flag = false; var $box = $(this); var $facet = $box.val ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

What could be causing the Bootstrap4 modal to not display data on my Django Template?

Looking for a solution to display data in the modal body using django variables. I'm new to ajax and django, so struggling with it. The ajax function sends the id of the Galeria object, and then the view returns a JsonResponse with the data. Why is th ...

Create an interactive Chart.js displaying real-time data fetched through ajax requests, designed to be fully responsive. Addressing

Chart.js (http://www.chartjs.org/docs/) is the tool I'm using for charting purposes. I am looking to retrieve data from an Ajax request while ensuring that the chart is responsive. Within my HTML markup, I've included a canvas element like this ...

Tips for displaying HTML content in an AJAX success alert message with ASP.NET MVC and jQuery

I have an action result that sends content in the following format: public ActionResult MyAction() { string mystring = //doing something return Content(mystring , "html"); } Client Side: $.ajax({ url: "/MyController ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

Sorting data within an Angular directive using a filtering service

I have created a custom directive called <jobs type="1" /> to display a specific set of data based on the attribute value. The 'type' attribute determines which type of job the user should see, and I'm using the following code in my te ...