Steps for displaying a notification when the variable "Angular" is no longer present after the session ends

I am facing a problem with my Angular app. The issue arises when the {{controllername.name}} disappears to display the username after a session timeout. Even though the warning from ngIdle pops up, users can still refresh the screen without being redirected back to the login page.

The {{ctrlDash.userinfo.name}} vanishes after 20 minutes (refer to code snippet below).

<ul class='nav'>
    <li class='dropdown dark user-menu'>
        <a class='dropdown-toggle' data-toggle='dropdown' href='#'>
            <img width="23" height="23" alt="" src="assets/images/avatar.jpg" />
            <span class='user-name'>{{ctrlDash.userInfo.name}}</span>
            <b class='caret'></b>
        </a>
        <ul class='dropdown-menu'>
            <li>
                <a href='user_profile.html'>
                    <i class='icon-user'></i>
                    Profile
                </a>
            </li>
            <li>
                <a href='user_profile.html'>
                    <i class='icon-cog'></i>
                    Settings
                </a>
            </li>
            <li class='divider'></li>
            <li>
                <a href='sign_in.html' target="_self">
                    <i class='icon-signout'></i>
                    Sign out
                </a>
            </li>
        </ul>
    </li>
</ul>

What I want is a template feature that can "DETECT" this and force the user to log in again;

Below is the ng-template located at the bottom of the same page:

<!-- Templates for Modals -->
    <script type="text/ng-template" id="warning-dialog.html">
        <div class="modal-header">
            <h3>You're Idle. Do Something!</h3>
        </div>
        <div class="modal-body" idle-countdown="countdown" ng-init="countdown=5">
            <p>You'll be logged out in <span class="label label-warning">{{countdown}}</span> <span ng-pluralize="" count="countdown" when="{'one': 'second', 'other': 'seconds' }"></span>.</p>
            <progressbar max="20" value="countdown" animate="true" class="progress-striped active" type="warning"></progressbar>
        </div>
        <div class="modal-footer">
            Quick! Move your mouse and your session will reset...
        </div>

    </script>
    <script type="text/ng-template" id="timedout-dialog.html">
        <div class="modal-header">
            <h3>Oh, Snap! You've Timed Out!</h3>
        </div>
        <div class="modal-body">
            <p>
            You were idle too long.  Click the button below to be redirected to the login page and begin again.
            </p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-danger btn-small" data-ng-click="goBack()">Back To Login</button>
        </div>
    </script>
    <!-- End Templates for Modals -->

Initially, the TIMER detects IDLE and then a WARNING notifies the user to log in again. However, upon refreshing the page, the {{ctrlDash.userInfo.name}} becomes empty.

Here is the code snippet for ngIdle:

//This is the IDLE function
            $scope.started = false;
            $scope.ended = false;

            $scope.events = [];
            $scope.idle = 20; //this is in ACTUAL seconds
            $scope.timeout = 20; //this is in ACTUAL seconds

            function closeModals() {
                if ($scope.warning) {
                    $scope.warning.close();
                    $scope.warning = null;
                }

                if ($scope.timedout) {
                    $scope.timedout.close();
                    $scope.timedout = null;
                }
            }

            $scope.$on('IdleStart', function () {
                closeModals();

                $scope.warning = $modal.open({
                    templateUrl: 'warning-dialog.html',
                    windowClass: 'modal-danger'
                });
            });

            $scope.$on('IdleEnd', function () {
                closeModals();
            });

            $scope.$on('IdleTimeout', function () {
                closeModals();
                $scope.timedout = $modal.open({
                    templateUrl: 'timedout-dialog.html',
                    windowClass: 'modal-danger'
                });
            });

            $scope.start = function () {
                closeModals();
                Idle.watch();
                $scope.started = true;
            };

            $scope.stop = function () {
                closeModals();
                Idle.unwatch();
                $scope.started = false;

            };
            if(!angular.isDefined($scope.goBack)) {

                console.log("I\'m not defined...");

                if(!angular.isFunction($scope.goBack)) {

                    console.log("I\'m not a function...")
                }
            }

            $scope.goBack = function _goBack() {
                closeModals();
                Idle.unwatch();
                $window.location.href = $scope.templateViews.logout;
            };

Lastly, the goBack() function inside the dashboardController = controller throws an unreferenced error.

Unreferenced error, goBack is NOT DEFINED.

These are the challenges I'm facing regarding my app. I would appreciate any assistance. Thank you.

Answer №1

As I venture into the world of Angular development, I find myself navigating through new territory with my first app. One of the features I recently tackled was implementing a logout functionality. After logging out, I wanted to ensure that any attempt to access pages would redirect the user back to the login page. This task involved checking for the presence of credentials in the controller and using `$location.path('/login');` to handle the redirection.

--Revamped from original comment

In my application, I have organized my code into two service modules, each containing factories. The first module handles communication with REST endpoints while the second module focuses on managing business logic. Upon successful login, user information is passed to the `setCreds` function.

