AuthorizableServlet.java 23 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.xss.XSSFilter
 *  javax.jcr.Credentials
 *  javax.jcr.Repository
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.SimpleCredentials
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  javax.servlet.ServletException
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.commons.collections.IteratorUtils
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.api.JackrabbitSession
 *  org.apache.jackrabbit.api.security.principal.PrincipalManager
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.jackrabbit.api.security.user.Group
 *  org.apache.jackrabbit.api.security.user.Impersonation
 *  org.apache.jackrabbit.api.security.user.User
 *  org.apache.jackrabbit.api.security.user.UserManager
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.request.RequestParameter
 *  org.apache.sling.api.request.RequestParameterMap
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.servlets.HtmlResponse
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.io.JSONWriter
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.security.user.internal.servlets;

import com.adobe.granite.security.user.UserProperties;
import com.adobe.granite.security.user.UserPropertiesManager;
import com.adobe.granite.security.user.UserPropertiesService;
import com.adobe.granite.security.user.internal.servlets.AbstractServlet;
import com.adobe.granite.security.user.util.AuthorizableJSONWriter;
import com.adobe.granite.xss.XSSFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.jcr.Credentials;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.IteratorUtils;
import org.apache.commons.lang3.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.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.principal.PrincipalManager;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Impersonation;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.request.RequestParameterMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.HtmlResponse;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.io.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=0)
@Service
@Properties(value={@Property(name="sling.servlet.paths", value={"rep/User/rw.json.GET.servlet", "rep/Group/rw.json.GET.servlet", "rep/SystemUser/rw.json.GET.servlet", "/libs/granite/security/currentuser.json", "rep/User/rw.html.POST.servlet", "rep/Group/rw.html.POST.servlet", "rep/SystemUser/rw.html.POST.servlet", "/libs/granite/security/post/authorizables"})})
public class AuthorizableServlet
extends AbstractServlet {
    private static final Logger log = LoggerFactory.getLogger(AuthorizableServlet.class);
    private static final String PARAM_DELETE = "deleteAuthorizable";
    private static final String PARAM_CREATE_USER = "createUser";
    private static final String PARAM_CREATE_GROUP = "createGroup";
    private static final int ACTION_CREATE_USER = 1;
    private static final int ACTION_CREATE_GROUP = 2;
    private static final int ACTION_DELETE = 4;
    private static final int ACTION_EDIT = 8;
    private static final String PARAM_AUTHORIZABLE_ID = "authorizableId";
    private static final String PARAM_PASSWORD = "rep:password";
    private static final String PARAM_CURRENT_PASSWORD = ":currentPassword";
    private static final String PARAM_PRINCIPAL_NAME = "rep:principalName";
    private static final String PARAM_INTERMEDIATE_PATH = "intermediatePath";
    private static final String PARAM_DISABLE = "disableUser";
    private static final String PARAM_ADD_IMPERSONATORS = "addImpersonators";
    private static final String PARAM_REMOVE_IMPERSONATORS = "removeImpersonators";
    private static final String PARAM_ADD_MEMBERS = "addMembers";
    private static final String PARAM_REMOVE_MEMBERS = "removeMembers";
    private static final String PARAM_COPY_MEMBERS_FROM_GROUP = "copyFromGroup";
    private static final String PARAM_MEMBERSHIP = "membership";
    private static final String PARAM_NAMED = "named";
    private static final String PROP_LASTMODIFIED = "cq:lastModified";
    private static final String PROP_LASTMODIFIEDBY = "cq:lastModifiedBy";
    private static final Set<String> RESERVED = new HashSet<String>();
    @Reference
    private UserPropertiesService upService;
    @Reference
    private XSSFilter xss;

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        block10 : {
            HtmlResponse errorResponse = null;
            ResourceResolver resolver = request.getResourceResolver();
            Authorizable authorizable = (Authorizable)request.getResource().adaptTo(Authorizable.class);
            if (authorizable == null) {
                authorizable = (Authorizable)resolver.adaptTo(Authorizable.class);
            }
            try {
                if (authorizable != null) {
                    Session session = (Session)resolver.adaptTo(Session.class);
                    UserPropertiesManager mgr = this.upService.createUserPropertiesManager(session, resolver);
                    RequestParameterMap params = request.getRequestParameterMap();
                    Set<String> outputProps = AuthorizableServlet.getProps(params);
                    AuthorizableServlet.setJsonResponseHeader((HttpServletResponse)response);
                    JSONWriter writer = new JSONWriter((Writer)response.getWriter());
                    AuthorizableJSONWriter authWriter = new AuthorizableJSONWriter(mgr, resolver, session, outputProps, this.xss);
                    authWriter.setLimit("members", AuthorizableServlet.getNonNegativeValue(params, "ml", -1));
                    authWriter.setLimit("offset", AuthorizableServlet.getNonNegativeValue(params, "offset", -1));
                    authWriter.setFilterPredicates(request.getParameterValues("named"));
                    authWriter.write(writer, authorizable);
                    break block10;
                }
                errorResponse = AuthorizableServlet.createErrorResponse(404, "No valid authorizable at path: " + request.getResource().getPath());
            }
            catch (JSONException e) {
                errorResponse = AuthorizableServlet.createErrorResponse((Exception)e);
            }
            catch (RepositoryException e) {
                errorResponse = AuthorizableServlet.createErrorResponse((Exception)e);
            }
            finally {
                if (errorResponse != null) {
                    errorResponse.send((HttpServletResponse)response, true);
                }
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        HtmlResponse errorResponse = null;
        boolean revertToAutoSave = false;
        ResourceResolver resolver = request.getResourceResolver();
        Session session = (Session)resolver.adaptTo(Session.class);
        UserManager userManager = (UserManager)resolver.adaptTo(UserManager.class);
        Authorizable authorizable = (Authorizable)request.getResource().adaptTo(Authorizable.class);
        try {
            if (userManager.isAutoSave()) {
                userManager.autoSave(false);
                revertToAutoSave = true;
            }
            RequestParameterMap params = request.getRequestParameterMap();
            int action = AuthorizableServlet.getAction(params);
            HtmlResponse result = new HtmlResponse();
            if (action == 4) {
                if (authorizable == null) {
                    errorResponse = AuthorizableServlet.createErrorResponse(404, "No valid authorizable at " + request.getResource().getPath());
                } else {
                    result.setPath(authorizable.getPath());
                    authorizable.remove();
                }
            } else if (action == 1 || action == 2) {
                UserPropertiesManager userPropertiesManager = this.upService.createUserPropertiesManager(resolver);
                authorizable = AuthorizableServlet.create(params, userManager, userPropertiesManager, action == 2);
                if (authorizable == null) {
                    errorResponse = AuthorizableServlet.createErrorResponse(400, "Incomplete request, failed to create user/group.");
                } else {
                    result.setCreateRequest(true);
                    result.setPath(authorizable.getPath());
                    AuthorizableServlet.update(authorizable, params, userManager, session);
                }
            } else if (authorizable == null) {
                errorResponse = AuthorizableServlet.createErrorResponse(404, "No valid authorizable at " + request.getResource().getPath());
            } else {
                result.setPath(authorizable.getPath());
                AuthorizableServlet.update(authorizable, params, userManager, session);
            }
            if (errorResponse == null) {
                session.save();
                result.send((HttpServletResponse)response, true);
            }
        }
        catch (Exception e) {
            log.error("Error while processing AuthorizableServlet POST", (Throwable)e);
            errorResponse = AuthorizableServlet.createErrorResponse(e);
        }
        finally {
            if (revertToAutoSave) {
                try {
                    userManager.autoSave(true);
                }
                catch (RepositoryException e) {
                    log.debug("Cannot revert autosave mode of user manager", (Object)e.getMessage());
                }
            }
            if (errorResponse != null) {
                try {
                    session.refresh(false);
                }
                catch (RepositoryException e) {
                    log.warn("Cannot revert transient modifications.", (Object)e.getMessage());
                }
                errorResponse.send((HttpServletResponse)response, true);
            }
        }
    }

    private static Authorizable create(RequestParameterMap params, UserManager userManager, UserPropertiesManager userPropertiesManager, boolean isGroup) throws RepositoryException {
        Group auth = null;
        if (params.containsKey((Object)"authorizableId")) {
            String id = null;
            if (params.containsKey((Object)"authorizableId")) {
                id = params.getValue("authorizableId").getString();
            }
            final String principalName = params.containsKey((Object)"rep:principalName") ? params.getValue("rep:principalName").getString() : id;
            Principal principal = new Principal(){

                @Override
                public String getName() {
                    return principalName;
                }
            };
            String intermediatePath = null;
            if (params.containsKey((Object)"intermediatePath")) {
                intermediatePath = params.getValue("intermediatePath").getString();
            }
            if (isGroup) {
                auth = userManager.createGroup(id, principal, intermediatePath);
            } else {
                RequestParameter pwParam = params.getValue("rep:password");
                String pw = pwParam == null ? null : (String)StringUtils.defaultIfEmpty((CharSequence)pwParam.getString(), (CharSequence)null);
                auth = userManager.createUser(id, pw, principal, intermediatePath);
                userPropertiesManager.createUserProperties(id, "profile");
            }
        } else {
            log.debug("Missing parameter {} : Cannot create new user/group", (Object)"authorizableId");
        }
        return auth;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private static void update(Authorizable authorizable, RequestParameterMap params, UserManager userManager, Session session) throws RepositoryException, IOException {
        if (!authorizable.isGroup()) {
            User user = (User)authorizable;
            if (params.containsKey((Object)"rep:password") && AuthorizableServlet.getAction(params) != 1) {
                String currentPw;
                String pw = params.getValue("rep:password").getString();
                String string = currentPw = params.containsKey((Object)":currentPassword") ? params.getValue(":currentPassword").getString() : "";
                if (!"".equals(pw)) {
                    if (user.getID().equals(session.getUserID())) {
                        user.changePassword(pw, currentPw);
                    } else {
                        Session test = null;
                        try {
                            test = session.getRepository().login((Credentials)new SimpleCredentials(session.getUserID(), currentPw.toCharArray()));
                            user.changePassword(pw);
                        }
                        finally {
                            if (test != null) {
                                test.logout();
                            }
                        }
                    }
                }
            }
            if (params.containsKey((Object)"addImpersonators")) {
                AuthorizableServlet.editImpersonation(user, params.getValues("addImpersonators"), session, false);
            }
            if (params.containsKey((Object)"removeImpersonators")) {
                AuthorizableServlet.editImpersonation(user, params.getValues("removeImpersonators"), session, true);
            }
            if (params.containsKey((Object)"disableUser")) {
                String reason = AuthorizableServlet.getStringValue(params, "disableUser", null);
                if ("".equals(reason)) {
                    reason = null;
                }
                user.disable(reason);
            }
        } else {
            Group group = (Group)authorizable;
            if (params.containsKey((Object)"copyFromGroup")) {
                AuthorizableServlet.copyMembers(group, params.getValue("copyFromGroup"), userManager);
            }
            if (params.containsKey((Object)"addMembers")) {
                AuthorizableServlet.editMembers(group, params.getValues("addMembers"), userManager, false);
            }
            if (params.containsKey((Object)"removeMembers")) {
                AuthorizableServlet.editMembers(group, params.getValues("removeMembers"), userManager, true);
            }
        }
        if (params.containsKey((Object)"membership")) {
            AuthorizableServlet.editMembership(authorizable, params.getValues("membership"), userManager);
        }
        ValueFactory vf = session.getValueFactory();
        block7 : for (String paramName : params.keySet()) {
            if (AuthorizableServlet.isReservedParameter(paramName, RESERVED)) continue;
            RequestParameter[] values = params.getValues(paramName);
            ArrayList<Value> jcrValues = new ArrayList<Value>(values.length);
            for (int i = 0; i < values.length; ++i) {
                if (values[i].isFormField()) {
                    String str = values[i].getString();
                    if (str == null || str.length() <= 0) continue;
                    jcrValues.add(vf.createValue(str));
                    continue;
                }
                jcrValues.add(vf.createValue(values[i].getInputStream()));
            }
            switch (jcrValues.size()) {
                case 0: {
                    authorizable.removeProperty(paramName);
                    continue block7;
                }
                case 1: {
                    authorizable.setProperty(paramName, (Value)jcrValues.get(0));
                    continue block7;
                }
            }
            authorizable.setProperty(paramName, jcrValues.toArray((T[])new Value[jcrValues.size()]));
        }
        Calendar currentData = Calendar.getInstance();
        authorizable.setProperty("{http://www.jcp.org/jcr/1.0}lastModified", vf.createValue(currentData));
        authorizable.setProperty("{http://www.jcp.org/jcr/1.0}lastModifiedBy", vf.createValue(session.getUserID()));
        authorizable.setProperty("cq:lastModified", vf.createValue(currentData));
        authorizable.setProperty("cq:lastModifiedBy", vf.createValue(session.getUserID()));
    }

    private static int getAction(RequestParameterMap params) {
        if (params.containsKey((Object)"deleteAuthorizable")) {
            return 4;
        }
        if (params.containsKey((Object)"createUser")) {
            return 1;
        }
        if (params.containsKey((Object)"createGroup")) {
            return 2;
        }
        return 8;
    }

    private static void editImpersonation(User user, RequestParameter[] impersonators, Session session, boolean isRemove) throws RepositoryException {
        PrincipalManager principalManager = AuthorizableServlet.getPrincipalManager(session);
        if (principalManager == null) {
            throw new RepositoryException("Cannot grant impersonation: PrincipalManager not available.");
        }
        Impersonation imps = user.getImpersonation();
        for (RequestParameter value : impersonators) {
            String principalName = Text.unescape((String)value.getString());
            Principal principal = principalManager.getPrincipal(principalName);
            if (principal != null) {
                if (isRemove) {
                    imps.revokeImpersonation(principal);
                    continue;
                }
                imps.grantImpersonation(principal);
                continue;
            }
            throw new RepositoryException("Cannot grant impersonation: Invalid principalName " + principalName);
        }
    }

    private static void copyMembers(Group targetGroup, RequestParameter sourceGroup, UserManager userManager) throws RepositoryException {
        String sourceGroupId = Text.unescape((String)sourceGroup.getString());
        Authorizable sourceAuth = userManager.getAuthorizable(sourceGroupId);
        if (sourceAuth != null && sourceAuth.isGroup()) {
            Iterator sourceGroupMembers = ((Group)sourceAuth).getDeclaredMembers();
            while (sourceGroupMembers.hasNext()) {
                targetGroup.addMember((Authorizable)sourceGroupMembers.next());
            }
        }
    }

    private static void editMembers(Group group, RequestParameter[] members, UserManager userManager, boolean isRemove) throws RepositoryException {
        for (RequestParameter parameter : members) {
            String memberID = Text.unescape((String)parameter.getString());
            Authorizable auth = userManager.getAuthorizable(memberID);
            if (auth == null) {
                throw new RepositoryException("Attempt to add/remove non-existing member " + memberID + " to group + " + group.getID() + ".");
            }
            if (isRemove) {
                group.removeMember(auth);
                continue;
            }
            group.addMember(auth);
        }
    }

    private static void editMembership(Authorizable authorizable, RequestParameter[] membership, UserManager userManager) throws RepositoryException {
        List existing = IteratorUtils.toList((Iterator)authorizable.declaredMemberOf());
        for (RequestParameter param : membership) {
            String groupId = Text.unescape((String)param.getString());
            Authorizable auth = userManager.getAuthorizable(groupId);
            if (auth == null || !auth.isGroup()) {
                throw new RepositoryException("Cannot edit membership: No valid group found for " + groupId);
            }
            Group group = (Group)auth;
            if (existing.remove((Object)group) || group.addMember(authorizable)) continue;
            throw new RepositoryException("Cannot add '" + authorizable.getID() + " as member of " + groupId);
        }
        for (Group group : existing) {
            if (group.removeMember(authorizable)) continue;
            throw new RepositoryException("Cannot remove '" + authorizable.getID() + "' from group " + group.getID());
        }
    }

    private static PrincipalManager getPrincipalManager(Session session) throws RepositoryException {
        if (session instanceof JackrabbitSession) {
            return ((JackrabbitSession)session).getPrincipalManager();
        }
        return null;
    }

    static {
        RESERVED.add("createUser");
        RESERVED.add("createGroup");
        RESERVED.add("authorizableId");
        RESERVED.add("rep:password");
        RESERVED.add("rep:principalName");
        RESERVED.add("intermediatePath");
        RESERVED.add("disableUser");
        RESERVED.add("addImpersonators");
        RESERVED.add("removeImpersonators");
        RESERVED.add("addMembers");
        RESERVED.add("removeMembers");
        RESERVED.add("membership");
        RESERVED.add("named");
        RESERVED.add("_charset_");
    }

    protected void bindUpService(UserPropertiesService userPropertiesService) {
        this.upService = userPropertiesService;
    }

    protected void unbindUpService(UserPropertiesService userPropertiesService) {
        if (this.upService == userPropertiesService) {
            this.upService = null;
        }
    }

    protected void bindXss(XSSFilter xSSFilter) {
        this.xss = xSSFilter;
    }

    protected void unbindXss(XSSFilter xSSFilter) {
        if (this.xss == xSSFilter) {
            this.xss = null;
        }
    }

}