AngularJS UI-Router Promise Caching Session

153 views
Skip to first unread message

Olajide Ogundipe Jr

unread,
Jul 7, 2014, 11:14:14 PM7/7/14
to ang...@googlegroups.com
When I log in with a different user Session is populated with from the last Session and not the current User, should I use $cacheFactory?

angular.module('services.auth', ['services.session'])
  .factory('AuthService', ['apiUrl', '$http', '$localStorage', 'Session', '$q', '$timeout',
    function (apiUrl, $http, $localStorage, Session, $q, $timeout) {
      return {
        login: function (credentials) {
          var deferredOne = $q.defer();
          var promiseOne = deferredOne.promise;
          $http
            .post(apiUrl + '/authentication', credentials)
              .success(function(data){
                $localStorage.token = data.token;
                deferredOne.resolve(data);
              })
              .error(function(err){
                deferredOne.reject(err);
              });

          var deferredTwo = $q.defer();
          var promiseTwo = deferredTwo.promise;

          $http.get(apiUrl + '/users/me')
          .success(function(data){
            deferredTwo.resolve(data);
          })
          .error(function(err){
            deferredTwo.reject(err);
          });
           
          return $q.all([promiseOne, promiseTwo])
            .then(function(promises){
              var user = promises[1];
                Session.create(user.id, user.firstName);
             // console.log(Session.firstName);
            });
        }, 
        logout: function(){
          $localStorage.$reset();
          Session.destroy();
        },
         isAuthenticated: function () {
          return !!Session.userId;
        },
         isAuthorized: function (authorizedRoles) {
          if (!angular.isArray(authorizedRoles)) {
            authorizedRoles = [authorizedRoles];
          }
          return (this.isAuthenticated() &&
            authorizedRoles.indexOf(Session.userRole) !== -1);
          } 
      };
  }]);

ThomasBurleson

unread,
Jul 8, 2014, 9:14:02 AM7/8/14
to ang...@googlegroups.com
First, your use of promise chains is way too complicated. Here is a simplified version:

function login(credentials)
{
  return authenticate( credentials )
              .then( cacheToLocal  )
              .then( loadMe        )
              .then( createSession );

    // Step (1)
    function authenticate( credentials )
    {
      return $http.post( apiUrl + '/authentication', credentials );
    }

    // Step (2)
    function cacheToLocal( data )
    {
      $localStorage.token = data.token;
      return data;
    }

    // Step (3)
    function loadMe( data ) 
    {
      return $http.get(apiUrl + '/users/me')
                  .then( function onResponse(me)
                  {
                      // me data is currently ignored... !!
                      return data;
                  });
    }

    // Step (4)
    function createSession( user )
    {
      Session.create(user.id, user.firstName);

Olajide Ogundipe Jr

unread,
Jul 8, 2014, 11:45:41 AM7/8/14
to ang...@googlegroups.com
Thanks Thomas, one of my team members rewrote it 
to this, I have archive your code because its very clean
Good articles on Angular by the way.

'use strict';

angular.module('services.auth', ['services.session'])
  .factory('AuthService', ['apiUrl', '$http', '$localStorage', 'Session',
    function (apiUrl, $http, $localStorage, Session) {
      return {
        login: function(credentials) {
          var getToken = function(credentials) {
            return $http.post(apiUrl + '/authentication', credentials)
              .then( function(resp) {
                var token = resp.data.token;
                $localStorage.token = token;
                $http.defaults.headers.common
                  .Authorization = 'Bearer ' + token;
                return resp.data;
              });
          };
          var getUser = function() {
            return $http.get(apiUrl + '/users/me')
              .then( function(resp) {
                Session.create(resp.data.id, resp.data.firstName);
                return resp;
              });
          };

          return getToken( credentials )
                  .then( getUser );
        },
        logout: function(){
          $localStorage.$reset();
          Session.destroy();
        },
         isAuthenticated: function () {
          return !!Session.userId;
        },
         isAuthorized: function (authorizedRoles) {
          if (!angular.isArray(authorizedRoles)) {
            authorizedRoles = [authorizedRoles];
          }
          return (this.isAuthenticated() &&
            authorizedRoles.indexOf(Session.userRole) !== -1);
          }
      };
  }]);

--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/om9HkHGDfVU/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.



--
Reply all
Reply to author
Forward
0 new messages