The Angular application must remain logged in until it is closed in the browser

Currently, my Angular app includes authentication functionality that is working smoothly. The only issue is that the application/session/token expires when there is no user activity and the app remains open in the browser.

I am looking for a solution where the token remains valid unless the user actively logs out themselves.

I have an idea to address this challenge by sending a request to the API every 10 minutes to refresh the access token. However, I am unsure of how to implement this logic at the application level.

Does anyone have suggestions on where I can integrate this logic effectively?

Thank you in advance, Danyal

Answer №1

One approach on the front end is to store the token in either a cookie or $window.sessionStorage so that it can be utilized for subsequent API calls requiring authentication. A factory can be created to manage the token.

.factory('AuthHandler', function ($window){

    return {

     saveToken: function(token){
        $window.sessionStorage.setItem('token', token);
     },


     getToken: function(){
       return $window.sessionStorage.getItem("token");
     }
  };
 });

The next step is to implement this logic in the controller:

.controller( 'MyCtrl', function ( $scope, AuthHandler, Api, $interval){

  function fetchData() {
     Api.get_token({username: $scope.username, password: $scope.password}).$promise.then(function(data){
       if(data.success){
         AuthHandler.saveToken(data.token);

       }
     });
  }
  fetchData(); 
  $interval(fetchData, 1000 * 60 * 10); 
 });

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

sliding to the right gets jammed

I am encountering a peculiar issue with Multi-page slide functionality. Whenever I attempt to switch pages, the new page gets stuck on the left before sliding out into position. Feel free to test this problem using my JSFiddle This is the JQuery code that ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

What are the steps to entering or accessing a MVC controller?

Having an issue with a dropdown list: @Html.DropDownListFor(m => m.SelectCountryId, Model.Countries, @Translator.Translate("PLEASE_SELECT"), new { id = "CountryID", @class = "form-control",ng_model="countryId", ng_change = "LoadRegions(countryId);", @r ...

Retrieve a variable from the context and assign it to the Angular scope

I'm having trouble accessing the sourcePath in the controller $scope. This is the code I have: (function() { var sourcePath; sourcePath = 'app/assets/javascripts/shared/controllers/some_controller.coffee'; angular.module("shared"). ...

Is there a specific index range in javascript or nodejs for accessing array items?

I recently came across this Ruby code snippet: module Plutus TAX_RATES = { (0..18_200) => { base_tax_amount: 0, tax_rate: 0 }, (18_201..37_000) => { base_tax_amount: 0, tax_rate: 0.19 }, (37_001..80_0 ...

Oops! Looks like there's an issue with the NextJS Custom Carousel bug. The error message reads: ReferenceError: document is not defined and is unable to read properties of undefined (

I have developed a unique carousel component to showcase text testimonials from scratch. The custom carousel utilizes a specialized script, carouselFunction.js, for navigational functionality to cycle through each testimonial. Here is an image of the carou ...

Direct your attention towards the bootstrap dropdown feature

I have encountered an issue with using a bootstrap dropdown. I need to focus on the dropdown in order to navigate through its options using the keyboard. However, my current attempt at achieving this using jQuery does not seem to be working when I use $(&a ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Troubleshooting tips for optimizing Opera and Internet Explorer performance

I'm currently on the hunt for solutions or techniques to debug my jquery script specifically under the Opera/IE browser. It appears that the ajax $.post() request is either not being sent at all, or it's being sent to the wrong address, among oth ...

Firebase Functions: Your functions are missing a definition

I have the following code in index.js: exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onCreate((snapshot, context) => { // Fetch the current value written to the Realtime Database. const original = snapshot. ...

Object with a specific name sitting within an array nested within another object

I have a node.js model that includes an array called keys containing multiple objects. I am looking to display these named objects in the view. Below is the model: var mongoose = require('mongoose'); var website = require('./website' ...

Using Ajax and Session Variables for a Worksafe Filter to selectively hide images

Creating a photography portfolio with some images containing nudity prompts the need to hide them by default until the user chooses to reveal them by clicking a "Toggle Worksafe Mode" button. To prevent "confirm form resubmission" errors when users naviga ...

When the Component is mounted, it triggers a GET request and passes the response as a prop to the child component. What occurs if I enter a URL that directly accesses the child

Consider a scenario where there are 2 URLs: website.com/Overview website.com/Overview/City When website.com/Overview is accessed, the component shown is Overview, while accessing website.com/Overview/City reveals the City component. An issue arises when ...

Mongoose: No documents are being returned by the .find() method

UPDATE : Similar question posted here: Trouble with Mongoose find() method I'm still new to working with nodejs and nosql databases. Today, I am building an API that retrieves data from my user collection which currently has two entries : The issue ...

Tips for clearing all content within a React Material UI table

How can I create a reset button to clear a table filled with user input data, without having to write functions from scratch? For example, similar to using clearLayer() for clearing a leaflet map. Thank you for any suggestions! //example of dynamical ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element. Check out my code snippet: const toggleButton = document.querySelector('button ...

Is there a way for me to store the output of an AJAX call?

One of the challenges I'm facing involves an AJAX request: $.ajax({ url: 'script.php?val1=' + value1 + '&val2=' + value2, dataType: "json", success: function (data) { var newValue1 = data[0]; ...

The JavaScript code appears to be missing or failing to execute on the website

Encountering a console error while trying to integrate jQuery into my website. The JavaScript file is throwing an error in the console that says: Uncaught ReferenceError: $ is not defined catergory.js:1 Even after following the suggested steps in this an ...