Sign Out Page for AngularJS

I am experiencing a problem with the logout page. When the logout option is clicked from a page, the login page should be loaded and even if the user attempts to click the back arrow in the browser, only the login page should be shown. I have attempted using $window.location.reload(); and sessionStorage.clear();, but these solutions did not work.

Currently, my logout page displays the login page, however, when the back button is clicked, all the details of the previously logged-in user are still visible. Here is the code:

index.html:

<body ng-app="app">
 <div class=" ">
    <div ui-view></div>
 </div>
</body>

login.html:

 <form ng-submit=submit()>
   <input type="text" name="username" placeholder="Username" ng-model="person.firstName" required />
   <input type="password" name="pswd" placeholder="Password" ng-model="person.pswd" required />
       <div class="submit">
          <input type="submit" value="LOGIN">
        </div>
  </form>

page.html:

<ul>
 <li><a ui-sref="logout">Logout</a></li>
</ul>

app.js:

var app = angular.module('app', ['ui.bootstrap', 'LocalStorageModule']);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider
          .state('page', {
             url: '/page/:id',
            templateUrl: 'page.html'
               })
         .state('login', {
             url: '/login',
             templateUrl: 'login.html',
             controller: 'LoginCtrl'
         })
         .state('tab', {
          url: '/tab/:id',
         templateUrl: 'views/tab.html'
            })
     .state('logout', {
         url: '/logout',
         templateUrl: 'logout.html',
         controller: 'LogoutCtrl'
     });
     });
app.controller('LogoutCtrl', function ($scope, $http, $location, $state) {
sessionStorage.clear();
$location.path('/login');
//this loads the login page, but the previous logged-in details remain if the back arrow is clicked//
});
app.controller('LoginCtrl', function ($scope, $http, $location, $state) {
  $scope.submit = function () {
      $http.get("url" + $scope.Name + "&Password=" + $scope.pswd)
       .success(function (data, status, headers, config) {
           debugger
           $scope.tableData = data;
           console.log(data)
           if (data == 'Exception') {
               window.alert('You have entered wrong username or password');

           }
           else $state.go('tab', { id: data.Table[0].UserId });
       })

}
});

In summary, what I require is that after logging out, the login page should be displayed and if the user tries to navigate back, only the login page should be visible. Any assistance would be greatly appreciated.

Answer №1

To ensure access to a certain page, it is essential to store the user's login details securely. This can be achieved by using cookies, localStorage, or SessionStorage. By validating the presence of these login details on the required page, you can control access accordingly.

One method is to establish a flag like loggedIn or utilize the loginID/UserName for authentication. If the credentials are detected, the user gains access; if not, they are redirected to the login page. To determine the user's login status, leverage Angular's stateChangeStart event and check for the existence of the loginID/UserName or designated flag. Proceed with the action if confirmed, otherwise direct the user to log in.

Upon logging out, it is crucial to remove these stored details for security purposes.

For assistance on storing user data in localStorage, refer to this helpful link.

Answer №2

<script src="bower_components/js/angular-local-storage.min.js"></script>
...
<script>
    var myApp = angular.module('myApp', ['LocalStorageModule']);

Include the localstorage module and establish a local storage to set conditions in the main controller. Ensure that if the local storage exists, redirect to the main page; otherwise, return to the login page.

Use localStorageService.remove(key); to clear all data upon logout.

In your controller:

myApp.controller('MainCtrl', function($scope, localStorageService) {
 var lsKeys = localStorageService.keys(); // To display all stored values
function submit(key, val) {
return localStorageService.set(key, val);
}
function removeItem(key) {
  return localStorageService.remove(key);
}
});

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

Troubleshooting the issue: Node.js application unable to utilize Mongodb's $addToSet functionality

I'm having an issue with mongo's $addToSet function not properly adding a Store to my stores array (where I have commented out seemed to work), resulting in duplicate IDs. Can anyone help me identify my mistake and suggest a solution? Thank you. ...

Enhancing Luxon DateTime with extension type support

Referencing the issue at https://github.com/moment/luxon/issues/260, I am looking to extend the DateTime object as shown below: import { DateTime } from 'luxon'; function fromUnix(tsp?: number): DateTime { return DateTime.fromMillis(tsp * 1000 ...

Display an assortment of various categories once every other time

