1/*2 * Copyright 2000-2004 The Apache Software Foundation.3 * 4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 * 8 * http://www.apache.org/licenses/LICENSE-2.09 * 10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */1617packageorg.apache.jetspeed.services.security.turbine;
1819import java.sql.Connection;
20import java.util.Iterator;
21import java.util.List;
22import java.util.HashMap;
23import java.util.Vector;
2425import javax.servlet.ServletConfig;
262728// Jetspeed Security29import org.apache.jetspeed.services.security.PermissionManagement;
30import org.apache.jetspeed.services.security.JetspeedSecurityCache;
3132import org.apache.jetspeed.om.security.Role;
33import org.apache.jetspeed.om.security.Permission;
3435import org.apache.jetspeed.services.JetspeedSecurity;
36import org.apache.jetspeed.services.security.JetspeedSecurityService;
3738// Jetspeed Security Exceptions39import org.apache.jetspeed.services.security.PermissionException;
40import org.apache.jetspeed.services.security.JetspeedSecurityException;
4142// Jetspeed Database OM43import org.apache.jetspeed.om.security.turbine.TurbinePermission;
44import org.apache.jetspeed.om.security.turbine.TurbinePermissionPeer;
45import org.apache.jetspeed.om.security.turbine.TurbineRolePermission;
46import org.apache.jetspeed.om.security.turbine.TurbineRolePermissionPeer;
4748// Jetspeed logging 49import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
50import org.apache.jetspeed.services.logging.JetspeedLogger;
5152// Torque53import org.apache.torque.util.Criteria;
54import org.apache.torque.om.NumberKey;
55import org.apache.torque.Torque;
5657// Rundata58import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
59import org.apache.jetspeed.services.rundata.JetspeedRunData;
60import org.apache.turbine.services.rundata.RunDataService;
6162// Turbine63import org.apache.turbine.services.TurbineBaseService;
64import org.apache.turbine.services.TurbineServices;
65import org.apache.turbine.services.InitializationException;
66import org.apache.turbine.services.resources.ResourceService;
6768/***69 * Default Jetspeed-Turbine Permission Management implementation70 *71 *72 * @author <a href="mailto:david@bluesunrise.com">David Sean Taylor</a>73 * @version $Id: TurbinePermissionManagement.java,v 1.10 2004/02/23 03:54:49 jford Exp $74 */7576publicclassTurbinePermissionManagementextends TurbineBaseService
77 implements PermissionManagement78 {
79/***80 * Static initialization of the logger for this class81 */82privatestaticfinalJetspeedLogger logger = JetspeedLogFactoryService.getLogger(TurbinePermissionManagement.class.getName());
8384privateJetspeedRunDataService runDataService = null;
85privatefinalstatic String CASCADE_DELETE = "programmatic.cascade.delete";
86privatefinalstaticboolean DEFAULT_CASCADE_DELETE = true;
87privatefinalstatic String CONFIG_SYSTEM_PERMISSIONS = "system.permissions";
88privateboolean cascadeDelete;
89privatefinalstatic String CACHING_ENABLE = "caching.enable";
90privateboolean cachingEnable = true;
91private Vector systemPermissions = null;
9293///////////////////////////////////////////////////////////////////////////94// Permission Management Interfaces95///////////////////////////////////////////////////////////////////////////9697/***98 * Retrieves all <code>Permission</code>s for a given rolename principal.99 *100 * The security service may optionally check the current user context101 * to determine if the requestor has permission to perform this action.102 *103 * @param rolename a role name identity to be retrieved.104 * @return Iterator over all permissions associated to the role principal.105 * @exception PermissionException when the security provider has a general failure.106 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege107 */108public Iterator getPermissions(String rolename)
109 throws JetspeedSecurityException110 {
111Role role = null;
112try113 {
114if (cachingEnable)
115 {
116 Iterator iterator = JetspeedSecurityCache.getPermissions(rolename);
117if (iterator != null)
118 {
119return iterator;
120 }
121 }
122 role = JetspeedSecurity.getRole(rolename);
123 }
124catch(JetspeedSecurityException e)
125 {
126 logger.error( "Failed to Retrieve Role: ", e );
127thrownewPermissionException("Failed to Retrieve Role: ", e);
128 }
129 Criteria criteria = new Criteria();
130 criteria.add(TurbineRolePermissionPeer.ROLE_ID, role.getId());
131 List rels;
132 HashMap perms;
133134try135 {
136 rels = TurbineRolePermissionPeer.doSelect(criteria);
137if (rels.size() > 0)
138 {
139 perms = new HashMap(rels.size());
140 }
141else142 perms = new HashMap();
143144for (int ix = 0; ix < rels.size(); ix++)
145 {
146TurbineRolePermission rel = (TurbineRolePermission)rels.get(ix);
147Permission perm = rel.getTurbinePermission();
148 perms.put(perm.getName(), perm);
149 }
150 }
151catch(Exception e)
152 {
153 logger.error( "Failed to retrieve permissions ", e );
154thrownewPermissionException("Failed to retrieve permissions ", e);
155 }
156return perms.values().iterator();
157 }
158159/***160 * Retrieves all <code>Permission</code>s.161 *162 * The security service may optionally check the current user context163 * to determine if the requestor has permission to perform this action.164 *165 * @return Iterator over all permissions.166 * @exception PermissionException when the security provider has a general failure.167 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege168 */169public Iterator getPermissions()
170 throws JetspeedSecurityException171 {
172 Criteria criteria = new Criteria();
173 List permissions;
174try175 {
176 permissions = TurbinePermissionPeer.doSelect(criteria);
177 }
178catch(Exception e)
179 {
180 logger.error( "Failed to retrieve permissions ", e);
181thrownewPermissionException("Failed to retrieve permissions ", e);
182 }
183return permissions.iterator();
184 }
185186/***187 * Adds a <code>Permission</code> into permanent storage.188 *189 * The security service may optionally check the current user context190 * to determine if the requestor has permission to perform this action.191 *192 * @exception PermissionException when the security provider has a general failure.193 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege194 */195publicvoid addPermission(Permission permission)
196 throws JetspeedSecurityException197 {
198if(permissionExists(permission.getName()))
199 {
200thrownewPermissionException("The permission '" +
201 permission.getName() + "' already exists");
202 }
203204try205 {
206TurbinePermission tpermission = newTurbinePermission();
207 tpermission.setPermissionName(permission.getName());
208 Criteria criteria = TurbinePermissionPeer.buildCriteria(tpermission);
209 NumberKey key = (NumberKey)TurbinePermissionPeer.doInsert(criteria);
210 permission.setId(key.toString());
211 }
212catch(Exception e)
213 {
214 String message = "Failed to create permission '" + permission.getName() + "'";
215 logger.error( message, e );
216thrownewPermissionException(message, e);
217 }
218 }
219220221/***222 * Saves a <code>Permission</code> into permanent storage.223 *224 * The security service may optionally check the current user context225 * to determine if the requestor has permission to perform this action.226 *227 * @exception PermissionException when the security provider has a general failure.228 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege229 */230publicvoid savePermission(Permission permission)
231 throws JetspeedSecurityException232 {
233if(!permissionExists(permission.getName()))
234 {
235thrownewPermissionException("The permission '" +
236 permission.getName() + "' doesn't exists");
237 }
238239try240 {
241if (permission instanceof TurbinePermission)
242 {
243 TurbinePermissionPeer.doUpdate((TurbinePermission)permission);
244 }
245else246 {
247thrownewPermissionException("TurbinePermissionManagment: Permission is not a Turbine permission, cannot update");
248 }
249250 }
251catch(Exception e)
252 {
253 String message = "Failed to create permission '" + permission.getName() + "'";
254 logger.error( message, e );
255thrownewPermissionException( message, e );
256 }
257258 }
259260/***261 * Removes a <code>Permission</code> from the permanent store.262 *263 * The security service may optionally check the current user context264 * to determine if the requestor has permission to perform this action.265 *266 * @param permissionName the principal identity of the permission to be retrieved.267 * @exception PermissionException when the security provider has a general failure.268 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege269 */270publicvoid removePermission(String permissionName)
271 throws JetspeedSecurityException272 {
273 Connection conn = null;
274try275 {
276277if (systemPermissions.contains(permissionName))
278 {
279thrownewPermissionException("[" + permissionName + "] is a system permission and cannot be removed");
280 }
281282 conn = Torque.getConnection();
283Permission permission = this.getPermission(permissionName);
284285 Criteria criteria = new Criteria();
286 criteria.add(TurbinePermissionPeer.PERMISSION_NAME, permissionName);
287288if(cascadeDelete)
289 {
290// CASCADE to TURBINE_ROLE_PERMISSION291 Criteria critRolePerm = new Criteria();
292 critRolePerm.add(TurbineRolePermissionPeer.PERMISSION_ID, permission.getId());
293 TurbineRolePermissionPeer.doDelete(critRolePerm, conn);
294 }
295 TurbinePermissionPeer.doDelete(criteria, conn);
296297 conn.commit();
298299if (cachingEnable)
300 {
301 JetspeedSecurityCache.removeAllPermissions(permissionName);
302 }
303 }
304catch(Exception e)
305 {
306try307 {
308 conn.rollback();
309 }
310catch (java.sql.SQLException sqle)
311 {
312 logger.error("SQLException", sqle);
313 }
314 String message = "Failed to remove permission '" + permissionName + "'";
315 logger.error( message, e );
316thrownewPermissionException( message, e );
317 }
318finally319 {
320try321 {
322 Torque.closeConnection(conn);
323 }
324catch (Throwable e)
325 {
326 logger.error( "Error closing Torque connection", e );
327 }
328 }
329330 }
331332/***333 * Grants a permission to a role.334 *335 * The security service may optionally check the current user context336 * to determine if the requestor has permission to perform this action.337 *338 * @param roleName grant a permission to this role.339 * @param permissionName the permission to grant to the role.340 * @exception PermissionException when the security provider has a general failure retrieving permissions.341 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege342 */343publicvoid grantPermission(String roleName, String permissionName)
344 throws JetspeedSecurityException345 {
346try347 {
348Role role = JetspeedSecurity.getRole(roleName);
349Permission permission = this.getPermission(permissionName);
350351 Criteria criteria = new Criteria();
352 criteria.add(TurbineRolePermissionPeer.ROLE_ID, role.getId());
353 criteria.add(TurbineRolePermissionPeer.PERMISSION_ID, permission.getId());
354 TurbineRolePermissionPeer.doInsert(criteria);
355if (cachingEnable)
356 {
357 JetspeedSecurityCache.addPermission(roleName,permission);
358 }
359 }
360catch(Exception e)
361 {
362 String message = "Grant permission '" + permissionName + "' to role '" + roleName + "' failed: ";
363 logger.error( message, e );
364thrownewPermissionException( message, e );
365 }
366 }
367368/***369 * Revokes a permission from a role.370 *371 * The security service may optionally check the current user context372 * to determine if the requestor has permission to perform this action.373 *374 * @param roleName grant a permission to this role.375 * @param permissionName the permission to grant to the role.376 * @exception PermissionException when the security provider has a general failure retrieving permissions.377 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege378 */379publicvoid revokePermission(String roleName, String permissionName)
380 throws JetspeedSecurityException381 {
382try383 {
384Role role = JetspeedSecurity.getRole(roleName);
385Permission permission = this.getPermission(permissionName);
386387 Criteria criteria = new Criteria();
388 criteria.add(TurbineRolePermissionPeer.ROLE_ID, role.getId());
389 criteria.add(TurbineRolePermissionPeer.PERMISSION_ID, permission.getId());
390 TurbineRolePermissionPeer.doDelete(criteria);
391if (cachingEnable)
392 {
393 JetspeedSecurityCache.removePermission(roleName, permissionName);
394 }
395 }
396catch(Exception e)
397 {
398 String message = "Revoke permission '" + permissionName + "' to role '" + roleName + "' failed: ";
399 logger.error( message, e );
400thrownewPermissionException( message, e);
401 }
402403 }
404405/***406 * Checks for the relationship of role has a permission. Returns true when the role has the given permission.407 *408 * The security service may optionally check the current user context409 * to determine if the requestor has permission to perform this action.410 *411 * @param roleName grant a permission to this role.412 * @param permissionName the permission to grant to the role.413 * @exception PermissionException when the security provider has a general failure retrieving permissions.414 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege415 */416publicboolean hasPermission(String roleName, String permissionName)
417 throws JetspeedSecurityException418 {
419 List permissions;
420421try422 {
423if (cachingEnable)
424 {
425return JetspeedSecurityCache.hasPermission(roleName, permissionName);
426 }
427428Role role = JetspeedSecurity.getRole(roleName);
429Permission permission = this.getPermission(permissionName);
430431 Criteria criteria = new Criteria();
432 criteria.add(TurbineRolePermissionPeer.ROLE_ID, role.getId());
433 criteria.add(TurbineRolePermissionPeer.PERMISSION_ID, permission.getId());
434 permissions = TurbineRolePermissionPeer.doSelect(criteria);
435436 }
437catch(Exception e)
438 {
439 String message = "Failed to check permission '" + permissionName + "'";
440 logger.error( message , e );
441thrownewPermissionException( message, e );
442 }
443return ( permissions.size() > 0 );
444 }
445446447/***448 * Retrieves a single <code>Permission</code> for a given permissionName principal.449 *450 * The security service may optionally check the current user context451 * to determine if the requestor has permission to perform this action.452 *453 * @param permissionName a permission principal identity to be retrieved.454 * @return Permission the permission record retrieved.455 * @exception PermissionException when the security provider has a general failure.456 * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege457 */458publicPermission getPermission(String permissionName)
459 throws JetspeedSecurityException460 {
461 List permissions;
462463try464 {
465 Criteria criteria = new Criteria();
466 criteria.add(TurbinePermissionPeer.PERMISSION_NAME, permissionName);
467 permissions = TurbinePermissionPeer.doSelect(criteria);
468 }
469catch(Exception e)
470 {
471 String message = "Failed to retrieve permission '" + permissionName + "'";
472 logger.error( message, e );
473thrownewPermissionException( message, e );
474 }
475if ( permissions.size() > 1 )
476 {
477thrownewPermissionException(
478"Multiple Permissions with same permissionname '" + permissionName + "'");
479 }
480if ( permissions.size() == 1 )
481 {
482TurbinePermission permission = (TurbinePermission)permissions.get(0);
483return permission;
484 }
485thrownewPermissionException("Unknown permission '" + permissionName + "'");
486487 }
488489490///////////////////////////////////////////////////////////////////////////491// Internal492///////////////////////////////////////////////////////////////////////////493494protectedJetspeedRunData getRunData()
495 {
496JetspeedRunData rundata = null;
497if (this.runDataService != null)
498 {
499 rundata = this.runDataService.getCurrentRunData();
500 }
501return rundata;
502 }
503504/***505 * Check whether a specified permission exists.506 *507 * The login name is used for looking up the account.508 *509 * @param permissionName the name of the permission to check for existence.510 * @return true if the specified account exists511 * @throws PermissionException if there was a general db access error512 *513 */514protectedboolean permissionExists(String permissionName)
515 throws PermissionException516 {
517 Criteria criteria = new Criteria();
518 criteria.add(TurbinePermissionPeer.PERMISSION_NAME, permissionName);
519 List permissions;
520try521 {
522 permissions = TurbinePermissionPeer.doSelect(criteria);
523 }
524catch(Exception e)
525 {
526 logger.error( "Failed to check account's presence", e );
527thrownewPermissionException(
528"Failed to check account's presence", e);
529 }
530if (permissions.size() < 1)
531 {
532return false;
533 }
534returntrue;
535 }
536537///////////////////////////////////////////////////////////////////////////538// Service Init539///////////////////////////////////////////////////////////////////////////540541542/***543 * This is the early initialization method called by the544 * Turbine <code>Service</code> framework545 * @param conf The <code>ServletConfig</code>546 * @exception throws a <code>InitializationException</code> if the service547 * fails to initialize548 */549publicsynchronizedvoid init(ServletConfig conf)
550 throws InitializationException
551 {
552if (getInit()) return;
553554super.init(conf);
555556// get configuration parameters from Jetspeed Resources557 ResourceService serviceConf = ((TurbineServices)TurbineServices.getInstance())
558 .getResources(JetspeedSecurityService.SERVICE_NAME);
559560this.runDataService =
561 (JetspeedRunDataService)TurbineServices.getInstance()
562 .getService(RunDataService.SERVICE_NAME);
563564 cascadeDelete = serviceConf.getBoolean( CASCADE_DELETE, DEFAULT_CASCADE_DELETE );
565 cachingEnable = serviceConf.getBoolean( CACHING_ENABLE, cachingEnable );
566 systemPermissions = serviceConf.getVector( CONFIG_SYSTEM_PERMISSIONS, new Vector() );
567 setInit(true);
568 }
569570571572 }
573574575