001/*
002 * (C) Copyright 2006-2008 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 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.webengine.util;
023
024import org.nuxeo.ecm.core.api.CoreSession;
025import org.nuxeo.ecm.core.api.DocumentRef;
026import org.nuxeo.ecm.core.api.security.ACE;
027import org.nuxeo.ecm.core.api.security.ACL;
028import org.nuxeo.ecm.core.api.security.ACP;
029import org.nuxeo.ecm.core.api.security.UserEntry;
030import org.nuxeo.ecm.core.api.security.impl.UserEntryImpl;
031
032/**
033 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
034 */
035public class ACLUtils {
036
037    private ACLUtils() {
038    }
039
040    public static void removePermission(CoreSession session, DocumentRef docRef, String username, String permission)
041            {
042        ACP acp = session.getACP(docRef);
043        if (acp == null) {
044            return;
045        }
046        ACL acl = acp.getACL(null);
047        if (acl == null) {
048            return;
049        }
050        ACE[] aces = acl.getACEs();
051
052        int i = 0;
053        for (; i < aces.length; i++) {
054            if (permission.equals(aces[i].getPermission()) && username.equals(aces[i].getUsername())) {
055                break;
056            }
057        }
058        if (i == aces.length) {
059            return;
060        }
061        UserEntry[] entries = new UserEntry[aces.length - 1];
062        if (i == 0) {
063            copyTo(aces, 1, entries, 0, entries.length);
064        } else if (i == aces.length - 1) {
065            copyTo(aces, 0, entries, 0, entries.length);
066        } else {
067            copyTo(aces, 0, entries, 0, i);
068            copyTo(aces, i + 1, entries, i, entries.length - i - 1);
069        }
070        acp.setRules(entries, true);
071        session.setACP(docRef, acp, true);
072    }
073
074    private static void copyTo(ACE[] aces, int s0, UserEntry[] entries, int s1, int len) {
075        for (int i = s0, k = s1; i < len; i++, k++) {
076            ACE ace = aces[i];
077            UserEntry entry = new UserEntryImpl(ace.getUsername());
078            entry.addPrivilege(ace.getPermission(), ace.isGranted(), false);
079            entries[k] = entry;
080        }
081    }
082
083}