View Javadoc
1   /**
2    * This file Copyright (c) 2003-2014 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.admininterface.dialogs;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.HierarchyManager;
38  import info.magnolia.cms.core.NodeData;
39  import info.magnolia.cms.gui.dialog.Dialog;
40  import info.magnolia.cms.gui.dialog.DialogControlImpl;
41  import info.magnolia.cms.security.AccessDeniedException;
42  import info.magnolia.context.MgnlContext;
43  import info.magnolia.module.admininterface.SaveHandler;
44  import info.magnolia.repository.RepositoryConstants;
45  import info.magnolia.util.EscapeUtil;
46  
47  import java.util.ArrayList;
48  import java.util.Iterator;
49  import java.util.List;
50  
51  import javax.jcr.ItemNotFoundException;
52  import javax.jcr.PathNotFoundException;
53  import javax.jcr.RepositoryException;
54  import javax.servlet.http.HttpServletRequest;
55  import javax.servlet.http.HttpServletResponse;
56  
57  import org.apache.commons.lang.StringUtils;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  
62  /**
63   * @author Fabrizio Giustina
64   * @version $Id$
65   */
66  public class UserEditDialog extends ConfiguredDialog {
67  
68      /**
69       * Stable serialVersionUID.
70       */
71      private static final long serialVersionUID = 222L;
72  
73      /**
74       * Logger.
75       */
76      protected static Logger log = LoggerFactory.getLogger(UserEditDialog.class);
77  
78      protected static final String NODE_ACLUSERS = "acl_users"; //$NON-NLS-1$
79  
80      protected static final String NODE_ACLROLES = "acl_userroles"; //$NON-NLS-1$
81  
82      protected static final String NODE_ACLCONFIG = "acl_config"; //$NON-NLS-1$
83  
84      /*
85       * (non-Javadoc)
86       * @see info.magnolia.module.admininterface.DialogMVCHandler#getRepository()
87       */
88      @Override
89      public String getRepository() {
90          String repository = super.getRepository();
91          if (repository == null) {
92              repository = RepositoryConstants.USERS;
93          }
94          return repository;
95      }
96  
97      /**
98       * @param name
99       * @param request
100      * @param response
101      * @param configNode
102      */
103     public UserEditDialog(String name, HttpServletRequest request, HttpServletResponse response, Content configNode) {
104         super(name, request, response, configNode);
105     }
106 
107     /**
108      * @see info.magnolia.module.admininterface.DialogMVCHandler#configureSaveHandler(info.magnolia.module.admininterface.SaveHandler)
109      */
110     @Override
111     protected void configureSaveHandler(SaveHandler save) {
112         super.configureSaveHandler(save);
113         save.setPath(path);
114     }
115 
116     /**
117      * Is called during showDialog(). Here can you create/ add controls for the dialog.
118      * @param configNode
119      * @param storageNode
120      * @throws javax.jcr.RepositoryException
121      */
122     @Override
123     protected Dialog createDialog(Content configNode, Content storageNode) throws RepositoryException {
124         Dialog dialog = super.createDialog(configNode, storageNode);
125         // don't do anything if command is "save"
126         if (this.getCommand().equalsIgnoreCase(COMMAND_SAVE)) {
127             return dialog;
128         }
129 
130         // replace UUID with Path for groups and roles
131         DialogControlImpl control = dialog.getSub("groups");
132         // it is ok to use system context here as long as it is used only to retrieve UUIDs of nodes we are interested in
133         HierarchyManager groupsHM = MgnlContext.getSystemContext().getHierarchyManager(RepositoryConstants.USER_GROUPS);
134         // replace uuid with path
135         replaceUUIDsWithNames(control, groupsHM);
136 
137         control = dialog.getSub("roles");
138         // it is ok to use system context here as long as it is used only to retrieve UUIDs of nodes we are interested in
139         HierarchyManager rolesHM = MgnlContext.getSystemContext().getHierarchyManager(RepositoryConstants.USER_ROLES);
140         // replace uuid with path
141         replaceUUIDsWithNames(control, rolesHM);
142 
143         return dialog;
144     }
145 
146     private void replaceUUIDsWithNames(DialogControlImpl control, HierarchyManager hm) throws RepositoryException {
147         List values = new ArrayList<String>();
148         Iterator it = control.getValues().iterator();
149         while(it.hasNext()){
150             String uuid = (String) it.next();
151             if (StringUtils.isEmpty(uuid)) {
152                 continue;
153             }
154             try {
155                 values.add(hm.getContentByUUID(uuid).getHandle());
156             }
157             catch (ItemNotFoundException e) {
158              // ignore - group/role doesn't exist anymore
159             }
160         }
161         control.getValues().clear();
162         control.getValues().addAll(values);
163     }
164 
165     /**
166      * Write ACL entries under the given user node
167      * @param node under which ACL for all workspaces needs to be created
168      */
169     protected void writeACL(Content node) throws RepositoryException {
170         // this silly method was rewriting some basic ACLs for user on every update while removing all others. Completely pointless and unnecessary.
171         // required permissions are now assigned at user creation time by the MgnlUserManager if necessary and are left untouched by this dialog.
172         // still keeping method as a hook for changing permissions directly on user node if ever needed
173     }
174 
175     private boolean escapeFormParam(String name) {
176         String[] oldValue = this.form.getParameterValues(name);
177         if (oldValue == null) {
178             return false;
179         }
180         //unescape first (don't allow to be escaped twice)
181         String[] newValue = EscapeUtil.escapeXss(EscapeUtil.unescapeXss(oldValue));
182         this.form.addparameterValues(name, newValue);
183         return true;
184     }
185 
186     @Override
187     protected boolean onPreSave(SaveHandler control) {
188         //escape to prevent XSS attack
189         escapeFormParam("groups");
190         escapeFormParam("roles");
191         return true;
192     }
193 
194     @Override
195     protected boolean onPostSave(SaveHandler saveControl) {
196 
197         Content node = this.getStorageNode();
198 
199         HierarchyManager groupsHM = MgnlContext.getHierarchyManager(
200             RepositoryConstants.USER_GROUPS);
201         HierarchyManager rolesHM = MgnlContext.getHierarchyManager(
202                 RepositoryConstants.USER_ROLES);
203 
204         try {
205             this.writeRolesOrGroups(groupsHM, node, "groups");
206             this.writeRolesOrGroups(rolesHM, node, "roles");
207             this.writeACL(node);
208             node.save();
209             return true;
210         } catch (RepositoryException re) {
211             log.error("Failed to update user, reverting all transient modifications made for this node", re);
212             try {
213                 node.refresh(false);
214             } catch (RepositoryException e) {
215                 log.error("Failed to revert transient modifications", re);
216             }
217         }
218         return false;
219     }
220 
221     private void writeRolesOrGroups(HierarchyManager hm, Content parentNode, String nodeName)
222             throws RepositoryException {
223         try {
224             Content groupOrRoleNode = parentNode.getContent(nodeName);
225             // remove existing roles, leave the node as is
226             Iterator existingNodes = groupOrRoleNode.getNodeDataCollection().iterator();
227             while (existingNodes.hasNext()) {
228                 ((NodeData) existingNodes.next()).delete();
229             }
230             List values = getDialog().getSub(nodeName).getValues();
231             String path = null;
232             for (int index = 0; index < values.size(); index++) {
233                 try {
234                     path = (String) values.get(index);
235                     if (StringUtils.isNotEmpty(path)) {
236                         groupOrRoleNode.createNodeData(Integer.toString(index)).setValue(hm.getContent(path).getUUID());
237                     }
238                 } catch(AccessDeniedException e) {
239                     String user = MgnlContext.getUser().getName();
240                     log.warn("User {} tried to assign {} {} to {} without having privileges to do so.", new Object[] {user, nodeName.substring(0, nodeName.length() - 1), path, (parentNode.getName() == user ? "self" : parentNode.getName())});
241                 }
242             }
243         } catch (PathNotFoundException e) {
244             // this might happen if all groups are deleted via dialog
245         }
246     }
247 }