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.cms.security;
35  
36  import static info.magnolia.cms.security.SecurityConstants.*;
37  
38  import info.magnolia.context.MgnlContext;
39  import info.magnolia.jcr.iterator.FilteringPropertyIterator;
40  import info.magnolia.jcr.util.NodeTypes;
41  import info.magnolia.jcr.util.NodeUtil;
42  import info.magnolia.repository.RepositoryConstants;
43  
44  import java.util.ArrayList;
45  import java.util.Collection;
46  import java.util.Collections;
47  import java.util.HashSet;
48  import java.util.Iterator;
49  import java.util.List;
50  
51  import javax.jcr.ItemNotFoundException;
52  import javax.jcr.Node;
53  import javax.jcr.NodeIterator;
54  import javax.jcr.Property;
55  import javax.jcr.PropertyIterator;
56  import javax.jcr.RepositoryException;
57  import javax.jcr.Session;
58  
59  import org.apache.commons.lang3.StringUtils;
60  import org.slf4j.Logger;
61  import org.slf4j.LoggerFactory;
62  
63  /**
64   * Group manager working directly with JCR API and returning simple groups (no JCR node aware).
65   *
66   */
67  public class MgnlGroupManager extends RepositoryBackedSecurityManager implements GroupManager {
68  
69      private static final Logger log = LoggerFactory.getLogger(MgnlGroupManager.class);
70  
71      @Override
72      public Group createGroup(final String name) throws AccessDeniedException {
73          return createGroup(null, name);
74      }
75  
76      /**
77       * Creates a new group in a specific folder. The folder must exist.
78       *
79       * @throws IllegalArgumentException if the name is not valid or if a group with this name already exists
80       * @throws UnsupportedOperationException if the implementation does not support writing
81       */
82      public Group createGroup(final String path, final String name) throws AccessDeniedException {
83          validateGroupName(name);
84          return MgnlContext.doInSystemContext(new SilentSessionOp<MgnlGroup>(getRepositoryName()) {
85  
86              @Override
87              public MgnlGroup doExec(Session session) throws RepositoryException {
88                  String parentPath = StringUtils.defaultString(path, "/");
89                  Node groupNode = session.getNode(parentPath).addNode(name, NodeTypes.Group.NAME);
90                  session.save();
91                  return new MgnlGroup(groupNode.getIdentifier(), groupNode.getName(), Collections.EMPTY_LIST, Collections.EMPTY_LIST);
92              }
93  
94              @Override
95              public String toString() {
96                  return "create group " + name;
97              }
98          });
99      }
100 
101     @Override
102     public Group getGroup(final String name) throws AccessDeniedException {
103         return MgnlContext.doInSystemContext(new SilentSessionOp<Group>(getRepositoryName()) {
104 
105             @Override
106             public Group doExec(Session session) throws RepositoryException {
107                 Node privilegedGroupNode = findPrincipalNode(name, session);
108                 if (privilegedGroupNode == null) {
109                     return null;
110                 }
111                 return newGroupInstance(privilegedGroupNode);
112             }
113 
114             @Override
115             public String toString() {
116                 return "get group " + name;
117             }
118         });
119     }
120 
121     @Override
122     public Collection<Group> getAllGroups() {
123         return MgnlContext.doInSystemContext(new SilentSessionOp<Collection<Group>>(getRepositoryName()) {
124 
125             @Override
126             public Collection<Group> doExec(Session session) throws RepositoryException {
127                 List<Group> groups = new ArrayList<Group>();
128                 Node rootNode = session.getNode("/");
129                 findAllGroupsInFolder(rootNode, groups);
130                 return groups;
131             }
132 
133             @Override
134             public String toString() {
135                 return "get all groups";
136             }
137 
138         });
139     }
140 
141     @Override
142     public Collection<String> getAllGroups(final String name) {
143         return MgnlContext.doInSystemContext(new SilentSessionOp<Collection<String>>(getRepositoryName()) {
144 
145             List<String> groups;
146 
147             @Override
148             public Collection<String> doExec(Session session) throws RepositoryException {
149                 Group group = getGroup(name);
150                 if(group == null){
151                     return null;
152                 }
153                 groups = new ArrayList<String>();
154                 collectGroups(group);
155 
156                 return groups;
157             }
158 
159             private void collectGroups(Group group) throws AccessDeniedException{
160                 for (Iterator iter = group.getGroups().iterator(); iter.hasNext();){
161                     Group subGroup = getGroup((String) iter.next());
162                     if(subGroup != null  && !groups.contains(subGroup.getName())){
163                         groups.add(subGroup.getName());
164                         collectGroups(subGroup);
165                     }
166                 }
167             }
168 
169             @Override
170             public String toString() {
171                 return "get all groups";
172             }
173         });
174     }
175 
176     protected Group newGroupInstance(Node node) throws RepositoryException {
177         // remove duplicates
178         Collection<String> groups = new HashSet<String>();
179         if (node.hasNode(NODE_GROUPS)) {
180             for (PropertyIterator iter = new FilteringPropertyIterator(node.getNode(NODE_GROUPS).getProperties(), NodeUtil.ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER); iter.hasNext();) {
181                 Property subgroup = iter.nextProperty();
182                 String resources = getResourceName(subgroup.getString());
183                 if(resources != null){
184                     groups.add(resources);
185                 }
186             }
187         }
188         Collection<String> roles = new HashSet<String>();
189         if (node.hasNode(NODE_ROLES)) {
190             RoleManager roleMan = SecuritySupport.Factory.getInstance().getRoleManager();
191             for (PropertyIterator iter = new FilteringPropertyIterator(node.getNode(NODE_ROLES).getProperties(), NodeUtil.ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER); iter.hasNext();) {
192                 Property role = iter.nextProperty();
193                 try {
194                     String roleName = roleMan.getRoleNameById(role.getString());
195                     if (roleName != null) {
196                         roles.add(roleName);
197                     }
198                 } catch (ItemNotFoundException e) {
199                     log.warn("assigned role {} doesn't exist.", role.getString());
200                 }
201             }
202         }
203         MgnlGroup group = new MgnlGroup(node.getIdentifier(), node.getName(), groups, roles);
204         return group;
205     }
206 
207     /**
208      * Helper method to find a group. Uses JCR Query.
209      * This will return null if group doesn't exist.
210      */
211     @Override
212     protected Node findPrincipalNode(String principalName, Session session) throws RepositoryException {
213         return findPrincipalNode(principalName, session, NodeTypes.Group.NAME);
214     }
215 
216     @Override
217     protected String getRepositoryName() {
218         return RepositoryConstants.USER_GROUPS;
219     }
220 
221     @Override
222     public Group addRole(Group group, String roleName) throws AccessDeniedException {
223         try {
224             add(group.getName(), roleName, NODE_ROLES);
225         } catch (PrincipalNotFoundException e) {
226             // group doesn't exist in this GM
227             return null;
228         }
229         return getGroup(group.getName());
230     }
231 
232     @Override
233     public Group addGroup(Group group, String groupName) throws AccessDeniedException {
234         try {
235             add(group.getName(), groupName, NODE_GROUPS);
236         } catch (PrincipalNotFoundException e) {
237             // group doesn't exist in this GM
238             return null;
239         }
240         return getGroup(groupName);
241     }
242 
243     /**
244      * Finds all groups located in the provided node or in sub-folders within it and adds them to the given collection.
245      * As this method bases on a method using jcr queries to find nodes, it might not see nodes that have been created but not saved yet (i.e. during installation of a module).
246      */
247     protected void findAllGroupsInFolder(Node node, Collection<Group> addTo) throws RepositoryException {
248         final NodeIterator nodesIter = findPrincipalNodes(node, NodeTypes.Group.NAME);
249         while (nodesIter.hasNext()) {
250             addTo.add(newGroupInstance(nodesIter.nextNode()));
251         }
252     }
253 
254     protected void validateGroupName(String name) throws AccessDeniedException {
255         if (StringUtils.isBlank(name)) {
256             throw new IllegalArgumentException(name + " is not a valid group name.");
257         }
258 
259         Group group = Security.getGroupManager().getGroup(name);
260 
261         if (group != null) {
262             throw new IllegalArgumentException("Group with name " + name + " already exists.");
263         }
264     }
265 
266     @Override
267     public Collection<String> getGroupsWithGroup(final String groupName) {
268         return MgnlContext.doInSystemContext(new SilentSessionOp<Collection<String>>(getRepositoryName()) {
269 
270             @Override
271             public Collection<String> doExec(Session session) throws RepositoryException {
272                 final Node groupNode = findPrincipalNode(groupName, session);
273                 return findUsersOrGroupsHavingAssignedGroupOrRoleWithUid(session, groupNode, GROUPS_NODE_NAME);
274             }
275 
276             @Override
277             public String toString() {
278                 return "get group " + groupName;
279             }
280         });
281     }
282 
283 
284     @Override
285     public Collection<String> getGroupsWithRole(final String roleName) {
286         return MgnlContext.doInSystemContext(new SilentSessionOp<Collection<String>>(getRepositoryName()) {
287 
288             @Override
289             public Collection<String> doExec(Session session) throws RepositoryException {
290                 final Node principalNode = findPrincipalNode(roleName, MgnlContext.getJCRSession(RepositoryConstants.USER_ROLES), NodeTypes.Role.NAME);
291                 return findUsersOrGroupsHavingAssignedGroupOrRoleWithUid(session, principalNode, ROLES_NODE_NAME);
292             }
293 
294             @Override
295             public String toString() {
296                 return "get group with role " + roleName;
297             }
298         });
299     }
300 }