2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.authorization.driver;
27 import java.util.ArrayList;
28 import java.util.HashSet;
29 import java.util.List;
30 import org.collectionspace.services.authorization.AuthZ;
31 import org.collectionspace.services.authorization.perms.Permission;
32 import org.collectionspace.services.authorization.PermissionRole;
33 import org.collectionspace.services.authorization.PermissionRoleRel;
34 import org.collectionspace.services.authorization.Role;
35 import org.collectionspace.services.authorization.SubjectType;
36 import org.collectionspace.services.authorization.importer.AuthorizationGen;
37 import org.collectionspace.services.authorization.importer.AuthorizationSeed;
38 import org.collectionspace.services.authorization.importer.AuthorizationStore;
39 import org.collectionspace.services.authorization.storage.PermissionRoleUtil;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.context.support.ClassPathXmlApplicationContext;
43 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
44 import org.springframework.security.core.Authentication;
45 import org.springframework.security.core.GrantedAuthority;
46 import org.springframework.security.core.authority.GrantedAuthorityImpl;
47 import org.springframework.security.core.context.SecurityContextHolder;
48 import org.springframework.transaction.TransactionDefinition;
49 import org.springframework.transaction.TransactionStatus;
50 import org.springframework.transaction.support.DefaultTransactionDefinition;
53 * A driver for seeding authorization
56 public class AuthorizationSeedDriver {
58 final Logger logger = LoggerFactory.getLogger(AuthorizationSeedDriver.class);
59 final static private String SPRING_SECURITY_METADATA = "applicationContext-authorization-test.xml";
60 final static private String ROLE_FILE = "import-roles.xml";
61 final static private String PERMISSION_FILE = "import-permissions.xml";
62 final static private String PERMISSION_ROLE_FILE = "import-permissions-roles.xml";
64 private String password;
65 private String tenantBindingFile;
66 private String exportDir;
67 private AuthorizationGen authzGen;
68 private org.springframework.jdbc.datasource.DataSourceTransactionManager txManager;
71 * AuthorizationSeedDriver
72 * @param user to use to establish security context. should be in ROLE_ADMINISTRATOR
74 * @param tenantBindingFile
75 * @param importDir dir to import permisison/permission role file from. same as
76 * export dir by default
77 * @param exportDir dir to export permission/permission role file to
79 public AuthorizationSeedDriver(String user, String password,
80 String tenantBindingFile,
82 if (user == null || user.isEmpty()) {
83 throw new IllegalArgumentException("username required.");
87 if (password == null || password.isEmpty()) {
88 throw new IllegalArgumentException("password required.");
90 this.password = password;
92 if (tenantBindingFile == null || tenantBindingFile.isEmpty()) {
93 throw new IllegalArgumentException("tenantbinding file are required.");
95 this.tenantBindingFile = tenantBindingFile;
96 if (exportDir == null || exportDir.isEmpty()) {
97 throw new IllegalArgumentException("exportdir required.");
99 this.exportDir = exportDir;
103 public void generate() {
105 authzGen = new AuthorizationGen();
106 authzGen.initialize(tenantBindingFile);
107 authzGen.createDefaultRoles();
108 authzGen.createDefaultPermissions();
109 authzGen.associateDefaultPermissionsRoles();
110 authzGen.exportDefaultRoles(exportDir + File.separator + ROLE_FILE);
111 authzGen.exportDefaultPermissions(exportDir + File.separator + PERMISSION_FILE);
112 authzGen.exportDefaultPermissionRoles(exportDir + File.separator + PERMISSION_ROLE_FILE);
113 if (logger.isDebugEnabled()) {
114 logger.debug("Authorization generation completed but not yet persisted.");
116 } catch (Exception ex) {
117 logger.error("AuthorizationSeedDriver caught an exception: ", ex);
118 throw new RuntimeException(ex);
123 TransactionStatus status = null;
125 // Push all the authz info into the cspace DB tables.
129 status = beginTransaction("seedData");
130 AuthorizationSeed authzSeed = new AuthorizationSeed();
131 authzSeed.seedPermissions(exportDir + File.separator + PERMISSION_FILE,
132 exportDir + File.separator + PERMISSION_ROLE_FILE);
133 if (logger.isDebugEnabled()) {
134 logger.debug("authorization seeding completed ");
136 } catch (Exception ex) {
137 if (status != null) {
138 rollbackTransaction(status);
140 if (logger.isDebugEnabled()) {
141 ex.printStackTrace();
143 throw new RuntimeException(ex);
145 if (status != null) {
146 commitTransaction(status);
152 private void setupSpring() {
154 ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
155 new String[]{SPRING_SECURITY_METADATA});
157 System.setProperty("spring-beans-config", SPRING_SECURITY_METADATA);
158 // authZ local not used but call to AuthZ.get() has side-effect of initializing our Spring Security context
159 AuthZ authZ = AuthZ.get();
160 txManager = (org.springframework.jdbc.datasource.DataSourceTransactionManager) appContext.getBean("transactionManager");
161 if (logger.isDebugEnabled()) {
162 logger.debug("Spring Security setup complete.");
166 private void login() {
167 //GrantedAuthority cspace_admin = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR");
168 GrantedAuthority spring_security_admin = new GrantedAuthorityImpl("ROLE_SPRING_ADMIN");
169 HashSet<GrantedAuthority> gauths = new HashSet<GrantedAuthority>();
170 //gauths.add(cspace_admin);
171 gauths.add(spring_security_admin);
172 Authentication authRequest = new UsernamePasswordAuthenticationToken(user, password, gauths);
173 SecurityContextHolder.getContext().setAuthentication(authRequest);
174 if (logger.isDebugEnabled()) {
175 logger.debug("Spring Security login successful for user=" + user);
179 private void logout() {
180 SecurityContextHolder.getContext().setAuthentication(null);
181 if (logger.isDebugEnabled()) {
182 logger.debug("Spring Security logged out user=" + user);
186 private void store() throws Exception {
187 AuthorizationStore authzStore = new AuthorizationStore();
188 for (Role role : authzGen.getDefaultRoles()) {
189 authzStore.store(role);
192 for (Permission perm : authzGen.getDefaultPermissions()) {
193 authzStore.store(perm);
196 List<PermissionRoleRel> permRoleRels = new ArrayList<PermissionRoleRel>();
197 for (PermissionRole pr : authzGen.getDefaultPermissionRoles()) {
198 PermissionRoleUtil.buildPermissionRoleRel(pr, SubjectType.ROLE, permRoleRels, false /*not for delete*/);
200 for (PermissionRoleRel permRoleRel : permRoleRels) {
201 authzStore.store(permRoleRel);
204 if (logger.isInfoEnabled()) {
205 logger.info("Authroization metata persisted.");
209 private TransactionStatus beginTransaction(String name) {
210 DefaultTransactionDefinition def = new DefaultTransactionDefinition();
211 // explicitly setting the transaction name is something that can only be done programmatically
213 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
214 return txManager.getTransaction(def);
217 private void rollbackTransaction(TransactionStatus status) {
218 txManager.rollback(status);
221 private void commitTransaction(TransactionStatus status) {
222 txManager.commit(status);