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 long serialVersionUID = 1L; 043 044 private static final Log log = LogFactory.getLog(PermissionFilter.class); 045 046 protected final Set<String> required; 047 048 protected final Set<String> excluded; 049 050 public PermissionFilter(List<String> required, List<String> excluded) { 051 if (required == null) { 052 this.required = Collections.emptySet(); 053 } else { 054 this.required = new HashSet<>(required); 055 } 056 if (excluded == null) { 057 this.excluded = Collections.emptySet(); 058 } else { 059 this.excluded = new HashSet<>(excluded); 060 } 061 } 062 063 public PermissionFilter(String permission, boolean isRequired) { 064 if (isRequired) { 065 required = Collections.singleton(permission); 066 excluded = Collections.emptySet(); 067 } else { 068 required = Collections.emptySet(); 069 excluded = Collections.singleton(permission); 070 } 071 } 072 073 @Override 074 public boolean accept(DocumentModel docModel) { 075 CoreSession session = docModel.getCoreSession(); 076 return session != null && hasPermission(session, docModel, excluded, false) 077 && hasPermission(session, docModel, required, true); 078 079 } 080 081 protected boolean hasPermission(CoreSession session, DocumentModel doc, Set<String> permissions, boolean required) { 082 for (String permission : permissions) { 083 if ((required && !session.hasPermission(doc.getRef(), permission)) 084 || (!required && session.hasPermission(doc.getRef(), permission))) { 085 return false; 086 } 087 } 088 return true; 089 } 090 091}