Filter search result of Elasticsearch to only show user data in JHipster

When we generate a project by JHipster, it doesn't manage that users only access to their data. By default, a user can see all data of an entity (You can find a solution by simple google it).
But after we add Elasticsearch to handle our search, we get a new problem. if user search, he can see result from all data that exists otherwise every user must see their data, not more! by default, the search method is something like this that makes a problem:


return StreamSupport.stream(categorySearchRepository.search(queryStringQuery(query))
    .spliterator(), false).collect(Collectors.toList());

And we have to change it to this one to fix the problem: 


BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
if (SecurityUtils.isAuthenticated() && !SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)) {
 queryBuilder = queryBuilder.filter(matchQuery("user.login", SecurityUtils.getCurrentUserLogin().orElse("")));
}
return StreamSupport.stream(categorySearchRepository.search(queryBuilder).spliterator(), false).collect(Collectors.toList());

In that code, we check if the user doesn't have Admin role (), then we add another filter to quryBuilder to limit the search for the current user.
The solution exists at the 21-point sample project on GitHub that I use it for the source of this post (PointsResource.java).

No comments: