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