Angular authentication function not invoked

I am currently using Angular along with a JWT token for user authentication.

However, I have encountered an issue where the login() function assigned to $scope is not being called. Any assistance on this matter would be greatly appreciated.

app.js snippet:


var admin = angular.module('admin',['admin.core','admin.auth']);
angular.module('admin.core', ['ui.router', 'satellizer', 'ngResource', 'ngAnimate',
'ngStorage']);

admin.config(function($httpProvider, $stateProvider, $urlRouterProvider, 
$authProvider, $provide, $locationProvider) {
     $authProvider.loginUrl = '/api/authenticate';
$urlRouterProvider.otherwise('/login');

$locationProvider.html5Mode(true);

$stateProvider
    .state('login', {
        url: '/login',
        templateUrl: '/partials/admin/login.html',
        title : 'Admin Login'
    })
});
    
angular.module("admin.auth", []).controller("AuthController", AuthController);
function AuthController($auth, $state, $http, $rootScope, $scope) {
  console.log("Auth Called");
   $scope.email='';
   $scope.password='';
   $scope.newUser={};
   $scope.loginError=false;
   $scope.loginErrorText='';

   $scope.login = function() {

    var credentials = {
        email: $scope.email,
        password: $scope.password
    }

    $auth.login(credentials).then(function() {
        return $http.get('/api/authenticate/user');
    }, function(error) {
        $scope.loginError = true;
        $scope.loginErrorText = error.data.error;
    }).then(function(response) {
        if(typeof response != "undefined"){
          var user = JSON.stringify(response.data.user);
          localStorage.setItem('user', user);
          $rootScope.authenticated = true;
          $rootScope.currentUser = response.data.user;
          $scope.loginError = false;
          $scope.loginErrorText = '';
          $state.go('dashboard');
        }
    });
}

   $scope.logout = function() {
    $auth.logout().then(function() {
        // Remove the authenticated user from local storage
        localStorage.removeItem('user');
        // Set authenticated to false so that certain UI elements dependent on the user's login status are no longer displayed
        $rootScope.authenticated = false;
        // Delete current user info from rootscope
        $rootScope.currentUser = null;
        $state.go('login');
    });
}
}

I am also attempting to utilize AuthConrtoller as follows:


 <body ng-controller="AuthController">
     <ui-view></ui-view>
 </body>

Additionally, the content of login.html is shown below:


<form name="loginForm" autocomplete="off" novalidate>
    <md-input-container class="md-block">
    <label for="email">Username</label>
     <input type="text" name="email" required="required" ng-model="email" md-no-asterisk/>
     <div ng-messages="loginForm.email.$error" role="alert">
        <div ng-message="required">Username is required</div>
      </div>
     </md-input-container>
      <md-input-container class="md-block">
        <label for="password">Password</label>
        <input type="password" name="password" required="required" ng-model="password" md-no-asterisk/>
        <div ng-messages="loginForm.password.$error" role="alert">
            <div ng-message="required">Password can not be blank</div>
        </div>
     </md-input-container>
      <md-button type="submit" class="md-primary md-raised" ng-disabled="!loginForm.$valid" ng-click="login()">Login</md-button>
</form>

Answer №1

Make sure to include the controller in the route configuration,

$stateProvider
    .state('login', {
        url: '/login',
        templateUrl: '/partials/admin/login.html',
        controller : 'AuthController',
        title : 'Admin Login'
    })
});

To manage the login and logout functionality, you can create a service and utilize its functions within different controllers.

DEMO

var app = angular.module('app', []);
app.controller('loginController',['$scope', 'MyUser',function($scope, MyUser)
{
    $scope.isloggedin = MyUser.getStatus();
    alert($scope.isloggedin);
}]);
app.service('MyUser', [function($scope) {
  this.loggedIn = false;
  return {
    getStatus: function() {
       this.loggedIn = true;
       return this.loggedIn;
    }
  }
}]);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
</head>
<body ng-app="app" ng-controller="loginController">
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>   
</body>
</html>

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

