How to get permission of current user in servlet?

bhoang 10-07-2018

Hi friends,

In my AEM, I created some user groups (ex: my-group-1, my-group-2, my-group-3, my-group-4, etc). So, I create some users (ex: my-user-1, my-user-2, my-user-3) and add the user into some groups. Example:

my-user-1 in groups: my-group-1 , my-group-2, my-group-3

my-user-2 in groups: my-group-2 , my-group-3

Now, I want to create a Servlet to get all group of the current user that have a permission. Example, when I login to AEM with my-user-1. I will get a result with (my-group-1 , my-group-2, my-group-3). If I login to AEM with my-user-2, I will get a result with (my-group-2 , my-group-3).

How to do that?

Please, help me with a simple servlet.

Thank you so much,

BienHV

Answers (5)

Answers (5)

Arun_Patidar
MVP
11-07-2018

Hi,

did you check the code which I shared?

you can easily get user group from user

Example :

User currentUser = request.getResourceResolver().adaptTo(User.class);

  Iterator<Group> currentUserGroups = currentUser.memberOf();

  while (currentUserGroups.hasNext()) {

  Group grp = (Group) currentUserGroups.next();

  groupName = grp.getID();

  hmap.put("groupName", groupName);

  }

Thanks
Arun

bhoang 29-07-2018

Thanks you for your helps,

There are my code to do that>

I create a class AEMGroupUser.java@

package com.abcxyz.core.servlets;

import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.sling.api.SlingHttpServletRequest;

import javax.jcr.RepositoryException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/*
* Get all groups of current user
* */

public class AEMGroupUser {

   private final SlingHttpServletRequest req;
  private static final String GROUP_ID = "groupID";

  public AEMGroupUser(SlingHttpServletRequest req){

   this.req = req;
   }

   public HashMap<String, List<String>> getGroupUser(){

   //Hmap user groups
   User currentUser = req.getResourceResolver().adaptTo(User.class);

   Iterator<Group> currentUserGroups = null;
  try {

  currentUserGroups = currentUser.memberOf();
   } catch (RepositoryException e) {

  e.printStackTrace();
   }

  HashMap<String, List<String>> hmap = new HashMap<>();
  while (currentUserGroups.hasNext()) {

  org.apache.jackrabbit.api.security.user.Group grp = currentUserGroups.next();
  try {

   final String groupID = grp.getID();
  if (groupID != null && groupID.length() > 0) {

   if (!hmap.containsKey(GROUP_ID)) {

  List<String> groupValue = new ArrayList<>();
   groupValue.add(groupID);
   hmap.put(GROUP_ID, groupValue);
   } else {

  List<String> groupValue = hmap.get(GROUP_ID);
   groupValue.add(groupID);
   }

  }

  } catch (RepositoryException e) {

  e.printStackTrace();
   }

  }

   return hmap;
   }

}

So, I created a servlet: CountryListRegistrationFormServlet

package com.abcxyz.core.servlets;

import com.capitaland.lyf.core.dto.CountryAemDto;
import com.capitaland.lyf.core.models.HostConfigUtill;
import com.capitaland.lyf.core.utility.ApiManagementConfiguration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component(service = Servlet.class, property = {Constants.SERVICE_DESCRIPTION + "=Capitaland Room Filter Servlet",
   "sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.selectors=countrylistregistrationform",
   "sling.servlet.resourceTypes=" + "sling/servlet/default", "sling.servlet.extensions=" + "json"})

public class CountryListRegistrationFormServlet extends SlingSafeMethodsServlet {

   /**
  *
  */
   private static final Gson gson = new Gson();
  private static final long serialVersionUID = 1L;

   /**
  *
  */
   @Override
   protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp)

   throws ServletException, IOException {

  String langCode = ((SlingHttpServletRequestWrapper) req).getRequest().getLocale().getLanguage();

   ResourceResolver resourceResolver = req.getResourceResolver();
   ApiManagementConfiguration lyfServiceHost = HostConfigUtill.getHost(resourceResolver);

   List<CountryAemDto> countryAemDtoList = new ArrayList<>();

   String responseData = null;
  try {

  responseData = Unirest.get(lyfServiceHost.getHost() + "countries?langCode" + langCode).headers(lyfServiceHost.toHeaderMap()).asString().getBody();
   countryAemDtoList = gson.fromJson(responseData, new TypeToken<List<CountryAemDto>>(){}.getType());

   } catch (UnirestException e) {

  e.printStackTrace();
   }

  AEMGroupUser aemGroupUser = new AEMGroupUser(req);
   HashMap<String, List<String>> hashMap = aemGroupUser.getGroupUser();

   ArrayList<String> arrayList = (ArrayList<String>) hashMap.get("groupID");

   ArrayList<CountryAemDto> countryAemDtos = new ArrayList<>();
  for(CountryAemDto countryAemDto : countryAemDtoList){

   if(arrayList.contains(countryAemDto.getManagingGroup())){

  countryAemDtos.add(countryAemDto);
   }

  }

  String jsonInString = gson.toJson(countryAemDtos);
   resp.setContentType("application/json");
   resp.getWriter().write(jsonInString);
   resp.getWriter().flush();
   }

}

Thanks & Best regards,

BienHV

bhoang 10-07-2018

Hi,

I was created a simple server let to get user groups. I can get userId, but I don't know how to get user groups. Could you help me how to do that?

Thank you so much!

import com.google.gson.Gson;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.*;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import javax.jcr.Session;

/**
* Servlet that writes some sample content into the response. It is mounted for
* all resources of a specific Sling resource type. The
* {@link SlingSafeMethodsServlet} shall be used for HTTP methods that are
* idempotent. For write operations use the {@link SlingAllMethodsServlet}.
*/
@Component(service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=User group Servlet",
   "sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.selectors=userGroupsPermission",
   "sling.servlet.resourceTypes=" + "sling/servlet/default", "sling.servlet.extensions=" + "json" })

public class UserServlet extends SlingSafeMethodsServlet {

   /**
  *
  */
   private static final long serialVersionUID = 1L;
  private static final Gson gson = new Gson();

   @Override
   protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp)

   throws ServletException, IOException {

  ResourceResolver resourceResolver = req.getResourceResolver();
   Session session = resourceResolver.adaptTo(Session.class);
   String userId = session.getUserID();
   String userName = session.getUserName();
   //String groupName = session.getGroupName();

   HashMap<String, String> hmap = new HashMap<String, String>();
   hmap.put("userId",userId);
   //hmap.put("userName",userName);
  //hmap.put("groupName", groupName);


   String responseData = "";
   responseData = gson.toJson(hmap);

   resp.setContentType("application/json");
   resp.getWriter().write(responseData);
   }

}