KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > rights > ManageRights


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 package org.jahia.engines.rights;
14
15 import java.security.Principal JavaDoc;
16 import java.util.Enumeration JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.Map JavaDoc;
19 import java.util.Vector JavaDoc;
20
21 import javax.servlet.http.HttpSession JavaDoc;
22
23 import org.apache.log4j.Logger;
24 import org.jahia.engines.JahiaEngine;
25 import org.jahia.engines.users.SelectUG_Engine;
26 import org.jahia.exceptions.JahiaException;
27 import org.jahia.exceptions.JahiaInitializationException;
28 import org.jahia.exceptions.JahiaSessionExpirationException;
29 import org.jahia.params.ParamBean;
30 import org.jahia.registries.ServicesRegistry;
31 import org.jahia.services.acl.ACLInfo;
32 import org.jahia.services.acl.JahiaACLEntry;
33 import org.jahia.services.acl.JahiaACLException;
34 import org.jahia.services.acl.JahiaAbstractACL;
35 import org.jahia.services.acl.JahiaBaseACL;
36 import org.jahia.services.cache.CacheFactory;
37 import org.jahia.services.cache.HtmlCache;
38 import org.jahia.services.pages.JahiaPage;
39 import org.jahia.services.pages.JahiaPageService;
40 import org.jahia.services.pages.PageLoadFlags;
41 import org.jahia.services.usermanager.JahiaGroup;
42 import org.jahia.services.usermanager.JahiaGroupManagerService;
43 import org.jahia.services.usermanager.JahiaUser;
44 import org.jahia.services.usermanager.JahiaUserManagerService;
45
46 /**
47  * <p>
48  * Title: Jahia right management
49  * </p>
50  * <p>
51  * Description: CMS Enterprise Portal
52  * </p>
53  * <p>
54  * Copyright: Copyright (c) 2002-2003
55  * </p>
56  * <p>
57  * Company: Jahia SA
58  * </p>
59  *
60  * @author MAP
61  * @version 1.1
62  */

