Prevent the user from being redirected to the login page again after they have already logged in, even if they attempt to go back using the browser's back button

I am in the process of building a login page that checks certain conditions and redirects the user to the home page. However, I want to implement a feature where once the user has visited the home page, they cannot go back to the login page by clicking the back button on their browser. I attempted to use a variable called "isLoggedIn" that starts as false, then gets set to true after checking the username and password. I stored this variable in local storage as a flag, but I seem to be missing something

Below is my app.js code:

var validationApp = angular.module('validationApp',['ngRoute','ngStorage']);
var loggedIn = false;
validationApp.run(function($rootScope, $localStorage){
  //var loggedIn = false;
    //if(!loggedIn) {
        storage = window.localStorage;
        //storage.setItem("loggedIn", true);
        //console.log(storage.getItem("loggedIn"));
//    $rootScope.$storage = $localStorage.$default({
//        loggedIn: false
//    })
//    }
});

validationApp.controller('mainController', function($scope,loginservice,$localStorage) {
    $scope.dologin = function () {
        //storage.setItem("loggedIn" ,true);
        //loginsucess = storage.getItem("loggedIn");

        if(loggedIn == false) {
            //console.log(loginsucess);
            if ($scope.userForm.$valid) {
                loginservice.login($scope.user.email, $scope.user.password);
            }
            storage.setItem("loggedIn", true);
        }
    }
});

I also tried implementing a check condition in my routes, but now even with valid credentials, I cannot access the home page.

validationApp.config(

    function($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'main.html',
                controller: 'mainController'
            })
            .when('/home', {
                templateUrl: 'home.html',
                resolve:{
                    "check":function($location){
                        if(storage.getItem(loggedIn) == true)
                        {
                            alert(loggedIn);
                            $location.path("/home");
                        }
                        else
                        {
                            $location.path("/main");
                        }
                    }
                },
                controller: 'mainController'
            })
            .otherwise({
                redirectTo: '/'
            });
});


validationApp.service('loginservice',function($location)
{
    this.login = function(username, password){
        console.log(username,password);

        if(username == "example@email.com" && password=="1234")
        {
            //alert('thank you for submitting your form');
            $location.path("/home");

            //console.log(storage.getItem("loggedIn"));
        }
        else
        {
          //alert("invalid username and password");
            $location.path("/main");

        }
    }
});

Answer №1

To see a demonstration in action, please visit the following link: http://plnkr.co/edit/46O0znC5HFDE4cYXSm5h?p=preview

Here is an example of storing data in cookies within a login function:

$cookies.userinfo = {
    'id': 1,
    'name': 'pqr'
};

When logging out, you can remove this data using the following code:

delete $cookies.userinfo;

You can then check if the cookie 'userinfo' exists by using 'angular.isDefined($cookies.userinfo)'. If it does exist, you can redirect to a specific page after login. Here's how you can achieve this:

app.run(function ($cookies) {
      $rootScope.$on("$routeChangeStart", function () {
        if (angular.isDefined($cookies.userinfo)) {
            $location.path("/pathname");
        }

      });
});

Answer №2

Check out this code to see if it meets your needs

var validationApp = angular.module('validationApp',  ['ngRoute','ngStorage']);

    var loggedIn = false;
    validationApp.run(function($rootScope, $localStorage, $location){

       storage = window.localStorage;
       $rootScope.$on("$routeChangeStart", function (evt, next, current) {

           if(storage.getItem(loggedIn) == true) {
                if (next.$$route.originalPath == '/login')
                    $location.path('/home');
           }
           else
             $location.path('/login');
       });


});

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

Angular routing does not properly update to the child's path

I've organized my project's file structure as follows: app/ (contains all automatically built files) app-routing.module.ts components/ layout/ top/ side/ banner/ pages/ ...

Organizing a specific group of graph nodes in a unique layout with cytoscape.js

When working with Cytoscape JS, one can take advantage of the intriguing feature known as LAYOUTS. My goal is to organize a group of nodes in a circular layout. However, I do not wish for all the nodes in my network graph to be placed on that circle. Is t ...

