]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
bf84ab4867095b89dfe0c9098fc51390fc8c107c
[tmp/jakarta-migration.git] /
1 /**
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:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
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.
23  */
24 package org.collectionspace.services.authorization.driver;
25
26 import java.io.File;
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.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;
51
52 /**
53  * A driver for seeding authorization
54  * @author 
55  */
56 public class AuthorizationSeedDriver {
57
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";
63     private String user;
64     private String password;
65     private String tenantBindingFile;
66     private String exportDir;
67     private AuthorizationGen authzGen;
68     private org.springframework.jdbc.datasource.DataSourceTransactionManager txManager;
69
70     /**
71      * AuthorizationSeedDriver
72      * @param user to use to establish security context. should be in ROLE_ADMINISTRATOR
73      * @param password
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
78      */
79     public AuthorizationSeedDriver(String user, String password,
80             String tenantBindingFile,
81             String exportDir) {
82         if (user == null || user.isEmpty()) {
83             throw new IllegalArgumentException("username required.");
84         }
85         this.user = user;
86
87         if (password == null || password.isEmpty()) {
88             throw new IllegalArgumentException("password required.");
89         }
90         this.password = password;
91         
92         if (tenantBindingFile == null || tenantBindingFile.isEmpty()) {
93             throw new IllegalArgumentException("tenantbinding file are required.");
94         }
95         this.tenantBindingFile = tenantBindingFile;
96         if (exportDir == null || exportDir.isEmpty()) {
97             throw new IllegalArgumentException("exportdir required.");
98         }
99         this.exportDir = exportDir;
100
101     }
102
103     public void generate() {
104         try {
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("authroization generation completed ");
115             }
116         } catch (Exception ex) {
117             if (logger.isDebugEnabled()) {
118                 ex.printStackTrace();
119             }
120             throw new RuntimeException(ex);
121         }
122     }
123
124     public void seed() {
125         TransactionStatus status = null;
126         try {
127             store();
128
129             setupSpring();
130             status = beginTransaction("seedData");
131             AuthorizationSeed authzSeed = new AuthorizationSeed();
132             authzSeed.seedPermissions(exportDir + File.separator + PERMISSION_FILE,
133                     exportDir + File.separator + PERMISSION_ROLE_FILE);
134             if (logger.isDebugEnabled()) {
135                 logger.debug("authorization seeding completed ");
136             }
137         } catch (Exception ex) {
138             if (status != null) {
139                 rollbackTransaction(status);
140             }
141             if (logger.isDebugEnabled()) {
142                 ex.printStackTrace();
143             }
144             throw new RuntimeException(ex);
145         } finally {
146             if (status != null) {
147                 commitTransaction(status);
148             }
149             logout();
150         }
151     }
152
153     private void setupSpring() {
154
155         ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
156                 new String[]{SPRING_SECURITY_METADATA});
157         login();
158         System.setProperty("spring-beans-config", SPRING_SECURITY_METADATA);
159         AuthZ authZ = AuthZ.get();
160         txManager = (org.springframework.jdbc.datasource.DataSourceTransactionManager) appContext.getBean("transactionManager");
161         if (logger.isDebugEnabled()) {
162             logger.debug("spring setup complete");
163         }
164     }
165
166     private void login() {
167         GrantedAuthority gauth = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR");
168         HashSet<GrantedAuthority> gauths = new HashSet<GrantedAuthority>();
169         gauths.add(gauth);
170         Authentication authRequest = new UsernamePasswordAuthenticationToken(user, password, gauths);
171         SecurityContextHolder.getContext().setAuthentication(authRequest);
172         if (logger.isDebugEnabled()) {
173             logger.debug("login successful for user=" + user);
174         }
175     }
176
177     private void logout() {
178         SecurityContextHolder.getContext().setAuthentication(null);
179         if (logger.isDebugEnabled()) {
180             logger.debug("logged out user=" + user);
181         }
182     }
183
184     private void store() throws Exception {
185         AuthorizationStore authzStore = new AuthorizationStore();
186         for (Role role : authzGen.getDefaultRoles()) {
187             authzStore.store(role);
188         }
189
190         for (Permission perm : authzGen.getDefaultPermissions()) {
191             authzStore.store(perm);
192         }
193
194         List<PermissionRoleRel> permRoleRels = new ArrayList<PermissionRoleRel>();
195         for (PermissionRole pr : authzGen.getDefaultPermissionRoles()) {
196             PermissionRoleUtil.buildPermissionRoleRel(pr, SubjectType.ROLE, permRoleRels, false /*not for delete*/);
197         }
198         for (PermissionRoleRel permRoleRel : permRoleRels) {
199             authzStore.store(permRoleRel);
200         }
201
202         if (logger.isDebugEnabled()) {
203             logger.debug("authroization storage completed ");
204         }
205
206     }
207
208     private TransactionStatus beginTransaction(String name) {
209         DefaultTransactionDefinition def = new DefaultTransactionDefinition();
210         // explicitly setting the transaction name is something that can only be done programmatically
211         def.setName(name);
212         def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
213         return txManager.getTransaction(def);
214     }
215
216     private void rollbackTransaction(TransactionStatus status) {
217         txManager.rollback(status);
218     }
219
220     private void commitTransaction(TransactionStatus status) {
221         txManager.commit(status);
222     }
223 }