001package org.nuxeo.elasticsearch.http.readonly.filter;/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Benoit Delbosc
016 */
017
018import org.json.JSONException;
019import org.json.JSONObject;
020import org.nuxeo.ecm.core.security.SecurityService;
021import org.nuxeo.elasticsearch.http.readonly.AbstractSearchRequestFilterImpl;
022
023/**
024 * Rewrite an Elsaticsearch search request to add security filter.
025 *
026 * URI Search are turned into Request body search.
027 *
028 * @since 7.3
029 */
030public class DefaultSearchRequestFilter extends AbstractSearchRequestFilterImpl {
031
032    public String getPayload() throws JSONException {
033        if (principal.isAdministrator()) {
034            return payload;
035        }
036        if (filteredPayload == null) {
037            String[] principals = SecurityService.getPrincipalsToCheck(principal);
038            if (payload.contains("\\")) {
039                // JSONObject removes backslash so we need to hide them
040                payload = payload.replaceAll("\\\\", BACKSLASH_MARKER);
041            }
042            JSONObject payloadJson = new JSONObject(payload);
043            JSONObject query;
044            if (payloadJson.has("query")) {
045                query = payloadJson.getJSONObject("query");
046
047                payloadJson.remove("query");
048            } else {
049                query = new JSONObject("{\"match_all\":{}}");
050            }
051            JSONObject filter = new JSONObject().put("terms", new JSONObject().put("ecm:acl", principals));
052            JSONObject newQuery = new JSONObject().put("filtered",
053                    new JSONObject().put("query", query).put("filter", filter));
054            payloadJson.put("query", newQuery);
055            filteredPayload = payloadJson.toString();
056            if (filteredPayload.contains(BACKSLASH_MARKER)) {
057                filteredPayload = filteredPayload.replaceAll(BACKSLASH_MARKER, "\\\\");
058            }
059
060        }
061        return filteredPayload;
062    }
063
064}