Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.apache.sling.jackrabbit.usermanager.impl.post;
 
 import java.util.List;
 import java.util.Map;
 
 
 import  org.osgi.service.component.ComponentContext;

Sling Post Servlet implementation for creating a user in the jackrabbit UserManager.

Rest Service Description

Creates a new user. Maps on to nodes of resourceType sling/users like /rep:system/rep:userManager/rep:users mapped to a resource url /system/userManager/user. This servlet responds at /system/userManager/user.create.html

Methods

  • POST

Post Parameters

:name
The name of the new user (required)
:pwd
The password of the new user (required)
:pwdConfirm
The password of the new user (required)
*
Any additional parameters become properties of the user node (optional)

Response

200
Success, a redirect is sent to the users resource locator. The redirect comes with HTML describing the status.
500
Failure, including user already exists. HTML explains the failure.

Example

curl -F:name=ieb -Fpwd=password -FpwdConfirm=password -Fproperty1=value1 http://localhost:8080/system/userManager/user.create.html

Scr.component:
immediate="true" label="%createUser.post.operation.name" description="%createUser.post.operation.description"
Scr.service:
interface="javax.servlet.Servlet"
Scr.property:
name="sling.servlet.resourceTypes" value="sling/users"
Scr.property:
name="sling.servlet.methods" value="POST"
Scr.property:
name="sling.servlet.selectors" value="create"
 
 public class CreateUserServlet extends AbstractUserPostServlet {
     private static final long serialVersionUID = 6871481922737658675L;

    
default log
 
     private final Logger log = LoggerFactory.getLogger(getClass());

    

Scr.property:
label="%self.registration.enabled.name" description="%self.registration.enabled.description" valueRef="DEFAULT_SELF_REGISTRATION_ENABLED"
    private static final String PROP_SELF_REGISTRATION_ENABLED = "self.registration.enabled";
    private static final Boolean DEFAULT_SELF_REGISTRATION_ENABLED = .;
The JCR Repository we access to resolve resources

Scr.reference:
    private SlingRepository repository;

    
Returns the JCR repository used by this service.
    protected SlingRepository getRepository() {
        return ;
    }

    
Returns an administrative session to the default workspace.
    private Session getSession() throws RepositoryException {
        return getRepository().loginAdministrative(null);
    }

    
Return the administrative session and close it.
    private void ungetSession(final Session session) {
        if (session != null) {
            try {
                session.logout();
            } catch (Throwable t) {
                .error("Unable to log out of session: " + t.getMessage(), t);
            }
        }
    }
    // ---------- SCR integration ---------------------------------------------

    
Activates this component.

Parameters:
componentContext The OSGi ComponentContext of this component.
    protected void activate(ComponentContext componentContext) {
        super.activate(componentContext);
        Dictionary<?, ?> props = componentContext.getProperties();
        Object propValue = props.get();
        if (propValue instanceof Boolean) {
        	 = (Boolean)propValue;
        } else if (propValue instanceof String) {
             = Boolean.parseBoolean((StringpropValue);
        } else {
        }
    }
    /*
     * (non-Javadoc)
     * @see
     * org.apache.sling.jackrabbit.usermanager.post.AbstractAuthorizablePostServlet
     * #handleOperation(org.apache.sling.api.SlingHttpServletRequest,
     * org.apache.sling.api.servlets.HtmlResponse, java.util.List)
     */
    @Override
    protected void handleOperation(SlingHttpServletRequest request,
            HtmlResponse responseList<Modificationchanges)
            throws RepositoryException {
      
        // check for an administrator
        boolean administrator = false;
        try {
            Session currentSession = request.getResourceResolver().adaptTo(Session.class);
            UserManager um = AccessControlUtil.getUserManager(currentSession);
            User currentUser = (Userum.getAuthorizable(currentSession.getUserID());
            administrator = currentUser.isAdmin();
        } catch ( Exception ex ) {
            .warn("Failed to determin if the user is an admin, assuming not. Cause: "+ex.getMessage());
            administrator = false;
        }
            
      
        // make sure user self-registration is enabled
        if (!administrator && !) {
            throw new RepositoryException(
                "Sorry, registration of new users is not currently enabled.  Please try again later.");
        }
        Session session = request.getResourceResolver().adaptTo(Session.class);
        if (session == null) {
            throw new RepositoryException("JCR Session not found");
        }
        // check that the submitted parameter values have valid values.
        String principalName = request.getParameter(.);
        if (principalName == null) {
            throw new RepositoryException("User name was not submitted");
        }
        String pwd = request.getParameter("pwd");
        if (pwd == null) {
            throw new RepositoryException("Password was not submitted");
        }
        String pwdConfirm = request.getParameter("pwdConfirm");
        if (!pwd.equals(pwdConfirm)) {
            throw new RepositoryException(
                "Password value does not match the confirmation password");
        }
        Session selfRegSession = null;
        try {
            selfRegSession = getSession();
            UserManager userManager = AccessControlUtil.getUserManager(selfRegSession);
            Authorizable authorizable = userManager.getAuthorizable(principalName);
            if (authorizable != null) {
                // user already exists!
                throw new RepositoryException(
                    "A principal already exists with the requested name: "
                        + principalName);
            } else {
                User user = userManager.createUser(principalName,
                    digestPassword(pwd));
                String userPath = .
                    + user.getID();
                
                Map<StringRequestPropertyreqProperties = collectContent(
                    requestresponseuserPath);
                response.setPath(userPath);
                response.setLocation(externalizePath(requestuserPath));
                response.setParentLocation(externalizePath(request,
                    .));
                changes.add(Modification.onCreated(userPath));
                // write content from form
                writeContent(selfRegSessionuserreqPropertieschanges);
                if (selfRegSession.hasPendingChanges()) {
                    selfRegSession.save();
                }
            }
        } finally {
            ungetSession(selfRegSession);
        }
    }
New to GrepCode? Check out our FAQ X