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

Tips for implementing WebSockets with Play Framework

I recently downloaded Play Framework from GitHub and successfully compiled it. My goal now is to implement WebSockets using a JavaScript client along with a WebSocket controller similar to the one outlined in the Using WebSockets documentation. However, de ...

Under what circumstances is it possible to iterate through an empty array?

When defining arrays in JavaScript using Array(n), it creates an empty array. If I write the following code: Array(2).map((val) => console.log(val)) Nothing happens when running this code, but if I spread out the elements of the array into another a ...

Unable to successfully update DIV content in JavaScript due to incorrect file path specified

I came across this code online and it seems to be functioning properly. However, no matter what name I give the file that is supposed to load into the DIV, I consistently receive an error message stating "Object was not found." What specific steps do I nee ...

Creating a Custom Error Object in Feathersjs: A Step-by-Step Guide

If I were to throw a GeneralError when calling a service, how can I create an error object with the following structure: { "status": "Failed", "code": "500_1", "detail": "Something is wrong with your API" } I have attempted to add this in the error hook: ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...

Maximizing JavaScript efficiency: Returning a value within an if statement in an AJAX call

In my function, I have a condition that checks the idType. If it is 1, an ajax call is made to a php file to retrieve the name associated with the specific idName and return it. Otherwise, another example value is returned. function obtainName(idName, idTy ...

Assigning a variable within a parent function from a child function in JavaScript

Struggling to assign the value of "result" in the inner function. Any suggestions on how to do this? I am able to console log the result variable inside the function, but a friend recommended using promises. However, I have no clue how to implement that ...

I'm having some unexpected reflections with the threejs cube camera

I'm currently experimenting with creating an object that reflects on all sides. Although I've made progress, I seem to be encountering some issues. At certain angles, I can only see partial reflections and the scale of the reflection is much larg ...

Is there a way to still access the data from a radio button even if it hasn't been selected?

I'm currently working on a questionnaire feature and facing an issue where I need to capture all answers, even if the radio button is not checked. Here's a snippet of the HTML code: $('input:radio').each(function () { if ($(this). ...

Waiting for a method to finish in Node.js/Javascript

Currently, I am in the process of creating a trade bot for Steam. However, I have encountered an issue where the for-loop does not wait for the method inside it to finish before moving on to the next iteration. As a result, the code is not functioning as i ...

"Caution: Refs cannot be assigned to function components" message encountered when utilizing a custom component in Next.js

I created a component called HeaderIcon with the following code: function HeaderIcon({ inactiveIcon, activeIcon }) { const [isActive, setIsActive] = useState(false); return ( <div onClick={() => setIsActive(!isActive)}> {isActive ? ...

Locate records through an array of nested references using Moongoose (MongoDB)

Given the collection schema shown below: var terminalSchema = new mongoose.Schema({ name: 'String', ip: 'String' }); var wayPointSchema = new mongoose.Schema({ name: 'String', description: 'String' ...

I encountered an issue stating, "The function `req.redirect` is not recognized."

Recently starting out with node development. Encountering the error below: TypeError: req.redirect is not a function at Post.create (/var/www/html/node_blog/index.js:40:7) at /var/www/html/node_blog/node_modules/mongoose/lib/utils.js:276:16 a ...

Is there a way to retrieve the disabled drop-down field value after submitting the form?

I'm struggling with a dropdown field that becomes disabled once an item is selected. After submitting the form, the dropdown field loses its value and I'm left with an empty field. Any suggestions on how to keep a value in the dropdown after subm ...

Unable to modify attribute within $templateCache through an AngularJS Directive

Here is my Directive code: module.directive('iconSwitcher', function() { return { restrict : 'A', link : function(scope, elem, attrs) { var currentState = true; elem.on('click', function() { ...

Issue: The object is unable to be executed as a function, resulting in the failure to return an array

Currently, I am extracting table values from the UI row by row. This involves clicking on each row and retrieving the corresponding data. exports.getTableData = function(callback){     var uiArray =[];     var count;         aLib.loadCheck(c ...

Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cas ...

When the setDetached() function was called on an entity, it resulted in the removal of the getValidationErrors

When an entity is detached or not added to the manager, does the array of validations on the entity get destroyed? Will a newly created entity without being added to the manager lack the validation set on your model? This poses an issue for me as I am dy ...

It appears that the lodash throttle function is not being invoked

I recently started utilizing lodash's throttle function to control the number of calls made to an API. However, I am facing difficulties as the call doesn't seem to be triggered successfully. Below is a simplified version of what I have attempte ...