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 static org.nuxeo.ecm.permissions.Constants.ACE_GRANTED_TEMPLATE;
023import static org.nuxeo.ecm.permissions.Constants.ACE_INFO_COMMENT;
024import static org.nuxeo.ecm.permissions.Constants.ACE_INFO_DIRECTORY;
025import static org.nuxeo.ecm.permissions.Constants.ACE_KEY;
026import static org.nuxeo.ecm.permissions.Constants.ACL_NAME_KEY;
027import static org.nuxeo.ecm.permissions.Constants.PERMISSION_NOTIFICATION_EVENT;
028
029import java.util.Collections;
030import java.util.Locale;
031
032import org.apache.commons.lang.StringEscapeUtils;
033import org.apache.commons.logging.Log;
034import org.apache.commons.logging.LogFactory;
035import org.nuxeo.common.utils.i18n.I18NUtils;
036import org.nuxeo.ecm.automation.AutomationService;
037import org.nuxeo.ecm.automation.OperationChain;
038import org.nuxeo.ecm.automation.OperationContext;
039import org.nuxeo.ecm.automation.OperationException;
040import org.nuxeo.ecm.automation.core.operations.notification.SendMail;
041import org.nuxeo.ecm.automation.core.scripting.Expression;
042import org.nuxeo.ecm.automation.core.scripting.Scripting;
043import org.nuxeo.ecm.automation.core.util.StringList;
044import org.nuxeo.ecm.automation.features.PlatformFunctions;
045import org.nuxeo.ecm.core.api.CoreSession;
046import org.nuxeo.ecm.core.api.DocumentModel;
047import org.nuxeo.ecm.core.api.NuxeoGroup;
048import org.nuxeo.ecm.core.api.NuxeoPrincipal;
049import org.nuxeo.ecm.core.api.security.ACE;
050import org.nuxeo.ecm.core.event.Event;
051import org.nuxeo.ecm.core.event.EventBundle;
052import org.nuxeo.ecm.core.event.EventContext;
053import org.nuxeo.ecm.core.event.PostCommitFilteringEventListener;
054import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
055import org.nuxeo.ecm.directory.Session;
056import org.nuxeo.ecm.directory.api.DirectoryService;
057import org.nuxeo.ecm.platform.ec.notification.service.NotificationService;
058import org.nuxeo.ecm.platform.ec.notification.service.NotificationServiceHelper;
059import org.nuxeo.ecm.platform.ui.web.tag.fn.Functions;
060import org.nuxeo.ecm.platform.usermanager.UserManager;
061import org.nuxeo.ecm.tokenauth.service.TokenAuthenticationService;
062import org.nuxeo.runtime.api.Framework;
063
064/**
065 * Listener sending an email notification for a granted ACE.
066 * <p>
067 * This listener checks only if the ACE is granted. It assumes that other checks (such as the ACE becomes effective)
068 * have been done before.
069 *
070 * @since 7.4
071 */
072public class PermissionGrantedNotificationListener implements PostCommitFilteringEventListener {
073
074    public static final String LABEL_SUBJECT_NEW_PERMISSION = "label.subject.new.permission";
075
076    private static final Log log = LogFactory.getLog(PermissionGrantedNotificationListener.class);
077
078    public static final String SUBJECT_FORMAT = "%s %s";
079
080    @Override
081    public void handleEvent(EventBundle events) {
082        for (Event event : events) {
083            handleEvent(event);
084        }
085    }
086
087    protected void handleEvent(Event event) {
088        EventContext eventCtx = event.getContext();
089        if (!(eventCtx instanceof DocumentEventContext)) {
090            return;
091        }
092
093        DocumentEventContext docCtx = (DocumentEventContext) eventCtx;
094        CoreSession coreSession = docCtx.getCoreSession();
095        DocumentModel doc = docCtx.getSourceDocument();
096        if (doc == null || !coreSession.exists(doc.getRef())) {
097            return;
098        }
099
100        ACE ace = (ACE) docCtx.getProperty(ACE_KEY);
101        String aclName = (String) docCtx.getProperty(ACL_NAME_KEY);
102        if (ace == null || ace.isDenied() || aclName == null) {
103            return;
104        }
105
106        String username = ace.getUsername();
107        StringList to = getRecipients(username);
108        if (to == null) {
109            // no recipient
110            return;
111        }
112
113        Expression from = Scripting.newExpression("Env[\"mail.from\"]");
114        NotificationService notificationService = NotificationServiceHelper.getNotificationService();
115        String subject = String.format(SUBJECT_FORMAT, notificationService.getEMailSubjectPrefix(),
116                I18NUtils.getMessageString("messages", LABEL_SUBJECT_NEW_PERMISSION, new Object[] { doc.getTitle() },
117                        Locale.ENGLISH));
118
119        DirectoryService directoryService = Framework.getService(DirectoryService.class);
120        try (Session session = directoryService.open(ACE_INFO_DIRECTORY)) {
121            String id = PermissionHelper.computeDirectoryId(doc, aclName, ace.getId());
122            DocumentModel entry = session.getEntry(id);
123
124            OperationContext ctx = new OperationContext(coreSession);
125            ctx.setInput(doc);
126            ctx.put("ace", ace);
127            if (entry != null) {
128                String comment = (String) entry.getPropertyValue(ACE_INFO_COMMENT);
129                if (comment != null) {
130                    comment = StringEscapeUtils.escapeHtml(comment);
131                    comment = comment.replaceAll("\n", "<br/>");
132                    ctx.put("comment", comment);
133                }
134            }
135            String aceCreator = ace.getCreator();
136            if (aceCreator != null) {
137                UserManager userManager = Framework.getService(UserManager.class);
138                NuxeoPrincipal creator = userManager.getPrincipal(aceCreator);
139                if (creator != null) {
140                    ctx.put("aceCreator",
141                            String.format("%s (%s)", Functions.principalFullName(creator), creator.getName()));
142                }
143            }
144
145            if (NuxeoPrincipal.isTransientUsername(username)) {
146                TokenAuthenticationService tokenAuthenticationService = Framework
147                        .getService(TokenAuthenticationService.class);
148                String token = tokenAuthenticationService.getToken(username, doc.getRepositoryName(), doc.getId());
149                if (token != null) {
150                    ctx.put("token", token);
151                }
152            }
153
154            OperationChain chain = new OperationChain("SendMail");
155            chain.add(SendMail.ID).set("from", from).set("to", to).set("HTML", true).set("subject", subject)
156                    .set("message", ACE_GRANTED_TEMPLATE);
157            Framework.getService(AutomationService.class).run(ctx, chain);
158        } catch (OperationException e) {
159            log.warn("Unable to notify user", e);
160            log.debug(e, e);
161        }
162    }
163
164    protected StringList getRecipients(String username) {
165        UserManager userManager = Framework.getService(UserManager.class);
166        NuxeoPrincipal principal = userManager.getPrincipal(username);
167        StringList to = null;
168        if (principal != null) {
169            to = new StringList(Collections.singletonList(principal.getEmail()));
170        } else {
171            NuxeoGroup group = userManager.getGroup(username);
172            if (group != null) {
173                PlatformFunctions platformFunctions = new PlatformFunctions();
174                to = platformFunctions.getEmailsFromGroup(group.getName());
175            }
176        }
177        return to;
178    }
179
180    @Override
181    public boolean acceptEvent(Event event) {
182        String eventName = event.getName();
183        return PERMISSION_NOTIFICATION_EVENT.equals(eventName);
184    }
185}