Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs Cookie not working

I am learning Angular JS and am having issues with cookies. I have a simple login working fine, but when I refresh after logging in it takes me back to the login page. I want to set the cookie and then stay logged in.

app.js

var myApp = angular.module('myApp', ['ngRoute', 'ngResource', 'ngCookies']);

myApp.config(['$routeProvider', function($routeProvider){
  $routeProvider.
  when('/', {
    templateUrl: 'views/home.html',
    controller: 'loginController'
}).
when('/admin', {
    resolve: {
        "check": function($location, $rootScope){
            if(!$rootScope.loggedIn){
                $location.path('/')
            }
        }
    },
    templateUrl: 'views/admin.html',
    controller: 'loginController'
}).
otherwise({
    redirectTo: '/'
});
}]);

loginController.js

myApp.controller('loginController', ['$scope', '$http', '$location',     '$rootScope', 'userService', 'authService' '$cookies', function($scope, $http, $location, $rootScope, userService, authService, $cookies){

$scope.submitLogin = function(){
    if($scope.username == 'admin' && $scope.password == 'admin'){
        $rootScope.loggedIn = true;
        //set date to 24 hours
        var expireDate = new Date();
        expireDate.setDate(expireDate.getDate() + 1);
        //set cookie
        $cookies.put('userName', $scope.username, {
            'expires': expireDate
        });
        //get cookie
        $rootScope.cookie = $cookies.get('userName');
        $location.path('/admin');
    } else {
        alert("Wrong user name / password");
    }
}

}]);
like image 540
Jmostaind55 Avatar asked Jan 29 '26 22:01

Jmostaind55


1 Answers

When you refresh the page $rootScope.loggedIn no longer exists. You need to check for the existence of the cookie rather than relying on a in memory variable.

I can't get the codepen working without all of the dependencies, but basically your resolve function should look something like this:

resolve: {
      "check": function($location, $rootScope) {
        var cookie = $cookies.get('userName');
        console.log(cookie)
        if (!cookie) {
          $location.path('/')
        }
      }
like image 133
Mike Feltman Avatar answered Jan 31 '26 23:01

Mike Feltman