DataSourcePopulator.java 13 KB

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