As a novice AngularJS user, I am looking to showcase a collection in my HTML code using a specific directive: displaying items alternately on the left and right side. For example, the first item on the left, the second on the right, the third on the left, ...

Calculation for determining the fill of a DIV's remaining height

Here is what I have: <div id="modal-container"> <div id="modal-body"></div> <div id="modal-footer"></div> </div> I am currently working on a JavaScript function to adjust the height of #modal-body to fill in the re ...

Activate the CSS on a click event using the onClick method

I am trying to implement a transition that triggers when clicking on a specific div element. Currently, the transition only occurs with the active css class. How can I achieve this effect by simply clicking on the div itself? I am using reactjs and believe ...

The toggleCategories function seems to be malfunctioning as it is only showing the sequence number as 0 in ReactJS

I am currently working on a portfolio using the React framework. One of the features I have implemented is a project page where multiple projects are displayed within tabs. However, I am facing some issues with the functionality. toggleCategories(){ ...

The curious case of jQuery.parseJSON() failing to decode a seemingly valid Json string on a Windows-based server

I am currently running a WordPress JavaScript function code on a Linux server that also includes a PHP function called "get_form_data". jQuery.ajax({ type: "POST", url: MyAjax.ajaxurl, data: {action: "get_fo ...

"Troubleshooting: Jquery Draggable Function Fails to Execute

I'm currently working on a JSP page where I am attempting to make the rows of a table draggable. Despite multiple attempts and combinations, I have been unable to make any elements draggable. The rows are appended after an AJAX call, but still no succ ...

"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want. function show_image() { var img = document.create ...

Javascript functions properly on Chrome, Opera, and Edge browsers, but unfortunately does not work on FireFox and IE 11

If you're interested, I have some code available on JS Fiddle that showcases my skills. var getJSON = function (url) { "use strict"; return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('get' ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

What is the best way to move data from one HTML link to another HTML link using AngularJS?

<tr ng-repeat="greeting in posts"> <!--<td>{{greeting.user}}</td>--> <td> <div ng-controller="MyCtrl"> <a href="quizlist.js">{{greeting.page_name}} </a> </div> & ...

Obtaining an array from an object with Meteor and MongoDB

I've been struggling for about a week trying to accomplish a simple task with MongoDB. Here is the document I'm working with: { _id: "mkikuQzrYdyQjL7Ry", links:[ 1: "link1" 2: "link2" 3: "link3" 4: "link4" ] } Is there a way to retrieve al ...

Can Angular retrieve the inner HTML content of an element?

Check out this demo . In this demonstration, I have created a list of "names" and I'm trying to retrieve the text of the selected element. However, whenever I click on an item from the list, I consistently get the same "innerHTML" for all users. Is ...

The data displayed in the <span> element isn't reflecting the response from the loaded page, despite being visible in Firebug

I have encountered a problem while trying to load a signup.php page into a div on my main page. All the elements (forms, JavaScript, etc.) function correctly in the loaded page, except for one issue - I cannot get the response from the PHP script to displa ...

Surprising lack of elements in the array

Apologies for the lengthy code, but unfortunately, I was unable to create a minimal example that reproduces the issue. The function below returns two arrays, with each cell containing a number: function VNtorus(R, r, nx, ny) { var Vertices = new Array ...

Utilizing CSS-in-JS to eliminate arrow buttons from a TextField

I'm currently developing a webpage using React and Material-UI. One of the components I have is a TextField element, and I need to remove the arrow buttons that typically appear on number input fields. If I were utilizing CSS, I could easily achieve t ...

I am able to see the Redux props showing up in Redux DevTools, but for some reason they are not

I am facing an issue where I am passing a Redux prop to a component that is fetched from a payload. The payload successfully updates the state in my reducer and the component receives the prop (an array of objects fetched in the action) according to my Red ...

How can we utilize a loop to continuously sum up numbers until we reach a multiple of another number, let's say when the total is divisible by 4?

I am trying to create a function in JavaScript that will detect when a given number is not a multiple of 4. If the number is not a multiple of 4, I want to add numbers incrementally until it reaches the closest multiple of 4. Here’s what I have so far: ...

Setting the state to an array of objects in React: A beginner's guide

Currently, I am developing a flashcard application using React. To store the data entered by the user, I have initialized my state as an array of objects that can hold up to 10 terms and definitions at a time: state = { allTerms: [ { ...