Vue 2 - Error: The function is not defined at HTMLInputElement.invoker (vue.esm.js?65d7:1810)TypeError: cloned[i].apply

I encountered the following error: Uncaught TypeError: cloned[i].apply is not a function at HTMLInputElement.invoker (vue.esm.js?65d7:1810) I have set up my project using vue-cli (simple webpack), and below is the code for my component: <template ...

Multiple executions of Google API sign in listener

I have been working on a Vue module that allows users to add events to Google Calendar easily. Once a user signs in, there is a listener in place to call a method for adding an event to the calendar. To access the gapi functionalities required for this tas ...

Leveraging setter methods within knockoutjs bindings allows for efficient data manipulation

As the day comes to a close, my mind is winding down for the night. I've been diving into the world of setters when dynamically binding to Html elements and trying to wrap my head around it. While I have read through several examples, these URLs below ...

What is the best way to transform an array of objects into an array that contains a distinct identifier in JavaScript?

I am currently working with an array of objects structured like this: { "data": [ { "id": 1, "from": "2022-08-01", "to": "2022-08-05", & ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Replicate the ctrl+/- function through coding

While browsing with your browser, you have the ability to adjust the font size by using CTRL + + or CTRL + -. Is there a way to replicate this functionality through code, such as with JavaScript? I am looking to add buttons on my website that allow users ...

Understanding how to use the 'this' variable in Vue components is essential for efficiently modifying DOM elements. Let's dive into a clarification on the usage of 'this'

Within my vue component, the structure is as follows: export default{ name: '', data: function () { return { var1 :{}, var2 : {}, ... } }, created: function () { this.methodName1() }, methods: { me ...

Transferring data from JavaScript to PHP using the $.ajax method for storing information in a MySQL database

I am attempting to make a POST call from a JavaScript file to a PHP file in order to insert a variable into a MySQL database. Here are the basic files I am working with: 1° PHP file for sending the call <html> <head> <script ...

Adjust the maximum and minimum values on a dual thumb slider

I have implemented a two thumb range slider to define the maximum and minimum values. However, I recently discovered that it is possible for the thumbs to cross over each other - the max value can exceed the min value and vice versa. I am looking for a s ...

No compatible version of Angular could be located

I'm receiving this error continuously. Any thoughts on why? $ bower install ng-roundabout --save bower cached git://github.com/angular/bower-angular-mocks.git#1.3.15 bower validate 1.3.15 against git://github.com/angular/bower-angular-moc ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

Dynamically insert letters into each row as the HTML table increases

How can I display dynamically increasing alphabets in a newly generated cell on the left side of each row, based on the option selected in a dropdown list? These alphabets will serve as bullet points or serial numbers for the text boxes in each row. View ...

When building websites, pages, or applications with React, how do you determine the best choice between JavaScript, TypeScript, or JavaScriptXML?

After completing my portfolio and an eCommerce website design using Figma, I started learning React and Tailwind with Vite. I'm comfortable with basic JavaScript but now I want to understand the differences between .js, .jsx, and .ts files when workin ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

Using an external script to modify or call a Vue.js method

My Vue app is constructed using Webpack and includes a few basic computed properties, such as calculating the sum amount from input values. However, I now require the capability to replace the summation function with one stored in a separate file that is n ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

The jQuery autocomplete feature presents all choices regardless of what is typed into the input field

I'm currently working on a jQuery script that retrieves a JSON response and creates individual "player" objects based on the data received. These player objects are then added to the availablePlayers array, which serves as the data source for the aut ...

Set up a remapping for Istanbul to encompass every source file

Currently, I am setting up my Ionic 2 application with Angular 2 and TypeScript to produce code coverage reports for my test files. For unit testing and coverage report generation, I am utilizing Jasmine, Karma, and remap-istanbul. I came across an inform ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...