Asif
Asif

Reputation: 429

How to get the current logged in user using Principal or Account service

I am trying to load $scope.projects specific to logged in user. The REST api side is

@RequestMapping(value = "/users/{id}/projects", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<Project>> getAllProjects(@PathVariable("id") String id,
        HttpServletResponse response)
        throws URISyntaxException {
    log.debug("REST request to get User : {}", id);
    User user = userRepository.findOneByLogin(id);
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    List<Project> page = projectRepository.findByUserIsCurrentUser();
    return new ResponseEntity<List<Project>>(page,
            HttpStatus.OK);
}

Checked this with swagger client.

    angular.module('tfmappApp')
.factory('UserProject', function ($resource) {
    return $resource('api/users/:id/projects', {}, {
            'query': {method: 'GET', isArray: true, params: { id: '@login'}},
            'get': {
                method: 'GET',
                transformResponse: function (data) {
                    data = angular.fromJson(data);
                    return data;
                }
            }
        });
    });

angular.module('tfmappApp')
.controller('ProjectController', function ($scope, Principal, Project, User, UserProject, ParseLinks) {
    $scope.projects = [];
    $scope.page = 1;

    Principal.identity().then(function(account) {
        $scope.account = account;
        $scope.isAuthenticated = Principal.isAuthenticated;
    });
    $scope.loadAll = function() {
        $scope.projects = UserProject.query({id: $scope.account.login});

    };
    $scope.loadPage = function(page) {
        $scope.page = page;
        $scope.loadAll();
    };
    $scope.loadAll();});

Principal service is Jhipster generated. The below code is not working, or I am missing something.

Principal.identity().then(function(account) {
        $scope.account = account;
        $scope.isAuthenticated = Principal.isAuthenticated;
    });

How can I get the currently logged in user?

What is the right way to get Account or Principal or User who is currently logged in?

I am using Jhipster generated HTTP Session Authentication.

Upvotes: 4

Views: 7903

Answers (2)

slim
slim

Reputation: 469

I think that the current user must not be returned from the server every time we want it... The current user must be registered in the Principal service because in an application, we could want to call this function many times for different purposes. And if in an other service, you don't want to receive promise to verify current user, you can use the current user variable in the Principal service. So, for this, i just created a Principal field wich i update every time a user logged in... (every time identity function is called in Principal service) :

var principalService = this;
// retrieve the identity data from the server, update the identity object, and then resolve.
Account.get().$promise
            .then(function (account) {
                _identity = account.data;
                principalService.currentIdentity = angular.copy(_identity);
                console.log('current identity :' + JSON.stringify(principalService.currentIdentity));

                _authenticated = true;
                deferred.resolve(_identity);
                Tracker.connect();
            })
            .catch(function () {
                _identity = null;
                _authenticated = false;
                deferred.resolve(_identity);
            });
        return deferred.promise; 

of course, you have to reset it or set it to {} or whatever, when the user logs out.

Upvotes: 0

Asif
Asif

Reputation: 429

I got some solution for this problem. Not the exact that I want.

@Query("select project from Project project where project.user.login = ?#{principal.username}")
List<Project> findByUserIsCurrentUser();

is jhipster generated code to load project list of current user. There is Many-to-one from Project to User.

So there is no need for REST url like /users/{id}/projects we can directly use /projects in factory as well as java rest controller.

This will eventually help to get the list of projects of currently logged in user.

May this help someone.

Upvotes: 1

Related Questions