View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 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.beans.config.ContentRepository;
37  import info.magnolia.cms.core.Content;
38  import info.magnolia.cms.core.HierarchyManager;
39  import info.magnolia.cms.core.ItemType;
40  import info.magnolia.cms.core.NodeData;
41  import info.magnolia.cms.core.Path;
42  import info.magnolia.cms.util.NodeDataUtil;
43  import info.magnolia.cms.util.SystemContentWrapper;
44  
45  import org.apache.commons.codec.binary.Base64;
46  import org.apache.commons.lang.StringUtils;
47  import org.apache.commons.lang.exception.ExceptionUtils;
48  import org.slf4j.Logger;
49  import org.slf4j.LoggerFactory;
50  
51  import javax.jcr.ItemNotFoundException;
52  import javax.jcr.PathNotFoundException;
53  import javax.jcr.PropertyType;
54  import javax.jcr.RepositoryException;
55  import java.io.Serializable;
56  import java.util.Collection;
57  import java.util.GregorianCalendar;
58  import java.util.Set;
59  import java.util.TreeSet;
60  
61  
62  /**
63   * This class wraps a user content object to provide some nice methods
64   * @author philipp
65   * @version $Revision: 36050 $ ($Author: gjoseph $)
66   */
67  public class MgnlUser extends AbstractUser implements Serializable {
68  
69      private static final long serialVersionUID = 222L;
70  
71      private static final Logger log = LoggerFactory.getLogger(MgnlUser.class);
72  
73      /**
74       * Under this subnodes the assigned roles are saved
75       */
76      private static final String NODE_ROLES = "roles"; //$NON-NLS-1$
77  
78      private static final String NODE_GROUPS = "groups"; //$NON-NLS-1$
79  
80      /**
81       * Used for a global synchronization
82       */
83      private static final Object mutex = new Object();
84  
85      // serialized
86      private final SystemContentWrapper userNode;
87  
88      /**
89       * @param userNode the Content object representing this user
90       */
91      protected MgnlUser(Content userNode) {
92          this.userNode = new SystemContentWrapper(userNode);
93      }
94  
95      /**
96       * Is this user in a specified role?
97       * @param groupName the name of the role
98       * @return true if in role
99       */
100     public boolean inGroup(String groupName) {
101         return this.hasAny(groupName, NODE_GROUPS);
102     }
103 
104     /**
105      * Remove a group. Implementation is optional
106      * @param groupName
107      */
108     public void removeGroup(String groupName) throws UnsupportedOperationException {
109         this.remove(groupName, NODE_GROUPS);
110     }
111 
112     /**
113      * Adds this user to a group. Implementation is optional
114      * @param groupName
115      */
116     public void addGroup(String groupName) throws UnsupportedOperationException {
117         this.add(groupName, NODE_GROUPS);
118     }
119 
120     public boolean isEnabled() {
121         return NodeDataUtil.getBoolean(getUserNode(), "enabled", true);
122     }
123 
124     public void setEnabled(boolean enabled) {
125         try {
126             NodeDataUtil.getOrCreateAndSet(getUserNode(), "enabled", enabled);
127             getUserNode().save();
128         } catch (RepositoryException e) {
129             throw new RuntimeException(e); // TODO
130         }
131     }
132 
133     /**
134      * Is this user in a specified role?
135      * @param roleName the name of the role
136      * @return true if in role
137      */
138     public boolean hasRole(String roleName) {
139         return this.hasAny(roleName, NODE_ROLES);
140     }
141 
142     public void removeRole(String roleName) {
143         this.remove(roleName, NODE_ROLES);
144     }
145 
146     /**
147      * Adds a role to this user
148      * @param roleName the name of the role
149      */
150     public void addRole(String roleName) {
151         this.add(roleName, NODE_ROLES);
152     }
153 
154     /**
155      * checks is any object exist with the given name under this node
156      * @param name
157      * @param nodeName
158      */
159     private boolean hasAny(String name, String nodeName) {
160         try {
161             HierarchyManager hm;
162             if (StringUtils.equalsIgnoreCase(nodeName, NODE_ROLES)) {
163                 hm = MgnlSecurityUtil.getSystemHierarchyManager(ContentRepository.USER_ROLES);
164             }
165             else {
166                 hm = MgnlSecurityUtil.getSystemHierarchyManager(ContentRepository.USER_GROUPS);
167             }
168 
169             Content node = this.getUserNode().getContent(nodeName);
170             for (NodeData nodeData : node.getNodeDataCollection()) {
171                 // check for the existence of this ID
172                 try {
173                     if (hm.getContentByUUID(nodeData.getString()).getName().equalsIgnoreCase(name)) {
174                         return true;
175                     }
176                 }
177                 catch (ItemNotFoundException e) {
178                     log.debug("Role [{}] does not exist in the ROLES repository", name);
179                 }
180                 catch (IllegalArgumentException e) {
181                     log.debug("{} has invalid value", nodeData.getHandle());
182                 }
183             }
184         }
185         catch (RepositoryException e) {
186             log.debug(e.getMessage(), e);
187         }
188         return false;
189     }
190 
191     /**
192      * removed node
193      * @param name
194      * @param nodeName
195      */
196     private void remove(String name, String nodeName) {
197         try {
198             HierarchyManager hm;
199             if (StringUtils.equalsIgnoreCase(nodeName, NODE_ROLES)) {
200                 hm = MgnlSecurityUtil.getContextHierarchyManager(ContentRepository.USER_ROLES);
201             }
202             else {
203                 hm = MgnlSecurityUtil.getContextHierarchyManager(ContentRepository.USER_GROUPS);
204             }
205             Content node = this.getUserNode().getContent(nodeName);
206 
207             for (NodeData nodeData : node.getNodeDataCollection()) {
208                 // check for the existence of this ID
209                 try {
210                     if (hm.getContentByUUID(nodeData.getString()).getName().equalsIgnoreCase(name)) {
211                         nodeData.delete();
212                     }
213                 }
214                 catch (ItemNotFoundException e) {
215                     log.debug("Role [{}] does not exist in the ROLES repository", name);
216                 }
217                 catch (IllegalArgumentException e) {
218                     log.debug("{} has invalid value", nodeData.getHandle());
219                 }
220             }
221             this.getUserNode().save();
222         }
223         catch (RepositoryException e) {
224             log.error("failed to remove " + name + " from user [" + this.getName() + "]", e);
225         }
226     }
227 
228     /**
229      * adds a new node under specified node collection
230      */
231     private void add(String name, String nodeName) {
232         try {
233             final String hmName;
234             if (StringUtils.equalsIgnoreCase(nodeName, NODE_ROLES)) {
235                 hmName = ContentRepository.USER_ROLES;
236             }
237             else {
238                 hmName = ContentRepository.USER_GROUPS;
239             }
240             final HierarchyManager hm = MgnlSecurityUtil.getContextHierarchyManager(hmName);
241 
242             if (!this.hasAny(name, nodeName)) {
243                if (!this.getUserNode().hasContent(nodeName)) {
244                     this.getUserNode().createContent(nodeName, ItemType.CONTENTNODE);
245                }
246                 Content node = this.getUserNode().getContent(nodeName);
247                 // add corresponding ID
248                 try {
249                     String value = hm.getContent("/" + name).getUUID(); // assuming that there is a flat hierarchy
250                     // used only to get the unique label
251                     HierarchyManager usersHM = MgnlSecurityUtil.getSystemHierarchyManager(ContentRepository.USERS);
252                     String newName = Path.getUniqueLabel(usersHM, node.getHandle(), "0");
253                     node.createNodeData(newName).setValue(value);
254                     this.getUserNode().save();
255                 }
256                 catch (PathNotFoundException e) {
257                     log.debug("[{}] does not exist in the {} repository", name, hmName);
258                 }
259             }
260         }
261         catch (RepositoryException e) {
262             log.error("failed to add " + name + " to user [" + this.getName() + "]", e);
263         }
264     }
265 
266     /**
267      * The name of the user
268      * @return the name of the user
269      */
270     public String getName() {
271         return this.getUserNode().getName();
272     }
273 
274     /**
275      * get user password
276      * @return password string
277      */
278     public String getPassword() {
279         final String encodedPassword = this.getUserNode().getNodeData("pswd").getString().trim();
280         return decodePassword(encodedPassword);
281     }
282 
283     protected String decodePassword(String encodedPassword) {
284         return new String(Base64.decodeBase64(encodedPassword.getBytes()));
285     }
286 
287     /**
288      * the language of the current user
289      */
290     public String getLanguage() {
291         return this.getUserNode().getNodeData("language").getString(); //$NON-NLS-1$
292     }
293 
294     public String getProperty(String propertyName) {
295         return NodeDataUtil.getString(getUserNode(), propertyName, null);
296     }
297 
298     public void setProperty(String propertyName, String value) {
299         try {
300             NodeDataUtil.getOrCreateAndSet(getUserNode(), propertyName, value);
301             getUserNode().save();
302         } catch (RepositoryException e) {
303             throw new RuntimeException(e); // TODO
304         }
305     }
306 
307     public Collection<String> getGroups() {
308         return MgnlSecurityUtil.collectPropertyNames(getUserNode(), "groups", ContentRepository.USER_GROUPS, false);
309     }
310 
311     public Collection<String> getAllGroups() {
312         final Set<String> allGroups = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
313         try {
314             // add the user's direct groups
315             final Collection<String> groups = getGroups();
316             allGroups.addAll(groups);
317 
318             // add all groups from direct groups
319             final GroupManager gm = SecuritySupport.Factory.getInstance().getGroupManager();
320             for (String groupName : groups) {
321                 final Group g = gm.getGroup(groupName);
322                 allGroups.addAll(g.getAllGroups());
323             }
324 
325             return allGroups;
326         } catch (AccessDeniedException e) {
327             throw new RuntimeException(e); // TODO
328         }
329     }
330 
331     public Collection<String> getRoles() {
332         return MgnlSecurityUtil.collectPropertyNames(getUserNode(), "roles", ContentRepository.USER_ROLES, false);
333     }
334 
335     public Collection<String> getAllRoles() {
336         final Set<String> allRoles = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
337         try {
338             // add the user's direct roles
339             allRoles.addAll(getRoles());
340 
341             // add roles from all groups
342             final GroupManager gm = SecuritySupport.Factory.getInstance().getGroupManager();
343             final Collection<String> allGroups = getAllGroups();
344             for (String groupName : allGroups) {
345                 final Group g = gm.getGroup(groupName);
346                 allRoles.addAll(g.getRoles());
347             }
348 
349             return allRoles;
350         } catch (AccessDeniedException e) {
351             throw new RuntimeException(e); // TODO
352         }
353     }
354 
355     /**
356      * Update the "last access" timestamp.
357      */
358     public void setLastAccess() {
359         NodeData lastaccess;
360         Exception finalException = null;
361         boolean success = false;
362         // try three times to save the lastaccess property
363         for(int i= 1; !success && i <=3; i++){
364             finalException = null;
365             try {
366                 // synchronize on a static mutex
367                 synchronized (mutex) {
368                     // refresh the session on retries
369                     if(i>1){
370                         getUserNode().refresh(false);
371                     }
372                     lastaccess = NodeDataUtil.getOrCreate(this.getUserNode(), "lastaccess", PropertyType.DATE);
373                     lastaccess.setValue(new GregorianCalendar());
374                     getUserNode().save();
375                     success = true;
376                 }
377             }
378             catch (RepositoryException e) {
379                 finalException = e;
380                 log.debug("Unable to set the last access", e);
381             }
382         }
383         if(finalException != null){
384             log.warn("Unable to set the last access date due to a " + ExceptionUtils.getMessage(finalException));
385         }
386     }
387 
388     public Content getUserNode() {
389         return userNode;
390     }
391 }