Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

How to fetch Users of a group, through Javascript Code

Avatar

Level 4

Hi Team

 

I want to know to which group the logged in user belongs to using javascript

 

Please advise.

 

Thanks 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @Prashardan ,

You may have a look

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/aem6-5-how-to-get-user-det...

As mentioned in above blog below point returns required data which can be processed in frontend to extract the required group

http://localhost:4502/bin/security/authorizables.json?filter=admin

here admin is user id

https://stackoverflow.com/questions/34285379/how-can-i-check-if-logged-in-user-is-admin-or-members-o...

 

Or we can write custom logic in servlet and call that servlet in frontend JS

Below is a sample servlet which returns list of principal name of groups

 

package com.example.group.core.servlets;//write your package name

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;

import javax.jcr.RepositoryException;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Logger;

@Component(
        service = {Servlet.class},
        property = {
                "sling.servlet.paths=/bin/getUserGroups",
                "sling.servlet.methods=GET"
        }
)
public class UserGroupsServlet extends SlingAllMethodsServlet {
    private static final Logger logger = Logger.getLogger(UserGroupsServlet.class.getName());
    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
        JsonObject jsonResponse = new JsonObject();
        JsonArray groupsArray = new JsonArray();
        try {
            UserManager userManager = request.getResourceResolver().adaptTo(UserManager.class);
            User user = getUser(request.getUserPrincipal().getName(), userManager);
            if (user == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                jsonResponse.addProperty("error", "User not found.");
                response.getWriter().write(jsonResponse.toString());
                return;
            }

            Iterator<Group> userGroups = user.memberOf();
            while (userGroups.hasNext()) {
                Group group = userGroups.next();
                if (group != null) {
                    groupsArray.add(group.getPrincipal().getName());
                }
            }

            jsonResponse.add("groups", groupsArray);
            jsonResponse.addProperty("userId", request.getUserPrincipal().getName());

        } catch (RepositoryException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            jsonResponse.addProperty("error", "Repository exception: " + e.getMessage());
        }

        response.setContentType("application/json");
        response.getWriter().write(jsonResponse.toString());
    }

    private User getUser(String userId, UserManager userManager) {
        try {
            return (User) userManager.getAuthorizable(userId);
        } catch (RepositoryException e) {
            logger.severe("Error getting user: " + e.getMessage());
        }
        return null;
    }
}

 

MukeshYadav__0-1724423732220.png

 

Thanks

 

View solution in original post

2 Replies

Avatar

Correct answer by
Community Advisor

Hi @Prashardan ,

You may have a look

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/aem6-5-how-to-get-user-det...

As mentioned in above blog below point returns required data which can be processed in frontend to extract the required group

http://localhost:4502/bin/security/authorizables.json?filter=admin

here admin is user id

https://stackoverflow.com/questions/34285379/how-can-i-check-if-logged-in-user-is-admin-or-members-o...

 

Or we can write custom logic in servlet and call that servlet in frontend JS

Below is a sample servlet which returns list of principal name of groups

 

package com.example.group.core.servlets;//write your package name

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;

import javax.jcr.RepositoryException;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Logger;

@Component(
        service = {Servlet.class},
        property = {
                "sling.servlet.paths=/bin/getUserGroups",
                "sling.servlet.methods=GET"
        }
)
public class UserGroupsServlet extends SlingAllMethodsServlet {
    private static final Logger logger = Logger.getLogger(UserGroupsServlet.class.getName());
    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
        JsonObject jsonResponse = new JsonObject();
        JsonArray groupsArray = new JsonArray();
        try {
            UserManager userManager = request.getResourceResolver().adaptTo(UserManager.class);
            User user = getUser(request.getUserPrincipal().getName(), userManager);
            if (user == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                jsonResponse.addProperty("error", "User not found.");
                response.getWriter().write(jsonResponse.toString());
                return;
            }

            Iterator<Group> userGroups = user.memberOf();
            while (userGroups.hasNext()) {
                Group group = userGroups.next();
                if (group != null) {
                    groupsArray.add(group.getPrincipal().getName());
                }
            }

            jsonResponse.add("groups", groupsArray);
            jsonResponse.addProperty("userId", request.getUserPrincipal().getName());

        } catch (RepositoryException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            jsonResponse.addProperty("error", "Repository exception: " + e.getMessage());
        }

        response.setContentType("application/json");
        response.getWriter().write(jsonResponse.toString());
    }

    private User getUser(String userId, UserManager userManager) {
        try {
            return (User) userManager.getAuthorizable(userId);
        } catch (RepositoryException e) {
            logger.severe("Error getting user: " + e.getMessage());
        }
        return null;
    }
}

 

MukeshYadav__0-1724423732220.png

 

Thanks

 

Avatar

Community Advisor

Hi @Prashardan 

You need to write a custom servlet and call from javascript to know the user group.

There is a OOTB servlet but that did not return groups, just return user info

http://localhost:4502/libs/cq/security/userinfo.json?cq_ck=1724417012162 



Arun Patidar