var businessService = angular.module('businessService', ['ngCookies']);
businessService.factory('setCreds', ['$cookies', function ($cookies) {
    return function(un, pw, userRole) {
        var token = un.concat(":", pw);
        $cookies.creds = token;
        $cookies.usersRole = userRole;

Subsequently, every controller in my application begins by verifying credentials using `checkCreds` before proceeding to fetch data for the view.

if (!checkCreds()) {       
    $location.path('/login');
} else { ..continue fetching data

The implementation of `checkCreds` involves checking for the existence of credentials stored in cookies.

businessService.factory('checkCreds', ['$cookies', function ($cookies) {
    return function () {
        var returnVal = false;
        var creds = $cookies.creds;
        if (creds !== undefined && creds !== "") {
            returnVal = true;
        }
        return returnVal;
    };
}]);

It's important to remember to inject `businessService` into your app and the relevant service factory into your controllers for seamless functionality.

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

Encountering a 403 (Forbidden) error while attempting to retrieve JSON data using a GET request from the Wordpress API

Link to code: http://plnkr.co/edit/0eHQPVRHmCWelK6VEYVE?p=preview I'm currently working on creating an Analytics Chart using JSON Data extracted from my WordPress Site, and integrating it with ChartJS for an AngularJS app. However, I've encount ...

What is the best way to handle clients who disable Javascript on their browsers?

Concerns have arisen regarding clients who disable Javascript in their browsers for security purposes. My web application heavily relies on jQuery for tasks such as validation, AJAX, and more. A colleague has suggested implementing server-side validation ...

Execute a zoom out action by pressing the (Ctrl) and (-) keys simultaneously in Javascript

I'm trying to figure out how to simulate a Ctrl - zoom out using Javascript. I've noticed that using the style zoom property or the transform property gives different results with white space in the corners, rather than the smooth zoom out effect ...

Having trouble locating the issue in my React application

As part of a tutorial project, I am developing an e-Commerce application using React. Currently, I am encountering an error message stating 'TypeError: Cannot read property 'length' of undefined' when dealing with a cart object. Let me ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

Tips for retrieving all error messages within a script tag using Vee Validate Version 4 in Vue 3

I am currently working with Vue 3 and vee-validate V4, but I'm facing an issue where I can't retrieve all error messages within the script tag. Is there a way to access all error messages from the script tag? <Form v-slot="{ errors }" ...

Is my Javascript experiencing a shortage of asyncIds? (Encountered RangeError in inspector_async_hook.js)

One issue that I frequently encounter while using async/await is the following error: RangeError: Value undefined out of range for undefined options property undefined at Set.add (<anonymous>) at AsyncHook.init (internal/inspector_async_hook ...

A guide to printing a web page within an ion-view container

I am currently utilizing the Ionic Framework for my web application. Each page within the app is displayed using ion-view. I have a requirement to display graphs and possibly save them as PDF files. Below is a snippet of my code: <ion-view title="Repo ...

`Trying out an HTTP POST request`

I have created a save function: $scope.save = function(){ $scope.product.$save(function(){... Update The $save functionality has been implemented in my resource: .factory('SingleProduct', function($resource){ return $resource(' ...

Trick to enable editing in Bootstrap Select Combobox

Is there a way for users to add their own options to bootstrap-select? Greetings! I have spent some time searching for a straightforward solution that is compatible with Bootstrap 4 styling. Despite exploring various suggestions, as well as unresolved thr ...

Updating environment variables in a React app without the need to rebuild the image

As I work on developing a Dockerized React application, I have encountered the challenge of defining environment variables for API URLs. React injects these variables during the build phase, meaning that I have to rebuild the entire image every time the en ...

Refreshing the Angular page using ng-route in html5 mode fails to redirect to index.html

My goal is to implement html5 mode for my mean app. Below is the view router code in my angular script: app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider // define r ...

Protect a web address with the power of AngularJS, Firebase, and S3

I am looking to create a website using an AWS S3 bucket for storing videos, along with AngularJS and Firebase for authentication. My main concern is ensuring that the URL to access the video content (/video) is secure and can only be accessed by authentica ...

ESLint encountered an error while attempting to load the configuration "next/babel" for extension

Every time I try to generate a build of my Next.js app by running "npm run build," I keep encountering this error. Check out the error I'm getting while running npm run build here. Also, take a look at my .eslintrc.json file here and my .babelrc file ...

What is the process for sorting an item based on a specific criteria?

I am working with an object that looks like this: [insert image description here][1] The object on the screen is represented by dataUserProfile.permissions[dataOriginSelect].permissions I am trying to sort this object based on the 'order' para ...

Enhancing the functionality of XMLHttpRequest.open()

How can I intercept and modify the arguments of the XMLHttpRequest.open() method? I attempted using the proxy method, but it was unsuccessful. I removed the override when XMLHttpRequest() was called: (function() { var intercepted = window.XMLHttpReque ...

What is the best way to organize a complicated array in Javascript?

Struggling with this question for quite some time. I have a nested list with the following structure: Volume1 Chapter4 Chapter3 Section3-6 Section3-1 Volume2... ... I am looking to create a sorting function to organize volumes, ch ...

The properties of Angular interface objects are not defined

Here is an example of an interface for an object: export interface IProduct { vendor?: string; price?: number, quantity?: number, savings?: number, productId?: number, vendorsPrice?: number[], title?: string, images?: objec ...

My project is unable to run with Karma and Jasmine

As I was following the book AngularJS: Up and Running, I reached a chapter where the author introduced Karma and Jasmine for testing purposes. However, the instructions on how to organize the project and where to install Karma and Jasmine were not very cle ...

Unable to retrieve the saved user from the Express.js session

Below is the code in question: app.post('/api/command', function (req, res, next) { var clientCommand = req.body.command; console.log("ClientCommand: ", clientCommand); if (!req.session.step || req.session.step === EMAIL) { ...