001/*
002 * (C) Copyright 2015-2018 Nuxeo (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.text.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.usermanager.UserManager;
060import org.nuxeo.runtime.api.Framework;
061
062/**
063 * Listener sending an email notification for a granted ACE.
064 * <p>
065 * This listener checks only if the ACE is granted. It assumes that other checks (such as the ACE becomes effective)
066 * have been done before.
067 *
068 * @since 7.4
069 */
070public class PermissionGrantedNotificationListener implements PostCommitFilteringEventListener {
071
072    public static final String LABEL_SUBJECT_NEW_PERMISSION = "label.subject.new.permission";
073
074    private static final Log log = LogFactory.getLog(PermissionGrantedNotificationListener.class);
075
076    public static final String SUBJECT_FORMAT = "%s %s";
077
078    @Override
079    public void handleEvent(EventBundle events) {
080        for (Event event : events) {
081            handleEvent(event);
082        }
083    }
084
085    protected void handleEvent(Event event) {
086        EventContext eventCtx = event.getContext();
087        if (!(eventCtx instanceof DocumentEventContext)) {
088            return;
089        }
090
091        DocumentEventContext docCtx = (DocumentEventContext) eventCtx;
092        CoreSession coreSession = docCtx.getCoreSession();
093        DocumentModel doc = docCtx.getSourceDocument();
094        if (doc == null || !coreSession.exists(doc.getRef())) {
095            return;
096        }
097
098        ACE ace = (ACE) docCtx.getProperty(ACE_KEY);
099        String aclName = (String) docCtx.getProperty(ACL_NAME_KEY);
100        if (ace == null || ace.isDenied() || aclName == null) {
101            return;
102        }
103
104        String username = ace.getUsername();
105        StringList to = getRecipients(username);
106        if (to == null) {
107            // no recipient
108            return;
109        }
110
111        Expression from = Scripting.newExpression("Env[\"mail.from\"]");
112        NotificationService notificationService = NotificationServiceHelper.getNotificationService();
113        String subject = String.format(SUBJECT_FORMAT, notificationService.getEMailSubjectPrefix(),
114                I18NUtils.getMessageString("messages", LABEL_SUBJECT_NEW_PERMISSION, new Object[] { doc.getTitle() },
115                        Locale.ENGLISH));
116
117        try (OperationContext ctx = new OperationContext(coreSession)) {
118            ctx.setInput(doc);
119            ctx.put("ace", ace);
120
121            Framework.doPrivileged(() -> {
122                DirectoryService directoryService = Framework.getService(DirectoryService.class);
123                try (Session session = directoryService.open(ACE_INFO_DIRECTORY)) {
124                    String id = PermissionHelper.computeDirectoryId(doc, aclName, ace.getId());
125                    DocumentModel entry = session.getEntry(id);
126                    if (entry != null) {
127                        String comment = (String) entry.getPropertyValue(ACE_INFO_COMMENT);
128                        if (comment != null) {
129                            comment = StringEscapeUtils.escapeHtml4(comment);
130                            comment = comment.replaceAll("\n", "<br/>");
131                            ctx.put("comment", comment);
132                        }
133                    }
134                }
135            });
136
137            String aceCreator = ace.getCreator();
138            if (aceCreator != null) {
139                UserManager userManager = Framework.getService(UserManager.class);
140                NuxeoPrincipal creator = userManager.getPrincipal(aceCreator);
141                if (creator != null) {
142                    ctx.put("aceCreator", String.format("%s (%s)", principalFullName(creator), creator.getName()));
143                }
144            }
145
146            if (NuxeoPrincipal.isTransientUsername(username)) {
147                String token = TransientUserPermissionHelper.getToken(username);
148                if (token != null) {
149                    ctx.put("token", token);
150                }
151            }
152
153            OperationChain chain = new OperationChain("SendMail");
154
155            // if there is more than one recipient use "bcc:" instead of "to:" for avoiding email sharing
156            final boolean useBcc = to.size() > 1;
157            chain.add(SendMail.ID)
158                 .set("from", from)
159                 .set("to", useBcc ? null : to)
160                 .set("bcc", useBcc ? to : null)
161                 .set("HTML", true)
162                 .set("subject", subject)
163                 .set("message", ACE_GRANTED_TEMPLATE);
164            Framework.getService(AutomationService.class).run(ctx, chain);
165        } catch (OperationException e) {
166            log.warn("Unable to notify user", e);
167            log.debug(e, e);
168        }
169    }
170
171    // copied from org.nuxeo.ecm.platform.ui.web.tag.fn.Functions which lives in nuxeo-platform-ui-web
172    public static String principalFullName(NuxeoPrincipal principal) {
173        String first = principal.getFirstName();
174        String last = principal.getLastName();
175        return userDisplayName(principal.getName(), first, last);
176    }
177
178    public static String userDisplayName(String id, String first, String last) {
179        if (first == null || first.length() == 0) {
180            if (last == null || last.length() == 0) {
181                return id;
182            } else {
183                return last;
184            }
185        } else {
186            if (last == null || last.length() == 0) {
187                return first;
188            } else {
189                return first + ' ' + last;
190            }
191        }
192    }
193
194    protected StringList getRecipients(String username) {
195        UserManager userManager = Framework.getService(UserManager.class);
196        NuxeoPrincipal principal = userManager.getPrincipal(username);
197        StringList to = null;
198        if (principal != null) {
199            to = new StringList(Collections.singletonList(principal.getEmail()));
200        } else {
201            NuxeoGroup group = userManager.getGroup(username);
202            if (group != null) {
203                PlatformFunctions platformFunctions = new PlatformFunctions();
204                to = platformFunctions.getEmailsFromGroup(group.getName());
205            }
206        }
207        return to;
208    }
209
210    @Override
211    public boolean acceptEvent(Event event) {
212        String eventName = event.getName();
213        return PERMISSION_NOTIFICATION_EVENT.equals(eventName);
214    }
215}