Skip to content
This repository has been archived by the owner on Jul 16, 2019. It is now read-only.

Commit

Permalink
* RAS-63: Allow consumer to do something with the user (e.g. validati…
Browse files Browse the repository at this point in the history
…ng and throwing exception in case it fails) before using user on sign-in and refresh
  • Loading branch information
AihiAhazi committed Nov 13, 2015
1 parent bd22a84 commit 7c92526
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import java.io.IOException;
import java.security.PublicKey;
import java.util.Date;
import java.util.function.Consumer;

import static org.apache.commons.codec.binary.Base64.decodeBase64;

Expand Down Expand Up @@ -65,7 +66,7 @@ public class Authority<USER extends User<? extends Role>,
private final ClientAccessPolicy _clientAccessPolicy;
private final KeyPairProvider _issuerKeyProvider;
private final ExpiryDateCalculator<USER> _expiryDateCalculator;

private Consumer<USER> _checkUserToFulfillAllRequirementsToSignInOrRefreshConsumer = user -> { /* No-op by default */ };

/**
* Sets up a new Authority singleton.
Expand All @@ -89,6 +90,15 @@ public Authority(final UserStore<USER, CREDENTIALS, SIGNUP_ACCCOUNT_DATA> userSt
_expiryDateCalculator = expiryDateCalculator;
}

/**
* The consumer will be invoked before a sign-in or refresh is permitted. The Consumer may throw any {@link java.lang.RuntimeException} in case
* the given user does not fulfill the criteria to successfully complete e.g. a sign-in or refresh. For example when the user have a expiry date
* and this date is expired the consumer may throw an exception to force the action to fail.
*/
public void setCheckUserToFulfillAllRequirementsToSignInOrRefreshConsumer(final Consumer<USER> checkUserToFulfillAllRequirementsToSignInOrRefreshConsumer) {
_checkUserToFulfillAllRequirementsToSignInOrRefreshConsumer = checkUserToFulfillAllRequirementsToSignInOrRefreshConsumer;
}

