KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > policyframework > ResourceUtil


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.policyframework;
21
22 import java.util.ArrayList JavaDoc;
23 import java.util.Collection JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.struts.util.LabelValueBean;
31
32 import com.sslexplorer.properties.ProfilesFactory;
33 import com.sslexplorer.properties.Property;
34 import com.sslexplorer.properties.impl.systemconfig.SystemConfigKey;
35 import com.sslexplorer.security.AuthenticationScheme;
36 import com.sslexplorer.security.Constants;
37 import com.sslexplorer.security.LogonControllerFactory;
38 import com.sslexplorer.security.SessionInfo;
39 import com.sslexplorer.security.SystemDatabaseFactory;
40 import com.sslexplorer.security.User;
41
42 /**
43  * A set of utilities for dealing with <i>Resources</i>
44  *
45  * @author Brett Smith <a HREF="mailto:brett@3sp.com">&lt;brett@3sp.com&gt;</a>
46  */

47 public class ResourceUtil {
48     
49     final static Log log = LogFactory.getLog(ResourceUtil.class);
50
51     /*
52      * Private constructor to prevent instantiation
53      */

54     private ResourceUtil() {
55     }
56
57     /**
58      * Filter a {@link List} of {@link Resource} objects, looking for either
59      * resources owned by the supplied username, or global resources that have
60      * the correct policy.
61      *
62      * @param user user
63      * @param resources list of owned resources
64      * @param includeSuperUser include super user permitted resources
65      * @return list of filtered owned resources
66      * @throws Exception on any error
67      */

68     public static List JavaDoc filterResources(User user, List JavaDoc resources, boolean includeSuperUser) throws Exception JavaDoc {
69         List JavaDoc validResources = new ArrayList JavaDoc();
70         for (Iterator JavaDoc i = resources.iterator(); i.hasNext();) {
71             Resource p = (Resource) i.next();
72             // Include the resource if the current user created it
73
if (p instanceof OwnedResource && ((OwnedResource) p).getOwnerUsername() != null
74                             && !((OwnedResource) p).getOwnerUsername().equals("")) {
75                 if (((OwnedResource) p).getOwnerUsername().equals(user.getPrincipalName())) {
76                     validResources.add(p);
77                 }
78             } else {
79                 if (PolicyDatabaseFactory.getInstance().isPrincipalAllowed(user, p, includeSuperUser)) {
80                     validResources.add(p);
81                 }
82             }
83         }
84         return validResources;
85
86     }
87
88     private static void addResources(User user, boolean includeSuperUser, List JavaDoc validResources, Resource p) throws Exception JavaDoc {
89         // Include the resource if the current user created it
90
if (p instanceof OwnedResource && ((OwnedResource) p).getOwnerUsername() != null
91                         && !((OwnedResource) p).getOwnerUsername().equals("")) {
92             if (((OwnedResource) p).getOwnerUsername().equals(user.getPrincipalName())) {
93                 validResources.add(p);
94             }
95         } else {
96             if (PolicyDatabaseFactory.getInstance().isPrincipalAllowed(user, p, includeSuperUser)) {
97                 validResources.add(p);
98             }
99         }
100     }
101
102     /**
103      * Set the current list of available profiles for this session as a session
104      * attribute.
105      *
106      * @param session session
107      * @return the available profiles
108      * @throws Exception
109      */

110     public static List JavaDoc setAvailableProfiles(SessionInfo session) throws Exception JavaDoc {
111         User user = LogonControllerFactory.getInstance().getUser(session.getHttpSession(), null);
112         List JavaDoc profiles = filterResources(user, ProfilesFactory.getInstance().getPropertyProfiles(
113                         user.getPrincipalName(), true, session.getUser().getRealm().getResourceId()), false);
114         session.getHttpSession().setAttribute(Constants.PROFILES, profiles);
115         return profiles;
116     }
117
118     /**
119      * Create a {@link List} or {@link org.apache.struts.util.LabelValueBean}
120      * objects from a {@link List} of {@link Resource} objects.
121      *
122      * @param resourceList resource list
123      * @return list of objects suitable for struts list components
124      */

125     public static List JavaDoc resourceListAsLabelValueBeanList(List JavaDoc resourceList) {
126         List JavaDoc l = new ArrayList JavaDoc();
127         Resource r;
128         for (Iterator JavaDoc i = resourceList.iterator(); i.hasNext();) {
129             r = (Resource) i.next();
130             l.add(new LabelValueBean(r.getResourceName(), String.valueOf(r.getResourceId())));
131         }
132         return l;
133     }
134
135     /**
136      * Filter a list of {@link OwnedResource} obects for those that do
137      * <strong>not</strong> have an owner.
138      *
139      * @param resources resources
140      * @return filtered resources
141      */

142     public static List JavaDoc filterOwned(List JavaDoc resources) {
143         List JavaDoc l = new ArrayList JavaDoc();
144         for (Iterator JavaDoc i = resources.iterator(); i.hasNext();) {
145             Resource resource = (Resource) i.next();
146             if (resource instanceof OwnedResource && ((OwnedResource) resource).getOwnerUsername() == null) {
147                 l.add(resource);
148             }
149         }
150         return l;
151     }
152
153     /**
154      * Get if a single resource may be managed by the specified user. For a
155      * resource to be manageable, a user must either be the super user or the
156      * parent resource permission of the resource must be attached to a policy
157      * that the specified user. A resource will also be manageable if one of its
158      * parents is manageable.
159      * <p>
160      * If a permission is provided, any resource permission that matches must
161      * contain the permission
162      *
163      * @param resource resource to test
164      * @param user user
165      * @param permission permission
166      * @return <code>true</code> if the resource is manageable
167      * @throws Exception on any error
168      */

169     public static boolean isManageableResource(Resource resource, User user, Permission permission) throws Exception JavaDoc {
170         boolean b = false;
171         if (LogonControllerFactory.getInstance().isAdministrator(user)){
172                 return true;
173                 }
174         else{
175             b = PolicyDatabaseFactory.getInstance().isPermitted(resource.getResourceType(), new Permission[] {permission}, user, false);
176         }
177
178         return b;
179     }
180
181     /**
182      * Get if the list of {@link ResourceItem} objects contains any obects that
183      * wrap the specified {@link Resource}
184      *
185      * @param items items to search
186      * @param resource resource to search for
187      * @return resource found
188      */

189     public static boolean resourceItemListContainsResource(List JavaDoc items, Resource resource) {
190         ResourceItem ri;
191         for (Iterator JavaDoc i = items.iterator(); i.hasNext();) {
192             ri = (ResourceItem) i.next();
193             if (ri.getResource().equals(resource)) {
194                 return true;
195             }
196         }
197         return false;
198     }
199
200     /**
201      * Check if the current resource may be managed (i.e. edited, removed etc)
202      * taking into account the current navigation context, whether the resource
203      * is owned and if rights to manage it have been delegated to the current
204      * user
205      *
206      * @param resource resource
207      * @param session session
208      * @param permissions permissions required for management. if any of these
209      * are assigned the the resource may be managed
210      * @throws NoPermissionException if not allowed
211      */

212     public static void checkResourceManagementRights(Resource resource, SessionInfo session, Permission[] permissions)
213                     throws NoPermissionException {
214         for (int i = 0; i < permissions.length; i++) {
215             try {
216                 ResourceType resourceType = resource.getResourceType();
217                 // If in the management console, this resource must be
218
// manageable
219
if (session.getNavigationContext() == SessionInfo.MANAGEMENT_CONSOLE_CONTEXT) {
220                     try {
221                         if (!ResourceUtil.isManageableResource(resource, session.getUser(), permissions[i])) {
222                             throw new NoPermissionException("You do not have permission to manage this resource.", session
223                                             .getUser(), resourceType);
224                         }
225                     } catch (NoPermissionException npe) {
226                         throw npe;
227                     } catch (Exception JavaDoc e) {
228                         throw new NoPermissionException("Failed to determine if resource is manangeable.", session.getUser(),
229                                         resourceType);
230                     }
231                 }
232                 // If in the user console the resource must be owned
233
else if (session.getNavigationContext() == SessionInfo.USER_CONSOLE_CONTEXT) {
234                     if (!(resource instanceof OwnedResource)) {
235                         throw new NoPermissionException("You may not managed this resource here.", session.getUser(), resourceType);
236                     } else {
237                         if (!(session.getUser().getPrincipalName().equals(((OwnedResource) resource).getOwnerUsername()))) {
238                             throw new NoPermissionException("You do not have permission to manage this resource.", session
239                                             .getUser(), resourceType);
240                         }
241                     }
242                 } else {
243                     throw new NoPermissionException("You may not manage this resource here.", session.getUser(), resourceType);
244                 }
245                 break;
246             } catch (NoPermissionException npe) {
247                 if (i == (permissions.length - 1)) {
248                     throw npe;
249                 }
250             }
251         }
252
253     }
254
255     /**
256      * Check if the current resource may be accessed taking into account the
257      * current navigation context, whether the resource is owned and if rights
258      * to access it have been assigned to the current user
259      *
260      * @param resource resource
261      * @param session session
262      * @throws NoPermissionException if not allowed
263      */

264     public static void checkResourceAccessRights(Resource resource, SessionInfo session) throws NoPermissionException {
265         ResourceType resourceType = resource.getResourceType();
266         // If in the management console, this resource must be manageable
267
if (session.getNavigationContext() == SessionInfo.MANAGEMENT_CONSOLE_CONTEXT) {
268             try {
269                 if (!ResourceUtil.isManageableResource(resource, session.getUser(), null)) {
270                     throw new NoPermissionException("You do not have permission to access this resource.", session.getUser(),
271                                     resourceType);
272                 }
273             } catch (NoPermissionException npe) {
274                 throw npe;
275             } catch (Exception JavaDoc e) {
276                 throw new NoPermissionException("Failed to determine if resource is accessable.", session.getUser(), resourceType);
277             }
278         }
279         // If in the user console the resource must be assigned or owned
280
else if (session.getNavigationContext() == SessionInfo.USER_CONSOLE_CONTEXT) {
281             if (!(resource instanceof OwnedResource)
282                             || (resource instanceof OwnedResource && ((OwnedResource) resource).getOwnerUsername() == null)) {
283                 try {
284                     // assigned
285
if (!PolicyDatabaseFactory.getInstance().isPrincipalAllowed(session.getUser(), resource, false)) {
286                         throw new NoPermissionException("You may not access this resource here.", session.getUser(), resourceType);
287                     }
288                 } catch (NoPermissionException npe) {
289                     throw npe;
290                 } catch (Exception JavaDoc e) {
291                     throw new NoPermissionException("Failed to determine if resource is accessable.", session.getUser(),
292                                     resourceType);
293                 }
294             } else {
295                 // or owned
296
if (!(session.getUser().getPrincipalName().equals(((OwnedResource) resource).getOwnerUsername()))) {
297                     throw new NoPermissionException("You do not have permission to access this resource.", session.getUser(),
298                                     resourceType);
299                 }
300             }
301         } else {
302             throw new NoPermissionException("You may not access this resource here.", session.getUser(), resourceType);
303         }
304     }
305
306     /**
307      * Check if {@link AccessRights} may be viewed, edited or removed.
308      * If the <code>actionTarget</code> supplied is <strong>view</strong>
309      * then a check is made to see if the resource permission is one that
310      * permits the current user to perform actions. If <strong>edit</strong>,
311      * <strong>remove</strong> or <strong>confirmRemove</strong> is supplied
312      * then a check if made if the resource has a parent that the current user
313      * has access to.
314      *
315      * @param resource resource to check
316      * @param session session of current user
317      * @param actionTarget action target
318      * @throws NoPermissionException no permission excepion
319      */

320     public static void checkAccessRightsValid(AccessRights resource, SessionInfo session, String JavaDoc actionTarget)
321                     throws NoPermissionException {
322
323         if (actionTarget.equals("edit") || actionTarget.equals("remove") || actionTarget.equals("confirmRemove")) {
324             ResourceUtil.checkResourceManagementRights(resource, session, new Permission[]{});
325         } else if (actionTarget.equals("view")) {
326             try {
327                 List JavaDoc l = LogonControllerFactory.getInstance().isAdministrator(session.getUser()) ? new ArrayList JavaDoc()
328                                 : PolicyDatabaseFactory.getInstance().getPermittingAccessRights(null, null, null,
329                                                 session.getUser());
330                 if (!l.contains(resource)) {
331                     throw new NoPermissionException("Permission denied.", session.getUser(),
332                                     PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE);
333                 }
334             } catch (NoPermissionException npe) {
335                 throw npe;
336             } catch (Exception JavaDoc e) {
337                 throw new NoPermissionException("Failed to determine management rights.", session.getUser(),
338                                 PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE);
339             }
340         } else {
341             throw new Error JavaDoc("checkValid() only supports edit, remove or view here, not '" + actionTarget + "'.");
342         }
343
344     }
345
346     /**
347      * @param user
348      * @return List
349      * @throws Exception
350      */

351     public static List JavaDoc getSignonAuthenticationSchemeIDs(User user) throws Exception JavaDoc {
352         List JavaDoc<Integer JavaDoc> resourceIds = PolicyDatabaseFactory.getInstance().getGrantedResourcesOfType(user,
353                         PolicyConstants.AUTHENTICATION_SCHEMES_RESOURCE_TYPE);
354         List JavaDoc<Integer JavaDoc> filteredResourceIDs = new ArrayList JavaDoc<Integer JavaDoc>();
355         for (Integer JavaDoc integer : resourceIds) {
356             AuthenticationScheme authenticationScheme = SystemDatabaseFactory.getInstance().getAuthenticationSchemeSequence(integer);
357             // Need to check for null because a plugin may have been removed that provided a previously valid scheme
358
if (authenticationScheme != null && !authenticationScheme.isSystemScheme())
359                 filteredResourceIDs.add(authenticationScheme.getResourceId());
360         }
361         return filteredResourceIDs;
362     }
363
364     /**
365      * Obtain a list of all resources assigned to a user.
366      * @param session
367      * @return
368      * @throws Exception
369      */

370     public static List JavaDoc getGrantedResources(SessionInfo session) throws Exception JavaDoc {
371         
372         List JavaDoc allResources = new ArrayList JavaDoc();
373         List JavaDoc types = PolicyDatabaseFactory.getInstance().getResourceTypes(null);
374         
375         for(Iterator JavaDoc it = types.iterator(); it.hasNext();) {
376             ResourceType type = (ResourceType) it.next();
377             
378             allResources.addAll(ResourceUtil.getGrantedResource(session, type));
379         }
380         
381         return allResources;
382     }
383
384     /**
385      * Gets a list of {@link Resource} granted for use for the specified
386      * session.
387      *
388      * @param session session
389      * @param resourceType resource type
390      * @return list of resources
391      * @throws Exception
392      */

393     public static List JavaDoc getGrantedResource(SessionInfo session, ResourceType resourceType) throws Exception JavaDoc {
394         List JavaDoc l = new ArrayList JavaDoc();
395         List JavaDoc granted = PolicyDatabaseFactory.getInstance().getGrantedResourcesOfType(session.getUser(), resourceType);
396         for (Iterator JavaDoc i = granted.iterator(); i.hasNext();) {
397             Integer JavaDoc r = (Integer JavaDoc) i.next();
398             Resource resource = resourceType.getResourceById(r.intValue());
399             if(resource == null) {
400                 log.warn("Could not locate resource with ID of " + r.intValue() + " for type " + resourceType.getResourceTypeId());
401             }
402             else {
403                 if (isPolicyResourceTypeEnforceable(resourceType)
404                                 && Property.getPropertyBoolean(new SystemConfigKey("security.enforce.policy.resource.access"))) {
405                     for (Iterator JavaDoc iter = PolicyDatabaseFactory.getInstance().getPoliciesAttachedToResource(resource,
406                                     session.getUser().getRealm()).iterator(); iter.hasNext();) {
407                         Policy element = (Policy) iter.next();
408                         List JavaDoc authSchemePolicies = (List JavaDoc) session.getHttpSession().getAttribute("auth.scheme.policies");
409                         if (authSchemePolicies != null && (authSchemePolicies).contains(element)) {
410                             l.add(resource);
411                         }
412                     }
413                 } else {
414                     l.add(resource);
415                 }
416             }
417         }
418         return l;
419     }
420
421     public static boolean isPolicyResourceTypeEnforceable(ResourceType rt) {
422         if (rt.equals(PolicyConstants.PROFILE_RESOURCE_TYPE) || rt.equals(PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE)
423                         || rt.equals(PolicyConstants.POLICY_RESOURCE_TYPE)
424                         || rt.equals(PolicyConstants.AUTHENTICATION_SCHEMES_RESOURCE_TYPE))
425             return false;
426         else
427             return true;
428     }
429
430
431     /**
432      * Filter a list of {@link Integer} objects containing resource ids for
433      * those that have a global favorite.
434      *
435      * @param resources resources
436      * @param resourceType resource type
437      * @return filtered list of resources that have favorites
438      * @throws Exception on any error
439      */

440     public static List JavaDoc filterResourceIdsForGlobalFavorites(List JavaDoc resources, ResourceType resourceType) throws Exception JavaDoc {
441         List JavaDoc l = new ArrayList JavaDoc();
442         for (Iterator JavaDoc i = resources.iterator(); i.hasNext();) {
443             Integer JavaDoc r = (Integer JavaDoc) i.next();
444             if (SystemDatabaseFactory.getInstance().getFavorite(resourceType.getResourceTypeId(), null, r.intValue()) != null) {
445                 l.add(r);
446             }
447         }
448         return l;
449     }
450
451     /**
452      * Set whether a resource is a global favorite (available to all have
453      * who policy to use it).
454      *
455      * @param resource resource
456      * @param addToFavorites add to favorites
457      * @throws Exception on any error
458      */

459     public static void setResourceGlobalFavorite(Resource resource, boolean addToFavorites) throws Exception JavaDoc {
460         if(addToFavorites != isResourceGlobalFavorite(resource)) {
461             if(addToFavorites) {
462                 SystemDatabaseFactory.getInstance().addFavorite(resource.getResourceType().getResourceTypeId(), resource.getResourceId(), null);
463             }
464             else {
465                 SystemDatabaseFactory.getInstance().removeFavorite(resource.getResourceType().getResourceTypeId(), resource.getResourceId(), null);
466             }
467         }
468     }
469
470     /**
471      * Get if a resource is added as a global favorite (available to all have
472      * who policy to use it).
473      *
474      * @param resource resource
475      * @return added as a favorite
476      * @throws Exception
477      */

478     public static boolean isResourceGlobalFavorite(Resource resource) throws Exception JavaDoc {
479         return SystemDatabaseFactory.getInstance().getFavorite(resource.getResourceType().getResourceTypeId(), null, resource.getResourceId()) != null;
480     }
481
482 }
483
Popular Tags