Tuesday 1 March 2016

CQ User Creation Using UserManager API

Introduction:

Users:

Users will log in to AEM with their account. Each user account is unique and holds the basic account details, together with the privileges assigned.
Users are often members of Groups, which simplify the allocation of these permissions and/or privileges.

Groups:

Groups are collections of users and/or other groups; these are all called Members of a group.
Their primary purpose is to simplify the maintenance process by reducing the number of entities to be updated, as a change made to a group is applied to all members of the group. Groups often reflect:
  • a role within the application; such as someone who is allowed to surf the content, or someone who is allowed to contribute content.
  • your own organization; you may want to extend the roles to differentiate between contributors from different departments when they are restricted to different branches in the content tree.
Therefore groups tend to remain stable, whereas users come and go more frequently.
With planning and a clean structure, the use of groups can reflect your structure, giving you a clear overview and an efficient mechanism for updates.


User Creation Servlet:

Below Servlet creates user under specified paths and add them to specified group when you hit the servlet as 

http://localhost:4502/libs/cqusercreation?email=mani@gmail.com&firstName=firstName&lastName=lastName&givenName=givenName&displayName=displayName

with different parameters you can use these servlet in any async call to make a call from the component.

Servlet

package com.geometrixx.sightly.servlets;

import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.JackrabbitSession;
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.jackrabbit.value.StringValue;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



@Component(immediate = true, description="User Creation")
@Service(value = javax.servlet.Servlet.class)
@Properties(value={
@Property(name="sling.servlet.extensions",value={"html","json"}),
@Property(name="sling.servlet.methods",value={"GET","POST"}),
@Property(name="sling.servlet.paths",value={"/libs/cqusercreation"})
})
public class CQUserCreationServlet extends SlingAllMethodsServlet {
private static final Logger Log = LoggerFactory
.getLogger(CQUserCreationServlet.class);
protected void doGet(final SlingHttpServletRequest req,
            final SlingHttpServletResponse resp) throws ServletException, IOException {
Log.debug("doGet");
        doPost(req, resp);
    }
protected void doPost(final SlingHttpServletRequest req,
            final SlingHttpServletResponse resp) throws ServletException, IOException {
Log.debug("doPost");
createNewCqUser(req,resp);
}
public void createNewCqUser(SlingHttpServletRequest req,
SlingHttpServletResponse resp) {
// TODO Auto-generated method stub
Log.debug("createNewCqUser");
Map<String, String> userProperties = new HashMap<String, String>();
String userEmailId = req.getParameter("email");
final String loginId= userEmailId;
String firstName = req.getParameter("firstName");
String lastName = req.getParameter("lastName");
String givenName = req.getParameter("givenName");
String displayName = req.getParameter("displayName");
userProperties.put("profile/email", userEmailId);
userProperties.put("profile/firstName", firstName);
userProperties.put("profile/lastName", lastName);
userProperties.put("profile/givenName", givenName);
userProperties.put("profile/displayName", displayName);
Log.debug("Map {}",userProperties );
Session session = req.getResourceResolver().adaptTo(Session.class);
Group userGroup;
Principal principal;
User newUser;
try {
UserManager userManager = ((JackrabbitSession) session)
.getUserManager();
Log.debug("userManager {}",userManager );
userGroup = (Group) userManager
.getAuthorizableByPath("/home/groups/e/everyone");
principal = new Principal() {
public String getName() {
return loginId;
}
};
newUser = userManager.createUser(loginId, "123456", principal,
"/home/users/geometrixx");
Log.debug("newUser {}",newUser );
if (null != newUser) {
updateAndInsertUserDetails(newUser, userProperties);
userGroup.addMember(newUser);
}
session.save();
}catch(Exception e){
}
}
public void updateAndInsertUserDetails(User user, Map<String, String> map)
throws RepositoryException {
for (Map.Entry<String, String> entry : map.entrySet()) {
setUserStringProperty(user, entry.getKey(), entry.getValue());
}
}
public void setUserStringProperty(User user, String property, String value) {
try {
if (isNotBlank(value)) {
user.setProperty(property, new StringValue(value));
}
} catch (RepositoryException e) {
}
}
public boolean isNotBlank(String value) {
return StringUtils.isNotBlank(value);
}
}


UserManager API Link:

No comments:

Post a Comment