Unable to display the popup modal dialog on my Rails application

I currently have two models, Post and Comment. A Post has many Comments and a Comment belongs to a Post. Everything is functioning properly with the creation of posts and comments for those posts. Now, I have a new requirement where when clicking on "crea ...

Create a dynamic animation effect for the placeholder in an input field that triggers when the user starts typing

Have you ever come across interactive demos like this one? I've noticed that most examples involve creating a new element. parent().append("<span>" + $input.attr('placeholder') + "</span>"); Is there a way to make the placehol ...

The handlebar does not undergo any modifications once the authentication process is completed

This file is named header.hbs <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{{ title }}</title> ...

Using JavaScript to pass a newly created variable as an argument in a default

Currently, I am developing a node application that heavily utilizes promises. To enhance the readability of my code, I have been removing anonymous functions and storing them in a JavaScript object called "myCallbacks". Here's an example: let myCallb ...

Submit a collection of images and an object to the server using ReactJS

I'm currently working with Reactjs on the frontend. In order to set the profile picture to state, I've implemented the following code: handleImageChange = (event) => { event.preventDefault(); var file = event.target.files[ ...

Ionic app on mobile device experiencing issue with Autocomplete feature not filtering correctly in Angular

I am facing an issue with my autocomplete form. It works perfectly fine locally, but once compiled to a PWA, the data filtering feature stops functioning properly. The API is returning a JSON array response as expected. var modify = function (term) ...

Having trouble converting data back to JSON format after using JSON.parse in an ejs file with node and express

I'm retrieving data from an external API on my server, then attempting to pass that data to an ejs file using JSON.stringify(data), and trying to read the data in the ejs file by parsing it with JSON.parse(data). However, I am encountering issues wher ...

Currently attempting to troubleshoot a factory operation that is experiencing difficulties with injection

As a newcomer to Angular and testing in general, I am attempting to create a simple test to check if the object is defined before proceeding with further testing. An error message that I encounter is: Error: [$injector:unpr] Unknown provider: $statePar ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

The necessity of utilizing a dummy object for storing events in JavaScript is evident in certain situations

I am confused as to why in some instances a dummy object is needed in JavaScript to store events, like in the following code: Metal.Gold = function() { var temp = $("<div>"); //dummy object this.Submit = function(url1, method, data){ ...

What is the best way to determine if a value stored in localStorage is present in an

After reading this particular response, I learned that I should utilize $.inArray. Following this advice, my code looks like this: var curPostId = $(".my_post_id").attr("data-id"); if($.inArray(curPostId, lines)) { $('#'+localStorage.getItem( ...

Utilizing Ajax in PHP to handle post requests and gracefully handle errors

I have retrieved data from a database and I am presenting it in a pie chart using chartjs. My goal is to allow the user to select a specific range of dates. When the user clicks the filter button, the pie chart should update to display data based on the s ...

What is the process for retaining data in mongoose without generating a new database object?

Whenever I try to save data using a bot command, a new object is created every time the data is submitted. I want to ensure that only one object is created, but every time the same user submits data, it should automatically update rather than create a new ...

When clicking on an element, all elements will change, not just the specific one

I have been experimenting with basic Jquery and noticed something peculiar. On my page, I have an h1 heading and a generic link. When I click the link, I expect the text to change to "This text has now changed". However, what actually happens is either the ...

What could be causing the visibility issue with my navigation items in the bootstrap navigation bar?

Currently, I am experiencing a puzzling issue with the navigation bar on my live website. The navigation items seem to flicker for a brief moment and then disappear entirely. This unexpected behavior is certainly causing me some concern. I crafted the us ...

Create pathways for direct access

I've been studying some code written by someone else to improve my understanding. The way they are setting up routes seems a bit unclear to me. app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist'))) // mount rou ...

Styling does not affect an Angular component that is injected into an iframe

I am facing an issue with styling in an iframe when trying to append my own angular component. Despite various attempts, I have been unsuccessful in getting the styling to apply to the component within the iframe. Upon loading the iframe, I use JavaScript ...