63 public class ManageRights {
64     private static ManageRights instance = null;
65
66     private static final String JavaDoc JSP_FILE = "/jsp/jahia/engines/rights/manage_rights.jsp";
67
68     private static final Logger logger = Logger.getLogger(ManageRights.class);
69
70     public static final String JavaDoc PARAM_ACL_ENTRIES = "aclEntries";
71
72     public static final int V_ADDED_ACL = 0;
73
74     public static final int V_RESET_CHILD_PERMISSION = 1;
75
76     public static final int V_REM_ACL_ENTRY = 2;
77
78     public static final int V_RIGHT_CHANGE = 3;
79
80     public static final int V_DEFAULT_PERMISSION = 8;
81
82     private int vNbOfPerm = -1;
83
84     private int vDefualtInherit = -1;
85
86     private int vName = -1;
87
88     /**
89      * @return a single instance of the object
90      */

91     public static synchronized ManageRights getInstance() {
92         if (instance == null) {
93             instance = new ManageRights();
94         }
95         return instance;
96     }
97
98     protected ManageRights() {
99     }
100
101     public int getNumberOfPermissions() {
102         if (vNbOfPerm == -1) {
103             try {
104                 vNbOfPerm = new JahiaBaseACL().size();
105             } catch (JahiaException ex) {
106                 logger.error("Error getting number of permissions", ex);
107             }
108         }
109         return vNbOfPerm;
110     }
111
112     public int getVDefaultInherit() {
113         if (vDefualtInherit == -1)
114             vDefualtInherit = V_DEFAULT_PERMISSION + getNumberOfPermissions();
115         return vDefualtInherit;
116     }
117
118     public int getVName() {
119         if (vName == -1)
120             vName = getVDefaultInherit() + 1;
121         return vName;
122     }
123
124     public int getVKey(Integer JavaDoc userNameWidth) {
125         return getVName() + userNameWidth.intValue() + 1;
126     }
127
128     /**
129      * @param jParams
130      * a ParamBean object
131      * @param mode
132      * the mode, according to JahiaEngine
133      * @param engineMap
134      * the engine parameters stored in a HashMap
135      * @param aclID
136      * the ACL DB identifier from "jahia_acl" table
137      * @return true if action was executed whithout problem
138      * @throws JahiaException
139      * @throws JahiaSessionExpirationException
140      * @see org.jahia.engines.JahiaEngine
141      */

142     public boolean handleActions(ParamBean jParams, int mode,
143             HashMap JavaDoc engineMap, int aclID) throws JahiaException,
144             JahiaSessionExpirationException {
145         JahiaBaseACL theACL;
146         try {
147             theACL = new JahiaBaseACL(aclID);
148         } catch (JahiaException ex) {
149             return false;
150         }
151         HttpSession JavaDoc session = jParams.getSession();
152         session.setAttribute("jahia_session_acl", theACL);
153         switch (mode) {
154         case (JahiaEngine.LOAD_MODE):
155             return loadACLEntries(jParams, engineMap, theACL);
156         case (JahiaEngine.UPDATE_MODE):
157             return update(engineMap);
158         case (JahiaEngine.SAVE_MODE):
159             return saveACLEntries(jParams, theACL);
160         }
161         return false;
162     }
163
164     /**
165      * Load all the ACL entries and inherited ACL from parent object and store
166      * the resulting principals to an HashSet.
167      *
168      * @param jParams
169      * a Parambean object
170      * @param engineMap
171      * the engine parameters stored in a HashMap
172      * @param acl
173      * the ACL DB identifier from "jahia_acl" table
174      * @return true if the entries are loaded successfully
175      * @throws JahiaException
176      * when acl "getID" failed or when renderLink to select user
177      * popup failed.
178      */

179     private boolean loadACLEntries(ParamBean jParams, HashMap JavaDoc engineMap,
180             JahiaBaseACL acl) throws JahiaException {
181         logger
182             .debug("Load ACL entries in ManageRights - AclID: " + acl.getID());
183         logger.debug(acl.toString());
184
185         HashMap JavaDoc aclEntries = new HashMap JavaDoc();
186         engineMap.put("hasNegativePermissions", Boolean.FALSE);
187         engineMap.put("actionNames", JahiaAbstractACL.getActionNames());
188         engineMap.put("symbols", JahiaBaseACL.getSymbols());
189         Integer JavaDoc userNameWidth = new Integer JavaDoc(15);
190         engineMap.put("userNameWidth", userNameWidth);
191         putInt(engineMap, "nbOfPerm", getNumberOfPermissions());
192         putInt(engineMap, "vDefInherit", getVDefaultInherit());
193         putInt(engineMap, "vDefPerm", V_DEFAULT_PERMISSION);
194         putInt(engineMap, "vAddAcl", V_ADDED_ACL);
195         putInt(engineMap, "vRemoveAcl", V_REM_ACL_ENTRY);
196         putInt(engineMap, "vChangeAcl", V_RIGHT_CHANGE);
197         putInt(engineMap, "vKey", getVKey(userNameWidth));
198
199         // Lookup for user ACL entries and inherited ACL
200
ServicesRegistry sReg = ServicesRegistry.getInstance();
201         JahiaUserManagerService uMgr = sReg.getJahiaUserManagerService();
202         JahiaGroupManagerService gMgr = sReg.getJahiaGroupManagerService();
203         Vector JavaDoc userList = acl.getUsernameList(null);
204         Enumeration JavaDoc userListEnum = userList.elements();
205         while (userListEnum.hasMoreElements()) {
206             String JavaDoc userKey = (String JavaDoc) userListEnum.nextElement();
207             JahiaUser user = uMgr.lookupUser(userKey);
208             aclEntries.put(user, new Integer JavaDoc(getPermissions(user, acl)));
209         }
210         // Look up group
211
Vector JavaDoc groupList = acl.getGroupnameListNoAdmin(null);
212         Enumeration JavaDoc groupListEnum = groupList.elements();
213         while (groupListEnum.hasMoreElements()) {
214             String JavaDoc groupKey = (String JavaDoc) groupListEnum.nextElement();
215             JahiaGroup group = gMgr.lookupGroup(groupKey);
216             aclEntries.put(group, new Integer JavaDoc(getPermissions(group, acl)));
217         }
218         engineMap.put("aclEntries", aclEntries);
219         // engineMap.put("aclID", new Integer(acl.getID()));
220
engineMap.put("selectUsrGrp", SelectUG_Engine.getInstance().renderLink(
221             jParams, ""));
222         engineMap.put("inheritance", new Integer JavaDoc(acl.getInheritance()));
223         engineMap.put("fieldForm", ServicesRegistry.getInstance()
224             .getJahiaFetcherService().fetchServlet(jParams, JSP_FILE));
225         return true;
226     }
227
228     private int getPermissions(Principal JavaDoc p, JahiaBaseACL acl) {
229         try {
230             JahiaACLEntry aclEntry = p instanceof JahiaUser ? acl
231                 .getUserEntry((JahiaUser) p) : acl
232                 .getGroupEntry((JahiaGroup) p);
233             if (aclEntry != null) {
234                 // Look up permissions in the local ACL entry; foget the partial
235
// inheritance.
236
int permissions = aclEntry.getState();
237                 return permissions;
238             } else { // Look up permissions; pur inheritance
239
int permissions = JahiaBaseACL.RIGHTS_INHERITANCE_FLAG;
240                 if (p instanceof JahiaUser) {
241                     JahiaUser user = (JahiaUser) p;
242                     for (int i = 0; i < JahiaBaseACL.RIGHTS_MAX_OFFSET; i++)
243                         permissions |= acl.getPermission(user, i) ? 1 << i : 0;
244                 } else {
245                     JahiaGroup group = (JahiaGroup) p;
246                     for (int i = 0; i < JahiaBaseACL.RIGHTS_MAX_OFFSET; i++)
247                         permissions |= acl.getPermission(group, i) ? 1 << i : 0;
248                 }
249                 return permissions;
250             }
251         } catch (JahiaACLException jae) {
252             logger.error("Cannot get user or group ACL entry !!", jae);
253             return 0;
254         }
255     }
256
257     /**
258      * @param engineMap
259      * the engine parameters stored in a HashMap
260      * @return always true
261      */

262     private boolean update(HashMap JavaDoc engineMap) {
263         logger.debug("Calling update, just setting updated flag");
264         engineMap.put("rightsUpdated", Boolean.TRUE);
265         return true;
266     }
267
268     /**
269      * Save all ACL entries modifications.
270      *
271      * @param jParams
272      * a Parambean object
273      * @param acl
274      * the ACL DB identifier from "jahia_acl" table
275      * @return true if save successful
276      * @throws JahiaException
277      */

278     private boolean saveACLEntries(ParamBean jParams, JahiaBaseACL acl)
279             throws JahiaException {
280         logger
281             .debug("Save ACL entries in ManageRights - AclID: " + acl.getID());
282         // Check if the inheritance has to be permanently prevent or not.
283
String JavaDoc cutRestAllInherit = jParams.getRequest().getParameter(
284             "cutRestAllInherit");
285         if (cutRestAllInherit != null) { // Is the check box checked ?
286
if (acl.getInheritance() == ACLInfo.INHERITANCE) { // Has it changed ?
287
acl.setInheritance(ACLInfo.NO_INHERITANCE);
288             }
289         } else {
290             if (acl.getInheritance() == ACLInfo.NO_INHERITANCE) { // Has the checkbox changed ?
291
acl.setInheritance(ACLInfo.INHERITANCE);
292             }
293         }
294         // format: [00000000r--*users gusers:1]
295
// [0..7] - flags
296
// [8..8+nbOfPerm] - permissions
297
// [8+nbOpPerm] - inheritance
298
// [inheritance+1..inheritance+1+namelength] - name
299
// [name+nameLength+2..*] - key
300
// [key-1] - type
301
String JavaDoc[] submitedACLEntries = jParams.getRequest().getParameterValues(
302             PARAM_ACL_ENTRIES);
303         Integer JavaDoc userNameWidth = (Integer JavaDoc) jParams.getRequest().getSession()
304             .getAttribute("userNameWidth");
305         if (submitedACLEntries == null
306                 || submitedACLEntries[0].substring(0, 4).equals("null")) {
307             return true;
308         }
309         for (int i = 0; i < submitedACLEntries.length; i++) {
310             String JavaDoc aclEntry = submitedACLEntries[i];
311             if ("00000000".equals(aclEntry.substring(0, 8)))
312                 continue; // Don't do anything if no changes to the ACL entry.
313

314             // What kind of object has to be saved : user or group ?
315
Principal JavaDoc usr_grp;
316             String JavaDoc usr_grpName;
317             logger.debug("Submited ACL entry : " + aclEntry);
318             int typeOffs = getVKey(userNameWidth) - 1;
319             switch (aclEntry.charAt(typeOffs)) {
320             case 'u':
321                 usr_grp = ServicesRegistry.getInstance()
322                     .getJahiaUserManagerService().lookupUser(
323                         aclEntry.substring(getVKey(userNameWidth)));
324                 usr_grpName = ((JahiaUser) usr_grp).getUsername();
325                 break;
326             case 'g':
327                 usr_grp = ServicesRegistry.getInstance()
328                     .getJahiaGroupManagerService().lookupGroup(
329                         aclEntry.substring(getVKey(userNameWidth)));
330                 usr_grpName = ((JahiaGroup) usr_grp).getGroupname();
331                 break;
332             default:
333                 logger.error("Unknown principal type");
334                 return false;
335             }
336             // Decode the select box value parameters
337
String JavaDoc permissions = aclEntry.substring(V_DEFAULT_PERMISSION,
338                 getVDefaultInherit());
339             if (aclEntry.charAt(V_ADDED_ACL) == '1') {
340                 if (aclEntry.charAt(V_REM_ACL_ENTRY) == '1'
341                         || emptyPermissions(permissions))
342                     continue; // dont add "todelete" nor empty
343
logger.debug("Added ACL entry for user : " + usr_grpName);
344                 setACLEntry(usr_grp, permissions, acl);
345             } else if (aclEntry.charAt(getVDefaultInherit()) == '%') {
346                 logger.debug("Cut inheritance for user : " + usr_grpName);
347                 setACLEntry(usr_grp, permissions, acl);
348             } else if (aclEntry.charAt(V_REM_ACL_ENTRY) == '1') {
349                 if (!removeAClEntry(usr_grp, acl))
350                     return false;
351                 // continue;
352
} else if (aclEntry.charAt(V_RIGHT_CHANGE) == '1') {
353                 if (!emptyPermissions(permissions)) {
354                     logger.debug("Permissions have changed to " + permissions
355                             + " for user : " + usr_grpName);
356                     setACLEntry(usr_grp, permissions, acl);
357                 } else
358                     removeAClEntry(usr_grp, acl);
359             }
360             if (aclEntry.charAt(V_RESET_CHILD_PERMISSION) == '1') {
361                 // logger.debug("Reset child permissions for user : " +
362
// user.getUsername());
363
/** @todo Reset child permissions. */
364             }
365         }
366         if (submitedACLEntries.length > 0) {
367             // Flush PageCache
368
JahiaPageService pageService = ServicesRegistry.getInstance()
369                 .getJahiaPageService();
370             Vector JavaDoc childs = pageService.getPageSubTree(jParams.getPageID(),
371                 PageLoadFlags.ALL, jParams);
372             for (int i = 0; i < childs.size(); i++) {
373                 JahiaPage aPage = (JahiaPage) childs.get(i);
374                 pageService.invalidatePageCache(aPage.getID());
375             }
376             pageService.invalidatePageCache(jParams.getPageID());
377         }
378         return true;
379     }
380
381     private boolean emptyPermissions(String JavaDoc permissions) {
382         for (int j = 0, len = permissions.length(); j < len; j++)
383             if (permissions.charAt(j) != JahiaAbstractACL.SYMBOL_EMPTY)
384                 return false;
385         return true;
386     }
387
388     private void putInt(Map JavaDoc map, Object JavaDoc key, int value) {
389         map.put(key, new Integer JavaDoc(value));
390     }
391
392     private boolean removeAClEntry(Principal JavaDoc usr_grp, JahiaBaseACL acl) {
393         logger.debug("Remove ACL for user : " + usr_grp.getName());
394         try {
395             if (usr_grp instanceof JahiaUser)
396                 acl.removeUserEntry((JahiaUser) usr_grp);
397             else
398                 acl.removeGroupEntry((JahiaGroup) usr_grp);
399             return true;
400         } catch (JahiaACLException jae) {
401             logger.warn("Cannot remove user '" + usr_grp.getName()
402                     + "' entry from ACL !", jae);
403             return false;
404         }
405     }
406
407     /**
408      * Save or update the ACL modifications to the DB.
409      *
410      * @param p
411      * the principal object to save
412      * @param perm
413      * the permissions to set
414      * @param acl
415      * the corresponding DB acl ID
416      */

417     private void setACLEntry(Principal JavaDoc p, String JavaDoc perm, JahiaBaseACL acl) {
418         try {
419             final HtmlCache htmlCacheInstance = CacheFactory.getHtmlCache();
420         JahiaACLEntry permissions = new JahiaACLEntry();
421         char[] actions = JahiaBaseACL.getSymbols();
422         int size = perm.length() < JahiaBaseACL.RIGHTS_MAX_OFFSET ? perm
423             .length() : JahiaBaseACL.RIGHTS_MAX_OFFSET;
424         for (int i = 0; i < size; i++)
425             permissions.setPermission(i,
426                 perm.charAt(i) == actions[i] ? JahiaACLEntry.ACL_YES
427                         : JahiaACLEntry.ACL_NO);
428         try {
429             if (p instanceof JahiaUser) {
430                     JahiaUser user = (JahiaUser) p;
431                     acl.setUserEntry(user, permissions);
432                     htmlCacheInstance.invalidateUserEntries(user.getUsername());
433                 } else {
434                     JahiaGroup group = (JahiaGroup) p;
435                     acl.setGroupEntry(group, permissions);
436                     Enumeration JavaDoc users = group.members();
437                     while (users.hasMoreElements()) {
438                         JahiaUser user = (JahiaUser) users.nextElement();
439                         htmlCacheInstance.invalidateUserEntries(user
440                             .getUsername());
441                     }
442                 }
443             } catch (JahiaACLException jae) {
444                 logger.error("Cannot set user or group ACL entry !!", jae);
445             }
446         } catch (JahiaInitializationException e) {
447             logger.error("Problem with Jahia initialization");
448         }
449     }
450 }
Popular Tags