1 28 package net.sf.jguard.ext.authentication.manager; 29 30 import java.io.File ; 31 import java.io.FileInputStream ; 32 import java.io.FileNotFoundException ; 33 import java.io.IOException ; 34 import java.net.URI ; 35 import java.net.URISyntaxException ; 36 import java.security.Principal ; 37 import java.sql.Connection ; 38 import java.sql.PreparedStatement ; 39 import java.sql.ResultSet ; 40 import java.sql.SQLException ; 41 import java.util.ArrayList ; 42 import java.util.Collection ; 43 import java.util.HashMap ; 44 import java.util.HashSet ; 45 import java.util.Iterator ; 46 import java.util.List ; 47 import java.util.Map ; 48 import java.util.Properties ; 49 import java.util.Set ; 50 import java.util.logging.Level ; 51 import java.util.logging.Logger ; 52 53 import javax.security.auth.Subject ; 54 55 import net.sf.jguard.core.CoreConstants; 56 import net.sf.jguard.core.authentication.credentials.JGuardCredential; 57 import net.sf.jguard.core.principals.RolePrincipal; 58 import net.sf.jguard.core.util.FileUtils; 59 import net.sf.jguard.ext.SecurityConstants; 60 import net.sf.jguard.ext.authentication.AuthenticationException; 61 import net.sf.jguard.ext.database.ConnectionFactory; 62 import net.sf.jguard.ext.database.DatabaseUtils; 63 import net.sf.jguard.ext.principals.PrincipalUtils; 64 import net.sf.jguard.ext.registration.SubjectTemplate; 65 import net.sf.jguard.ext.util.XMLUtils; 66 67 76 public class JdbcAuthenticationManager extends AbstractAuthenticationManager implements AuthenticationManager { 77 78 private static final Logger logger = Logger.getLogger(JdbcAuthenticationManager.class.getName()); 79 private Properties properties = null; 80 private String dbPropertiesLocation = null; 81 private ConnectionFactory connectionFactory = null; 82 83 public JdbcAuthenticationManager() { 84 super(); 85 } 86 87 protected void persistPrincipal(Principal principal) throws AuthenticationException { 88 Connection connection = null; 89 try { 90 connection = connectionFactory.getConnection(); 91 PreparedStatement pst = connection.prepareStatement(properties.getProperty("ADD_PRINCIPAL")); 92 93 if (principal instanceof RolePrincipal) { 94 pst.setString(1, ((RolePrincipal) principal).getLocalName()); 95 pst.setString(2, ((RolePrincipal) principal).getApplicationName()); 96 } else { 97 pst.setString(1, principal.getName()); 98 pst.setString(2, applicationName); 99 } 100 pst.setString(3, principal.getClass().getName()); 101 pst.executeUpdate(); 102 pst.close(); 103 104 localPrincipals.put(principal.getName(), principal); 105 localPrincipalsSet.add(principal); 106 107 } catch (SQLException e) { 108 logger.log(Level.SEVERE, " persistPrincipal(Principal) ", e); 109 throw new AuthenticationException(e); 110 } finally { 111 try { 112 connection.close(); 113 } catch (SQLException e) { 114 logger.log(Level.SEVERE, " persistPrincipal(Principal) ", e); 115 throw new AuthenticationException(e); 116 } 117 } 118 119 } 120 121 public void init(Map map) { 122 123 dbPropertiesLocation = (String ) map.get(SecurityConstants.AUTHENTICATION_DATABASE_FILE_LOCATION); 124 dbPropertiesLocation = XMLUtils.resolveLocation(dbPropertiesLocation); 125 properties = new Properties (); 126 try { 127 File file = FileUtils.getFile(new URI (dbPropertiesLocation)); 128 properties.load(new FileInputStream (file)); 129 } catch (FileNotFoundException e) { 130 logger.severe(" authorization database properties file is not found at this location " + dbPropertiesLocation); 131 } catch (IOException e) { 132 logger.severe(" authorization database properties file is not accesible this location " + dbPropertiesLocation + "\n " 133 + e.getMessage()); 134 } catch (URISyntaxException e) { 135 logger.log(Level.SEVERE, " uri of the authorization database properties file hasn't got a valid synthax ", e); 136 } 137 138 logger.finest("JdbcAuthenticationManager connectionFactory init map =" + map); 139 logger.finest("JdbcAuthenticationManager connectionFactory properties=" + properties); 140 connectionFactory = new ConnectionFactory(map); 142 super.applicationName = (String ) map.get(CoreConstants.APPLICATION_NAME); 143 createRequiredDatabaseEntities(properties, this.connectionFactory); 144 145 boolean empty = isEmpty(); 146 if (empty) { 147 insertRequiredData(); 148 } 149 150 154 try { 155 initPrincipals(); 156 } catch (SQLException e) { 157 logger.log(Level.SEVERE, " principals cannot be initialized ", e); 158 } 159 160 try { 161 subjectTemplate = getSubjectTemplate(DEFAULT); 162 } catch (AuthenticationException e) { 163 logger.log(Level.SEVERE, " default subjectTemplate cannot be initialized ", e); 164 } 165 166 } 167 168 private static void createRequiredDatabaseEntities(Properties properties, ConnectionFactory connectionFactory) { 169 List tablesNames = new ArrayList (); 170 tablesNames.add("JG_PRINCIPAL"); 171 tablesNames.add("JG_USER"); 172 tablesNames.add("JG_CREDENTIAL"); 173 tablesNames.add("JG_USER_PRINCIPAL"); 174 175 tablesNames.add("JG_ST_CREDENTIAL"); 176 tablesNames.add("JG_ST_PRINCIPAL"); 177 tablesNames.add("JG_ST_USER"); 178 179 List foreignkeysNames = new ArrayList (); 180 foreignkeysNames.add("FK_USER_USER_PRINCIPAL"); 181 foreignkeysNames.add("FK_USER_PRINCIPAL"); 182 foreignkeysNames.add("FK_CREDENTIAL_USER_ID"); 183 184 foreignkeysNames.add("FK_ST_USER_PRINCIPAL"); 185 foreignkeysNames.add("FK_ST_USER_CREDENTIAL"); 186 187 List sequencesNames = new ArrayList (); 188 sequencesNames.add("JG_PRINCIPAL_SEQ"); 189 sequencesNames.add("JG_USER_SEQ"); 190 sequencesNames.add("JG_CREDENTIAL_SEQ"); 191 192 sequencesNames.add("JG_ST_CREDENTIAL_SEQ"); 193 sequencesNames.add("JG_ST_PRINCIPAL_SEQ"); 194 sequencesNames.add("JG_ST_USER_SEQ"); 195 DatabaseUtils.createRequiredDatabaseEntities(properties, connectionFactory, sequencesNames, tablesNames, foreignkeysNames); 197 } 198 199 204 private void initPrincipals() throws SQLException { 205 Connection connection = null; 206 ResultSet rs = null; 207 PreparedStatement pst = null; 208 try{ 209 connection = connectionFactory.getConnection(); 210 pst = connection.prepareStatement(properties.getProperty("LOCAL_PRINCIPALS")); 211 pst.setString(1, this.applicationName); 212 rs = pst.executeQuery(); 213 while (rs.next()) { 214 String name = rs.getString(2); 215 String applicationName = rs.getString(3); 216 String className = rs.getString(4); 217 if (className.equals(RolePrincipal.class.getName())) { 218 name = RolePrincipal.getName(name,applicationName); 219 } 220 Principal principal = PrincipalUtils.getPrincipal(className, name); 221 localPrincipalsSet.add(principal); 222 localPrincipals.put(principal.getName(), principal); 223 } 224 }finally{ 225 rs.close(); 226 pst.close(); 227 connection.close(); 228 } 229 } 230 231 private void insertRequiredData() { 232 Map options = new HashMap (); 233 options.put(CoreConstants.APPLICATION_NAME, applicationName); 234 String XmlFileLocation = dbPropertiesLocation.substring(0, dbPropertiesLocation.lastIndexOf('/')) 235 + "/jGuardUsersPrincipals.xml"; 236 options.put(SecurityConstants.AUTHENTICATION_XML_FILE_LOCATION, XmlFileLocation); 237 AuthenticationManager authentManager = new XmlAuthenticationManager(); 238 authentManager.init(options); 239 importAuthenticationManager(authentManager); 240 241 } 242 243 public boolean isEmpty() { 244 List selectQueries = new ArrayList (); 245 selectQueries.add("PRINCIPALS"); 246 selectQueries.add("CREDENTIALS"); 247 selectQueries.add("CREDENTIALS"); 248 selectQueries.add("USERS"); 249 250 return DatabaseUtils.isEmpty(this.properties, connectionFactory, selectQueries); 251 252 } 253 254 protected void updateUserImpl(JGuardCredential cred, Subject user) throws AuthenticationException { 255 256 Connection connection = null; 257 try { 258 long subjectId = getSubjectId(cred, user); 259 connection = connectionFactory.getConnection(); 260 Subject oldUser = getUser(subjectId); 262 263 connection.setAutoCommit(false); 264 265 updatePrivateCredentials(connection, subjectId, user, oldUser); 266 updatePublicCredentials(connection, subjectId, user, oldUser); 267 updatePrincipals(connection, subjectId, user, oldUser); 268 269 connection.commit(); 270 connection.setAutoCommit(true); 271 } catch (SQLException e) { 272 logger.log(Level.SEVERE, " user can not be updated ", e); 273 if (connection != null) 274 try { 275 connection.rollback(); 276 } catch (SQLException excep) { 277 throw new AuthenticationException(e); 278 } 279 throw new AuthenticationException(e); 280 } catch (SecurityException e) { 281 logger.log(Level.FINEST, " user can not be updated: you don't have the permission to update private credentials", e); 282 if (connection != null) 283 try { 284 connection.rollback(); 285 } catch (SQLException excep) { 286 throw new AuthenticationException(excep); 287 } 288 throw new AuthenticationException(e); 289 } finally { 290 try { 291 connection.close(); 292 } catch (SQLException e) { 293 logger.log(Level.SEVERE, " user can not be updated ", e); 294 throw new AuthenticationException(e); 295 } 296 } 297 298 } 299 300 314 315 private void updatePrincipals(Connection connection, long subjectId, Subject user, Subject oldUser) throws SQLException { 316 unlinkUserFromPrincipals(connection, subjectId, oldUser.getPrincipals()); 317 linkUserToPrincipals(connection, subjectId, user.getPrincipals()); 318 } 319 320 private long getPrincipalId(Principal principal) throws SQLException { 321 ResultSet rs = null; 322 Connection connection = null; 323 PreparedStatement pst = null; 324 long principalId = -1; 325 try{ 326 connection = connectionFactory.getConnection(); 327 pst = connection.prepareStatement(properties.getProperty("GET_PRINCIPAL_ID")); 328 329 330 if (principal instanceof RolePrincipal) { 331 pst.setString(1, ((RolePrincipal)principal).getLocalName()); 332 pst.setString(2, ((RolePrincipal) principal).getApplicationName()); 333 } else { 334 pst.setString(1, principal.getName()); 335 pst.setString(2, applicationName); 336 } 337 rs = pst.executeQuery(); 338 rs.next(); 339 principalId = rs.getLong(1); 340 }finally{ 341 rs.close(); 342 pst.close(); 343 connection.close(); 344 } 345 346 return principalId; 347 } 348 349 private void unlinkUserFromPrincipals(Connection connection, long subjectId, Set principals) throws SQLException { 350 351 PreparedStatement pst = connection.prepareStatement(properties.getProperty("UNLINK_USER_PRINCIPAL")); 352 Iterator it = principals.iterator(); 353 while (it.hasNext()) { 354 Principal principal = (Principal ) it.next(); 355 long principalId = getPrincipalId(principal); 356 pst.setLong(1, subjectId); 357 pst.setLong(2, principalId); 358 pst.executeUpdate(); 359 } 360 pst.close(); 361 } 362 363 private void linkUserToPrincipals(Connection connection, long subjectId, Set principals) throws SQLException { 364 PreparedStatement pst = connection.prepareStatement(properties.getProperty("LINK_USER_PRINCIPAL")); 365 Iterator it = principals.iterator(); 366 while (it.hasNext()) { 367 Principal principal = (Principal ) it.next(); 368 long principalId = getPrincipalId(principal); 369 pst.setLong(1, subjectId); 370 pst.setLong(2, principalId); 371 if(principal instanceof RolePrincipal) { 372 pst.setString(3, ((RolePrincipal)principal).getDefinition()); 373 pst.setBoolean(4, ((RolePrincipal)principal).isActive()); 374 } 375 pst.executeUpdate(); 376 } 377 pst.close(); 378 } 379 380 private void updatePrivateCredentials(Connection connection, long subjectId, Subject user, Subject oldUser) 381 throws SQLException { 382 383 Set deletedPrivateCredentials = new HashSet (oldUser.getPrivateCredentials(JGuardCredential.class)); 385 deletedPrivateCredentials.removeAll(user.getPrivateCredentials(JGuardCredential.class)); 386 Iterator itDeletedPrivateCredentials = deletedPrivateCredentials.iterator(); 387 while (itDeletedPrivateCredentials.hasNext()) { 388 deleteCredential(connection, (JGuardCredential) itDeletedPrivateCredentials.next(), subjectId); 389 } 390 391 Set newPrivateCredentials = new HashSet (user.getPrivateCredentials(JGuardCredential.class)); 393 newPrivateCredentials.removeAll(oldUser.getPrivateCredentials(JGuardCredential.class)); 394 Iterator itNewPrivateCredentials = newPrivateCredentials.iterator(); 395 while (itNewPrivateCredentials.hasNext()) { 396 persistCredential(connection, (JGuardCredential) itNewPrivateCredentials.next(), subjectId, false); 397 } 398 } 399 400 private void updatePublicCredentials(Connection connection, long subjectId, Subject user, Subject oldUser) 401 throws SQLException { 402 403 Set deletedPublicCredentials = new HashSet (oldUser.getPublicCredentials(JGuardCredential.class)); 405 deletedPublicCredentials.removeAll(user.getPublicCredentials(JGuardCredential.class)); 406 Iterator itDeletedPublicCredentials = deletedPublicCredentials.iterator(); 407 while (itDeletedPublicCredentials.hasNext()) { 408 deleteCredential(connection, (JGuardCredential) itDeletedPublicCredentials.next(), subjectId); 409 } 410 411 Set newPublicCredentials = new HashSet (user.getPublicCredentials(JGuardCredential.class)); 413 newPublicCredentials.removeAll(oldUser.getPublicCredentials(JGuardCredential.class)); 414 Iterator itNewPublicCredentials = newPublicCredentials.iterator(); 415 while (itNewPublicCredentials.hasNext()) { 416 persistCredential(connection, (JGuardCredential) itNewPublicCredentials.next(), subjectId, true); 417 } 418 } 419 420 public void deleteUser(Subject user) throws AuthenticationException { 421 422 PreparedStatement pst = null; 423 Connection connection = null; 424 try { 425 connection = connectionFactory.getConnection(); 426 connection.setAutoCommit(false); 427 long subjectId = getSubjectId(user); 428 429 deleteCredentials(connection, subjectId); 430 deletePrincipals(connection, subjectId); 431 432 pst = connection.prepareStatement(properties.getProperty("DELETE_SUBJECT")); 433 pst.setLong(1, subjectId); 434 pst.executeUpdate(); 435 pst.close(); 436 437 connection.commit(); 438 connection.setAutoCommit(true); 439 440 } catch (SQLException e) { 441 logger.log(Level.SEVERE, "deleteUser(Subject user)", e); 442 if (connection != null) 443 try { 444 connection.rollback(); 445 } catch (SQLException excep) { 446 throw new AuthenticationException(excep); 447 } 448 throw new AuthenticationException(e); 449 } finally { 450 try { 451 connection.close(); 452 } catch (SQLException e) { 453 logger.log(Level.SEVERE, "deleteUser(Subject user)", e); 454 throw new AuthenticationException(e); 455 } 456 } 457 458 } 459 460 private long getSubjectId(Subject user) throws SQLException , AuthenticationException { 461 JGuardCredential identityCred = extractIdentityCredentialFromUser(user); 462 return getSubjectId(identityCred, user); 463 } 464 465 private long getSubjectId(JGuardCredential identityCred, Subject user) throws SQLException , AuthenticationException { 466 long userId = -1; 467 Connection connection = null; 468 PreparedStatement pst = null; 469 ResultSet rs = null; 470 try{ 471 connection = connectionFactory.getConnection(); 472 pst = connection.prepareStatement(properties.getProperty("GET_USER_ID")); 473 pst.setString(1, identityCred.getId()); 474 pst.setString(2, (String ) identityCred.getValue()); 475 476 rs = pst.executeQuery(); 477 while (rs.next()) { 478 if (userId != -1) { 479 logger.severe("it exists more than one user with this identity credential "); 480 throw new AuthenticationException("it exists more than one user with this identity credential "); 481 } 482 userId = rs.getLong(1); 483 } 484 if (userId == -1) { 485 logger.severe("no user exists with this identity credential "); 486 throw new AuthenticationException("no user exists with this identity credential "); 487 } 488 }finally{ 489 rs.close(); 490 pst.close(); 491 connection.close(); 492 } 493 return userId; 494 } 495 496 private void deletePrincipals(Connection connection, long subjectId) throws SQLException { 497 PreparedStatement pst = null; 498 pst = connection.prepareStatement(properties.getProperty("DELETE_USER_PRINCIPALS")); 499 pst.setLong(1, subjectId); 500 pst.executeUpdate(); 501 pst.close(); 502 } 503 504 private void deleteCredentials(Connection connection, long subjectId) throws SQLException { 505 PreparedStatement pst = null; 506 pst = connection.prepareStatement(properties.getProperty("DELETE_USER_CREDENTIALS")); 507 pst.setLong(1, subjectId); 508 pst.executeUpdate(); 509 pst.close(); 510 } 511 512 private void persistCredentials(Connection connection, Subject subject, long subjectId) throws SQLException { 513 Set publicCredentials = subject.getPublicCredentials(); 514 Iterator itPublic = publicCredentials.iterator(); 515 while (itPublic.hasNext()) { 516 JGuardCredential jgCred = (JGuardCredential) itPublic.next(); 517 persistCredential(connection, jgCred, subjectId, true); 518 } 519 520 Set privateCredentials = subject.getPrivateCredentials(); 521 Iterator itPrivate = privateCredentials.iterator(); 522 while (itPrivate.hasNext()) { 523 JGuardCredential jgCred = (JGuardCredential) itPrivate.next(); 524 persistCredential(connection, jgCred, subjectId, false); 525 } 526 527 } 528 529 private void persistCredential(Connection connection, JGuardCredential jgCred, long userId, boolean publicVisibility) 530 throws SQLException { 531 532 PreparedStatement pst = connection.prepareStatement(properties.getProperty("ADD_CREDENTIAL")); 533 pst.setLong(1, userId); 534 pst.setBoolean(2, publicVisibility); 535 pst.setString(3, jgCred.getId()); 536 pst.setString(4, (String ) jgCred.getValue()); 537 pst.executeUpdate(); 538 pst.close(); 539 } 540 541 private void updateCredential(Connection connection, JGuardCredential jgCred, long userId) throws SQLException { 544 545 PreparedStatement pst = connection.prepareStatement(properties.getProperty("UPDATE_CREDENTIAL")); 546 pst.setString(1, (String ) jgCred.getValue()); 547 pst.setLong(2, userId); 548 pst.setString(3, jgCred.getId()); 549 pst.executeUpdate(); 550 pst.close(); 551 } 552 553 private void deleteCredential(Connection connection, JGuardCredential jgCred, long userId) throws SQLException { 554 555 PreparedStatement pst = connection.prepareStatement(properties.getProperty("DELETE_CREDENTIAL")); 556 pst.setLong(1, userId); 557 pst.setString(2, jgCred.getId()); 558 pst.setString(3, (jgCred.getValue() != null ? jgCred.getValue().toString() : "")); 559 pst.executeUpdate(); 560 pst.close(); 561 } 562 563 private void persistPrincipals(Connection connection, Subject subject, long subjectId) throws SQLException , 564 AuthenticationException { 565 566 PreparedStatement pst = connection.prepareStatement(properties.getProperty("LINK_USER_PRINCIPAL")); 567 Set principals = subject.getPrincipals(); 568 Iterator it = principals.iterator(); 569 while (it.hasNext()) { 570 Principal ppal = (Principal ) it.next(); 571 createPrincipal(ppal); 572 573 long principalId = getPrincipalId(ppal); 574 575 pst.setLong(1, subjectId); 576 pst.setLong(2, principalId); 577 if(ppal instanceof RolePrincipal) { 578 pst.setString(3, ((RolePrincipal)ppal).getDefinition()); 579 pst.setBoolean(4, ((RolePrincipal)ppal).isActive()); 580 } 581 582 pst.executeUpdate(); 583 } 584 pst.close(); 585 } 586 587 protected void persistUser(Subject user) throws AuthenticationException { 588 589 PreparedStatement pst = null; 590 PreparedStatement pst2 = null; 591 ResultSet rs2 = null; 592 Connection connection = null; 593 try { 594 connection = connectionFactory.getConnection(); 595 connection.setAutoCommit(false); 596 597 pst = connection.prepareStatement(properties.getProperty("ADD_SUBJECT")); 598 pst.executeUpdate(); 599 pst.close(); 600 601 pst2 = connection.prepareStatement(properties.getProperty("GET_SUBJECT_ID")); 602 rs2 = pst2.executeQuery(); 603 rs2.next(); 604 long subjectId = rs2.getLong(1); 605 rs2.close(); 606 pst2.close(); 607 608 persistCredentials(connection, user, subjectId); 609 persistPrincipals(connection, user, subjectId); 610 611 connection.commit(); 612 connection.setAutoCommit(true); 613 614 } catch (SQLException e) { 615 logger.log(Level.SEVERE, "persistUser(Subject user)", e); 616 if (connection != null) 617 try { 618 connection.rollback(); 619 } catch (SQLException excep) { 620 throw new AuthenticationException(excep); 621 } 622 throw new AuthenticationException(e); 623 } finally { 624 try { 625 connection.close(); 626 } catch (SQLException e) { 627 logger.log(Level.SEVERE, "persistUser(Subject user)", e); 628 throw new AuthenticationException(e); 629 } 630 } 631 632 } 633 634 public void updateDefaultSubjectTemplate(SubjectTemplate template) throws AuthenticationException { 635 Connection connection = null; 636 637 try { 638 connection = connectionFactory.getConnection(); 639 connection.setAutoCommit(false); 640 long defaultSubjecttemplateID = getSubjectTemplateID(DEFAULT); 641 persistSubjectTemplateCredentials(connection, template, defaultSubjecttemplateID); 642 persistSubjectTemplatePrincipals(connection, template, defaultSubjecttemplateID); 643 644 connection.commit(); 645 connection.setAutoCommit(true); 646 } catch (SQLException e) { 647 logger.log(Level.SEVERE, " default subject_template cannot be updated ", e); 648 if (connection != null) 649 try { 650 connection.rollback(); 651 } catch (SQLException excep) { 652 throw new AuthenticationException(excep); 653 } 654 throw new AuthenticationException(e); 655 }finally { 656 try { 657 connection.close(); 658 } catch (SQLException e) { 659 logger.log(Level.SEVERE, "default subject_template cannot be updated ", e); 660 throw new AuthenticationException(e); 661 } 662 } 663 664 } 665 666 public void persistSubjectTemplate(SubjectTemplate template) throws AuthenticationException { 667 Connection connection = null; 668 long stId = -1; 669 try { 670 connection = connectionFactory.getConnection(); 671 connection.setAutoCommit(false); 672 673 PreparedStatement pst = connection.prepareStatement(properties.getProperty("ADD_SUBJECT_TEMPLATE")); 674 pst.setString(1, template.getName()); 675 pst.executeUpdate(); 676 pst.close(); 677 678 PreparedStatement pst2 = connection.prepareStatement(properties.getProperty("GET_SUBJECT_TEMPLATE_ID")); 679 ResultSet rs2 = pst2.executeQuery(); 680 rs2.next(); 681 stId = rs2.getLong(1); 682 rs2.close(); 683 pst2.close(); 684 685 persistSubjectTemplateCredentials(connection, template, stId); 686 persistSubjectTemplatePrincipals(connection, template, stId); 687 688 connection.commit(); 689 connection.setAutoCommit(true); 690 } catch (SQLException e) { 691 logger.log(Level.SEVERE, " subject_template cannot be created ", e); 692 if (connection != null) 693 try { 694 connection.rollback(); 695 } catch (SQLException excep) { 696 throw new AuthenticationException(excep); 697 } 698 throw new AuthenticationException(e); 699 } finally { 700 try { 701 connection.close(); 702 } catch (SQLException e) { 703 logger.log(Level.SEVERE, "subject_template cannot be created", e); 704 throw new AuthenticationException(e); 705 } 706 } 707 } 708 709 private void persistSubjectTemplatePrincipals(Connection connection, SubjectTemplate template, long stId) throws SQLException { 710 711 Set genericPrincipals = template.getPrincipals(); 712 Iterator itGenPrincipals = genericPrincipals.iterator(); 713 while (itGenPrincipals.hasNext()) { 714 Principal ppal = (Principal ) itGenPrincipals.next(); 715 persistSubjectTemplatePrincipal(connection, ppal, stId); 716 } 717 } 718 719 private void persistSubjectTemplatePrincipal(Connection connection, Principal principal, long stId) throws SQLException { 720 721 PreparedStatement pst = connection.prepareStatement(properties.getProperty("ADD_ST_PRINCIPAL")); 722 if (principal instanceof RolePrincipal) { 723 pst.setString(1, ((RolePrincipal)principal).getLocalName()); 724 pst.setString(2, ((RolePrincipal) principal).getApplicationName()); 725 } else { 726 pst.setString(1, principal.getName()); 727 pst.setString(2, applicationName); 728 } 729 pst.setString(3, principal.getClass().getName()); 730 731 pst.setLong(4, stId); 732 pst.executeUpdate(); 733 pst.close(); 734 735 localPrincipals.put(principal.getName(), principal); 736 localPrincipalsSet.add(principal); 737 } 738 739 private void persistSubjectTemplateCredentials(Connection connection, SubjectTemplate st, long subjectTemplateId) 740 throws SQLException { 741 742 Set privateRequiredCred = st.getPrivateRequiredCredentials(); 743 Iterator itPrivateRequiredCred = privateRequiredCred.iterator(); 744 while (itPrivateRequiredCred.hasNext()) { 745 JGuardCredential jgCred = (JGuardCredential) itPrivateRequiredCred.next(); 746 persistStCredential(connection, jgCred, subjectTemplateId, true, false); 748 } 749 750 Set publicRequiredCreds = st.getPublicRequiredCredentials(); 751 Iterator itPublicRequiredCred = publicRequiredCreds.iterator(); 752 while (itPublicRequiredCred.hasNext()) { 753 JGuardCredential jgCred = (JGuardCredential) itPublicRequiredCred.next(); 754 persistStCredential(connection, jgCred, subjectTemplateId, true, true); 756 } 757 758 Set privateOptionalCred = st.getPrivateOptionalCredentials(); 759 Iterator itPrivateOptionalCred = privateOptionalCred.iterator(); 760 while (itPrivateOptionalCred.hasNext()) { 761 JGuardCredential jgCred = (JGuardCredential) itPrivateOptionalCred.next(); 762 persistStCredential(connection, jgCred, subjectTemplateId, false, false); 764 } 765 766 Set publicOptionalCreds = st.getPublicOptionalCredentials(); 767 Iterator itPublicOptionalCred = publicOptionalCreds.iterator(); 768 while (itPublicOptionalCred.hasNext()) { 769 JGuardCredential jgCred = (JGuardCredential) itPublicOptionalCred.next(); 770 persistStCredential(connection, jgCred, subjectTemplateId, false, true); 772 } 773 } 774 775 private void persistStCredential(Connection connection, JGuardCredential jgCred, long subjectTemplateId, boolean required, 776 boolean public_visibility) throws SQLException { 777 778 PreparedStatement pst = connection.prepareStatement(properties.getProperty("ADD_ST_CREDENTIAL")); 779 pst.setString(1, jgCred.getId()); 780 pst.setBoolean(2, public_visibility); 781 pst.setBoolean(3, required); 782 pst.setBoolean(4, jgCred.isIdentity()); 783 pst.setLong(5, subjectTemplateId); 784 pst.executeUpdate(); 785 pst.close(); 786 } 787 788 public final ConnectionFactory getConnectionFactory() { 789 return connectionFactory; 790 } 791 792 public final Properties getProperties() { 793 return properties; 794 } 795 796 public final void setProperties(Properties properties) { 797 this.properties = properties; 798 } 799 800 public SubjectTemplate getSubjectTemplate(String name) throws AuthenticationException { 801 802 SubjectTemplate st = new SubjectTemplate(); 803 try { 804 long subjectTemplateId = getSubjectTemplateID(name); 805 populateSubjectTemplatePrincipals(st, subjectTemplateId); 806 populateSubjectTemplateCredentials(st, subjectTemplateId); 807 808 } catch (SQLException e) { 809 logger.log(Level.SEVERE, " subject_template cannot be grabbed ", e); 810 throw new AuthenticationException(e); 811 } 812 813 return st; 814 815 } 816 817 private void populateSubjectTemplatePrincipals(SubjectTemplate st, long subjectTemplateId) throws SQLException { 818 Connection connection= null; 819 820 try{ 821 connection = connectionFactory.getConnection(); 822 PreparedStatement pst2 = connection.prepareStatement(properties.getProperty("GET_ST_PRINCIPALS")); 823 pst2.setLong(1, subjectTemplateId); 824 ResultSet rs2 = pst2.executeQuery(); 825 Set genericPrincipals = new HashSet (); 826 while (rs2.next()) { 827 String className = rs2.getString(4); 828 String principalName = (String ) rs2.getString(2); 829 if (className.equals(RolePrincipal.class.getName())) { 830 principalName = RolePrincipal.getName(principalName,rs2.getString(3)); 831 } 832 Principal ppal = PrincipalUtils.getPrincipal(className, principalName); 833 genericPrincipals.add(ppal); 834 } 835 rs2.close(); 836 pst2.close(); 837 st.setPrincipals(genericPrincipals); 838 }finally{ 839 connection.close(); 840 } 841 842 } 843 844 private void populateSubjectTemplateCredentials(SubjectTemplate st, long subjectTemplateId) throws SQLException { 845 Connection connection = null; 846 try{ 847 848 connection = connectionFactory.getConnection(); 849 PreparedStatement pst3 = connection.prepareStatement(properties.getProperty("GET_ST_CREDENTIALS")); 850 pst3.setLong(1, subjectTemplateId); 851 ResultSet rs3 = pst3.executeQuery(); 852 Set privateOptionalCredentials = new HashSet (); 853 Set privateRequiredCredentials = new HashSet (); 854 Set publicOptionalCredentials = new HashSet (); 855 Set publicRequiredCredentials = new HashSet (); 856 857 while (rs3.next()) { 858 JGuardCredential cred = new JGuardCredential(); 859 cred.setId(rs3.getString(2)); 860 boolean public_visibility = rs3.getBoolean(3); 861 boolean required = rs3.getBoolean(4); 862 cred.setIdentity(rs3.getBoolean(5)); 863 if (public_visibility && required) { 864 publicRequiredCredentials.add(cred); 865 } else if (!public_visibility && required) { 866 privateRequiredCredentials.add(cred); 867 } else if (public_visibility && !required) { 868 publicOptionalCredentials.add(cred); 869 } else if (!public_visibility && !required) { 870 privateOptionalCredentials.add(cred); 871 } 872 873 } 874 rs3.close(); 875 pst3.close(); 876 st.setPrivateOptionalCredentials(privateOptionalCredentials); 877 st.setPrivateRequiredCredentials(privateRequiredCredentials); 878 st.setPublicOptionalCredentials(publicOptionalCredentials); 879 st.setPublicRequiredCredentials(publicRequiredCredentials); 880 }finally{ 881 connection.close(); 882 } 883 } 884 885 892 private long getSubjectTemplateID(String name) throws SQLException , AuthenticationException { 893 Connection connection = null; 894 PreparedStatement pst; 895 ResultSet rs; 896 long subjectTemplateId = -1; 897 int subjectTemplateFound = 0; 898 try{ 899 connection = connectionFactory.getConnection(); 900 pst = connection.prepareStatement(properties.getProperty("GET_SUBJECT_TEMPLATE")); 901 pst.setString(1, name); 902 rs = pst.executeQuery(); 903 904 while (rs.next()) { 905 subjectTemplateId = rs.getLong(1); 906 subjectTemplateFound++; 907 } 908 rs.close(); 909 pst.close(); 910 911 }finally{ 912 connection.close(); 913 } 914 if(subjectTemplateId==-1){ 915 throw new AuthenticationException(" subjectTemplate ID intitled "+name+" cannot be found "); 916 } 917 if(subjectTemplateFound>1){ 918 throw new AuthenticationException(" more than one ID for subjectTemplate intitled "+name+" has been found "); 919 } 920 return subjectTemplateId; 921 } 922 923 public Set getAllPrincipalsSet() throws AuthenticationException { 924 Set allPrincipals = new HashSet (); 925 926 PreparedStatement pst = null; 927 ResultSet rs = null; 928 Connection connection = null; 929 try { 930 connection = connectionFactory.getConnection(); 931 pst = connection.prepareStatement(properties.getProperty("PRINCIPALS")); 932 rs = pst.executeQuery(); 933 while (rs.next()) { 934 String name = rs.getString(2); 935 String className = rs.getString(4); 936 String applicationName = rs.getString(3); 937 if (RolePrincipal.class.getName().equals(className)) { 938 name= RolePrincipal.getName(name, applicationName); 939 } 940 Principal principal = PrincipalUtils.getPrincipal(className, name); 941 942 allPrincipals.add(principal); 943 } 944 945 rs.close(); 946 pst.close(); 947 } catch (SQLException e) { 948 logger.log(Level.SEVERE, " principals cannot be grabbed ", e); 949 throw new AuthenticationException(e); 950 } finally { 951 try { 952 connection.close(); 953 } catch (SQLException e) { 954 logger.log(Level.SEVERE, " principals cannot be grabbed ", e); 955 throw new AuthenticationException(e); 956 } 957 } 958 return allPrincipals; 959 } 960 961 968 public Set findUsers(Collection credentials) throws AuthenticationException { 969 Set users = new HashSet (); 970 971 if (credentials.isEmpty()) 972 return users; 973 974 Connection connection = null; 975 PreparedStatement pst = null; 976 ResultSet rs = null; 977 String findUsers = properties.getProperty("FIND_USERS"); 978 String [] tokens = findUsers.split(" "); 979 String user_id = tokens[2]; 980 String jg_credential = tokens[4]; 981 String cred_name = tokens[6]; 982 String cred_value = tokens[9]; 983 try { 984 connection = connectionFactory.getConnection(); 985 StringBuffer dynamicQuery = new StringBuffer (); 987 StringBuffer tables = new StringBuffer (); 988 StringBuffer conditions = new StringBuffer (); 989 990 for (int count = 0; count < credentials.size(); count++) { 991 if (count > 0) { 992 tables.append(','); 993 conditions.append(" and "); 994 } else { 995 conditions.append(" where "); 996 } 997 StringBuffer alias = new StringBuffer ("cred").append(count); 998 tables.append(' ').append(jg_credential).append(' ').append(alias); 999 conditions.append(alias).append('.').append(cred_name).append("= ? and "); 1000 conditions.append(alias).append('.').append(cred_value).append("= ? "); 1001 if (count > 0) { 1002 conditions.append(" and cred0.").append(user_id).append('='); 1003 conditions.append(alias).append('.').append(user_id).append(' '); 1004 } 1005 } 1006 1007 dynamicQuery.append(" select distinct cred0.").append(user_id).append(" from "); 1008 dynamicQuery.append(tables); 1009 dynamicQuery.append(conditions); 1010 logger.finest(dynamicQuery.toString()); 1011 pst = connection.prepareStatement(dynamicQuery.toString()); 1012 1013 Iterator itCredentials = credentials.iterator(); 1014 int count2 = 1; 1015 while (itCredentials.hasNext()) { 1016 JGuardCredential jcred = (JGuardCredential) itCredentials.next(); 1017 pst.setString(count2, jcred.getId()); 1018 count2++; 1019 pst.setString(count2, jcred.getValue().toString()); 1020 count2++; 1021 } 1022 rs = pst.executeQuery(); 1023 while (rs.next()) { 1024 Subject user = null; 1025 int userId = rs.getInt(1); 1026 user = getUser(userId); 1027 users.add(user); 1028 } 1029 1030 rs.close(); 1031 pst.close(); 1032 } catch (SQLException e) { 1033 logger.log(Level.SEVERE, " error when we try to find users which maps to credentials ", e); 1034 throw new AuthenticationException(e); 1035 } finally { 1036 try { 1037 connection.close(); 1038 } catch (SQLException e) { 1039 logger.log(Level.SEVERE, "users cannot be found ", e); 1040 throw new AuthenticationException(e); 1041 } 1042 } 1043 return users; 1044 } 1045 1046 1053 private static Set getUserPrincipals(long usrId) throws SQLException { 1054 JdbcAuthenticationManager authManager = (JdbcAuthenticationManager) AuthenticationManagerFactory 1055 .getAuthenticationManager(); 1056 ConnectionFactory connectionFactory = authManager.getConnectionFactory(); 1057 Connection connection = null; 1058 PreparedStatement pst = null; 1059 ResultSet rs = null; 1060 Set userPrincipals = new HashSet (); 1061 try{ 1062 connection = connectionFactory.getConnection(); 1063 1064 pst = connection.prepareStatement(authManager.getProperties().getProperty("GET_USER_PRINCIPALS")); 1065 pst.setLong(1, usrId); 1066 rs = pst.executeQuery(); 1067 while (rs.next()) { 1068 RolePrincipal principal = new RolePrincipal(); 1069 principal.setLocalName(rs.getString(1)); 1070 principal.setApplicationName(rs.getString(2)); 1071 logger.finest("principal added" + principal + " to user " + usrId); 1072 userPrincipals.add(principal); 1073 1074 } 1075 }catch(SQLException e){ 1076 logger.warning(" principals for user with id="+usrId+" cannot be found"); 1077 throw e; 1078 1079 }finally{ 1080 rs.close(); 1081 pst.close(); 1082 connection.close(); 1083 } 1084 return userPrincipals; 1085 } 1086 1087 1095 private static Set getUserCredentials(long usrId, boolean publicVisibility) throws SQLException { 1096 JdbcAuthenticationManager authManager = (JdbcAuthenticationManager) AuthenticationManagerFactory 1097 .getAuthenticationManager(); 1098 ConnectionFactory connectionFactory = authManager.getConnectionFactory(); 1099 Connection connection = null; 1100 PreparedStatement pst = null; 1101 ResultSet rs = null; 1102 Set userCredentials = new HashSet (); 1103 try{ 1104 connection = connectionFactory.getConnection(); 1105 1106 pst = connection.prepareStatement(authManager.getProperties().getProperty("GET_USER_CREDENTIALS")); 1107 pst.setLong(1, usrId); 1108 pst.setBoolean(2, publicVisibility); 1109 rs = pst.executeQuery(); 1110 while (rs.next()) { 1111 JGuardCredential cred = new JGuardCredential(); 1112 cred.setId(rs.getString(1)); 1113 cred.setValue(rs.getString(2)); 1114 userCredentials.add(cred); 1115 logger.finest(" credential added " + cred + " to user " + usrId); 1116 } 1117 }finally{ 1118 rs.close(); 1119 pst.close(); 1120 connection.close(); 1121 } 1122 1123 return userCredentials; 1124 } 1125 1126 1129 public Set getUsers() throws AuthenticationException { 1130 Set users = new HashSet (); 1131 1132 PreparedStatement pst = null; 1133 ResultSet rs = null; 1134 Connection connection = null; 1135 try { 1136 connection = connectionFactory.getConnection(); 1137 pst = connection.prepareStatement(properties.getProperty("GET_USERS")); 1138 rs = pst.executeQuery(); 1139 while (rs.next()) { 1140 long userId = rs.getLong(1); 1141 Subject user = getUser(userId); 1142 users.add(user); 1143 } 1144 1145 rs.close(); 1146 pst.close(); 1147 } catch (SQLException e) { 1148 logger.log(Level.SEVERE, " users cannot be grabbed ", e); 1149 throw new AuthenticationException(e); 1150 } finally { 1151 try { 1152 connection.close(); 1153 } catch (SQLException e) { 1154 logger.log(Level.SEVERE, " users cannot be grabbed ", e); 1155 throw new AuthenticationException(e); 1156 } 1157 } 1158 return users; 1159 } 1160 1161 1167 public static Subject getUser(long userId) throws SQLException { 1168 Set userPrincipals = getUserPrincipals(userId); 1170 Set userPubCred = getUserCredentials(userId, true); 1171 Set userPrivCred = getUserCredentials(userId, false); 1172 Subject user = new Subject (false, userPrincipals, userPubCred, userPrivCred); 1174 return user; 1175 } 1176 1177 public void updatePrincipal(String oldName, Principal principal) throws AuthenticationException { 1178 if (oldName.equals(principal.getName())) { 1179 return; 1180 } 1181 Connection connection = null; 1182 PreparedStatement pst = null; 1183 try { 1184 connection = connectionFactory.getConnection(); 1185 pst = connection.prepareStatement(properties.getProperty("UPDATE_PRINCIPAL")); 1186 pst.setString(1, principal.getName()); 1187 pst.setString(2, oldName); 1188 pst.setString(3, applicationName); 1189 pst.executeUpdate(); 1190 pst.close(); 1191 1192 } catch (SQLException e) { 1193 logger.log(Level.SEVERE, "updatePrincipal(String oldName, Principal principal)", e); 1194 throw new AuthenticationException(e); 1195 } finally { 1196 try { 1197 connection.close(); 1198 } catch (SQLException e) { 1199 logger.log(Level.SEVERE, "updatePrincipal(String oldName, Principal principal)", e); 1200 throw new AuthenticationException(e); 1201 } 1202 } 1203 1204 Principal oldPal = (Principal )localPrincipals.remove(oldName); 1206 localPrincipalsSet.remove(oldPal); 1207 localPrincipals.put(principal.getName(), principal); 1208 localPrincipalsSet.add(principal); 1209 1210 1211 } 1212 1213 public boolean deletePrincipal(Principal principal) throws AuthenticationException { 1214 1215 PreparedStatement pst = null; 1216 PreparedStatement pst2 = null; 1217 PreparedStatement pst3 = null; 1218 Connection connection = null; 1219 ResultSet rs = null; 1220 try { 1221 connection = connectionFactory.getConnection(); 1222 connection.setAutoCommit(false); 1223 1224 pst = connection.prepareStatement(properties.getProperty("GET_PRINCIPAL_ID")); 1226 pst.setString(1, principal.getName()); 1227 pst.setString(2, applicationName); 1228 rs = pst.executeQuery(); 1229 long principalId = -1; 1230 if (rs.next()){ 1231 principalId = rs.getLong(1); 1232 }else{ 1233 logger.finest(" there is no principal to delete: " + principal.getName()); 1234 return false; 1235 } 1236 1237 1238 pst2 = connection.prepareStatement(properties.getProperty("DELETE_PRINCIPAL_USERS")); 1240 pst2.setLong(1, principalId); 1241 pst2.executeUpdate(); 1242 pst2.close(); 1243 1244 pst3 = connection.prepareStatement(properties.getProperty("DELETE_PRINCIPAL")); 1246 pst3.setString(1, principal.getName()); 1247 pst3.executeUpdate(); 1248 pst3.close(); 1249 1250 connection.commit(); 1251 connection.setAutoCommit(true); 1252 1253 } catch (SQLException e) { 1254 logger.log(Level.SEVERE, "deletePrincipal(Principal principal)", e); 1255 if (connection != null) 1256 try { 1257 connection.rollback(); 1258 } catch (SQLException excep) { 1259 throw new AuthenticationException(e); 1260 } 1261 throw new AuthenticationException(e); 1262 } finally { 1263 try { 1264 rs.close(); 1265 pst.close(); 1266 connection.close(); 1267 } catch (SQLException e) { 1268 logger.log(Level.SEVERE, "deletePrincipal(Principal principal)", e); 1269 throw new AuthenticationException(e); 1270 } 1271 } 1272 1273 Principal oldPal = (Principal )localPrincipals.remove(principal.getName()); 1275 localPrincipalsSet.remove(oldPal); 1276 return true; 1277 } 1278 1279} 1280 | Popular Tags |