Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality.

loginController.js:

var loginAdmin=angular.module('Channabasavashwara');
loginAdmin.controller('loginController',function($scope,$http,$location){
    $scope.user_name = ''; 
    $scope.user_pass = '';
    $scope.user_login=function(){
    if($scope.user_name==''){
        alert('Username field should not be blank');
    }else if($scope.user_pass==''){
        alert('Password field should not be blank');
    }else{
        var userData={'user_name':$scope.user_name,'user_pass':$scope.user_pass};
        console.log('user',userData);
        $http({
            method: 'POST',
            url: "php/Login/login.php",
            data: userData,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(function successCallback(response){
            console.log('response',response);
            alert(response.data['msg']);
            $location.path('dashboard');
        },function errorCallback(response) {
            alert(response.data['msg']);
        });
    }
    }
});

My goal is to store the session when the user successfully logs in, and logout automatically after an expiration time (let's say 10 minutes) using cookies with an alert message. Any help would be appreciated!

Answer №1

To include the necessary cookie module in your project, you can use AngularJS and add the ngCookie module from this link. However, if you prefer, you can also handle cookies using basic JavaScript.

Below is a function called setCookie that takes the cookie name, value, and number of days for expiration as parameters. This function allows you to set a cookie when a user logs in and remove it when they log out.

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

Here is an example using AngularJS for handling cookies:

 angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Retrieve a cookie
  var favoriteCookie = $cookies.get('myFavorite');
  // Set a cookie
  $cookies.put('myFavorite', 'oatmeal');
}]);

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

Modifying the HTML attribute value (of input) does not impact the value property

After inputting a single tag, I ran the following code in my Chrome console: https://i.stack.imgur.com/ySErA.jpg The result was unexpected for me. According to what I have read in a book, when I change an HTML attribute, the corresponding property should ...

Step-by-step guide on transforming jQuery code into Vue JS:

Recently delving into Vue, attempting to translate previous JS + JQuery code into Vue Here is the list I'm working with: <ul id="progressbar"> <li class="active">integration Ip's</li> <li>T ...

Return a response from the controller method without using the express response object

When attempting to handle the scenario where a fetch for an item does not return anything from another method that lacks the express response, I encounter an issue. I invoke this method from another one that has the express response: const updateItem = asy ...

Switch between various height and width options using JavaScript

Is there a way to create a toggle that changes both the height and width of an element when it is clicked? <div class="flexbox-container" id="main" onclick="staybig()">Create Account</div> .flexbox-container { ...

Top approach for inserting Class instance into a group

I need some guidance on how to approach this issue. I am interested in creating a set of objects similar to the example below: Person P = new Person(); P.Name = 'John'; P.Surname = 'Dough'; var People = []; People.push(P); Can this b ...

Unable to properly access required file path through HTML source

I have a confidential folder named 'inc' where I store sensitive files such as passwords in php connection files. This folder is located at the same level as the 'public_html' folder. I successfully accessed php files with database conn ...

The Loopback access control list (ACL) for the admin role is failing to be

Seeking assistance with troubleshooting why my 'admin' role is not functioning in loopback 3.x. Here are the codes I am using: script.js - Contains code for creating admin roles in a postgres database. module.exports = function (app) { var User ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

Issue: [$injector:modulerr] - Error with AngularJS module "mean". More details can be found at http://errors.angularjs.org/1.5.0/$injector/modulerr?p0=mean&p1=%5B%24injector%3Amodulerr%5D%

Error: [$injector:modulerr] http://errors.angularjs.org/1.5.0/$injector/modulerr?p0=mean&p1=%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.0%2F%24injector%2Fmodulerr%3Fp0%3Dmean.circles%26p1%3D%255B%2524injector%253Amodulerr%255 ...

Background of jQuery-UI Slider

Can the background color of a jQuery-UI Slider widget be set using JavaScript? This is the default setting: What I am trying to accomplish is the following: The green range should be determined based on historical data. I want to visually show the user ...

What are the steps to modify or remove a node in react-sortable-tree?

I am currently working on implementing a drag and drop tree view using react-sortable-tree. Along with that, I also need to incorporate CRUD operations within the tree view. So far, I have been successful in adding, editing, and deleting nodes within the p ...

I want to know how to move data (variables) between different HTML pages. I am currently implementing this using HTML and the Django framework

I am currently working on a code where I am fetching elements from a database and displaying them using a loop. When the user clicks on the buy button, I need to pass the specific product ID to another page. How can I retrieve the product ID and successful ...

Confirmation of Angular Password Verification

I am having an issue with the password matching functionality on my website. When a user types their password and then re-enters it in the confirm password field, they immediately receive a message saying the passwords do not match. I would like to displ ...

Encountering an issue with React npm causing errors that I am unable to resolve

Hey there, I'm a newbie to React. After setting everything up, I encountered an error after running "npm start." Can anyone help me figure out how to fix this? Thanks in advance! Click here for image description ...

Tips for avoiding cursor sticking in css rotate transform in firefox?

I have a unique challenge in this code where I want the user to grab the black square and rotate it around the inner circle. Check out the code snippet here. While attempting to rotate the square, you might notice that the cursor sometimes gets stuck in ...

Is it possible to create a DOM element with a click handler all in one step?

I am looking to dynamically create an element, like this: var productItemTop = $( "<span>" + "<a class='spamItemsX' href='#' " + "onclick=" + eval(launchGenericProductSearch(topProducts)) ...

How can I create distinct component IDs effectively with the Catberry Framework?

When working with Catberry, it is essential that all components have unique IDs. How can you ensure that each ID remains distinctive even within a complex structure of nested components? ...

Alter a prototype method belonging to another module

If I wanted to create a custom plugin or module that alters the behavior of an object exported in another module, how can I go about modifying one of its methods? The code below illustrates my attempt at achieving this, but it seems like there may be a cru ...

Regular Expression for jQuery to match both letters and numbers, including special characters

Is there a way to validate text input using a jquery regex that includes specific characters such as A-Z, a-z, 0-9, !, #, $, £ (preferably all currency characters), %, &, -, and _? If so, how can this be implemented? I have attempted to use the regex pa ...

Error: The method api.createContextKey is not defined while running the Next.js development server

I am currently facing an issue while attempting to start the development server for my Next.js project. The problem arises when I try to incorporate MUI into my project, resulting in these specific errors. The error message points to a TypeError related to ...