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        OperationContext ctx = new OperationContext(coreSession);
119        ctx.setInput(doc);
120        ctx.put("ace", ace);
121
122        Framework.doPrivileged(() -> {
123            DirectoryService directoryService = Framework.getService(DirectoryService.class);
124            try (Session session = directoryService.open(ACE_INFO_DIRECTORY)) {
125                String id = PermissionHelper.computeDirectoryId(doc, aclName, ace.getId());
126                DocumentModel entry = session.getEntry(id);
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            }
136        });
137
138        try {
139            String aceCreator = ace.getCreator();
140            if (aceCreator != null) {
141                UserManager userManager = Framework.getService(UserManager.class);
142                NuxeoPrincipal creator = userManager.getPrincipal(aceCreator);
143                if (creator != null) {
144                    ctx.put("aceCreator",
145                            String.format("%s (%s)", principalFullName(creator), creator.getName()));
146                }
147            }
148
149            if (NuxeoPrincipal.isTransientUsername(username)) {
150                TokenAuthenticationService tokenAuthenticationService = Framework
151                        .getService(TokenAuthenticationService.class);
152                String token = tokenAuthenticationService.getToken(username, doc.getRepositoryName(), doc.getId());
153                if (token != null) {
154                    ctx.put("token", token);
155                }
156            }
157
158            OperationChain chain = new OperationChain("SendMail");
159            chain.add(SendMail.ID).set("from", from).set("to", to).set("HTML", true).set("subject", subject)
160                    .set("message", ACE_GRANTED_TEMPLATE);
161            Framework.getService(AutomationService.class).run(ctx, chain);
162        } catch (OperationException e) {
163            log.warn("Unable to notify user", e);
164            log.debug(e, e);
165        }
166    }
167
168    // copied from org.nuxeo.ecm.platform.ui.web.tag.fn.Functions which lives in nuxeo-platform-ui-web
169    public static String principalFullName(NuxeoPrincipal principal) {
170        String first = principal.getFirstName();
171        String last = principal.getLastName();
172        return userDisplayName(principal.getName(), first, last);
173    }
174
175    public static String userDisplayName(String id, String first, String last) {
176        if (first == null || first.length() == 0) {
177            if (last == null || last.length() == 0) {
178                return id;
179            } else {
180                return last;
181            }
182        } else {
183            if (last == null || last.length() == 0) {
184                return first;
185            } else {
186                return first + ' ' + last;
187            }
188        }
189    }
190
191    protected StringList getRecipients(String username) {
192        UserManager userManager = Framework.getService(UserManager.class);
193        NuxeoPrincipal principal = userManager.getPrincipal(username);
194        StringList to = null;
195        if (principal != null) {
196            to = new StringList(Collections.singletonList(principal.getEmail()));
197        } else {
198            NuxeoGroup group = userManager.getGroup(username);
199            if (group != null) {
200                PlatformFunctions platformFunctions = new PlatformFunctions();
201                to = platformFunctions.getEmailsFromGroup(group.getName());
202            }
203        }
204        return to;
205    }
206
207    @Override
208    public boolean acceptEvent(Event event) {
209        String eventName = event.getName();
210        return PERMISSION_NOTIFICATION_EVENT.equals(eventName);
211    }
212}