Merge pull request #220 from AuthMe/1073-email-cooldown

Configurable cooldown for /email recovery
This commit is contained in:
ljacqu
2017-02-26 22:44:39 +01:00
committed by GitHub
41 changed files with 612 additions and 119 deletions
@@ -1,29 +1,39 @@
package fr.xephi.authme.command.executable.email;
import ch.jalu.injector.testing.BeforeInjecting;
import ch.jalu.injector.testing.DelayedInjectionRunner;
import ch.jalu.injector.testing.InjectDelayed;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.RecoveryCodeService;
import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.util.expiring.Duration;
import org.bukkit.entity.Player;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.Mockito;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import static fr.xephi.authme.AuthMeMatchers.stringWithLength;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -38,19 +48,19 @@ import static org.mockito.Mockito.verifyZeroInteractions;
/**
* Test for {@link RecoverEmailCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
@RunWith(DelayedInjectionRunner.class)
public class RecoverEmailCommandTest {
private static final String DEFAULT_EMAIL = "your@email.com";
@InjectMocks
@InjectDelayed
private RecoverEmailCommand command;
@Mock
private PasswordSecurity passwordSecurity;
@Mock
private CommonService commandService;
private CommonService commonService;
@Mock
private DataSource dataSource;
@@ -64,11 +74,19 @@ public class RecoverEmailCommandTest {
@Mock
private RecoveryCodeService recoveryCodeService;
@Mock
private Messages messages;
@BeforeClass
public static void initLogger() {
TestHelper.setupLogger();
}
@BeforeInjecting
public void initSettings() {
given(commonService.getProperty(SecuritySettings.EMAIL_RECOVERY_COOLDOWN_SECONDS)).willReturn(40);
}
@Test
public void shouldHandleMissingMailProperties() {
// given
@@ -79,7 +97,7 @@ public class RecoverEmailCommandTest {
command.executeCommand(sender, Collections.singletonList("some@email.tld"));
// then
verify(commandService).send(sender, MessageKey.INCOMPLETE_EMAIL_SETTINGS);
verify(commonService).send(sender, MessageKey.INCOMPLETE_EMAIL_SETTINGS);
verifyZeroInteractions(dataSource, passwordSecurity);
}
@@ -98,7 +116,7 @@ public class RecoverEmailCommandTest {
// then
verify(emailService).hasAllInformation();
verifyZeroInteractions(dataSource);
verify(commandService).send(sender, MessageKey.ALREADY_LOGGED_IN_ERROR);
verify(commonService).send(sender, MessageKey.ALREADY_LOGGED_IN_ERROR);
}
@Test
@@ -118,7 +136,7 @@ public class RecoverEmailCommandTest {
verify(emailService).hasAllInformation();
verify(dataSource).getAuth(name);
verifyNoMoreInteractions(dataSource);
verify(commandService).send(sender, MessageKey.USAGE_REGISTER);
verify(commonService).send(sender, MessageKey.USAGE_REGISTER);
}
@Test
@@ -138,7 +156,7 @@ public class RecoverEmailCommandTest {
verify(emailService).hasAllInformation();
verify(dataSource).getAuth(name);
verifyNoMoreInteractions(dataSource);
verify(commandService).send(sender, MessageKey.INVALID_EMAIL);
verify(commonService).send(sender, MessageKey.INVALID_EMAIL);
}
@Test
@@ -158,7 +176,7 @@ public class RecoverEmailCommandTest {
verify(emailService).hasAllInformation();
verify(dataSource).getAuth(name);
verifyNoMoreInteractions(dataSource);
verify(commandService).send(sender, MessageKey.INVALID_EMAIL);
verify(commonService).send(sender, MessageKey.INVALID_EMAIL);
}
@Test
@@ -183,7 +201,7 @@ public class RecoverEmailCommandTest {
verify(emailService).hasAllInformation();
verify(dataSource).getAuth(name);
verify(recoveryCodeService).generateCode(name);
verify(commandService).send(sender, MessageKey.RECOVERY_CODE_SENT);
verify(commonService).send(sender, MessageKey.RECOVERY_CODE_SENT);
verify(emailService).sendRecoveryCode(name, email, code);
}
@@ -207,7 +225,7 @@ public class RecoverEmailCommandTest {
// then
verify(emailService).hasAllInformation();
verify(dataSource, only()).getAuth(name);
verify(commandService).send(sender, MessageKey.INCORRECT_RECOVERY_CODE);
verify(commonService).send(sender, MessageKey.INCORRECT_RECOVERY_CODE);
verifyNoMoreInteractions(emailService);
}
@@ -224,7 +242,7 @@ public class RecoverEmailCommandTest {
String code = "A6EF3AC8";
PlayerAuth auth = newAuthWithEmail(email);
given(dataSource.getAuth(name)).willReturn(auth);
given(commandService.getProperty(EmailSettings.RECOVERY_PASSWORD_LENGTH)).willReturn(20);
given(commonService.getProperty(EmailSettings.RECOVERY_PASSWORD_LENGTH)).willReturn(20);
given(passwordSecurity.computeHash(anyString(), eq(name)))
.willAnswer(invocation -> new HashedPassword(invocation.getArgument(0)));
given(recoveryCodeService.isRecoveryCodeNeeded()).willReturn(true);
@@ -243,7 +261,7 @@ public class RecoverEmailCommandTest {
verify(dataSource).updatePassword(eq(name), any(HashedPassword.class));
verify(recoveryCodeService).removeCode(name);
verify(emailService).sendPasswordMail(name, email, generatedPassword);
verify(commandService).send(sender, MessageKey.RECOVERY_EMAIL_SENT_MESSAGE);
verify(commonService).send(sender, MessageKey.RECOVERY_EMAIL_SENT_MESSAGE);
}
@Test
@@ -258,7 +276,7 @@ public class RecoverEmailCommandTest {
String email = "shark@example.org";
PlayerAuth auth = newAuthWithEmail(email);
given(dataSource.getAuth(name)).willReturn(auth);
given(commandService.getProperty(EmailSettings.RECOVERY_PASSWORD_LENGTH)).willReturn(20);
given(commonService.getProperty(EmailSettings.RECOVERY_PASSWORD_LENGTH)).willReturn(20);
given(passwordSecurity.computeHash(anyString(), eq(name)))
.willAnswer(invocation -> new HashedPassword(invocation.getArgument(0)));
given(recoveryCodeService.isRecoveryCodeNeeded()).willReturn(false);
@@ -275,7 +293,40 @@ public class RecoverEmailCommandTest {
assertThat(generatedPassword, stringWithLength(20));
verify(dataSource).updatePassword(eq(name), any(HashedPassword.class));
verify(emailService).sendPasswordMail(name, email, generatedPassword);
verify(commandService).send(sender, MessageKey.RECOVERY_EMAIL_SENT_MESSAGE);
verify(commonService).send(sender, MessageKey.RECOVERY_EMAIL_SENT_MESSAGE);
}
@Test
public void shouldNotSendEmailIfCooldownCheckFails() {
// given
String name = "feverRay";
Player sender = mock(Player.class);
given(sender.getName()).willReturn(name);
given(emailService.hasAllInformation()).willReturn(true);
given(emailService.sendRecoveryCode(anyString(), anyString(), anyString())).willReturn(true);
given(playerCache.isAuthenticated(name)).willReturn(false);
String email = "mymail@example.org";
PlayerAuth auth = newAuthWithEmail(email);
given(dataSource.getAuth(name)).willReturn(auth);
given(recoveryCodeService.isRecoveryCodeNeeded()).willReturn(true);
given(recoveryCodeService.generateCode(anyString())).willReturn("Code");
// Trigger sending of recovery code
command.executeCommand(sender, Collections.singletonList(email));
Mockito.reset(emailService, commonService);
given(emailService.hasAllInformation()).willReturn(true);
given(messages.formatDuration(any(Duration.class))).willReturn("8 minutes");
// when
command.executeCommand(sender, Collections.singletonList(email));
// then
verify(emailService, only()).hasAllInformation();
ArgumentCaptor<Duration> durationCaptor = ArgumentCaptor.forClass(Duration.class);
verify(messages).formatDuration(durationCaptor.capture());
assertThat(durationCaptor.getValue().getDuration(), both(lessThan(41L)).and(greaterThan(36L)));
assertThat(durationCaptor.getValue().getTimeUnit(), equalTo(TimeUnit.SECONDS));
verify(messages).send(sender, MessageKey.EMAIL_COOLDOWN_ERROR, "8 minutes");
}
@@ -1,7 +1,9 @@
package fr.xephi.authme.message;
import com.google.common.collect.ImmutableMap;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.util.expiring.Duration;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Before;
@@ -11,6 +13,8 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Logger;
@@ -230,6 +234,26 @@ public class MessagesIntegrationTest {
assertThat(result, equalTo("Use /captcha 24680 to solve the captcha"));
}
@Test
public void shouldFormatDurationObjects() {
// given
Map<Duration, String> expectedTexts = ImmutableMap.<Duration, String>builder()
.put(new Duration(1, TimeUnit.SECONDS), "1 second")
.put(new Duration(12, TimeUnit.SECONDS), "12 seconds")
.put(new Duration(1, TimeUnit.MINUTES), "1 minute")
.put(new Duration(0, TimeUnit.MINUTES), "0 minutes")
.put(new Duration(1, TimeUnit.HOURS), "1 hour")
.put(new Duration(-4, TimeUnit.HOURS), "-4 hours")
.put(new Duration(1, TimeUnit.DAYS), "1 day")
.put(new Duration(44, TimeUnit.DAYS), "44 days")
.build();
// when / then
for (Map.Entry<Duration, String> entry : expectedTexts.entrySet()) {
assertThat(messages.formatDuration(entry.getKey()), equalTo(entry.getValue()));
}
}
@SuppressWarnings("unchecked")
private static MessageFileHandlerProvider providerReturning(File file, String defaultFile) {
MessageFileHandlerProvider handler = mock(MessageFileHandlerProvider.class);
@@ -4,7 +4,6 @@ import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@@ -97,14 +96,31 @@ public class ExpiringSetTest {
set.add("my entry");
// when
long expiresInHours = set.getExpiration("my entry", TimeUnit.HOURS);
long expiresInMinutes = set.getExpiration("my entry", TimeUnit.MINUTES);
long unknownExpires = set.getExpiration("bogus", TimeUnit.SECONDS);
Duration expiration = set.getExpiration("my entry");
Duration unknownExpiration = set.getExpiration("bogus");
// then
assertThat(expiresInHours, equalTo(2L));
assertThat(expiresInMinutes, either(equalTo(122L)).or(equalTo(123L)));
assertThat(unknownExpires, equalTo(-1L));
assertIsDuration(expiration, 2, TimeUnit.HOURS);
assertIsDuration(unknownExpiration, -1, TimeUnit.SECONDS);
}
@Test
public void shouldReturnExpirationInSuitableUnits() {
// given
ExpiringSet<Integer> set = new ExpiringSet<>(601, TimeUnit.SECONDS);
set.add(12);
set.setExpiration(49, TimeUnit.HOURS);
set.add(23);
// when
Duration expiration12 = set.getExpiration(12);
Duration expiration23 = set.getExpiration(23);
Duration expectedUnknown = set.getExpiration(-100);
// then
assertIsDuration(expiration12, 10, TimeUnit.MINUTES);
assertIsDuration(expiration23, 2, TimeUnit.DAYS);
assertIsDuration(expectedUnknown, -1, TimeUnit.SECONDS);
}
@Test
@@ -114,9 +130,14 @@ public class ExpiringSetTest {
set.add(23);
// when
long expiresInSeconds = set.getExpiration(23, TimeUnit.SECONDS);
Duration expiration = set.getExpiration(23);
// then
assertThat(expiresInSeconds, equalTo(-1L));
assertIsDuration(expiration, -1, TimeUnit.SECONDS);
}
private static void assertIsDuration(Duration duration, long expectedDuration, TimeUnit expectedUnit) {
assertThat(duration.getTimeUnit(), equalTo(expectedUnit));
assertThat(duration.getDuration(), equalTo(expectedDuration));
}
}