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 *     Thomas Roger
018 */
019
020package org.nuxeo.ecm.permissions;
021
022import org.nuxeo.ecm.core.api.DocumentModel;
023import org.nuxeo.ecm.core.api.NuxeoPrincipal;
024import org.nuxeo.ecm.core.api.security.ACE;
025import org.nuxeo.ecm.core.api.security.ACL;
026import org.nuxeo.ecm.core.api.security.ACP;
027import org.nuxeo.ecm.tokenauth.service.TokenAuthenticationService;
028import org.nuxeo.runtime.api.Framework;
029
030/**
031 * @since 8.1
032 */
033public class TransientUserPermissionHelper {
034
035    private TransientUserPermissionHelper() {
036        // helper class
037    }
038
039    public static String acquireToken(String username, DocumentModel doc, String permission) {
040        if (NuxeoPrincipal.isTransientUsername(username)) {
041            TokenAuthenticationService tokenAuthenticationService = Framework.getService(TokenAuthenticationService.class);
042            return tokenAuthenticationService.acquireToken(username, doc.getRepositoryName(), doc.getId(), null,
043                    permission);
044        }
045        return null;
046    }
047
048    public static void revokeToken(String username, DocumentModel doc) {
049        if (NuxeoPrincipal.isTransientUsername(username)) {
050            // check if the transient user has other ACE on the document
051            ACP acp = doc.getACP();
052            for (ACL acl : acp.getACLs()) {
053                if (ACL.INHERITED_ACL.equals(acl.getName())) {
054                    continue;
055                }
056
057                for (ACE ace : acl) {
058                    if (username.equals(ace.getUsername()) && !ace.isArchived()) {
059                        // skip token removal
060                        return;
061                    }
062                }
063            }
064
065            TokenAuthenticationService tokenAuthenticationService = Framework.getService(TokenAuthenticationService.class);
066            String token = tokenAuthenticationService.getToken(username, doc.getRepositoryName(), doc.getId());
067            if (token != null) {
068                tokenAuthenticationService.revokeToken(token);
069            }
070        }
071    }
072}