1 package org.collectionspace.services.common.authorization_mgt;
\r
3 import java.sql.Connection;
\r
4 import java.sql.PreparedStatement;
\r
5 import java.sql.ResultSet;
\r
6 import java.sql.SQLException;
\r
7 import java.sql.Statement;
\r
8 import java.util.ArrayList;
\r
9 import java.util.Date;
\r
10 import java.util.HashMap;
\r
11 import java.util.Hashtable;
\r
12 import java.util.List;
\r
13 import java.util.UUID;
\r
15 import javax.naming.NamingException;
\r
16 import javax.persistence.EntityManager;
\r
17 import javax.persistence.EntityManagerFactory;
\r
19 import org.collectionspace.authentication.AuthN;
\r
20 import org.collectionspace.services.authorization.AuthZ;
\r
21 import org.collectionspace.services.authorization.CSpaceAction;
\r
22 import org.collectionspace.services.authorization.PermissionException;
\r
23 import org.collectionspace.services.authorization.PermissionRole;
\r
24 import org.collectionspace.services.authorization.PermissionRoleRel;
\r
25 import org.collectionspace.services.authorization.PermissionValue;
\r
26 import org.collectionspace.services.authorization.Role;
\r
27 import org.collectionspace.services.authorization.RoleValue;
\r
28 import org.collectionspace.services.authorization.SubjectType;
\r
29 import org.collectionspace.services.authorization.URIResourceImpl;
\r
30 import org.collectionspace.services.authorization.perms.ActionType;
\r
31 import org.collectionspace.services.authorization.perms.EffectType;
\r
32 import org.collectionspace.services.authorization.perms.Permission;
\r
33 import org.collectionspace.services.authorization.perms.PermissionAction;
\r
35 import org.collectionspace.services.client.Profiler;
\r
36 import org.collectionspace.services.client.RoleClient;
\r
37 import org.collectionspace.services.client.workflow.WorkflowClient;
\r
38 import org.collectionspace.services.common.config.ServiceConfigUtils;
\r
39 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
\r
40 import org.collectionspace.services.common.context.ServiceBindingUtils;
\r
41 import org.collectionspace.services.common.document.DocumentHandler;
\r
42 import org.collectionspace.services.common.security.SecurityUtils;
\r
43 import org.collectionspace.services.common.storage.DatabaseProductType;
\r
44 import org.collectionspace.services.common.storage.JDBCTools;
\r
45 import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
\r
46 import org.collectionspace.services.config.service.ServiceBindingType;
\r
47 import org.collectionspace.services.config.tenant.TenantBindingType;
\r
49 import org.collectionspace.services.lifecycle.Lifecycle;
\r
50 import org.collectionspace.services.lifecycle.TransitionDef;
\r
51 import org.collectionspace.services.lifecycle.TransitionDefList;
\r
53 //import org.mortbay.log.Log;
\r
54 import org.slf4j.Logger;
\r
55 import org.slf4j.LoggerFactory;
\r
57 import org.springframework.security.acls.model.AlreadyExistsException;
\r
60 public class AuthorizationCommon {
\r
62 final public static String REFRESH_AUTZ_PROP = "refreshAuthZOnStartup";
\r
64 // ActionGroup labels/constants
\r
68 final public static String ACTIONGROUP_CRUDL_NAME = "CRUDL";
\r
69 final public static ActionType[] ACTIONSET_CRUDL = {ActionType.CREATE, ActionType.READ, ActionType.UPDATE, ActionType.DELETE, ActionType.SEARCH};
\r
71 final public static String ACTIONGROUP_RL_NAME = "RL";
\r
72 final public static ActionType[] ACTIONSET_RL = {ActionType.READ, ActionType.SEARCH};
\r
76 * Inner class to deal with predefined ADMIN and READER action groupds
\r
78 public class ActionGroup {
\r
80 ActionType[] actions;
\r
83 static ActionGroup ACTIONGROUP_CRUDL;
\r
84 static ActionGroup ACTIONGROUP_RL;
\r
86 // A static block to initialize the predefined action groups
\r
88 AuthorizationCommon ac = new AuthorizationCommon();
\r
90 ACTIONGROUP_CRUDL = ac.new ActionGroup();
\r
91 ACTIONGROUP_CRUDL.name = ACTIONGROUP_CRUDL_NAME;
\r
92 ACTIONGROUP_CRUDL.actions = ACTIONSET_CRUDL;
\r
94 ACTIONGROUP_RL = ac.new ActionGroup();
\r
95 ACTIONGROUP_RL.name = ACTIONGROUP_RL_NAME;
\r
96 ACTIONGROUP_RL.actions = ACTIONSET_RL;
\r
100 final static Logger logger = LoggerFactory.getLogger(AuthorizationCommon.class);
\r
103 // The "super" role has a predefined ID of "0" and a tenant ID of "0";
\r
105 final public static String ROLE_ALL_TENANTS_MANAGER = "ALL_TENANTS_MANAGER";
\r
106 final public static String ROLE_ALL_TENANTS_MANAGER_ID = "0";
\r
107 final public static String ALL_TENANTS_MANAGER_TENANT_ID = "0";
\r
109 final public static String ROLE_TENANT_ADMINISTRATOR = "TENANT_ADMINISTRATOR";
\r
110 final public static String ROLE_TENANT_READER = "TENANT_READER";
\r
112 public static final String TENANT_MANAGER_USER = "tenantManager";
\r
113 public static final String TENANT_MANAGER_SCREEN_NAME = TENANT_MANAGER_USER;
\r
114 public static final String DEFAULT_TENANT_MANAGER_PASSWORD = "manage";
\r
115 public static final String DEFAULT_TENANT_MANAGER_EMAIL = "tenantManager@collectionspace.org";
\r
117 public static final String TENANT_ADMIN_ACCT_PREFIX = "admin@";
\r
118 public static final String TENANT_READER_ACCT_PREFIX = "reader@";
\r
119 public static final String ROLE_PREFIX = "ROLE_";
\r
120 public static final String SPRING_ADMIN_ROLE = "ROLE_SPRING_ADMIN";
\r
121 public static final String TENANT_ADMIN_ROLE_SUFFIX = "_TENANT_ADMINISTRATOR";
\r
122 public static final String TENANT_READER_ROLE_SUFFIX = "_TENANT_READER";
\r
123 public static final String DEFAULT_ADMIN_PASSWORD = "Administrator";
\r
124 public static final String DEFAULT_READER_PASSWORD = "reader";
\r
126 public static final String ROLE_SPRING_ADMIN_ID = "-1";
\r
127 public static final String ROLE_SPRING_ADMIN_NAME = "ROLE_SPRING_ADMIN";
\r
129 // SQL for init tasks
\r
130 final private static String INSERT_ACCOUNT_ROLE_SQL_MYSQL =
\r
131 "INSERT INTO accounts_roles(account_id, user_id, role_id, role_name, created_at)"
\r
132 +" VALUES(?, ?, ?, ?, now())";
\r
133 final private static String INSERT_ACCOUNT_ROLE_SQL_POSTGRES =
\r
134 "INSERT INTO accounts_roles(HJID, account_id, user_id, role_id, role_name, created_at)"
\r
135 +" VALUES(nextval('hibernate_sequence'), ?, ?, ?, ?, now())";
\r
136 final private static String QUERY_USERS_SQL =
\r
137 "SELECT username FROM users WHERE username LIKE '"
\r
138 +TENANT_ADMIN_ACCT_PREFIX+"%' OR username LIKE '"+TENANT_READER_ACCT_PREFIX+"%'";
\r
139 final private static String INSERT_USER_SQL =
\r
140 "INSERT INTO users (username,passwd, created_at) VALUES (?,?, now())";
\r
141 final private static String INSERT_ACCOUNT_SQL =
\r
142 "INSERT INTO accounts_common "
\r
143 + "(csid, email, userid, status, screen_name, metadata_protection, roles_protection, created_at) "
\r
144 + "VALUES (?,?,?,'ACTIVE',?, 'immutable', 'immutable', now())";
\r
146 // TENANT MANAGER specific SQL
\r
147 final private static String QUERY_TENANT_MGR_USER_SQL =
\r
148 "SELECT username FROM users WHERE username = '"+TENANT_MANAGER_USER+"'";
\r
149 final private static String GET_TENANT_MGR_ROLE_SQL =
\r
150 "SELECT csid from roles WHERE tenant_id='"+ALL_TENANTS_MANAGER_TENANT_ID+"' and rolename=?";
\r
152 public static Role getRole(String tenantId, String displayName) {
\r
155 String roleName = AuthorizationCommon.getQualifiedRoleName(tenantId, displayName);
\r
156 role = AuthorizationStore.getRoleByName(roleName, tenantId);
\r
161 public static Role getRole(EntityManager em, String tenantId, String displayName) {
\r
164 String roleName = AuthorizationCommon.getQualifiedRoleName(tenantId, displayName);
\r
165 role = AuthorizationStore.getRoleByName(em, roleName, tenantId);
\r
171 public static Role createRole(String tenantId, String name, String description) {
\r
172 return createRole(tenantId, name, description, false /* mutable by default */);
\r
175 public static Role createRole(String tenantId, String name, String description, boolean immutable) {
\r
176 Role role = new Role();
\r
178 role.setCreatedAtItem(new Date());
\r
179 role.setDisplayName(name);
\r
180 String roleName = AuthorizationCommon.getQualifiedRoleName(tenantId, name);
\r
181 role.setRoleName(roleName);
\r
182 String id = UUID.randomUUID().toString(); //FIXME: The qualified role name should be unique enough to use as an ID/key
\r
184 role.setDescription(description);
\r
185 role.setTenantId(tenantId);
\r
186 if (immutable == true) {
\r
187 role.setMetadataProtection(RoleClient.IMMUTABLE);
\r
188 role.setPermsProtection(RoleClient.IMMUTABLE);
\r
195 * Add permission to the Spring Security tables
\r
196 * with assumption that resource is of type URI
\r
197 * @param permission configuration
\r
199 public static void addPermissionsForUri(Permission perm,
\r
200 PermissionRole permRole) throws PermissionException {
\r
202 // First check the integrity of the incoming arguments.
\r
204 if (!perm.getCsid().equals(permRole.getPermission().get(0).getPermissionId())) {
\r
205 throw new IllegalArgumentException("permission ids do not"
\r
206 + " match for role=" + permRole.getRole().get(0).getRoleName()
\r
207 + " with permissionId=" + permRole.getPermission().get(0).getPermissionId()
\r
208 + " for permission with csid=" + perm.getCsid());
\r
211 List<String> principals = new ArrayList<String>();
\r
212 for (RoleValue roleValue : permRole.getRole()) {
\r
213 principals.add(roleValue.getRoleName());
\r
215 List<PermissionAction> permActions = perm.getAction();
\r
216 for (PermissionAction permAction : permActions) {
\r
218 CSpaceAction action = URIResourceImpl.getAction(permAction.getName());
\r
219 URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(),
\r
220 perm.getResourceName(), action);
\r
221 boolean grant = perm.getEffect().equals(EffectType.PERMIT) ? true : false;
\r
222 AuthZ.get().addPermissions(uriRes, principals.toArray(new String[0]), grant);//CSPACE-4967
\r
223 } catch (PermissionException e) {
\r
225 // Only throw the exception if it is *not* an already-exists exception
\r
227 if (e.getCause() instanceof AlreadyExistsException == false) {
\r
234 private static Connection getConnection() throws NamingException, SQLException {
\r
235 return JDBCTools.getConnection(JDBCTools.CSPACE_DATASOURCE_NAME,
\r
236 JDBCTools.DEFAULT_CSPACE_DATABASE_NAME);
\r
240 * Spring security seems to require that all of our role names start
\r
241 * with the ROLE_PREFIX string.
\r
243 public static String getQualifiedRoleName(String tenantId, String name) {
\r
244 String result = name;
\r
246 String qualifiedName = ROLE_PREFIX + tenantId.toUpperCase() + "_" + name.toUpperCase();
\r
247 if (name.equals(qualifiedName) == false) {
\r
248 result = qualifiedName;
\r
254 private static ActionGroup getActionGroup(String actionGroupStr) {
\r
255 ActionGroup result = null;
\r
257 if (actionGroupStr.equalsIgnoreCase(ACTIONGROUP_CRUDL_NAME)) {
\r
258 result = ACTIONGROUP_CRUDL;
\r
259 } else if (actionGroupStr.equalsIgnoreCase(ACTIONGROUP_RL_NAME)) {
\r
260 result = ACTIONGROUP_RL;
\r
266 public static Permission createPermission(String tenantId,
\r
267 String resourceName,
\r
268 String description,
\r
269 String actionGroupStr) {
\r
270 Permission result = null;
\r
272 ActionGroup actionGroup = getActionGroup(actionGroupStr);
\r
273 result = createPermission(tenantId, resourceName, description, actionGroup);
\r
278 private static Permission createPermission(String tenantId,
\r
279 String resourceName,
\r
280 String description,
\r
281 ActionGroup actionGroup) {
\r
282 String id = tenantId
\r
283 + "-" + resourceName.replace('/', '_') // Remove the slashes so the ID can be used in a URI/URL
\r
284 + "-" + actionGroup.name;
\r
285 Permission perm = new Permission();
\r
287 perm.setDescription(description);
\r
288 perm.setCreatedAtItem(new Date());
\r
289 perm.setResourceName(resourceName.toLowerCase().trim());
\r
290 perm.setEffect(EffectType.PERMIT);
\r
291 perm.setTenantId(tenantId);
\r
293 perm.setActionGroup(actionGroup.name);
\r
294 ArrayList<PermissionAction> pas = new ArrayList<PermissionAction>();
\r
295 perm.setAction(pas);
\r
296 for (ActionType actionType : actionGroup.actions) {
\r
297 PermissionAction permAction = createPermissionAction(perm, actionType);
\r
298 pas.add(permAction);
\r
304 private static Permission createWorkflowPermission(TenantBindingType tenantBinding,
\r
305 ServiceBindingType serviceBinding,
\r
306 TransitionDef transitionDef,
\r
307 ActionGroup actionGroup)
\r
309 Permission result = null;
\r
310 String workFlowServiceSuffix;
\r
311 String transitionName;
\r
312 if (transitionDef != null) {
\r
313 transitionName = transitionDef.getName();
\r
314 workFlowServiceSuffix = WorkflowClient.SERVICE_AUTHZ_SUFFIX;
\r
316 transitionName = ""; //since the transitionDef was null, we're assuming that this is the base workflow permission to be created
\r
317 workFlowServiceSuffix = WorkflowClient.SERVICE_PATH;
\r
320 String tenantId = tenantBinding.getId();
\r
321 String resourceName = "/"
\r
322 + serviceBinding.getName().toLowerCase().trim()
\r
323 + workFlowServiceSuffix
\r
325 String description = "A generated workflow permission for actiongroup " + actionGroup.name;
\r
326 result = createPermission(tenantId, resourceName, description, actionGroup);
\r
328 if (logger.isDebugEnabled() == true) {
\r
329 logger.debug("Generated a workflow permission: "
\r
330 + result.getResourceName()
\r
331 + ":" + transitionName
\r
332 + ":" + "tenant id=" + result.getTenantId()
\r
333 + ":" + actionGroup.name);
\r
339 private static PermissionRole createPermissionRole(EntityManager em,
\r
340 Permission permission,
\r
342 boolean enforceTenancy) throws Exception
\r
344 PermissionRole permRole = new PermissionRole();
\r
345 // Check to see if the tenant ID of the permission and the tenant ID of the role match
\r
346 boolean tenantIdsMatch = role.getTenantId().equalsIgnoreCase(permission.getTenantId());
\r
347 if (tenantIdsMatch == false && enforceTenancy == false) {
\r
348 tenantIdsMatch = true; // If we don't need to enforce tenancy then we'll just consider them matched.
\r
351 if (tenantIdsMatch == true) {
\r
352 permRole.setSubject(SubjectType.ROLE);
\r
354 // Set of the permission value list of the permrole
\r
356 List<PermissionValue> permValues = new ArrayList<PermissionValue>();
\r
357 PermissionValue permValue = new PermissionValue();
\r
358 permValue.setPermissionId(permission.getCsid());
\r
359 permValue.setResourceName(permission.getResourceName().toLowerCase());
\r
360 permValue.setActionGroup(permission.getActionGroup());
\r
361 permValues.add(permValue);
\r
362 permRole.setPermission(permValues);
\r
364 // Set of the role value list of the permrole
\r
366 List<RoleValue> roleValues = new ArrayList<RoleValue>();
\r
367 RoleValue rv = new RoleValue();
\r
368 // This needs to use the qualified name, not the display name
\r
369 rv.setRoleName(role.getRoleName());
\r
370 rv.setRoleId(role.getCsid());
\r
371 roleValues.add(rv);
\r
372 permRole.setRole(roleValues);
\r
374 String errMsg = "The tenant ID of the role: " + role.getTenantId()
\r
375 + " did not match the tenant ID of the permission: " + permission.getTenantId();
\r
376 throw new Exception(errMsg);
\r
382 private static Hashtable<String, String> getTenantNamesFromConfig(TenantBindingConfigReaderImpl tenantBindingConfigReader) {
\r
384 // Note that this only handles tenants not marked as "createDisabled"
\r
385 Hashtable<String, TenantBindingType> tenantBindings =
\r
386 tenantBindingConfigReader.getTenantBindings();
\r
387 Hashtable<String, String> tenantInfo = new Hashtable<String, String>();
\r
388 for (TenantBindingType tenantBinding : tenantBindings.values()) {
\r
389 String tId = tenantBinding.getId();
\r
390 String tName = tenantBinding.getName();
\r
391 tenantInfo.put(tId, tName);
\r
392 if (logger.isDebugEnabled()) {
\r
393 logger.debug("getTenantNamesFromConfig found configured tenant id: "+tId+" name: "+tName);
\r
399 private static ArrayList<String> compileExistingTenants(Connection conn, Hashtable<String, String> tenantInfo)
\r
400 throws SQLException, Exception {
\r
401 Statement stmt = null;
\r
402 ArrayList<String> existingTenants = new ArrayList<String>();
\r
403 // First find or create the tenants
\r
404 final String queryTenantSQL = "SELECT id,name FROM tenants";
\r
406 stmt = conn.createStatement();
\r
407 ResultSet rs = stmt.executeQuery(queryTenantSQL);
\r
408 while (rs.next()) {
\r
409 String tId = rs.getString("id");
\r
410 String tName = rs.getString("name");
\r
411 if(tenantInfo.containsKey(tId)) {
\r
412 existingTenants.add(tId);
\r
413 if(!tenantInfo.get(tId).equalsIgnoreCase(tName)) {
\r
414 logger.warn("Configured name for tenant: "
\r
415 +tId+" in repository: "+tName
\r
416 +" does not match config'd name: "+ tenantInfo.get(tId));
\r
421 } catch(Exception e) {
\r
428 return existingTenants;
\r
431 private static void createMissingTenants(Connection conn, Hashtable<String, String> tenantInfo,
\r
432 ArrayList<String> existingTenants) throws SQLException, Exception {
\r
433 // Need to define and look for a createDisabled attribute in tenant config
\r
434 final String insertTenantSQL =
\r
435 "INSERT INTO tenants (id,name,disabled,created_at) VALUES (?,?,FALSE,now())";
\r
436 PreparedStatement pstmt = null;
\r
438 pstmt = conn.prepareStatement(insertTenantSQL); // create a statement
\r
439 for(String tId : tenantInfo.keySet()) {
\r
440 if(existingTenants.contains(tId)) {
\r
441 if (logger.isDebugEnabled()) {
\r
442 logger.debug("createMissingTenants: tenant exists (skipping): "
\r
443 +tenantInfo.get(tId));
\r
447 pstmt.setString(1, tId); // set id param
\r
448 pstmt.setString(2, tenantInfo.get(tId)); // set name param
\r
449 if (logger.isDebugEnabled()) {
\r
450 logger.debug("createMissingTenants adding entry for tenant: "+tId);
\r
452 pstmt.executeUpdate();
\r
455 } catch(Exception e) {
\r
463 private static ArrayList<String> findOrCreateDefaultUsers(Connection conn, Hashtable<String, String> tenantInfo)
\r
464 throws SQLException, Exception {
\r
465 // Second find or create the users
\r
466 Statement stmt = null;
\r
467 PreparedStatement pstmt = null;
\r
468 ArrayList<String> usersInRepo = new ArrayList<String>();
\r
470 stmt = conn.createStatement();
\r
471 ResultSet rs = stmt.executeQuery(QUERY_USERS_SQL);
\r
472 while (rs.next()) {
\r
473 String uName = rs.getString("username");
\r
474 usersInRepo.add(uName);
\r
477 pstmt = conn.prepareStatement(INSERT_USER_SQL); // create a statement
\r
478 for(String tName : tenantInfo.values()) {
\r
479 String adminAcctName = getDefaultAdminUserID(tName);
\r
480 if(!usersInRepo.contains(adminAcctName)) {
\r
481 String secEncPasswd = SecurityUtils.createPasswordHash(
\r
482 adminAcctName, DEFAULT_ADMIN_PASSWORD);
\r
483 pstmt.setString(1, adminAcctName); // set username param
\r
484 pstmt.setString(2, secEncPasswd); // set passwd param
\r
485 if (logger.isDebugEnabled()) {
\r
486 logger.debug("createDefaultUsersAndAccounts adding user: "
\r
487 +adminAcctName+" for tenant: "+tName);
\r
489 pstmt.executeUpdate();
\r
490 } else if (logger.isDebugEnabled()) {
\r
491 logger.debug("createDefaultUsersAndAccounts: user: "+adminAcctName
\r
492 +" already exists - skipping.");
\r
496 String readerAcctName = getDefaultReaderUserID(tName);
\r
497 if(!usersInRepo.contains(readerAcctName)) {
\r
498 String secEncPasswd = SecurityUtils.createPasswordHash(
\r
499 readerAcctName, DEFAULT_READER_PASSWORD);
\r
500 pstmt.setString(1, readerAcctName); // set username param
\r
501 pstmt.setString(2, secEncPasswd); // set passwd param
\r
502 if (logger.isDebugEnabled()) {
\r
503 logger.debug("createDefaultUsersAndAccounts adding user: "
\r
504 +readerAcctName+" for tenant: "+tName);
\r
506 pstmt.executeUpdate();
\r
507 } else if (logger.isDebugEnabled()) {
\r
508 logger.debug("createDefaultUsersAndAccounts: user: "+readerAcctName
\r
509 +" already exists - skipping.");
\r
513 } catch(Exception e) {
\r
521 return usersInRepo;
\r
524 private static void findOrCreateDefaultAccounts(Connection conn, Hashtable<String, String> tenantInfo,
\r
525 ArrayList<String> usersInRepo,
\r
526 Hashtable<String, String> tenantAdminAcctCSIDs, Hashtable<String, String> tenantReaderAcctCSIDs)
\r
527 throws SQLException, Exception {
\r
528 // Third, create the accounts. Assume that if the users were already there,
\r
529 // then the accounts were as well
\r
530 PreparedStatement pstmt = null;
\r
532 pstmt = conn.prepareStatement(INSERT_ACCOUNT_SQL); // create a statement
\r
533 for(String tId : tenantInfo.keySet()) {
\r
534 String tName = tenantInfo.get(tId);
\r
535 String adminCSID = UUID.randomUUID().toString();
\r
536 tenantAdminAcctCSIDs.put(tId, adminCSID);
\r
537 String adminAcctName = getDefaultAdminUserID(tName);
\r
538 if(!usersInRepo.contains(adminAcctName)) {
\r
539 pstmt.setString(1, adminCSID); // set csid param
\r
540 pstmt.setString(2, adminAcctName); // set email param (bogus)
\r
541 pstmt.setString(3, adminAcctName); // set userid param
\r
542 pstmt.setString(4, "Administrator");// set screen name param
\r
543 if (logger.isDebugEnabled()) {
\r
544 logger.debug("createDefaultAccounts adding account: "
\r
545 +adminAcctName+" for tenant: "+tName);
\r
547 pstmt.executeUpdate();
\r
548 } else if (logger.isDebugEnabled()) {
\r
549 logger.debug("createDefaultAccounts: user: "+adminAcctName
\r
550 +" already exists - skipping account generation.");
\r
553 String readerCSID = UUID.randomUUID().toString();
\r
554 tenantReaderAcctCSIDs.put(tId, readerCSID);
\r
555 String readerAcctName = getDefaultReaderUserID(tName);
\r
556 if(!usersInRepo.contains(readerAcctName)) {
\r
557 pstmt.setString(1, readerCSID); // set csid param
\r
558 pstmt.setString(2, readerAcctName); // set email param (bogus)
\r
559 pstmt.setString(3, readerAcctName); // set userid param
\r
560 pstmt.setString(4, "Reader"); // set screen name param
\r
561 if (logger.isDebugEnabled()) {
\r
562 logger.debug("createDefaultAccounts adding account: "
\r
563 +readerAcctName+" for tenant: "+tName);
\r
565 pstmt.executeUpdate();
\r
566 } else if (logger.isDebugEnabled()) {
\r
567 logger.debug("createDefaultAccounts: user: "+readerAcctName
\r
568 +" already exists - skipping account creation.");
\r
572 } catch(Exception e) {
\r
580 private static boolean findOrCreateTenantManagerUserAndAccount(Connection conn)
\r
581 throws SQLException, Exception {
\r
582 // Find or create the special tenant manager account.
\r
583 // Later can make the user name for tenant manager be configurable, settable.
\r
584 Statement stmt = null;
\r
585 PreparedStatement pstmt = null;
\r
586 boolean created = false;
\r
588 boolean foundTMgrUser = false;
\r
589 stmt = conn.createStatement();
\r
590 ResultSet rs = stmt.executeQuery(QUERY_TENANT_MGR_USER_SQL);
\r
591 // Should only find one - only consider it
\r
593 String uName = rs.getString("username");
\r
594 foundTMgrUser = uName.equals(TENANT_MANAGER_USER);
\r
597 if(!foundTMgrUser) {
\r
598 pstmt = conn.prepareStatement(INSERT_USER_SQL); // create a statement
\r
599 String secEncPasswd = SecurityUtils.createPasswordHash(
\r
600 TENANT_MANAGER_USER, DEFAULT_TENANT_MANAGER_PASSWORD);
\r
601 pstmt.setString(1, TENANT_MANAGER_USER); // set username param
\r
602 pstmt.setString(2, secEncPasswd); // set passwd param
\r
603 if (logger.isDebugEnabled()) {
\r
604 logger.debug("findOrCreateTenantManagerUserAndAccount adding tenant manager user: "
\r
605 +TENANT_MANAGER_USER);
\r
607 pstmt.executeUpdate();
\r
609 // Now create the account to match
\r
610 pstmt = conn.prepareStatement(INSERT_ACCOUNT_SQL); // create a statement
\r
611 pstmt.setString(1, AuthN.TENANT_MANAGER_ACCT_ID); // set csid param
\r
612 pstmt.setString(2, DEFAULT_TENANT_MANAGER_EMAIL); // set email param (bogus)
\r
613 pstmt.setString(3, TENANT_MANAGER_USER); // set userid param
\r
614 pstmt.setString(4, TENANT_MANAGER_SCREEN_NAME);// set screen name param
\r
615 if (logger.isDebugEnabled()) {
\r
616 logger.debug("findOrCreateTenantManagerUserAndAccount adding tenant manager account: "
\r
617 +TENANT_MANAGER_USER);
\r
619 pstmt.executeUpdate();
\r
622 } else if (logger.isDebugEnabled()) {
\r
623 logger.debug("findOrCreateTenantManagerUserAndAccount: tenant manager: "+TENANT_MANAGER_USER
\r
624 +" already exists.");
\r
626 } catch(Exception e) {
\r
637 private static void bindDefaultAccountsToTenants(Connection conn, DatabaseProductType databaseProductType,
\r
638 Hashtable<String, String> tenantInfo, ArrayList<String> usersInRepo,
\r
639 Hashtable<String, String> tenantAdminAcctCSIDs, Hashtable<String, String> tenantReaderAcctCSIDs)
\r
640 throws SQLException, Exception {
\r
641 // Fourth, bind accounts to tenants. Assume that if the users were already there,
\r
642 // then the accounts were bound to tenants correctly
\r
643 PreparedStatement pstmt = null;
\r
645 String insertAccountTenantSQL;
\r
646 if (databaseProductType == DatabaseProductType.MYSQL) {
\r
647 insertAccountTenantSQL =
\r
648 "INSERT INTO accounts_tenants (TENANTS_ACCOUNTSCOMMON_CSID,tenant_id) "
\r
650 } else if (databaseProductType == DatabaseProductType.POSTGRESQL) {
\r
651 insertAccountTenantSQL =
\r
652 "INSERT INTO accounts_tenants (HJID, TENANTS_ACCOUNTSCOMMON_CSID,tenant_id) "
\r
653 + " VALUES(nextval('hibernate_sequence'), ?, ?)";
\r
655 throw new Exception("Unrecognized database system.");
\r
657 pstmt = conn.prepareStatement(insertAccountTenantSQL); // create a statement
\r
658 for(String tId : tenantInfo.keySet()) {
\r
659 String tName = tenantInfo.get(tId);
\r
660 if(!usersInRepo.contains(getDefaultAdminUserID(tName))) {
\r
661 String adminAcct = tenantAdminAcctCSIDs.get(tId);
\r
662 pstmt.setString(1, adminAcct); // set acct CSID param
\r
663 pstmt.setString(2, tId); // set tenant_id param
\r
664 if (logger.isDebugEnabled()) {
\r
665 logger.debug("createDefaultAccounts binding account id: "
\r
666 +adminAcct+" to tenant id: "+tId);
\r
668 pstmt.executeUpdate();
\r
670 if(!usersInRepo.contains(getDefaultReaderUserID(tName))) {
\r
671 String readerAcct = tenantReaderAcctCSIDs.get(tId);
\r
672 pstmt.setString(1, readerAcct); // set acct CSID param
\r
673 pstmt.setString(2, tId); // set tenant_id param
\r
674 if (logger.isDebugEnabled()) {
\r
675 logger.debug("createDefaultAccounts binding account id: "
\r
676 +readerAcct+" to tenant id: "+tId);
\r
678 pstmt.executeUpdate();
\r
682 } catch(Exception e) {
\r
691 private static String findOrCreateDefaultRoles(Connection conn, Hashtable<String, String> tenantInfo,
\r
692 Hashtable<String, String> tenantAdminRoleCSIDs, Hashtable<String, String> tenantReaderRoleCSIDs)
\r
693 throws SQLException, Exception {
\r
694 // Fifth, fetch and save the default roles
\r
695 String springAdminRoleCSID = null;
\r
696 Statement stmt = null;
\r
697 PreparedStatement pstmt = null;
\r
699 final String querySpringRole =
\r
700 "SELECT csid from roles WHERE rolename='"+SPRING_ADMIN_ROLE+"'";
\r
701 stmt = conn.createStatement();
\r
702 ResultSet rs = stmt.executeQuery(querySpringRole);
\r
704 springAdminRoleCSID = rs.getString(1);
\r
705 if (logger.isDebugEnabled()) {
\r
706 logger.debug("createDefaultAccounts found Spring Admin role: "
\r
707 +springAdminRoleCSID);
\r
710 final String insertSpringAdminRoleSQL =
\r
711 "INSERT INTO roles (csid, rolename, displayName, rolegroup, created_at, tenant_id) "
\r
712 + "VALUES ('-1', 'ROLE_SPRING_ADMIN', 'SPRING_ADMIN', 'Spring Security Administrator', now(), '0')";
\r
713 stmt.executeUpdate(insertSpringAdminRoleSQL);
\r
714 springAdminRoleCSID = "-1";
\r
715 if (logger.isDebugEnabled()) {
\r
716 logger.debug("createDefaultAccounts CREATED Spring Admin role: "
\r
717 +springAdminRoleCSID);
\r
721 final String getRoleCSIDSql =
\r
722 "SELECT csid from roles WHERE tenant_id=? and rolename=?";
\r
723 pstmt = conn.prepareStatement(getRoleCSIDSql); // create a statement
\r
725 for(String tId : tenantInfo.keySet()) {
\r
726 pstmt.setString(1, tId); // set tenant_id param
\r
727 pstmt.setString(2, getDefaultAdminRole(tId)); // set rolename param
\r
728 rs = pstmt.executeQuery();
\r
729 // extract data from the ResultSet
\r
731 throw new RuntimeException("Cannot find role: "+getDefaultAdminRole(tId)
\r
732 +" for tenant id: "+tId+" in roles!");
\r
734 String tenantAdminRoleCSID = rs.getString(1);
\r
735 if (logger.isDebugEnabled()) {
\r
736 logger.debug("createDefaultAccounts found role: "
\r
737 +getDefaultAdminRole(tId)+"("+tenantAdminRoleCSID
\r
738 +") for tenant id: "+tId);
\r
740 tenantAdminRoleCSIDs.put(tId, tenantAdminRoleCSID);
\r
741 pstmt.setString(1, tId); // set tenant_id param
\r
742 pstmt.setString(2, getDefaultReaderRole(tId)); // set rolename param
\r
744 rs = pstmt.executeQuery();
\r
745 // extract data from the ResultSet
\r
747 throw new RuntimeException("Cannot find role: "+getDefaultReaderRole(tId)
\r
748 +" for tenant id: "+tId+" in roles!");
\r
750 String tenantReaderRoleCSID = rs.getString(1);
\r
751 if (logger.isDebugEnabled()) {
\r
752 logger.debug("createDefaultAccounts found role: "
\r
753 +getDefaultReaderRole(tId)+"("+tenantReaderRoleCSID
\r
754 +") for tenant id: "+tId);
\r
756 tenantReaderRoleCSIDs.put(tId, tenantReaderRoleCSID);
\r
760 } catch(Exception e) {
\r
768 return springAdminRoleCSID;
\r
771 private static String findTenantManagerRole(Connection conn )
\r
772 throws SQLException, RuntimeException, Exception {
\r
773 String tenantMgrRoleCSID = null;
\r
774 PreparedStatement pstmt = null;
\r
776 String rolename = getQualifiedRoleName(ALL_TENANTS_MANAGER_TENANT_ID,
\r
777 ROLE_ALL_TENANTS_MANAGER);
\r
778 pstmt = conn.prepareStatement(GET_TENANT_MGR_ROLE_SQL); // create a statement
\r
779 ResultSet rs = null;
\r
780 pstmt.setString(1, rolename); // set rolename param
\r
781 rs = pstmt.executeQuery();
\r
783 tenantMgrRoleCSID = rs.getString(1);
\r
784 if (logger.isDebugEnabled()) {
\r
785 logger.debug("findTenantManagerRole found Tenant Mgr role: "
\r
786 +tenantMgrRoleCSID);
\r
790 } catch(Exception e) {
\r
796 if(tenantMgrRoleCSID==null)
\r
797 throw new RuntimeException("findTenantManagerRole: Cound not find tenant Manager Role!");
\r
798 return tenantMgrRoleCSID;
\r
801 private static void bindAccountsToRoles(Connection conn, DatabaseProductType databaseProductType,
\r
802 Hashtable<String, String> tenantInfo, ArrayList<String> usersInRepo,
\r
803 String springAdminRoleCSID,
\r
804 Hashtable<String, String> tenantAdminRoleCSIDs, Hashtable<String, String> tenantReaderRoleCSIDs,
\r
805 Hashtable<String, String> tenantAdminAcctCSIDs, Hashtable<String, String> tenantReaderAcctCSIDs)
\r
806 throws SQLException, Exception {
\r
807 // Sixth, bind the accounts to roles. If the users already existed,
\r
808 // we'll assume they were set up correctly.
\r
809 PreparedStatement pstmt = null;
\r
811 String insertAccountRoleSQL;
\r
812 if (databaseProductType == DatabaseProductType.MYSQL) {
\r
813 insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_MYSQL;
\r
814 } else if (databaseProductType == DatabaseProductType.POSTGRESQL) {
\r
815 insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_POSTGRES;
\r
817 throw new Exception("Unrecognized database system.");
\r
819 if (logger.isDebugEnabled()) {
\r
820 logger.debug("createDefaultAccounts binding accounts to roles with SQL:\n"
\r
821 +insertAccountRoleSQL);
\r
823 pstmt = conn.prepareStatement(insertAccountRoleSQL); // create a statement
\r
824 for(String tId : tenantInfo.keySet()) {
\r
825 String adminUserId = getDefaultAdminUserID(tenantInfo.get(tId));
\r
826 if(!usersInRepo.contains(adminUserId)) {
\r
827 String adminAcct = tenantAdminAcctCSIDs.get(tId);
\r
828 String adminRoleId = tenantAdminRoleCSIDs.get(tId);
\r
829 pstmt.setString(1, adminAcct); // set acct CSID param
\r
830 pstmt.setString(2, adminUserId); // set user_id param
\r
831 pstmt.setString(3, adminRoleId); // set role_id param
\r
832 pstmt.setString(4, getDefaultAdminRole(tId)); // set rolename param
\r
833 if (logger.isDebugEnabled()) {
\r
834 logger.debug("createDefaultAccounts binding account: "
\r
835 +adminUserId+" to Admin role("+adminRoleId
\r
836 +") for tenant id: "+tId);
\r
838 pstmt.executeUpdate();
\r
839 // Now add the Spring Admin Role to the admin accounts
\r
840 pstmt.setString(3, springAdminRoleCSID); // set role_id param
\r
841 pstmt.setString(4, SPRING_ADMIN_ROLE); // set rolename param
\r
842 if (logger.isDebugEnabled()) {
\r
843 logger.debug("createDefaultAccounts binding account: "
\r
844 +adminUserId+" to Spring Admin role: "+springAdminRoleCSID);
\r
846 pstmt.executeUpdate();
\r
848 String readerUserId = getDefaultReaderUserID(tenantInfo.get(tId));
\r
849 if(!usersInRepo.contains(readerUserId)) {
\r
850 String readerAcct = tenantReaderAcctCSIDs.get(tId);
\r
851 String readerRoleId = tenantReaderRoleCSIDs.get(tId);
\r
852 pstmt.setString(1, readerAcct); // set acct CSID param
\r
853 pstmt.setString(2, readerUserId); // set user_id param
\r
854 pstmt.setString(3, readerRoleId); // set role_id param
\r
855 pstmt.setString(4, getDefaultReaderRole(tId)); // set rolename param
\r
856 if (logger.isDebugEnabled()) {
\r
857 logger.debug("createDefaultAccounts binding account: "
\r
858 +readerUserId+" to Reader role("+readerRoleId
\r
859 +") for tenant id: "+tId);
\r
861 pstmt.executeUpdate();
\r
865 } catch(Exception e) {
\r
873 private static void bindTenantManagerAccountRole(Connection conn, DatabaseProductType databaseProductType,
\r
874 String tenantManagerUserID, String tenantManagerAccountID, String tenantManagerRoleID, String tenantManagerRoleName )
\r
875 throws SQLException, Exception {
\r
876 PreparedStatement pstmt = null;
\r
878 String insertAccountRoleSQL;
\r
879 if (databaseProductType == DatabaseProductType.MYSQL) {
\r
880 insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_MYSQL;
\r
881 } else if (databaseProductType == DatabaseProductType.POSTGRESQL) {
\r
882 insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_POSTGRES;
\r
884 throw new Exception("Unrecognized database system.");
\r
886 if (logger.isDebugEnabled()) {
\r
887 logger.debug("bindTenantManagerAccountRole binding account to role with SQL:\n"
\r
888 +insertAccountRoleSQL);
\r
890 pstmt = conn.prepareStatement(insertAccountRoleSQL); // create a statement
\r
891 pstmt.setString(1, tenantManagerAccountID); // set acct CSID param
\r
892 pstmt.setString(2, tenantManagerUserID); // set user_id param
\r
893 pstmt.setString(3, tenantManagerRoleID); // set role_id param
\r
894 pstmt.setString(4, tenantManagerRoleName); // set rolename param
\r
895 if (logger.isDebugEnabled()) {
\r
896 logger.debug("bindTenantManagerAccountRole binding user: "
\r
897 +tenantManagerUserID+" to Admin role("+tenantManagerRoleName+")");
\r
899 pstmt.executeUpdate();
\r
900 /* At this point, tenant manager should not need the Spring Admin Role
\r
901 pstmt.setString(3, springAdminRoleCSID); // set role_id param
\r
902 pstmt.setString(4, SPRING_ADMIN_ROLE); // set rolename param
\r
903 if (logger.isDebugEnabled()) {
\r
904 logger.debug("createDefaultAccounts binding account: "
\r
905 +adminUserId+" to Spring Admin role: "+springAdminRoleCSID);
\r
907 pstmt.executeUpdate();
\r
910 } catch(Exception e) {
\r
918 public static void createDefaultAccounts(TenantBindingConfigReaderImpl tenantBindingConfigReader) {
\r
919 if (logger.isDebugEnabled()) {
\r
920 logger.debug("ServiceMain.createDefaultAccounts starting...");
\r
923 Hashtable<String, String> tenantInfo = getTenantNamesFromConfig(tenantBindingConfigReader);
\r
925 Connection conn = null;
\r
926 // TODO - need to put in tests for existence first.
\r
927 // We could just look for the accounts per tenant up front, and assume that
\r
928 // the rest is there if the accounts are.
\r
929 // Could add a sql script to remove these if need be - Spring only does roles,
\r
930 // and we're not touching that, so we could safely toss the
\r
931 // accounts, users, account-tenants, account-roles, and start over.
\r
933 DatabaseProductType databaseProductType = JDBCTools.getDatabaseProductType(JDBCTools.CSPACE_DATASOURCE_NAME,
\r
934 JDBCTools.DEFAULT_CSPACE_DATABASE_NAME);
\r
935 conn = getConnection();
\r
936 ArrayList<String> existingTenants = compileExistingTenants(conn, tenantInfo);
\r
938 // Note that this only creates tenants not marked as "createDisabled"
\r
939 createMissingTenants(conn, tenantInfo, existingTenants);
\r
941 ArrayList<String> usersInRepo = findOrCreateDefaultUsers(conn, tenantInfo);
\r
943 Hashtable<String, String> tenantAdminAcctCSIDs = new Hashtable<String, String>();
\r
944 Hashtable<String, String> tenantReaderAcctCSIDs = new Hashtable<String, String>();
\r
945 findOrCreateDefaultAccounts(conn, tenantInfo, usersInRepo,
\r
946 tenantAdminAcctCSIDs, tenantReaderAcctCSIDs);
\r
948 bindDefaultAccountsToTenants(conn, databaseProductType, tenantInfo, usersInRepo,
\r
949 tenantAdminAcctCSIDs, tenantReaderAcctCSIDs);
\r
951 Hashtable<String, String> tenantAdminRoleCSIDs = new Hashtable<String, String>();
\r
952 Hashtable<String, String> tenantReaderRoleCSIDs = new Hashtable<String, String>();
\r
953 String springAdminRoleCSID = findOrCreateDefaultRoles(conn, tenantInfo,
\r
954 tenantAdminRoleCSIDs, tenantReaderRoleCSIDs);
\r
956 bindAccountsToRoles(conn, databaseProductType,
\r
957 tenantInfo, usersInRepo, springAdminRoleCSID,
\r
958 tenantAdminRoleCSIDs, tenantReaderRoleCSIDs,
\r
959 tenantAdminAcctCSIDs, tenantReaderAcctCSIDs);
\r
961 boolean createdTenantMgrAccount = findOrCreateTenantManagerUserAndAccount(conn);
\r
962 if(createdTenantMgrAccount) {
\r
963 // If we created the account, we need to create the bindings. Otherwise, assume they
\r
964 // are all set (from previous initialization).
\r
965 String tenantManagerRoleCSID = findTenantManagerRole(conn);
\r
966 bindTenantManagerAccountRole(conn, databaseProductType,
\r
967 TENANT_MANAGER_USER, AuthN.TENANT_MANAGER_ACCT_ID,
\r
968 tenantManagerRoleCSID, ROLE_ALL_TENANTS_MANAGER);
\r
970 } catch (RuntimeException rte) {
\r
971 if (logger.isDebugEnabled()) {
\r
972 logger.debug("Exception in createDefaultAccounts: "+
\r
973 rte.getLocalizedMessage());
\r
974 logger.debug(rte.getStackTrace().toString());
\r
977 } catch (SQLException sqle) {
\r
978 // SQLExceptions can be chained. We have at least one exception, so
\r
979 // set up a loop to make sure we let the user know about all of them
\r
980 // if there happens to be more than one.
\r
981 if (logger.isDebugEnabled()) {
\r
982 SQLException tempException = sqle;
\r
983 while (null != tempException) {
\r
984 logger.debug("SQL Exception: " + sqle.getLocalizedMessage());
\r
985 tempException = tempException.getNextException();
\r
987 logger.debug(sqle.getStackTrace().toString());
\r
989 throw new RuntimeException("SQL problem in createDefaultAccounts: ", sqle);
\r
990 } catch (Exception e) {
\r
991 if (logger.isDebugEnabled()) {
\r
992 logger.debug("Exception in createDefaultAccounts: "+
\r
993 e.getLocalizedMessage());
\r
999 } catch (SQLException sqle) {
\r
1000 if (logger.isDebugEnabled()) {
\r
1001 logger.debug("SQL Exception closing statement/connection: "
\r
1002 + sqle.getLocalizedMessage());
\r
1008 private static String getDefaultAdminRole(String tenantId) {
\r
1009 return ROLE_PREFIX+tenantId+TENANT_ADMIN_ROLE_SUFFIX;
\r
1012 private static String getDefaultReaderRole(String tenantId) {
\r
1013 return ROLE_PREFIX+tenantId+TENANT_READER_ROLE_SUFFIX;
\r
1016 private static String getDefaultAdminUserID(String tenantName) {
\r
1017 return TENANT_ADMIN_ACCT_PREFIX+tenantName;
\r
1020 private static String getDefaultReaderUserID(String tenantName) {
\r
1021 return TENANT_READER_ACCT_PREFIX+tenantName;
\r
1024 static public PermissionAction createPermissionAction(Permission perm,
\r
1025 ActionType actionType) {
\r
1026 PermissionAction pa = new PermissionAction();
\r
1028 CSpaceAction action = URIResourceImpl.getAction(actionType);
\r
1029 URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(),
\r
1030 perm.getResourceName(), action);
\r
1031 pa.setName(actionType);
\r
1032 pa.setObjectIdentity(uriRes.getHashedId().toString());
\r
1033 pa.setObjectIdentityResource(uriRes.getId());
\r
1038 static public PermissionAction update(Permission perm, PermissionAction permAction) {
\r
1039 PermissionAction pa = new PermissionAction();
\r
1041 CSpaceAction action = URIResourceImpl.getAction(permAction.getName());
\r
1042 URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(),
\r
1043 perm.getResourceName(), action);
\r
1044 pa.setObjectIdentity(uriRes.getHashedId().toString());
\r
1045 pa.setObjectIdentityResource(uriRes.getId());
\r
1050 private static TransitionDefList getTransitionDefList(TenantBindingType tenantBinding, ServiceBindingType serviceBinding) {
\r
1051 TransitionDefList result = null;
\r
1053 String serviceObjectName = serviceBinding.getObject().getName();
\r
1054 DocumentHandler docHandler = ServiceConfigUtils.createDocumentHandlerInstance(
\r
1055 tenantBinding, serviceBinding);
\r
1056 Lifecycle lifecycle = docHandler.getLifecycle(serviceObjectName);
\r
1057 if (lifecycle != null) {
\r
1058 result = lifecycle.getTransitionDefList();
\r
1060 } catch (Exception e) {
\r
1061 // Ignore this exception and return an empty non-null TransitionDefList
\r
1064 if (result == null) {
\r
1065 logger.warn("Could not retrieve a lifecycle transition definition list from: "
\r
1066 + serviceBinding.getName()
\r
1067 + " with tenant ID = "
\r
1068 + tenantBinding.getId());
\r
1069 // return an empty list
\r
1070 result = new TransitionDefList();
\r
1072 logger.debug("Successfully etrieved a lifecycle transition definition list from: "
\r
1073 + serviceBinding.getName()
\r
1074 + " with tenant ID = "
\r
1075 + tenantBinding.getId());
\r
1081 public static void createDefaultWorkflowPermissions(TenantBindingConfigReaderImpl tenantBindingConfigReader) throws Exception //FIXME: REM - 4/11/2012 - Rename to createWorkflowPermissions
\r
1083 AuthZ.get().login(); //login to Spring Security manager
\r
1085 EntityManagerFactory emf = JpaStorageUtils.getEntityManagerFactory(JpaStorageUtils.CS_PERSISTENCE_UNIT);
\r
1086 EntityManager em = null;
\r
1089 em = emf.createEntityManager();
\r
1091 Hashtable<String, TenantBindingType> tenantBindings =
\r
1092 tenantBindingConfigReader.getTenantBindings();
\r
1093 for (String tenantId : tenantBindings.keySet()) {
\r
1094 TenantBindingType tenantBinding = tenantBindings.get(tenantId);
\r
1095 Role adminRole = AuthorizationCommon.getRole(em, tenantBinding.getId(), ROLE_TENANT_ADMINISTRATOR);
\r
1096 Role readonlyRole = AuthorizationCommon.getRole(em, tenantBinding.getId(), ROLE_TENANT_READER);
\r
1097 for (ServiceBindingType serviceBinding : tenantBinding.getServiceBindings()) {
\r
1098 String prop = ServiceBindingUtils.getPropertyValue(serviceBinding, REFRESH_AUTZ_PROP);
\r
1099 if (prop == null ? true : Boolean.parseBoolean(prop)) {
\r
1101 em.getTransaction().begin();
\r
1102 TransitionDefList transitionDefList = getTransitionDefList(tenantBinding, serviceBinding);
\r
1103 for (TransitionDef transitionDef : transitionDefList.getTransitionDef()) {
\r
1105 // Create the permission for the admin role
\r
1106 Permission adminPerm = createWorkflowPermission(tenantBinding, serviceBinding, transitionDef, ACTIONGROUP_CRUDL);
\r
1107 persist(em, adminPerm, adminRole, true);
\r
1109 // Create the permission for the read-only role
\r
1110 Permission readonlyPerm = createWorkflowPermission(tenantBinding, serviceBinding, transitionDef, ACTIONGROUP_RL);
\r
1112 Profiler profiler = new Profiler(AuthorizationCommon.class, 1);
\r
1113 profiler.start("createDefaultPermissions started:" + readonlyPerm.getCsid());
\r
1114 persist(em, readonlyPerm, readonlyRole, true); // Persist/store the permission and permrole records and related Spring Security info
\r
1116 logger.debug("Finished full perm generation for "
\r
1117 + ":" + tenantBinding.getId()
\r
1118 + ":" + serviceBinding.getName()
\r
1119 + ":" + transitionDef.getName()
\r
1120 + ":" + ACTIONGROUP_RL
\r
1121 + ":" + profiler.getCumulativeTime());
\r
1123 em.getTransaction().commit();
\r
1124 } catch (IllegalStateException e) {
\r
1125 logger.debug(e.getLocalizedMessage(), e); //We end up here if there is no document handler for the service -this is ok for some of the services.
\r
1128 logger.warn("AuthZ refresh service binding property is set to FALSE so default permissions will NOT be refreshed for: "
\r
1129 + serviceBinding.getName());
\r
1134 } catch (Exception e) {
\r
1135 if (em != null && em.getTransaction().isActive()) {
\r
1136 em.getTransaction().rollback();
\r
1138 if (logger.isDebugEnabled()) {
\r
1139 logger.debug("Caught exception and rolling back permission creation: ", e);
\r
1144 JpaStorageUtils.releaseEntityManagerFactory(emf);
\r
1149 private static PermissionRoleRel findPermRoleRel(EntityManager em, String permissionId, String RoleId) {
\r
1150 PermissionRoleRel result = null;
\r
1153 String whereClause = "where permissionId = :id and roleId = :roleId";
\r
1154 HashMap<String, Object> params = new HashMap<String, Object>();
\r
1155 params.put("id", permissionId);
\r
1156 params.put("roleId", RoleId);
\r
1158 result = (PermissionRoleRel) JpaStorageUtils.getEntity(em,
\r
1159 PermissionRoleRel.class.getCanonicalName(), whereClause, params);
\r
1160 } catch (Exception e) {
\r
1161 //Do nothing. Will return null;
\r
1168 * Persists the Permission, PermissionRoleRel, and Spring Security table entries all in one transaction
\r
1170 private static void persist(EntityManager em, Permission permission, Role role, boolean enforceTenancy) throws Exception {
\r
1171 AuthorizationStore authzStore = new AuthorizationStore();
\r
1172 // First persist the Permission record
\r
1173 authzStore.store(em, permission);
\r
1175 // If the PermRoleRel doesn't already exists then relate the permission and the role in a new PermissionRole (the service payload)
\r
1176 // Create a PermissionRoleRel (the database relation table for the permission and role)
\r
1177 PermissionRoleRel permRoleRel = findPermRoleRel(em, permission.getCsid(), role.getCsid());
\r
1178 if (permRoleRel == null) {
\r
1179 PermissionRole permRole = createPermissionRole(em, permission, role, enforceTenancy);
\r
1180 List<PermissionRoleRel> permRoleRels = new ArrayList<PermissionRoleRel>();
\r
1181 PermissionRoleUtil.buildPermissionRoleRel(em, permRole, SubjectType.ROLE, permRoleRels, false /*not for delete*/);
\r
1182 for (PermissionRoleRel prr : permRoleRels) {
\r
1183 authzStore.store(em, prr);
\r
1185 Profiler profiler = new Profiler(AuthorizationCommon.class, 2);
\r
1187 // Add a corresponding entry in the Spring Security Tables
\r
1188 addPermissionsForUri(permission, permRole);
\r
1190 logger.debug("Finished full perm generation for "
\r
1191 + ":" + permission.getTenantId()
\r
1192 + ":" + permission.getResourceName()
\r
1193 + ":" + ACTIONGROUP_RL
\r
1194 + ":" + profiler.getCumulativeTime());
\r