#472 Add translatable messages and unit tests

This commit is contained in:
ljacqu
2016-09-16 23:18:32 +02:00
parent e30d7220bd
commit c78acee6e0
8 changed files with 196 additions and 15 deletions
@@ -1,5 +1,6 @@
package fr.xephi.authme.service;
import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Settings;
@@ -17,7 +18,7 @@ import static fr.xephi.authme.util.Utils.MILLIS_PER_HOUR;
*/
public class RecoveryCodeManager implements SettingsDependent {
private Map<String, TimedEntry> recoveryCodes = new ConcurrentHashMap<>();
private Map<String, ExpiringEntry> recoveryCodes = new ConcurrentHashMap<>();
private int recoveryCodeLength;
private long recoveryCodeExpirationMillis;
@@ -27,24 +28,45 @@ public class RecoveryCodeManager implements SettingsDependent {
reload(settings);
}
/**
* @return whether recovery codes are enabled or not
*/
public boolean isRecoveryCodeNeeded() {
return recoveryCodeExpirationMillis > 0;
return recoveryCodeLength > 0 && recoveryCodeExpirationMillis > 0;
}
/**
* Generates the recovery code for the given player.
*
* @param player the player to generate a code for
* @return the generated code
*/
public String generateCode(String player) {
String code = RandomString.generateHex(recoveryCodeLength);
recoveryCodes.put(player, new TimedEntry(code, System.currentTimeMillis() + recoveryCodeExpirationMillis));
recoveryCodes.put(player, new ExpiringEntry(code, System.currentTimeMillis() + recoveryCodeExpirationMillis));
return code;
}
/**
* Checks whether the supplied code is valid for the given player.
*
* @param player the player to check for
* @param code the code to check
* @return true if the code matches and has not expired, false otherwise
*/
public boolean isCodeValid(String player, String code) {
TimedEntry entry = recoveryCodes.get(player);
ExpiringEntry entry = recoveryCodes.get(player);
if (entry != null) {
return code != null && code.equals(entry.getCode());
}
return false;
}
/**
* Removes the player's recovery code if present.
*
* @param player the player
*/
public void removeCode(String player) {
recoveryCodes.remove(player);
}
@@ -55,17 +77,21 @@ public class RecoveryCodeManager implements SettingsDependent {
recoveryCodeExpirationMillis = settings.getProperty(RECOVERY_CODE_HOURS_VALID) * MILLIS_PER_HOUR;
}
private static final class TimedEntry {
/**
* Entry with an expiration.
*/
@VisibleForTesting
static final class ExpiringEntry {
private final String code;
private final long expiration;
TimedEntry(String code, long expiration) {
ExpiringEntry(String code, long expiration) {
this.code = code;
this.expiration = expiration;
}
public String getCode() {
String getCode() {
return System.currentTimeMillis() < expiration ? code : null;
}
}