How to create a new adobe aem User with user rights in the java code.
With a SlingAllMethodsServlet you can get the Parameter from a Post Request.
Than you can create a User with the given Informations. the User will be added in the CQ Server with the rights you gave him.
username = request.getParameter("username");
password = request.getParameter("password");
givenname = request.getParameter("givenname");
name = request.getParameter("name");
email = request.getParameter("email");
ResourceResolver resourceResolver = request.getResourceResolver();
Session session = resourceResolver.adaptTo(Session.class);
UserManager userManager = resourceResolver.adaptTo(UserManager.class);
User u = null;
try {
//check if user does exist, easy check with username, username is id in cq
u = (User) userManager.getAuthorizable(username);
} catch (RepositoryException e) {
logger.error("User cannot be checked: " + e.getMessage());
e.printStackTrace();
}
if(u != null) {
logger.error("User" + username + " exists already in CQ!! Can't create user again!");
try {
json.put("error", "User already exists");
response.setStatus(HttpServletResponse.SC_CONFLICT);
} catch (JSONException e) {
logger.error(e.getMessage());
}
}else {
/*Just create user if it does not exist*/
try {
user = userManager.createUser(username, password);
ValueFactory valueFactory = session.getValueFactory();
emailValue = valueFactory.createValue(email);
givennameValue = valueFactory.createValue(givenname);
nameValue = valueFactory.createValue(name);
//User class just accepts Value Object
user.setProperty("profile/" + UserProperties.EMAIL, emailValue);
user.setProperty("profile/" + UserProperties.FAMILY_NAME,nameValue);
user.setProperty("profile/" + UserProperties.GIVEN_NAME, nameValue);
} catch (RepositoryException e) {
logger.error("Failed while creating user: " + e.getMessage());
}
try {
/* add Group to user */
Group g = (Group) userManager.getAuthorizable(GROUP_NAME);
g.addMember(user);
session.save();
session.logout();
} catch (RepositoryException e) {
logger.error("Can't add group to new created User : " + username + e.getMessage());
}
How to get the CQ admin Session / How to get the CQ admin UserManager
if you can't save the user, with session and usermanager then you have to get the admin Session.
Add the dependency for AccessControlUtil (check the version)
add SlingRepository variable as @Reference
get the Usermanager with AccessControlUtil and the admin session
@Reference
private SlingRepository repository;
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
try {
Session adminSession = repository.loginAdministrative(null);
UserManager usermanager = AccessControlUtil.getUserManager(adminSession);
//your stuff like manipulating user, get authorizab
adminSession.save();
} catch (RepositoryException e) {
e.printStackTrace();
}
}