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  org.osgi.service.component.ComponentContext;

Changes the password associated with a user. Maps on to nodes of resourceType sling/user like /rep:system/rep:userManager/rep:users/ae/fd/3e/ieb mapped to a resource url /system/userManager/user/ieb. This servlet responds at /system/userManager/user/ieb.changePassword.html

Methods

  • POST

Post Parameters

oldPwd
The current password for the user (required for non-administrators)
newPwd
The new password for the user (required)
newPwdConfirm
The confirm new password for the user (required)

Response

200
Success sent with no body
404
If the user was not found.
500
Failure, including password validation errors. HTML explains the failure.

Example

curl -FoldPwd=oldpassword -FnewPwd=newpassword -FnewPwdConfirm=newpassword http://localhost:8080/system/userManager/user/ieb.changePassword.html

Notes

 
 @Component (metatype=true,
 		label="%changeUserPassword.post.operation.name",
 		description="%changeUserPassword.post.operation.description")
 @Service (value={
 	Servlet.class,
 })
 	@Property (name="sling.servlet.resourceTypes",
 			value="sling/user"),
 	@Property (name="sling.servlet.methods",
 			value="POST"),
 	@Property (name="sling.servlet.selectors",
			value="changePassword"),
            value={
            "EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
            "yyyy-MM-dd'T'HH:mm:ss",
            "yyyy-MM-dd",
            "dd.MM.yyyy HH:mm:ss",
            "dd.MM.yyyy"
            })
})
    private static final long serialVersionUID = 1923614318474654502L;

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

    
The default 'User administrator' group name

See also:
PAR_USER_ADMIN_GROUP_NAME
    private static final String DEFAULT_USER_ADMIN_GROUP_NAME = "UserAdmin";

    
The name of the configuration parameter providing the name of the group whose members are allowed to reset the password of a user without the 'oldPwd' value.
    private static final String PAR_USER_ADMIN_GROUP_NAME = "user.admin.group.name";
    // ---------- SCR integration ---------------------------------------------

    
Activates this component.

Parameters:
componentContext The OSGi ComponentContext of this component.
    @Override
    protected void activate(ComponentContext componentContext) {
        super.activate(componentContext);
        Dictionary<?, ?> props = componentContext.getProperties();
        this. = OsgiUtil.toString(props.get(),
                );
        .info("User Admin Group Name {}"this.);
    }
    @Override
    protected void deactivate(ComponentContext context) {
        super.deactivate(context);
    }
    /*
     * (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,
    		AbstractPostResponse responseList<Modificationchanges)
            throws RepositoryException {
        Resource resource = request.getResource();
        Session session = request.getResourceResolver().adaptTo(Session.class);
        changePassword(session,
                resource.getName(),
                request.getParameter("oldPwd"),
                request.getParameter("newPwd"),
                request.getParameter("newPwdConfirm"),
                changes);
    }
    /* (non-Javadoc)
     * @see org.apache.sling.jackrabbit.usermanager.ChangeUserPassword#changePassword(javax.jcr.Session, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.List)
     */
    public User changePassword(Session jcrSession,
                                String name,
                                String oldPassword,
                                String newPassword,
                                String newPasswordConfirm,
                                List<Modificationchanges)
                throws RepositoryException {
        if ("anonymous".equals(name)) {
            throw new RepositoryException(
                "Can not change the password of the anonymous user.");
        }
        User user;
        UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
        Authorizable authorizable = userManager.getAuthorizable(name);
        if (authorizable instanceof User) {
            user = (User)authorizable;
        } else {
            throw new ResourceNotFoundException(
                "User to update could not be determined");
        }
        //SLING-2069: if the current user is an administrator, then a missing oldPwd is ok,
        // otherwise the oldPwd must be supplied.
        boolean administrator = false;
        // check that the submitted parameter values have valid values.
        if (oldPassword == null || oldPassword.length() == 0) {
            try {
                UserManager um = AccessControlUtil.getUserManager(jcrSession);
                User currentUser = (Userum.getAuthorizable(jcrSession.getUserID());
                administrator = currentUser.isAdmin();
                if (!administrator) {
                    //check if the user is a member of the 'User administrator' group
                    Authorizable userAdmin = um.getAuthorizable(this.);
                    if (userAdmin instanceof Group) {
                        boolean isMember = ((Group)userAdmin).isMember(currentUser);
                        if (isMember) {
                            administrator = true;
                        }
                    }
                }
            } catch ( Exception ex ) {
                .warn("Failed to determine if the user is an admin, assuming not. Cause: "+ex.getMessage());
                administrator = false;
            }
            if (!administrator) {
                throw new RepositoryException("Old Password was not submitted");
            }
        }
        if (newPassword == null || newPassword.length() == 0) {
            throw new RepositoryException("New Password was not submitted");
        }
        if (!newPassword.equals(newPasswordConfirm)) {
            throw new RepositoryException(
                "New Password does not match the confirmation password");
        }
        if (oldPassword != null && oldPassword.length() > 0) {
            // verify old password
            checkPassword(authorizableoldPassword);
        }
        try {
            user.changePassword(newPassword);
            final String passwordPath = . + user.getID() + "/rep:password";
            changes.add(Modification.onModified(passwordPath));
        } catch (RepositoryException re) {
            throw new RepositoryException("Failed to change user password."re);
        }
        return user;
    }
    private void checkPassword(Authorizable authorizableString oldPassword)
            throws RepositoryException {
        Credentials oldCreds = ((Userauthorizable).getCredentials();
        if (oldCreds instanceof SimpleCredentials) {
            char[] oldCredsPwd = ((SimpleCredentialsoldCreds).getPassword();
            if (oldPassword.equals(String.valueOf(oldCredsPwd))) {
                return;
            }
        } else {
            try {
                // CryptSimpleCredentials.matches(SimpleCredentials credentials)
                Class<?> oldCredsClass = oldCreds.getClass();
                Method matcher = oldCredsClass.getMethod("matches",
                    SimpleCredentials.class);
                SimpleCredentials newCreds = new SimpleCredentials(
                    authorizable.getPrincipal().getName(),
                    oldPassword.toCharArray());
                boolean match = (Booleanmatcher.invoke(oldCredsnewCreds);
                if (match) {
                    return;
                }
            } catch (Throwable t) {
                // failure here, fall back to password check failure below
            }
        }
        throw new RepositoryException("Old Password does not match");
    }
New to GrepCode? Check out our FAQ X