title: ANGULARJS $cookieStore and SessionId
body: <p>I am new to Anguarjs and I am writing a mobile application that needs to capture the SessionId after authentication. </p>
  
  <p>I am using $ccoikestore in the application to store other data.</p>
  
  <p>How do I capture the SessionId to be used later?</p>
  
  <p>This is part of my Authentication Service:</p>
  
  <pre><code>/* Authentication Service
  **********************************/
  
  (function(){ 
  'use strict';
  
  var app = angular.module('Authentication')
  
  
  app.factory('AuthenticationService',
  ['Base64', '$http', '$cookieStore', '$rootScope', '$timeout', 'alertsManager',
  function (Base64, $http, $cookieStore, $rootScope, $timeout, alertsManager) {
      var service = {};
  
      service.Login = function (username, password, callback) {
  
          /* Dummy authentication for testing, uses $timeout to simulate api call
           ----------------------------------------------*/
                  //$timeout(function(){
          //  var response = { IsAuthenticated: username === 'test' &amp;&amp; password === 'test' };
          //      if(!response.IsAuthenticated) {
          //      alertsManager.addAlert('Username or password is incorrect', 'alert-danger');
          //    }
          //    callback(response);
          //}, 1000);
  
          /* Use this for real authentication
           ----------------------------------------------*/
                      $http.post('http://apps.laticrete.com/LSCWebApiService/lscapi/Session/Login', {username: username, password: password})
                          .success(function (response) {
                              if(!response.IsAuthenticated) {
                              alertsManager.addAlert('Username or password is incorrect', 'alert-danger');
                          }
             callback(response);
          });
  
  
      };
  
      service.SetCredentials = function (username, password) {
          var authdata = Base64.encode(username + ':' + password);
  
          $rootScope.globals = {
              currentUser: {
                  username: username,
                  password: authdata,
                              }
          };
  
          $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; 
          $cookieStore.put('globals', $rootScope.globals);
      };
  
      service.ClearCredentials = function () {
          $rootScope.globals = {};
          $cookieStore.remove('globals');
          $http.defaults.headers.common.Authorization = 'Basic ';
      };
  
      return service;
  }]);
  
  app.factory('Base64', function () {
  
  var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  
  return {
      encode: function (input) {
          var output = "";
          var chr1, chr2, chr3 = "";
          var enc1, enc2, enc3, enc4 = "";
          var i = 0;
  
          do {
              chr1 = input.charCodeAt(i++);
              chr2 = input.charCodeAt(i++);
              chr3 = input.charCodeAt(i++);
  
              enc1 = chr1 &gt;&gt; 2;
              enc2 = ((chr1 &amp; 3) &lt;&lt; 4) | (chr2 &gt;&gt; 4);
              enc3 = ((chr2 &amp; 15) &lt;&lt; 2) | (chr3 &gt;&gt; 6);
              enc4 = chr3 &amp; 63;
  
              if (isNaN(chr2)) {
                  enc3 = enc4 = 64;
              } else if (isNaN(chr3)) {
                  enc4 = 64;
              }
  
              output = output +
                  keyStr.charAt(enc1) +
                  keyStr.charAt(enc2) +
                  keyStr.charAt(enc3) +
                  keyStr.charAt(enc4);
              chr1 = chr2 = chr3 = "";
              enc1 = enc2 = enc3 = enc4 = "";
          } while (i &lt; input.length);
  
          return output;
      },
  
      decode: function (input) {
          var output = "";
          var chr1, chr2, chr3 = "";
          var enc1, enc2, enc3, enc4 = "";
          var i = 0;
  
          // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
          var base64test = /[^A-Za-z0-9\+\/\=]/g;
          if (base64test.exec(input)) {
              window.alert("There were invalid base64 characters in the input text.\n" +
                  "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
                  "Expect errors in decoding.");
          }
          input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  
          do {
              enc1 = keyStr.indexOf(input.charAt(i++));
              enc2 = keyStr.indexOf(input.charAt(i++));
              enc3 = keyStr.indexOf(input.charAt(i++));
              enc4 = keyStr.indexOf(input.charAt(i++));
  
              chr1 = (enc1 &lt;&lt; 2) | (enc2 &gt;&gt; 4);
              chr2 = ((enc2 &amp; 15) &lt;&lt; 4) | (enc3 &gt;&gt; 2);
              chr3 = ((enc3 &amp; 3) &lt;&lt; 6) | enc4;
  
              output = output + String.fromCharCode(chr1);
  
              if (enc3 != 64) {
                  output = output + String.fromCharCode(chr2);
              }
              if (enc4 != 64) {
                  output = output + String.fromCharCode(chr3);
              }
  
              chr1 = chr2 = chr3 = "";
              enc1 = enc2 = enc3 = enc4 = "";
  
          } while (i &lt; input.length);
  
          return output;
      }
  };
  
  });
  
  
  })();
  </code></pre>
  
  <p>And there is an Index:</p>
  
  <pre><code>app.run(['$rootScope', '$state', '$stateParams', '$location', '$cookieStore', '$http',
      function($rootScope, $state, $stateParams, $location, $cookieStore, $http) {
  
          // Keep user logged in after page refresh
          $rootScope.globals = $cookieStore.get('globals') || {};
  
          if($rootScope.globals.currentUser) {
              $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;
          }
          $rootScope.$on('$locationChangeStart', function(event, next, current) {
              // Redirect to login page if not logged in
              if($location.path() !== '/login' &amp;&amp; !$rootScope.globals.currentUser) {
                  $location.path('/login');
              }
          });
  
  
          $rootScope.appVersion = '1.0.0';
  
          $rootScope.$state = $state;
          $rootScope.$stateParams = $stateParams;
      }]);
  </code></pre>
  
  <p>My Authentication CTRL:</p>
  
  <p>/* Authentication Controller
   *************************************/</p>
  
  <p>(function(){
      'use strict';</p>
  
  <pre><code>var app = angular.module('Authentication');
  
  app.controller('LoginCtrl', ['$scope', '$rootScope', '$location', 'AuthenticationService', 'cfpLoadingBar', 'alertsManager', '$modal',
      function($scope, $rootScope, $location, AuthenticationService, cfpLoadingBar, alertsManager, $modal) {
  
      // Reset login status
      AuthenticationService.ClearCredentials();
  
      $scope.login = function() {
          cfpLoadingBar.start();
          AuthenticationService.Login($scope.username, $scope.password, function(response) {
              if(response.IsAuthenticated) {
                  AuthenticationService.SetCredentials($scope.username, $scope.password);
                  cfpLoadingBar.complete();
                  alertsManager.clearAlerts();
                  $location.path('/jobs');
              } else {
                  cfpLoadingBar.complete();
              }
          });
      };
  
      // Modal Instance
      $scope.animationsEnabled = false;
  
      $scope.open = function() {
          var modalInstance = $modal.open({
              animation: $scope.animationsEnabled,
              templateUrl: '../modules/authentication/login.modal.html',
              controller: 'ModalCtrl'
          });
      };
  
      $scope.imageSrc="img/img_pumpTruck.png";
  
      }]);
  </code></pre>
  
  <p>})();</p>
  
  <p>console: </p>
  
  <p>----------------------------------------------*/
                          $http.post('<a href="http://apps.laticrete.com/LSCWebApiService/lscapi/Session/Login" rel="nofollow">http://apps.laticrete.com/LSCWebApiService/lscapi/Session/Login</a>', {username: username, password: password})
                              .success(function (response) {
                                  if(!response.IsAuthenticated) {
                                  alertsManager.addAlert('Username or password is incorrect', 'alert-danger');
                              }
                              $cookies.put('SessionId');
                 callback(response);
              });</p>
  
  <pre><code>    };
  
      service.SetCredentials = function (username, password, SessionId) {
          var authdata = Base64.encode(username + ':' + password);
  
  
          $rootScope.globals = $cookies.getObject('SessionId') || {
              currentUser: {
                  username: username,
                  password: authdata,
                                      SessionId: $cookies.get('SessionId')
                              }
          };
  </code></pre>