View Javadoc
1   /**
2    * This file Copyright (c) 2003-2015 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 info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.HierarchyManager;
38  import info.magnolia.cms.core.Path;
39  import info.magnolia.context.MgnlContext;
40  import info.magnolia.jcr.iterator.SameChildNodeTypeIterator;
41  import info.magnolia.jcr.util.NodeTypes;
42  import info.magnolia.repository.RepositoryConstants;
43  
44  import javax.jcr.Node;
45  import javax.jcr.NodeIterator;
46  import javax.jcr.PathNotFoundException;
47  import javax.jcr.RepositoryException;
48  import javax.jcr.Session;
49  
50  import org.apache.commons.lang3.StringUtils;
51  import org.slf4j.Logger;
52  import org.slf4j.LoggerFactory;
53  
54  
55  /**
56   * Manages the users stored in the {@link info.magnolia.repository.RepositoryConstants#USER_ROLES} workspace.
57   */
58  public class MgnlRoleManager extends RepositoryBackedSecurityManager implements RoleManager {
59  
60      public static final String NODE_ACLROLES = "acl_userroles";
61  
62      private static final Logger log = LoggerFactory.getLogger(MgnlRoleManager.class);
63  
64      @Override
65      public Role getRole(final String name) {
66          return MgnlContext.doInSystemContext(new SilentSessionOp<MgnlRole>(getRepositoryName()) {
67  
68              @Override
69              public MgnlRole doExec(Session session) throws RepositoryException {
70                  Node roleNode = findPrincipalNode(name, MgnlContext.getJCRSession(getRepositoryName()));
71                  if (roleNode == null) {
72                      log.debug("can't find role [{}]", name);
73                      return null;
74                  }
75                  return newRoleInstance(roleNode);
76              }
77  
78              @Override
79              public String toString() {
80                  return "get role " + name;
81              }
82          });
83      }
84  
85      @Override
86      public Role createRole(String name) throws AccessDeniedException {
87          return createRole(null, name);
88      }
89  
90      /**
91       * Create a new role in a specific folder without any security restrictions.
92       *
93       * @throws IllegalArgumentException if the name is not valid or if a group with this name already exists
94       * @throws UnsupportedOperationException in case the role manager does not support this operation
95       */
96      @Override
97      public Role createRole(final String path, final String name) throws AccessDeniedException {
98          validateRoleName(name);
99          return MgnlContext.doInSystemContext(new SilentSessionOp<MgnlRole>(getRepositoryName()) {
100 
101             @Override
102             public MgnlRole doExec(Session session) throws RepositoryException {
103                 String parentPath = StringUtils.defaultString(path, "/");
104                 Node roleNode = session.getNode(parentPath).addNode(name, NodeTypes.Role.NAME);
105                 final Node acls = roleNode.addNode(NODE_ACLROLES, NodeTypes.ContentNode.NAME);
106                 // read only access to the role itself
107                 Node acl = acls.addNode(Path.getUniqueLabel(session, acls.getPath(), "0"), NodeTypes.ContentNode.NAME);
108                 acl.setProperty("path", roleNode.getPath());
109                 acl.setProperty("permissions", Permission.READ);
110 
111                 session.save();
112                 return newRoleInstance(roleNode);
113             }
114 
115             @Override
116             public String toString() {
117                 return "create role " + name;
118             }
119         });
120     }
121 
122     /**
123      * @deprecated since 4.5
124      */
125     @Deprecated
126     protected MgnlRole newRoleInstance(Content node) throws RepositoryException {
127         return newRoleInstance(node.getJCRNode());
128     }
129 
130     protected MgnlRole newRoleInstance(Node node) throws RepositoryException {
131         return new MgnlRole(node.getName(), node.getIdentifier(), getACLs(node).values());
132     }
133 
134     /**
135      * @deprecated since 5.2
136      */
137     @Deprecated
138     protected HierarchyManager getHierarchyManager() {
139         return MgnlContext.getHierarchyManager(RepositoryConstants.USER_ROLES);
140     }
141 
142     @Override
143     public void removePermission(final Role role, final String workspace, final String path, final long permission) {
144         MgnlContext.doInSystemContext(new SilentSessionOp<Object>(getRepositoryName()) {
145 
146             @Override
147             public Object doExec(Session session) throws Throwable {
148                 Node roleNode = session.getNodeByIdentifier(role.getId());
149                 Node aclNode = getAclNode(roleNode, workspace);
150                 NodeIterator children = new SameChildNodeTypeIterator(aclNode);
151                 while (children.hasNext()) {
152                     Node child = children.nextNode();
153                     if (child.getProperty("path").getString().equals(path)) {
154                         if (permission == MgnlRole.PERMISSION_ANY || child.getProperty("permissions").getLong() == permission) {
155                             child.remove();
156                         }
157                     }
158                 }
159                 session.save();
160                 return null;
161             }
162 
163             @Override
164             public String toString() {
165                 return "add permission to role " + role.getName();
166             }
167         });
168     }
169 
170     /**
171      * Get the ACL node for the current role node.
172      */
173     private Node getAclNode(Node roleNode, String repository) throws RepositoryException, PathNotFoundException,
174             AccessDeniedException {
175         Node aclNode;
176         if (!roleNode.hasNode("acl_" + repository)) {
177             aclNode = roleNode.addNode("acl_" + repository, NodeTypes.ContentNode.NAME);
178         } else {
179             aclNode = roleNode.getNode("acl_" + repository);
180         }
181         return aclNode;
182     }
183 
184     /**
185      * Does this permission exist?
186      */
187     private boolean existsPermission(Node aclNode, String path, long permission) throws RepositoryException {
188         NodeIterator children = aclNode.getNodes();
189         while (children.hasNext()) {
190             Node child = children.nextNode();
191             if (child.hasProperty("path") && child.getProperty("path").getString().equals(path)) {
192                 if (permission == MgnlRole.PERMISSION_ANY
193                         || child.getProperty("permissions").getLong() == permission) {
194                     return true;
195                 }
196             }
197         }
198         return false;
199     }
200 
201     @Override
202     public void addPermission(final Role role, final String workspace, final String path, final long permission) {
203         MgnlContext.doInSystemContext(new SilentSessionOp<Object>(getRepositoryName()) {
204 
205             @Override
206             public Object doExec(Session session) throws Throwable {
207                 Node roleNode = session.getNodeByIdentifier(role.getId());
208                 Node aclNode = getAclNode(roleNode, workspace);
209                 if (!existsPermission(aclNode, path, permission)) {
210                     String nodeName = Path.getUniqueLabel(session, aclNode.getPath(), "0");
211                     Node node = aclNode.addNode(nodeName, NodeTypes.ContentNode.NAME);
212                     node.setProperty("path", path);
213                     node.setProperty("permissions", permission);
214                     session.save();
215                 }
216                 return null;
217             }
218 
219             @Override
220             public String toString() {
221                 return "remove permission from role " + role.getName();
222             }
223         });
224     }
225 
226     /**
227      * Helper method to find a role.
228      * This will return null if role doesn't exist.
229      */
230     @Override
231     protected Node findPrincipalNode(String principalName, Session session) throws RepositoryException {
232         return findPrincipalNode(principalName, session, NodeTypes.Role.NAME);
233     }
234 
235     @Override
236     protected String getRepositoryName() {
237         return RepositoryConstants.USER_ROLES;
238     }
239 
240     @Override
241     public String getRoleNameById(String string) {
242         return getResourceName(string);
243     }
244 
245     protected void validateRoleName(String name) throws AccessDeniedException {
246         if (StringUtils.isBlank(name)) {
247             throw new IllegalArgumentException(name + " is not a valid role name.");
248         }
249 
250         Role role = Security.getRoleManager().getRole(name);
251 
252         if (role != null) {
253             throw new IllegalArgumentException("Role with name " + name + " already exists.");
254         }
255     }
256 }