angular-routing does not seem to redirect properly

I'm encountering an issue after logging in, as my page is not redirecting to the main page. Upon investigation, I found that the login condition works when using $window.location. However, I want to implement angular-route to restrict access to the main menu for users who are not logged in. The current problem is that if I use $window.location, users can still access the main menu without logging in. Here is an excerpt from my JavaScript file:

 app.config(function($routeProvider){
      $routeProvider
      .when('/',{
        templateUrl:'index.html'
      })
      .when('/mainmenu',{
    resolve:{
      "check":function($location,$rootScope){
        if (!$rootScope.loggedIn) {
          $location.path('/');
        }
      }
    },
    templateUrl:'content/mainmenu2.html'
  })      
.otherwise({
        redirectTo:'/'
      });
    });

    app.controller("logincont", ['$scope','$http','$window','$rootScope','$location',function($scope,$http,$window,$rootScope,$location){
    $scope.login = function () {
           $http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
           $scope.reslogin  = response.data;
          if($scope.reslogin == null)
            {
              alert('Login Incorrect'); 
            }
            else
            {
              $rootScope.loggedIn = true;
              $location.path('/mainmenu');

            }
      });
          };   

          }]);

Below is a snippet of my HTML code:

<form>
        <h1 class="tengah"> Form Login </h1>
        <div class="form-group">
            <label for="inputId">User Id</label>
            <input type="text" class="form-control" ng-model="userid" placeholder="userid" required>
        </div>
        <div class="form-group">
            <label for="inputPassword">Password</label>
            <input type="password" class="form-control" ng-model="pass" placeholder="Password" required>{{password}}
        </div>
        <button type="submit" class="btn btn-primary" ng-click="login()">
            <span class="fa fa-sign-out"></span>Login</button>
    </form>

Answer №1

If you want to bypass authentication for certain routes, you can achieve this by using a flag called allowUnauth. For example, if you have routes like login that you don't want to require authentication for, you can set the allowUnauth flag on those routes and adjust your routing as follows:

app.config(function($routeProvider){
      $routeProvider
      .when('/',{
        templateUrl:'index.html',
        allowUnauth:true
      })
      .when('/mainmenu',{
    templateUrl:'content/mainmenu2.html'
  }).otherwise({
        redirectTo:'/'
      });
    });

 var unauthRoutes= [];
    angular.forEach($route.routes, function(route, path) {
        // add route to unauthRoutes if allowUnauth is true
        route.allowUnauth && (unauthRoutes.push(path));
    });

    $rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) 
    {
        var atuhRoute= (-1 === unauthRoutes.indexOf($location.path()));
        if(atuhRoute && !$rootScope.loggedIn) {
            $location.path('/');
        }
    });

You can view a working plunker here

Answer №2

Consider trying this:

"use strict";

setUpApplication.$inject = ['$routeProvider'];
function setUpApplication($routeProvider) {
  $routeProvider
    .when('/homepage', {
      resolve: {
        checkAuthentication: (function() {
          checkAuthentication.$inject = ['$rootScope'];
          function checkAuthentication($rootScope) {
            if(!$rootScope.loggedIn) {
              return Promise.reject('not authenticated');
            }
            else return Promise.resolve();
          };
          return checkAuthentication;
        }())
      },
      templateUrl:'views/home.html'
    })
    .otherwise('/');
}

myApp.config(setUpApplication);

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

Fixed-bottom footer in Bootstrap 5 that overlays content

