001/* 002 * (C) Copyright 2013 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 * Thomas Roger 018 */ 019 020package org.nuxeo.ecm.core.api.impl; 021 022import java.util.Collections; 023import java.util.HashSet; 024import java.util.List; 025import java.util.Set; 026 027import org.apache.commons.logging.Log; 028import org.apache.commons.logging.LogFactory; 029import org.nuxeo.ecm.core.api.CoreSession; 030import org.nuxeo.ecm.core.api.DocumentModel; 031import org.nuxeo.ecm.core.api.Filter; 032 033/** 034 * A filter based on permissions. 035 * <p> 036 * If one of the permission check throws an Exception, the {@link #accept} method returns false. 037 * 038 * @since 5.7.2 039 */ 040public class PermissionFilter implements Filter { 041 042 private static final Log log = LogFactory.getLog(PermissionFilter.class); 043 044 protected final Set<String> required; 045 046 protected final Set<String> excluded; 047 048 public PermissionFilter(List<String> required, List<String> excluded) { 049 if (required == null) { 050 this.required = Collections.emptySet(); 051 } else { 052 this.required = new HashSet<>(required); 053 } 054 if (excluded == null) { 055 this.excluded = Collections.emptySet(); 056 } else { 057 this.excluded = new HashSet<>(excluded); 058 } 059 } 060 061 public PermissionFilter(String permission, boolean isRequired) { 062 if (isRequired) { 063 required = Collections.singleton(permission); 064 excluded = Collections.emptySet(); 065 } else { 066 required = Collections.emptySet(); 067 excluded = Collections.singleton(permission); 068 } 069 } 070 071 @Override 072 public boolean accept(DocumentModel docModel) { 073 CoreSession session = docModel.getCoreSession(); 074 return session != null && hasPermission(session, docModel, excluded, false) 075 && hasPermission(session, docModel, required, true); 076 077 } 078 079 protected boolean hasPermission(CoreSession session, DocumentModel doc, Set<String> permissions, boolean required) { 080 for (String permission : permissions) { 081 if ((required && !session.hasPermission(doc.getRef(), permission)) 082 || (!required && session.hasPermission(doc.getRef(), permission))) { 083 return false; 084 } 085 } 086 return true; 087 } 088 089}