001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Benoit Delbosc
018 */
019package org.nuxeo.elasticsearch.http.readonly.filter;
020
021import org.json.JSONException;
022import org.json.JSONObject;
023import org.nuxeo.ecm.core.security.SecurityService;
024import org.nuxeo.elasticsearch.http.readonly.AbstractSearchRequestFilterImpl;
025
026/**
027 * Rewrite an Elsaticsearch search request to add security filter.
028 *
029 * URI Search are turned into Request body search.
030 *
031 * @since 7.3
032 */
033public class DefaultSearchRequestFilter extends AbstractSearchRequestFilterImpl {
034
035    public String getPayload() throws JSONException {
036        if (principal.isAdministrator()) {
037            return payload;
038        }
039        if (filteredPayload == null) {
040            String[] principals = SecurityService.getPrincipalsToCheck(principal);
041            if (payload.contains("\\")) {
042                // JSONObject removes backslash so we need to hide them
043                payload = payload.replaceAll("\\\\", BACKSLASH_MARKER);
044            }
045            JSONObject payloadJson = new JSONObject(payload);
046            JSONObject query;
047            if (payloadJson.has("query")) {
048                query = payloadJson.getJSONObject("query");
049
050                payloadJson.remove("query");
051            } else {
052                query = new JSONObject("{\"match_all\":{}}");
053            }
054            JSONObject filter = new JSONObject().put("terms", new JSONObject().put("ecm:acl", principals));
055            JSONObject newQuery = new JSONObject().put("bool",
056                    new JSONObject().put("must", query).put("filter", filter));
057            payloadJson.put("query", newQuery);
058            filteredPayload = payloadJson.toString();
059            if (filteredPayload.contains(BACKSLASH_MARKER)) {
060                filteredPayload = filteredPayload.replaceAll(BACKSLASH_MARKER, "\\\\");
061            }
062
063        }
064        return filteredPayload;
065    }
066
067}