Having trouble creating a fixed footer using the fixed-bottom class in react & bootstrap. The issue is that it's covering some content and I've tried various solutions without success. Any suggestions on how to fix this? (Code and Demo provided b ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...

What is the best way to show the interior color of a cube in three.js?

My plan is to create a room using THREE.js starting from a basic cube. Here's what I have written so far: function loadModelcube() { console.log("Function executed successfully"); cube.traverse( function( node ) { if( node.material ) { ...

Tips for identifying modifications in an input text field and activating the save button

Currently, I am developing a function that can detect any changes made in the text field and then activate the save button accordingly. This code is being executed in Visual Studio 2017, using HTML and JavaScript. (function () { var customer_addres ...

tips for generating a random number for direct display

Can anyone help me figure out how to automatically display the total of numbers from this script on my blog post without having to click anything? Additionally, I need it to update if the browser is refreshed. ` http://jsfiddle.net/BenedictLewis/xmPgR/ ...

Tips for transferring variables as arguments in javascript

Currently, I am immersed in a test project aimed at expanding my knowledge of web development. Unexpectedly, I have encountered an issue that has left me puzzled on how to proceed. Within this project, there exists a table consisting of 11 cells. While 9 ...

Interactive Table - displays warning message in datatable

Incorporating serverside datatable into my project has been a game-changer. Now, I am trying to enhance the table's responsiveness. I experimented with the code snippet below in conjunction with my existing code. While it did deliver the desired outco ...

What is the process for triggering events when the previous and next buttons are clicked?

Within the jQuery fullcalendar, there are previous and next buttons. Is there a way to trigger specific events when these buttons are clicked? ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Is it possible to test code that utilizes a different framework from jQuery using QUnit?

Currently, I am in the process of developing a compact library that is capable of utilizing multiple frameworks (specifically jQuery, Prototype, YUI2). To ensure its functionality, I am conducting tests using QUnit. Nevertheless, one setback is that QUnit ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Authentication Error (401) in WordPress JWT

Recently, I came across WordPress and started using it. However, I encountered some issues while trying to integrate JWT with a custom endpoint. Despite configuring my API and JWT correctly, I faced an authentication problem during my AJAX request. It&ap ...

Navigate through the rows and columns of an HTML table by utilizing Javascript with webdriver, specifically for Protractor in a non-angular environment

I need help with iterating through rows and columns using Selenium Webdriver. I am currently using Protractor for a non-angular web page. I have some Java code that works with the WebElement class to get the number of links, but now I need to transition th ...

What is the technique for arranging the display of a component in React?

Is there a way to dynamically render a component in my react-app at a specific date and time, like 6.00PM on October 27, 2022? I want to release a form for signing up starting from that exact moment. The timestamp information will be stored in my database ...

Utilize the arrow keys to navigate through the search suggestions

I am facing an issue with my search bar where I am unable to navigate through the suggestions using arrow keys. I have been struggling with this problem for days and would appreciate any help in resolving it. var searchIndex = ["404 Error", "Address Bar ...

Combining Angular 2 and Symfony 3 for seamless integration

I am currently working on integrating Angular 2 with Symfony 3. After using npm to install node modules, I encountered an issue linking them from my base view base.html.twig. Despite adding scripts, none of them seem to be working or appearing in the page& ...

Attempting to trigger an action from a Vuex module proves futile as the error message "[vuex] unknown action type" is generated

I've been struggling to successfully register a Vuex module. Below is the code I've been working with: stores/index.js: import Vuex from 'vuex'; import resourcesModule from './resources'; import axios from '@/helpers/ax ...

Selecting images using jQuery

Currently, I am in search of a jQuery image picker plugin that possesses the following features: Show a collection of images and enable the user to select one (and only one) by clicking on it If the user dislikes any of the pre-defined images, they shoul ...

JavaScript conditional calculation mechanism

Here is the code snippet I am referring to: function myFunction() { var x = document.getElementById("ins-feet").value; if(x >= 0 && x <= 1499) { document.getElementById("show-cost").innerHTML = "Cost: $" + 300; } else if ...

Struggling to retrieve the accurate input value when the browser's return button is clicked?

Having multiple forms created for different conditions, each one submits to a different page. However, when I navigate back from the other page, all my forms display the same values as before. Here's the code snippet: <form action="<?php echo b ...