/**
* Implements sign-up. Creates a new User and a new Session.
*
Expand Down Expand Up @@ -122,6 +132,7 @@ public byte[] signIn(final CREDENTIALS credentials) {
if (!user.passwordMatches(credentials.getPassword())) {
throw new LoginFailedException("Login failed");
}
_checkUserToFulfillAllRequirementsToSignInOrRefreshConsumer.accept(user);
final PublicKeyWithMechanism publicKeyWithMechanism = new PublicKeyWithMechanism(credentials.getPublicKey());
if (_sessionCreationPolicy.mayCreateSession(user.getUserId(), publicKeyWithMechanism.getValue())) {
return createCertificateAndSession(credentials, user);
Expand All @@ -146,6 +157,7 @@ public byte[] refresh(final byte[] certificate, final byte[] signedBytes, final
verifySignature(signedBytes, signature, session);
throwExceptionWhenClientIdIsProhibited(session.getClientId());
final USER user = _userStore.findByUuid(session.getUserId()).orElseThrow(() -> new IllegalStateException("Could not find user with userId " + session.getUserId()));
_checkUserToFulfillAllRequirementsToSignInOrRefreshConsumer.accept(user);
try {
final byte[] newCertificate = createCertificate(user, clientPublicKeyFrom(session), session.getClientId());
session.setCertificate(newCertificate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

@SuppressWarnings("AbstractClassWithoutAbstractMethods")
public abstract class AuthorityTest {
private static final String TEST_CLIENT_ID = "asdf";
protected static final String TEST_CLIENT_ID = "asdf";
protected static final TestUserCredentials TEST_USER_CREDENTIALS = new TestUserCredentials("test@example.com", "right", TestKeyPairProvider.create().getPublicKey(), TEST_CLIENT_ID);
protected static final TestSignUpAccountData TEST_USER_ACCOUNT_DATA = TestSignUpAccountData.of(TEST_USER_CREDENTIALS);
protected static final TestUserCredentials CREDENTIALS_WITH_WRONG_PASSWORD = new TestUserCredentials(TEST_USER_CREDENTIALS.getIdentifier(), "wrong", TEST_USER_CREDENTIALS.getPublicKey(), TEST_CLIENT_ID);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.echocat.marquardt.common.TestKeyPairProvider;
import org.echocat.marquardt.common.domain.Signature;
import org.echocat.marquardt.common.exceptions.AlreadyLoggedInException;
import org.echocat.marquardt.common.exceptions.ClientNotAuthorizedException;
import org.echocat.marquardt.common.exceptions.LoginFailedException;
import org.echocat.marquardt.common.exceptions.NoSessionFoundException;
import org.echocat.marquardt.common.exceptions.SignatureValidationFailedException;
Expand All @@ -33,6 +34,7 @@
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import javax.validation.ValidationException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

Expand All @@ -43,6 +45,7 @@
import static org.hamcrest.core.IsNull.nullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

Expand Down Expand Up @@ -79,7 +82,6 @@ public void setup() throws Exception {
when(_signature.isValidFor(any(), any())).thenReturn(true);
super.setup();
_authority = new Authority<>(_userStore, _sessionStore, getSessionCreationPolicy(), _clientAccessPolicy, _issuerKeyProvider, _expiryDateCalculator);

}

@Test
Expand All @@ -91,7 +93,7 @@ public void shouldSignUpUser() throws Exception {
}

@Test(expected = CertificateCreationException.class)
public void shouldThrowCertificateCreationExceptionWhenSignupAndSignableSerializationFails() throws Exception {
public void shouldThrowCertificateCreationExceptionWhenSignUpAndSignableSerializationFails() throws Exception {
givenUserDoesNotExist();
givenSignableThrowingException();
whenSigningUp();
Expand All @@ -103,8 +105,15 @@ public void shouldThrowExceptionWhenUserAlreadyExistsWhenSignUp() throws Excepti
whenSigningUp();
}

@Test(expected = ClientNotAuthorizedException.class)
public void shouldThrowExceptionOnSignUpWhenClientPolicyProhibitsId() {
givenClientIdIsProhibited();
givenUserDoesNotExist();
whenSigningUp();
}

@Test
public void shouldSigninUser() throws Exception {
public void shouldSignInUser() throws Exception {
givenUserExists();
givenNoExistingSession();
givenSessionCreationPolicyAllowsAnotherSession();
Expand All @@ -113,8 +122,16 @@ public void shouldSigninUser() throws Exception {
thenCertificateIsMade();
}

@Test(expected = ClientNotAuthorizedException.class)
public void shouldThrowExceptionOnSignInWhenClientPolicyProhibitsId() {
givenClientIdIsProhibited();
givenUserExists();
givenNoExistingSession();
whenSigningIn();
}

@Test(expected = CertificateCreationException.class)
public void shouldThrowCerificateCreationFailedExceptionWhenSigningInButPayloadCannotBeSigned() throws Exception {
public void shouldThrowCertificateCreationFailedExceptionWhenSigningInButPayloadCannotBeSigned() throws Exception {
givenUserExists();
givenNoExistingSession();
givenSessionCreationPolicyAllowsAnotherSession();
Expand Down Expand Up @@ -151,6 +168,14 @@ public void shouldRefreshCertificate() throws Exception {
thenCertificateIsMade();
}

@Test(expected = ClientNotAuthorizedException.class)
public void shouldThrowExceptionOnRefreshWhenClientPolicyProhibitsId() {
givenClientIdIsProhibited();
givenUserExists();
givenExistingSession();
whenRefreshingCertificate();
}

@Test(expected = SignatureValidationFailedException.class)
public void shouldThrowExceptionWhenSignatureIsInvalidOnRefresh() throws Exception {
givenUserExists();
Expand Down Expand Up @@ -229,6 +254,32 @@ public void shouldAllowToSetDateProvider() throws Exception {
thenSessionExpiringNextYearIsCreated();
}

@Test(expected = ValidationException.class)
public void shouldAllowUserCheckConsumerToThrowExceptionOnRefresh() {
givenAuthorityIsConfiguredWithExceptionThrowingConsumer();
givenUserExists();
givenExistingSession();
whenRefreshingCertificate();
}

@Test(expected = ValidationException.class)
public void shouldAllowUserCheckConsumerToThrowExceptionOnSignIn() {
givenAuthorityIsConfiguredWithExceptionThrowingConsumer();
givenUserExists();
givenNoExistingSession();
whenSigningIn();
}

private void givenClientIdIsProhibited() {
doReturn(false).when(_clientAccessPolicy).isAllowed(TEST_CLIENT_ID);
}

private void givenAuthorityIsConfiguredWithExceptionThrowingConsumer() {
_authority.setCheckUserToFulfillAllRequirementsToSignInOrRefreshConsumer(testUser -> {
throw new ValidationException();
});
}

private void givenCustomDateProvider() {
_expiryDateCalculator.setDateProvider(CUSTOM_DATE_PROVIDER);
}
Expand Down

0 comments on commit 7c92526

Please sign in to comment.