DataSourcePopulator.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
  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 at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * 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 and
  14. * limitations under the License.
  15. */
  16. package sample.contact;
  17. import java.util.Random;
  18. import javax.sql.DataSource;
  19. import org.springframework.beans.factory.InitializingBean;
  20. import org.springframework.jdbc.core.JdbcTemplate;
  21. import org.springframework.security.acls.domain.AclImpl;
  22. import org.springframework.security.acls.domain.BasePermission;
  23. import org.springframework.security.acls.domain.ObjectIdentityImpl;
  24. import org.springframework.security.acls.domain.PrincipalSid;
  25. import org.springframework.security.acls.model.MutableAcl;
  26. import org.springframework.security.acls.model.MutableAclService;
  27. import org.springframework.security.acls.model.ObjectIdentity;
  28. import org.springframework.security.acls.model.Permission;
  29. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  30. import org.springframework.security.core.Authentication;
  31. import org.springframework.security.core.authority.AuthorityUtils;
  32. import org.springframework.security.core.context.SecurityContextHolder;
  33. import org.springframework.transaction.PlatformTransactionManager;
  34. import org.springframework.transaction.TransactionStatus;
  35. import org.springframework.transaction.support.TransactionCallback;
  36. import org.springframework.transaction.support.TransactionTemplate;
  37. import org.springframework.util.Assert;
  38. /**
  39. * Populates the Contacts in-memory database with contact and ACL information.
  40. *
  41. * @author Ben Alex
  42. */
  43. public class DataSourcePopulator implements InitializingBean {
  44. // ~ Instance fields
  45. // ================================================================================================
  46. JdbcTemplate template;
  47. private MutableAclService mutableAclService;
  48. final Random rnd = new Random();
  49. TransactionTemplate tt;
  50. final String[] firstNames = { "Bob", "Mary", "James", "Jane", "Kristy", "Kirsty",
  51. "Kate", "Jeni", "Angela", "Melanie", "Kent", "William", "Geoff", "Jeff",
  52. "Adrian", "Amanda", "Lisa", "Elizabeth", "Prue", "Richard", "Darin",
  53. "Phillip", "Michael", "Belinda", "Samantha", "Brian", "Greg", "Matthew" };
  54. final String[] lastNames = { "Smith", "Williams", "Jackson", "Rictor", "Nelson",
  55. "Fitzgerald", "McAlpine", "Sutherland", "Abbott", "Hall", "Edwards", "Gates",
  56. "Black", "Brown", "Gray", "Marwell", "Booch", "Johnson", "McTaggart",
  57. "Parklin", "Findlay", "Robinson", "Giugni", "Lang", "Chi", "Carmichael" };
  58. private int createEntities = 50;
  59. // ~ Methods
  60. // ========================================================================================================
  61. public void afterPropertiesSet() throws Exception {
  62. Assert.notNull(mutableAclService, "mutableAclService required");
  63. Assert.notNull(template, "dataSource required");
  64. Assert.notNull(tt, "platformTransactionManager required");
  65. // Set a user account that will initially own all the created data
  66. Authentication authRequest = new UsernamePasswordAuthenticationToken("rod",
  67. "koala", AuthorityUtils.createAuthorityList("ROLE_IGNORED"));
  68. SecurityContextHolder.getContext().setAuthentication(authRequest);
  69. try {
  70. template.execute("DROP TABLE CONTACTS");
  71. template.execute("DROP TABLE AUTHORITIES");
  72. template.execute("DROP TABLE USERS");
  73. template.execute("DROP TABLE ACL_ENTRY");
  74. template.execute("DROP TABLE ACL_OBJECT_IDENTITY");
  75. template.execute("DROP TABLE ACL_CLASS");
  76. template.execute("DROP TABLE ACL_SID");
  77. }
  78. catch (Exception e) {
  79. System.out.println("Failed to drop tables: " + e.getMessage());
  80. }
  81. template.execute("CREATE TABLE ACL_SID("
  82. + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
  83. + "PRINCIPAL BOOLEAN NOT NULL," + "SID VARCHAR_IGNORECASE(100) NOT NULL,"
  84. + "CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));");
  85. template.execute("CREATE TABLE ACL_CLASS("
  86. + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
  87. + "CLASS VARCHAR_IGNORECASE(100) NOT NULL,"
  88. + "CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));");
  89. template.execute("CREATE TABLE ACL_OBJECT_IDENTITY("
  90. + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
  91. + "OBJECT_ID_CLASS BIGINT NOT NULL,"
  92. + "OBJECT_ID_IDENTITY BIGINT NOT NULL,"
  93. + "PARENT_OBJECT BIGINT,"
  94. + "OWNER_SID BIGINT,"
  95. + "ENTRIES_INHERITING BOOLEAN NOT NULL,"
  96. + "CONSTRAINT UNIQUE_UK_3 UNIQUE(OBJECT_ID_CLASS,OBJECT_ID_IDENTITY),"
  97. + "CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID),"
  98. + "CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID),"
  99. + "CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));");
  100. template.execute("CREATE TABLE ACL_ENTRY("
  101. + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
  102. + "ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL,"
  103. + "MASK INTEGER NOT NULL,GRANTING BOOLEAN NOT NULL,AUDIT_SUCCESS BOOLEAN NOT NULL,"
  104. + "AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER),"
  105. + "CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID),"
  106. + "CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));");
  107. template.execute("CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL);");
  108. template.execute("CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));");
  109. template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);");
  110. template.execute("CREATE TABLE CONTACTS(ID BIGINT NOT NULL PRIMARY KEY, CONTACT_NAME VARCHAR_IGNORECASE(50) NOT NULL, EMAIL VARCHAR_IGNORECASE(50) NOT NULL)");
  111. /*
  112. * Passwords encoded using MD5, NOT in Base64 format, with null as salt Encoded
  113. * password for rod is "koala" Encoded password for dianne is "emu" Encoded
  114. * password for scott is "wombat" Encoded password for peter is "opal" (but user
  115. * is disabled) Encoded password for bill is "wombat" Encoded password for bob is
  116. * "wombat" Encoded password for jane is "wombat"
  117. */
  118. template.execute("INSERT INTO USERS VALUES('rod','$2a$10$75pBjapg4Nl8Pzd.3JRnUe7PDJmk9qBGwNEJDAlA3V.dEJxcDKn5O',TRUE);");
  119. template.execute("INSERT INTO USERS VALUES('dianne','$2a$04$bCMEyxrdF/7sgfUiUJ6Ose2vh9DAMaVBldS1Bw2fhi1jgutZrr9zm',TRUE);");
  120. template.execute("INSERT INTO USERS VALUES('scott','$2a$06$eChwvzAu3TSexnC3ynw4LOSw1qiEbtNItNeYv5uI40w1i3paoSfLu',TRUE);");
  121. template.execute("INSERT INTO USERS VALUES('peter','$2a$04$8.H8bCMROLF4CIgd7IpeQ.tcBXLP5w8iplO0n.kCIkISwrIgX28Ii',FALSE);");
  122. template.execute("INSERT INTO USERS VALUES('bill','$2a$04$8.H8bCMROLF4CIgd7IpeQ.3khQlPVNWbp8kzSQqidQHGFurim7P8O',TRUE);");
  123. template.execute("INSERT INTO USERS VALUES('bob','$2a$06$zMgxlMf01SfYNcdx7n4NpeFlAGU8apCETz/i2C7VlYWu6IcNyn4Ay',TRUE);");
  124. template.execute("INSERT INTO USERS VALUES('jane','$2a$05$ZrdS7yMhCZ1J.AAidXZhCOxdjD8LO/dhlv4FJzkXA6xh9gdEbBT/u',TRUE);");
  125. template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');");
  126. template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_SUPERVISOR');");
  127. template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');");
  128. template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');");
  129. template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');");
  130. template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');");
  131. template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');");
  132. template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");
  133. template.execute("INSERT INTO contacts VALUES (1, 'John Smith', 'john@somewhere.com');");
  134. template.execute("INSERT INTO contacts VALUES (2, 'Michael Citizen', 'michael@xyz.com');");
  135. template.execute("INSERT INTO contacts VALUES (3, 'Joe Bloggs', 'joe@demo.com');");
  136. template.execute("INSERT INTO contacts VALUES (4, 'Karen Sutherland', 'karen@sutherland.com');");
  137. template.execute("INSERT INTO contacts VALUES (5, 'Mitchell Howard', 'mitchell@abcdef.com');");
  138. template.execute("INSERT INTO contacts VALUES (6, 'Rose Costas', 'rose@xyz.com');");
  139. template.execute("INSERT INTO contacts VALUES (7, 'Amanda Smith', 'amanda@abcdef.com');");
  140. template.execute("INSERT INTO contacts VALUES (8, 'Cindy Smith', 'cindy@smith.com');");
  141. template.execute("INSERT INTO contacts VALUES (9, 'Jonathan Citizen', 'jonathan@xyz.com');");
  142. for (int i = 10; i < createEntities; i++) {
  143. String[] person = selectPerson();
  144. template.execute("INSERT INTO contacts VALUES (" + i + ", '" + person[2]
  145. + "', '" + person[0].toLowerCase() + "@" + person[1].toLowerCase()
  146. + ".com');");
  147. }
  148. // Create acl_object_identity rows (and also acl_class rows as needed
  149. for (int i = 1; i < createEntities; i++) {
  150. final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class,
  151. Long.valueOf(i));
  152. tt.execute(new TransactionCallback<Object>() {
  153. public Object doInTransaction(TransactionStatus arg0) {
  154. mutableAclService.createAcl(objectIdentity);
  155. return null;
  156. }
  157. });
  158. }
  159. // Now grant some permissions
  160. grantPermissions(1, "rod", BasePermission.ADMINISTRATION);
  161. grantPermissions(2, "rod", BasePermission.READ);
  162. grantPermissions(3, "rod", BasePermission.READ);
  163. grantPermissions(3, "rod", BasePermission.WRITE);
  164. grantPermissions(3, "rod", BasePermission.DELETE);
  165. grantPermissions(4, "rod", BasePermission.ADMINISTRATION);
  166. grantPermissions(4, "dianne", BasePermission.ADMINISTRATION);
  167. grantPermissions(4, "scott", BasePermission.READ);
  168. grantPermissions(5, "dianne", BasePermission.ADMINISTRATION);
  169. grantPermissions(5, "dianne", BasePermission.READ);
  170. grantPermissions(6, "dianne", BasePermission.READ);
  171. grantPermissions(6, "dianne", BasePermission.WRITE);
  172. grantPermissions(6, "dianne", BasePermission.DELETE);
  173. grantPermissions(6, "scott", BasePermission.READ);
  174. grantPermissions(7, "scott", BasePermission.ADMINISTRATION);
  175. grantPermissions(8, "dianne", BasePermission.ADMINISTRATION);
  176. grantPermissions(8, "dianne", BasePermission.READ);
  177. grantPermissions(8, "scott", BasePermission.READ);
  178. grantPermissions(9, "scott", BasePermission.ADMINISTRATION);
  179. grantPermissions(9, "scott", BasePermission.READ);
  180. grantPermissions(9, "scott", BasePermission.WRITE);
  181. grantPermissions(9, "scott", BasePermission.DELETE);
  182. // Now expressly change the owner of the first ten contacts
  183. // We have to do this last, because "rod" owns all of them (doing it sooner would
  184. // prevent ACL updates)
  185. // Note that ownership has no impact on permissions - they're separate (ownership
  186. // only allows ACl editing)
  187. changeOwner(5, "dianne");
  188. changeOwner(6, "dianne");
  189. changeOwner(7, "scott");
  190. changeOwner(8, "dianne");
  191. changeOwner(9, "scott");
  192. String[] users = { "bill", "bob", "jane" }; // don't want to mess around with
  193. // consistent sample data
  194. Permission[] permissions = { BasePermission.ADMINISTRATION, BasePermission.READ,
  195. BasePermission.DELETE };
  196. for (int i = 10; i < createEntities; i++) {
  197. String user = users[rnd.nextInt(users.length)];
  198. Permission permission = permissions[rnd.nextInt(permissions.length)];
  199. grantPermissions(i, user, permission);
  200. String user2 = users[rnd.nextInt(users.length)];
  201. Permission permission2 = permissions[rnd.nextInt(permissions.length)];
  202. grantPermissions(i, user2, permission2);
  203. }
  204. SecurityContextHolder.clearContext();
  205. }
  206. private void changeOwner(int contactNumber, String newOwnerUsername) {
  207. AclImpl acl = (AclImpl) mutableAclService.readAclById(new ObjectIdentityImpl(
  208. Contact.class, new Long(contactNumber)));
  209. acl.setOwner(new PrincipalSid(newOwnerUsername));
  210. updateAclInTransaction(acl);
  211. }
  212. public int getCreateEntities() {
  213. return createEntities;
  214. }
  215. private void grantPermissions(int contactNumber, String recipientUsername,
  216. Permission permission) {
  217. AclImpl acl = (AclImpl) mutableAclService.readAclById(new ObjectIdentityImpl(
  218. Contact.class, Long.valueOf(contactNumber)));
  219. acl.insertAce(acl.getEntries().size(), permission, new PrincipalSid(
  220. recipientUsername), true);
  221. updateAclInTransaction(acl);
  222. }
  223. private String[] selectPerson() {
  224. String firstName = firstNames[rnd.nextInt(firstNames.length)];
  225. String lastName = lastNames[rnd.nextInt(lastNames.length)];
  226. return new String[] { firstName, lastName, firstName + " " + lastName };
  227. }
  228. public void setCreateEntities(int createEntities) {
  229. this.createEntities = createEntities;
  230. }
  231. public void setDataSource(DataSource dataSource) {
  232. this.template = new JdbcTemplate(dataSource);
  233. }
  234. public void setMutableAclService(MutableAclService mutableAclService) {
  235. this.mutableAclService = mutableAclService;
  236. }
  237. public void setPlatformTransactionManager(
  238. PlatformTransactionManager platformTransactionManager) {
  239. this.tt = new TransactionTemplate(platformTransactionManager);
  240. }
  241. private void updateAclInTransaction(final MutableAcl acl) {
  242. tt.execute(new TransactionCallback<Object>() {
  243. public Object doInTransaction(TransactionStatus arg0) {
  244. mutableAclService.updateAcl(acl);
  245. return null;
  246. }
  247. });
  248. }
  249. }