Guest User

Untitled

a guest
Nov 26th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. package id.swhp.javaee.soteria.application.security;
  2.  
  3. import id.swhp.javaee.soteria.business.account.boundary.AccountStore;
  4. import id.swhp.javaee.soteria.business.account.entity.Account;
  5. import id.swhp.javaee.soteria.business.exception.boundary.AccountNotVerifiedException;
  6. import id.swhp.javaee.soteria.business.exception.boundary.InvalidCredentialException;
  7. import javax.enterprise.context.ApplicationScoped;
  8. import javax.inject.Inject;
  9. import javax.security.enterprise.credential.CallerOnlyCredential;
  10. import javax.security.enterprise.credential.Credential;
  11. import javax.security.enterprise.credential.UsernamePasswordCredential;
  12. import javax.security.enterprise.identitystore.CredentialValidationResult;
  13. import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;
  14. import static javax.security.enterprise.identitystore.CredentialValidationResult.NOT_VALIDATED_RESULT;
  15. import javax.security.enterprise.identitystore.IdentityStore;
  16.  
  17. /**
  18. *
  19. * @author Sukma Wardana
  20. * @since 1.0
  21. */
  22. @ApplicationScoped
  23. public class SoteriaIdentityStore implements IdentityStore {
  24.  
  25. // call our EJB service to validate the account
  26. @Inject
  27. AccountStore accountStore;
  28.  
  29. @Override
  30. public CredentialValidationResult validate(Credential credential) {
  31. try {
  32.  
  33. // check if the credential was UsernamePasswordCredential
  34. if (credential instanceof UsernamePasswordCredential) {
  35. String username = ((UsernamePasswordCredential) credential).getCaller();
  36. String password = ((UsernamePasswordCredential) credential).getPasswordAsString();
  37.  
  38. return validate(this.accountStore.getByUsernameAndPassword(username, password));
  39. }
  40.  
  41. // check if the credential was CallerOnlyCredential
  42. if (credential instanceof CallerOnlyCredential) {
  43. String username = ((CallerOnlyCredential) credential).getCaller();
  44.  
  45. return validate(
  46. this.accountStore.getByUsername(username)
  47. .orElseThrow(InvalidCredentialException::new)
  48. );
  49. }
  50.  
  51. } catch (InvalidCredentialException e) {
  52. return INVALID_RESULT;
  53. }
  54. return NOT_VALIDATED_RESULT;
  55. }
  56.  
  57. // before return the CredentialValidationResult, check if the account is active or not
  58. private CredentialValidationResult validate(Account account) {
  59. if (!account.isActive()) {
  60. throw new AccountNotVerifiedException();
  61. }
  62.  
  63. return new CredentialValidationResult(account.getUsername());
  64. }
  65. }
Add Comment
Please, Sign In to add comment