Moody
Moody

Reputation: 833

AngularJS retrieving user object from controller on every request

I have successfully setup a Spring Security project which authenticates the user whenever he logs in. However, after he logs in, I want to retrieve this user object (which is inside the session of Spring security) via the Rest controller in every controller function of AngularJS.

To clarify, how can I call the following method each in every controller to retrieve the user object?

@RequestMapping(value = "/getLoggedInUser", method = RequestMethod.GET, headers = "Accept=application/json")
    public User getLoggedInUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            User user = (User) SecurityContextHolder.getContext().getAuthentication()
                    .getPrincipal();
            return user;
        }
        return null;
}

What I did was the following:

$http.get(urlBase+'/getLoggedInUser').
 success(function(data) {
     $scope.users = data;
     console.log("The logged in user is: " + data.firstname);
})

This works and it prints the firstname, but I get some odd behaviour when I put the above method inside another $http get method. Is there a better option or possiblity of adding this function at the beginning of every angularjs controller to retrieve this user object and check whether it is null or set (so I can do some logic with it)?

***********UPDATE*********** After the suggestion of pankajparkar, I was able to now simply retrieve the user object. I put the get method in the application factory directly as such:

myApp.factory('accountService', function($http) {
    return {
         getUser: function() {
             return $http.get(urlBase+'/getLoggedInUser');
         }
     };
});

And from every controller, I can pas the accountService method and do the following:

var handleSuccess = function(user, status) {
     $scope.user = user;
};
accountService.getUser().success(handleSuccess);

This now works fine and I can get the data in each controller like that. Is this ok? Or can it get a bit nicer than that?

Upvotes: 3

Views: 1432

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You could use httpInterceptor, which can watch on your each $http request and response. Basically you could create a service with request & response function

Factory

angular.module('dashboardApp').factory('httpInterceptor', function httpInterceptor ($q, $window, $location) {
  return function (promise) {
      var success = function (response) {
          return response;
      };

      var error = function (response) {
          if (response.status === 401) {
              $location.url('/login');
          }

          return $q.reject(response);
      };

      return promise.then(success, error);
  };
});

Then do add this interceptor at configuration phase of angular life cycle that is using app.config (config block)

Config

angular.module('dashboardApp').config(['$httpProvider', function($httpProvider){
   $httpProvider.interceptors.push('myHttpInterceptor');
   //your other code here like register state & configuration settings
}]);

Also refer this link, which will provide you better idea how to implement this.

Upvotes: 1

Related Questions