From aeb8307a464fc6dcba17c9377cb7ea2c13afdcf1 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Tue, 1 Mar 2016 22:41:32 +0100 Subject: [PATCH 1/6] #432 #547 Remove public IP cache map; make processes use ProcessService - Create IP address manager for handling and caching IP addresses -> outside of the manager I do not want to care about caching details - Make more processes use the ProcessService in favor of statically injected objects --- src/main/java/fr/xephi/authme/AuthMe.java | 74 ++++++----------- .../xephi/authme/command/CommandService.java | 11 ++- .../executable/authme/GetIpCommand.java | 22 +++--- .../xephi/authme/hooks/BungeeCordMessage.java | 21 ++--- .../authme/manager/IpAddressManager.java | 79 +++++++++++++++++++ .../fr/xephi/authme/process/Management.java | 41 ++-------- .../xephi/authme/process/ProcessService.java | 19 ++++- .../process/email/AsyncChangeEmail.java | 6 +- .../authme/process/join/AsynchronousJoin.java | 16 ++-- .../process/login/AsynchronousLogin.java | 69 +++++++--------- .../authme/process/quit/AsynchronousQuit.java | 23 +++--- .../process/register/AsyncRegister.java | 63 ++++++++------- .../register/ProcessSyncEmailRegister.java | 43 +++++----- .../register/ProcessSyncPasswordRegister.java | 55 ++++++------- .../unregister/AsynchronousUnregister.java | 35 ++++---- .../fr/xephi/authme/settings/Settings.java | 6 +- .../fr/xephi/authme/task/MessageTask.java | 6 +- .../java/fr/xephi/authme/util/GeoLiteAPI.java | 3 + .../authme/command/CommandServiceTest.java | 16 +++- .../process/email/AsyncChangeEmailTest.java | 18 ++--- 20 files changed, 330 insertions(+), 296 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/manager/IpAddressManager.java diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 047cf4088..ceca76be9 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -1,8 +1,6 @@ package fr.xephi.authme; import com.earth2me.essentials.Essentials; -import com.google.common.base.Charsets; -import com.google.common.io.Resources; import com.onarandombox.MultiverseCore.MultiverseCore; import fr.xephi.authme.api.API; import fr.xephi.authme.api.NewAPI; @@ -35,6 +33,7 @@ import fr.xephi.authme.listener.AuthMeServerListener; import fr.xephi.authme.listener.AuthMeTabCompletePacketAdapter; import fr.xephi.authme.listener.AuthMeTablistPacketAdapter; import fr.xephi.authme.mail.SendMailSSL; +import fr.xephi.authme.manager.IpAddressManager; import fr.xephi.authme.output.ConsoleFilter; import fr.xephi.authme.output.Log4JFilter; import fr.xephi.authme.output.MessageKey; @@ -74,8 +73,6 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; import java.io.File; -import java.io.IOException; -import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; @@ -113,7 +110,7 @@ public class AuthMe extends JavaPlugin { public final ConcurrentHashMap sessions = new ConcurrentHashMap<>(); public final ConcurrentHashMap captcha = new ConcurrentHashMap<>(); public final ConcurrentHashMap cap = new ConcurrentHashMap<>(); - public final ConcurrentHashMap realIp = new ConcurrentHashMap<>(); + /* * Public Instances * TODO #432: Encapsulation @@ -141,6 +138,7 @@ public class AuthMe extends JavaPlugin { private JsonCache playerBackup; private PasswordSecurity passwordSecurity; private DataSource database; + private IpAddressManager ipAddressManager; /** * Get the plugin's instance. @@ -253,10 +251,11 @@ public class AuthMe extends JavaPlugin { MigrationService.changePlainTextToSha256(newSettings, database, new SHA256()); passwordSecurity = new PasswordSecurity(getDataSource(), newSettings.getProperty(SecuritySettings.PASSWORD_HASH), Bukkit.getPluginManager(), newSettings.getProperty(SecuritySettings.SUPPORT_OLD_PASSWORD_HASH)); + ipAddressManager = new IpAddressManager(newSettings); // Set up the permissions manager and command handler permsMan = initializePermissionsManager(); - commandHandler = initializeCommandHandler(permsMan, messages, passwordSecurity, newSettings); + commandHandler = initializeCommandHandler(permsMan, messages, passwordSecurity, newSettings, ipAddressManager); // Setup otherAccounts file this.otherAccounts = OtherAccounts.getInstance(); @@ -305,11 +304,11 @@ public class AuthMe extends JavaPlugin { setupApi(); // Set up the management - ProcessService processService = new ProcessService(newSettings, messages, this); + ProcessService processService = new ProcessService(newSettings, messages, this, ipAddressManager); management = new Management(this, processService, database, PlayerCache.getInstance()); // Set up the BungeeCord hook - setupBungeeCordHook(); + setupBungeeCordHook(newSettings, ipAddressManager); // Reload support hook reloadSupportHook(); @@ -410,20 +409,22 @@ public class AuthMe extends JavaPlugin { /** * Set up the BungeeCord hook. */ - private void setupBungeeCordHook() { - if (newSettings.getProperty(HooksSettings.BUNGEECORD)) { + private void setupBungeeCordHook(NewSetting settings, IpAddressManager ipAddressManager) { + if (settings.getProperty(HooksSettings.BUNGEECORD)) { Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); + Bukkit.getMessenger().registerIncomingPluginChannel( + this, "BungeeCord", new BungeeCordMessage(this, ipAddressManager)); } } private CommandHandler initializeCommandHandler(PermissionsManager permissionsManager, Messages messages, - PasswordSecurity passwordSecurity, NewSetting settings) { + PasswordSecurity passwordSecurity, NewSetting settings, + IpAddressManager ipAddressManager) { HelpProvider helpProvider = new HelpProvider(permissionsManager, settings.getProperty(HELP_HEADER)); Set baseCommands = CommandInitializer.buildCommands(); CommandMapper mapper = new CommandMapper(baseCommands, permissionsManager); CommandService commandService = new CommandService( - this, mapper, helpProvider, messages, passwordSecurity, permissionsManager, settings); + this, mapper, helpProvider, messages, passwordSecurity, permissionsManager, settings, ipAddressManager); return new CommandHandler(commandService); } @@ -804,59 +805,28 @@ public class AuthMe extends JavaPlugin { public String replaceAllInfo(String message, Player player) { String playersOnline = Integer.toString(Utils.getOnlinePlayers().size()); + String ipAddress = ipAddressManager.getPlayerIp(player); return message .replace("&", "\u00a7") .replace("{PLAYER}", player.getName()) .replace("{ONLINE}", playersOnline) .replace("{MAXPLAYERS}", Integer.toString(server.getMaxPlayers())) - .replace("{IP}", getIP(player)) + .replace("{IP}", ipAddress) .replace("{LOGINS}", Integer.toString(PlayerCache.getInstance().getLogged())) .replace("{WORLD}", player.getWorld().getName()) .replace("{SERVER}", server.getServerName()) .replace("{VERSION}", server.getBukkitVersion()) - .replace("{COUNTRY}", GeoLiteAPI.getCountryName(getIP(player))); - } - - /** - * Gets a player's real IP through VeryGames method. - * - * @param player The player to process. - */ - @Deprecated - public void getVerygamesIp(final Player player) { - final String name = player.getName().toLowerCase(); - String currentIp = player.getAddress().getAddress().getHostAddress(); - if (realIp.containsKey(name)) { - currentIp = realIp.get(name); - } - String sUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%"; - sUrl = sUrl.replace("%IP%", currentIp).replace("%PORT%", "" + player.getAddress().getPort()); - try { - String result = Resources.toString(new URL(sUrl), Charsets.UTF_8); - if (!StringUtils.isEmpty(result) && !result.equalsIgnoreCase("error") && !result.contains("error")) { - currentIp = result; - realIp.put(name, currentIp); - } - } catch (IOException e) { - ConsoleLogger.showError("Could not fetch Very Games API with URL '" + - sUrl + "' - " + StringUtils.formatException(e)); - } - } - - public String getIP(final Player player) { - final String name = player.getName().toLowerCase(); - String ip = player.getAddress().getAddress().getHostAddress(); - if (realIp.containsKey(name)) { - ip = realIp.get(name); - } - return ip; + .replace("{COUNTRY}", GeoLiteAPI.getCountryName(ipAddress)); } public boolean isLoggedIp(String name, String ip) { int count = 0; for (Player player : Utils.getOnlinePlayers()) { - if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name)) - count++; + if (ip.equalsIgnoreCase(ipAddressManager.getPlayerIp(player)) + && database.isLogged(player.getName().toLowerCase()) + && !player.getName().equalsIgnoreCase(name)) { + ++count; + } } return count >= Settings.getMaxLoginPerIp; } diff --git a/src/main/java/fr/xephi/authme/command/CommandService.java b/src/main/java/fr/xephi/authme/command/CommandService.java index 5b8b5e490..7c348ced0 100644 --- a/src/main/java/fr/xephi/authme/command/CommandService.java +++ b/src/main/java/fr/xephi/authme/command/CommandService.java @@ -3,6 +3,7 @@ package fr.xephi.authme.command; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.manager.IpAddressManager; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.PermissionsManager; @@ -28,6 +29,7 @@ public class CommandService { private final PasswordSecurity passwordSecurity; private final PermissionsManager permissionsManager; private final NewSetting settings; + private final IpAddressManager ipAddressManager; /** * Constructor. @@ -41,8 +43,8 @@ public class CommandService { * @param settings The settings manager */ public CommandService(AuthMe authMe, CommandMapper commandMapper, HelpProvider helpProvider, Messages messages, - PasswordSecurity passwordSecurity, PermissionsManager permissionsManager, - NewSetting settings) { + PasswordSecurity passwordSecurity, PermissionsManager permissionsManager, NewSetting settings, + IpAddressManager ipAddressManager) { this.authMe = authMe; this.messages = messages; this.helpProvider = helpProvider; @@ -50,6 +52,7 @@ public class CommandService { this.passwordSecurity = passwordSecurity; this.permissionsManager = permissionsManager; this.settings = settings; + this.ipAddressManager = ipAddressManager; } /** @@ -192,4 +195,8 @@ public class CommandService { return settings; } + public IpAddressManager getIpAddressManager() { + return ipAddressManager; + } + } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java index 7554d0fa9..d3ba537d5 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java @@ -1,21 +1,18 @@ package fr.xephi.authme.command.executable.authme; -import java.util.List; - +import fr.xephi.authme.command.CommandService; +import fr.xephi.authme.command.ExecutableCommand; +import fr.xephi.authme.settings.properties.HooksSettings; +import fr.xephi.authme.util.Utils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.command.CommandService; -import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.util.Utils; +import java.util.List; public class GetIpCommand implements ExecutableCommand { @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { - final AuthMe plugin = AuthMe.getInstance(); - // Get the player query String playerName = (arguments.size() >= 1) ? arguments.get(0) : sender.getName(); @@ -25,9 +22,12 @@ public class GetIpCommand implements ExecutableCommand { return; } - // TODO ljacqu 20151212: Revise the messages (actual IP vs. real IP...?) - sender.sendMessage(player.getName() + "'s actual IP is : " + player.getAddress().getAddress().getHostAddress() + sender.sendMessage(player.getName() + "'s IP is: " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort()); - sender.sendMessage(player.getName() + "'s real IP is : " + plugin.getIP(player)); + + if (commandService.getProperty(HooksSettings.ENABLE_VERYGAMES_IP_CHECK)) { + sender.sendMessage(player.getName() + "'s real IP is: " + + commandService.getIpAddressManager().getPlayerIp(player)); + } } } diff --git a/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java b/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java index 0c4fd2de9..e29743558 100644 --- a/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java +++ b/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java @@ -7,6 +7,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.manager.IpAddressManager; import fr.xephi.authme.security.crypts.HashedPassword; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; @@ -15,30 +16,32 @@ import org.bukkit.plugin.messaging.PluginMessageListener; */ public class BungeeCordMessage implements PluginMessageListener { - public final AuthMe plugin; + private final AuthMe plugin; + private final IpAddressManager ipAddressManager; /** * Constructor for BungeeCordMessage. * * @param plugin AuthMe */ - public BungeeCordMessage(AuthMe plugin) { + public BungeeCordMessage(AuthMe plugin, IpAddressManager ipAddressManager) { this.plugin = plugin; + this.ipAddressManager = ipAddressManager; } @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("BungeeCord")) { + if (!"BungeeCord".equals(channel)) { return; } ByteArrayDataInput in = ByteStreams.newDataInput(message); String subChannel = in.readUTF(); - if (subChannel.equals("IP")) { // We need only the IP channel + if ("IP".equals(subChannel)) { // We need only the IP channel String ip = in.readUTF(); // Put the IP (only the ip not the port) in the hashMap - plugin.realIp.put(player.getName().toLowerCase(), ip); + ipAddressManager.addCache(player.getName(), ip); } - if (subChannel.equalsIgnoreCase("AuthMe")) { + if ("AuthMe".equalsIgnoreCase(subChannel)) { String str = in.readUTF(); final String[] args = str.split(";"); final String act = args[0]; @@ -65,10 +68,10 @@ public class BungeeCordMessage implements PluginMessageListener { ConsoleLogger.info("Player " + auth.getNickname() + " has registered out from one of your server!"); } else if ("changepassword".equals(act)) { - final String password = args[2]; + final String password = args[2]; final String salt = args.length >= 4 ? args[3] : null; - auth.setPassword(new HashedPassword(password, salt)); - PlayerCache.getInstance().updatePlayer(auth); + auth.setPassword(new HashedPassword(password, salt)); + PlayerCache.getInstance().updatePlayer(auth); dataSource.updatePassword(auth); } diff --git a/src/main/java/fr/xephi/authme/manager/IpAddressManager.java b/src/main/java/fr/xephi/authme/manager/IpAddressManager.java new file mode 100644 index 000000000..b8be8db3c --- /dev/null +++ b/src/main/java/fr/xephi/authme/manager/IpAddressManager.java @@ -0,0 +1,79 @@ +package fr.xephi.authme.manager; + +import com.google.common.base.Charsets; +import com.google.common.io.Resources; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.NewSetting; +import fr.xephi.authme.settings.properties.HooksSettings; +import fr.xephi.authme.util.StringUtils; +import org.bukkit.entity.Player; + +import java.io.IOException; +import java.net.URL; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Stateful manager for looking up IP address appropriately, including caching. + */ +public class IpAddressManager { + + /** Cache for IP lookups per player. */ + private final ConcurrentHashMap ipCache; + /** Whether or not to use the VeryGames API for IP lookups. */ + private final boolean useVeryGamesIpCheck; + + /** + * Constructor. + * + * @param settings The settings instance + */ + public IpAddressManager(NewSetting settings) { + this.useVeryGamesIpCheck = settings.getProperty(HooksSettings.ENABLE_VERYGAMES_IP_CHECK); + this.ipCache = new ConcurrentHashMap<>(); + } + + public String getPlayerIp(Player player) { + final String playerName = player.getName().toLowerCase(); + final String cachedValue = ipCache.get(playerName); + if (cachedValue != null) { + return cachedValue; + } + + final String plainIp = player.getAddress().getAddress().getHostAddress(); + if (useVeryGamesIpCheck) { + String veryGamesResult = getVeryGamesIp(plainIp, player.getAddress().getPort()); + if (veryGamesResult != null) { + ipCache.put(playerName, veryGamesResult); + return veryGamesResult; + } + } else { + ipCache.put(playerName, plainIp); + } + return plainIp; + } + + public void addCache(String player, String ip) { + ipCache.put(player.toLowerCase(), ip); + } + + public void removeCache(String player) { + ipCache.remove(player.toLowerCase()); + } + + // returns null if IP could not be looked up --> expect that it won't be cached + private String getVeryGamesIp(final String plainIp, final int port) { + final String sUrl = String.format("http://monitor-1.verygames.net/api/?action=ipclean-real-ip" + + "&out=raw&ip=%s&port=%d", plainIp, port); + + try { + String result = Resources.toString(new URL(sUrl), Charsets.UTF_8); + if (!StringUtils.isEmpty(result) && !result.contains("error")) { + return result; + } + } catch (IOException e) { + ConsoleLogger.logException("Could not fetch Very Games API with URL '" + sUrl + "':", e); + } + return null; + } + +} diff --git a/src/main/java/fr/xephi/authme/process/Management.java b/src/main/java/fr/xephi/authme/process/Management.java index a42884aeb..c981e0c00 100644 --- a/src/main/java/fr/xephi/authme/process/Management.java +++ b/src/main/java/fr/xephi/authme/process/Management.java @@ -43,14 +43,7 @@ public class Management { } public void performLogin(final Player player, final String password, final boolean forceLogin) { - sched.runTaskAsynchronously(plugin, new Runnable() { - - @Override - public void run() { - new AsynchronousLogin(player, password, forceLogin, plugin, dataSource, settings) - .process(); - } - }); + runTask(new AsynchronousLogin(player, password, forceLogin, plugin, dataSource, processService)); } public void performLogout(final Player player) { @@ -64,23 +57,11 @@ public class Management { } public void performRegister(final Player player, final String password, final String email) { - sched.runTaskAsynchronously(plugin, new Runnable() { - - @Override - public void run() { - new AsyncRegister(player, password, email, plugin, dataSource, settings).process(); - } - }); + runTask(new AsyncRegister(player, password, email, plugin, dataSource, processService)); } public void performUnregister(final Player player, final String password, final boolean force) { - sched.runTaskAsynchronously(plugin, new Runnable() { - - @Override - public void run() { - new AsynchronousUnregister(player, password, force, plugin).process(); - } - }); + runTask(new AsynchronousUnregister(player, password, force, plugin, processService)); } public void performJoin(final Player player) { @@ -88,14 +69,7 @@ public class Management { } public void performQuit(final Player player, final boolean isKick) { - sched.runTaskAsynchronously(plugin, new Runnable() { - - @Override - public void run() { - new AsynchronousQuit(player, plugin, dataSource, isKick).process(); - } - - }); + runTask(new AsynchronousQuit(player, plugin, dataSource, isKick, processService)); } public void performAddEmail(final Player player, final String newEmail) { @@ -103,12 +77,7 @@ public class Management { } public void performChangeEmail(final Player player, final String oldEmail, final String newEmail) { - sched.runTaskAsynchronously(plugin, new Runnable() { - @Override - public void run() { - new AsyncChangeEmail(player, plugin, oldEmail, newEmail, dataSource, playerCache, settings).process(); - } - }); + runTask(new AsyncChangeEmail(player, plugin, oldEmail, newEmail, dataSource, playerCache, settings)); } private void runTask(Process process) { diff --git a/src/main/java/fr/xephi/authme/process/ProcessService.java b/src/main/java/fr/xephi/authme/process/ProcessService.java index e52e4235b..621cdf8fa 100644 --- a/src/main/java/fr/xephi/authme/process/ProcessService.java +++ b/src/main/java/fr/xephi/authme/process/ProcessService.java @@ -1,6 +1,7 @@ package fr.xephi.authme.process; import fr.xephi.authme.AuthMe; +import fr.xephi.authme.manager.IpAddressManager; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.NewSetting; @@ -17,11 +18,13 @@ public class ProcessService { private final NewSetting settings; private final Messages messages; private final AuthMe authMe; + private final IpAddressManager ipAddressManager; - public ProcessService(NewSetting settings, Messages messages, AuthMe authMe) { + public ProcessService(NewSetting settings, Messages messages, AuthMe authMe, IpAddressManager ipAddressManager) { this.settings = settings; this.messages = messages; this.authMe = authMe; + this.ipAddressManager = ipAddressManager; } public T getProperty(Property property) { @@ -36,7 +39,15 @@ public class ProcessService { messages.send(sender, key); } - public String retrieveMessage(MessageKey key) { + public void send(CommandSender sender, MessageKey key, String... replacements) { + messages.send(sender, key, replacements); + } + + public String[] retrieveMessage(MessageKey key) { + return messages.retrieve(key); + } + + public String retrieveSingleMessage(MessageKey key) { return messages.retrieveSingle(key); } @@ -60,4 +71,8 @@ public class ProcessService { return authMe; } + public IpAddressManager getIpAddressManager() { + return ipAddressManager; + } + } diff --git a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java index f9bbbd073..22833a202 100644 --- a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java +++ b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java @@ -6,6 +6,7 @@ import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; +import fr.xephi.authme.process.Process; import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.Utils; @@ -14,7 +15,7 @@ import org.bukkit.entity.Player; /** * Async task for changing the email. */ -public class AsyncChangeEmail { +public class AsyncChangeEmail implements Process { private final Player player; private final String oldEmail; @@ -35,7 +36,8 @@ public class AsyncChangeEmail { this.settings = settings; } - public void process() { + @Override + public void run() { String playerName = player.getName().toLowerCase(); if (playerCache.isAuthenticated(playerName)) { PlayerAuth auth = playerCache.getAuth(playerName); diff --git a/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java b/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java index 455c7683a..04377825d 100644 --- a/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java +++ b/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java @@ -59,15 +59,11 @@ public class AsynchronousJoin implements Process { return; } - if (service.getProperty(HooksSettings.ENABLE_VERYGAMES_IP_CHECK)) { - plugin.getVerygamesIp(player); - } - if (plugin.ess != null && service.getProperty(HooksSettings.DISABLE_SOCIAL_SPY)) { plugin.ess.getUser(player).setSocialSpyEnabled(false); } - final String ip = plugin.getIP(player); + final String ip = service.getIpAddressManager().getPlayerIp(player); if (isNameRestricted(name, ip, player.getAddress().getHostName(), service.getSettings())) { @@ -75,7 +71,7 @@ public class AsynchronousJoin implements Process { @Override public void run() { AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); - player.kickPlayer(service.retrieveMessage(MessageKey.NOT_OWNER_ERROR)); + player.kickPlayer(service.retrieveSingleMessage(MessageKey.NOT_OWNER_ERROR)); if (Settings.banUnsafeIp) { plugin.getServer().banIP(ip); } @@ -87,7 +83,7 @@ public class AsynchronousJoin implements Process { && !plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS) && !"127.0.0.1".equalsIgnoreCase(ip) && !"localhost".equalsIgnoreCase(ip) - && hasJoinedIp(player.getName(), ip, service.getSettings(), service.getAuthMe())) { + && hasJoinedIp(player.getName(), ip, service.getSettings())) { service.scheduleSyncDelayedTask(new Runnable() { @Override public void run() { @@ -295,11 +291,13 @@ public class AsynchronousJoin implements Process { return nameFound; } - private boolean hasJoinedIp(String name, String ip, NewSetting settings, AuthMe authMe) { + private boolean hasJoinedIp(String name, String ip, NewSetting settings) { int count = 0; for (Player player : Utils.getOnlinePlayers()) { - if (ip.equalsIgnoreCase(authMe.getIP(player)) && !player.getName().equalsIgnoreCase(name)) + if (ip.equalsIgnoreCase(service.getIpAddressManager().getPlayerIp(player)) + && !player.getName().equalsIgnoreCase(name)) { count++; + } } return count >= settings.getProperty(RestrictionSettings.MAX_JOIN_PER_IP); } diff --git a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java index d6f1f3278..e9af5045c 100644 --- a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java @@ -8,14 +8,15 @@ import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.AdminPermission; import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.permission.PlayerStatePermission; +import fr.xephi.authme.process.Process; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.security.RandomString; -import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.RegistrationSettings; +import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.util.StringUtils; import fr.xephi.authme.util.Utils; @@ -27,7 +28,7 @@ import java.util.List; /** */ -public class AsynchronousLogin { +public class AsynchronousLogin implements Process { private final Player player; private final String name; @@ -36,23 +37,11 @@ public class AsynchronousLogin { private final boolean forceLogin; private final AuthMe plugin; private final DataSource database; - private final Messages m; private final String ip; - private final NewSetting settings; + private final ProcessService service; - /** - * Constructor for AsynchronousLogin. - * - * @param player Player - * @param password String - * @param forceLogin boolean - * @param plugin AuthMe - * @param data DataSource - * @param settings The settings - */ public AsynchronousLogin(Player player, String password, boolean forceLogin, AuthMe plugin, DataSource data, - NewSetting settings) { - this.m = plugin.getMessages(); + ProcessService service) { this.player = player; this.name = player.getName().toLowerCase(); this.password = password; @@ -60,12 +49,12 @@ public class AsynchronousLogin { this.forceLogin = forceLogin; this.plugin = plugin; this.database = data; - this.ip = plugin.getIP(player); - this.settings = settings; + this.ip = service.getIpAddressManager().getPlayerIp(player); + this.service = service; } private boolean needsCaptcha() { - if (Settings.useCaptcha) { + if (service.getProperty(SecuritySettings.USE_CAPTCHA)) { if (!plugin.captcha.containsKey(name)) { plugin.captcha.putIfAbsent(name, 1); } else { @@ -75,7 +64,7 @@ public class AsynchronousLogin { } if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) > Settings.maxLoginTry) { plugin.cap.putIfAbsent(name, RandomString.generate(Settings.captchaLength)); - m.send(player, MessageKey.USAGE_CAPTCHA, plugin.cap.get(name)); + service.send(player, MessageKey.USAGE_CAPTCHA, plugin.cap.get(name)); return true; } } @@ -90,30 +79,27 @@ public class AsynchronousLogin { */ private PlayerAuth preAuth() { if (PlayerCache.getInstance().isAuthenticated(name)) { - m.send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); + service.send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); return null; } PlayerAuth pAuth = database.getAuth(name); if (pAuth == null) { - m.send(player, MessageKey.USER_NOT_REGISTERED); + service.send(player, MessageKey.USER_NOT_REGISTERED); if (LimboCache.getInstance().hasLimboPlayer(name)) { LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId().cancel(); - String[] msg; - if (Settings.emailRegistration) { - msg = m.retrieve(MessageKey.REGISTER_EMAIL_MESSAGE); - } else { - msg = m.retrieve(MessageKey.REGISTER_MESSAGE); - } - BukkitTask msgT = Bukkit.getScheduler().runTask(plugin, - new MessageTask(plugin, name, msg, settings.getProperty(RegistrationSettings.MESSAGE_INTERVAL))); - LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); + String[] msg = service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION) + ? service.retrieveMessage(MessageKey.REGISTER_EMAIL_MESSAGE) + : service.retrieveMessage(MessageKey.REGISTER_MESSAGE); + BukkitTask messageTask = service.runTask( + new MessageTask(plugin, name, msg, service.getProperty(RegistrationSettings.MESSAGE_INTERVAL))); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(messageTask); } return null; } if (!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) { - m.send(player, MessageKey.ACCOUNT_NOT_ACTIVATED); + service.send(player, MessageKey.ACCOUNT_NOT_ACTIVATED); return null; } @@ -121,7 +107,7 @@ public class AsynchronousLogin { && !plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS) && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost")) { if (plugin.isLoggedIp(name, ip)) { - m.send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); + service.send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); return null; } } @@ -134,7 +120,8 @@ public class AsynchronousLogin { return pAuth; } - public void process() { + @Override + public void run() { PlayerAuth pAuth = preAuth(); if (pAuth == null || needsCaptcha()) { return; @@ -170,12 +157,12 @@ public class AsynchronousLogin { player.setNoDamageTicks(0); if (!forceLogin) - m.send(player, MessageKey.LOGIN_SUCCESS); + service.send(player, MessageKey.LOGIN_SUCCESS); displayOtherAccounts(auth); if (Settings.recallEmail && (StringUtils.isEmpty(email) || "your@email.com".equalsIgnoreCase(email))) { - m.send(player, MessageKey.ADD_EMAIL_MESSAGE); + service.send(player, MessageKey.ADD_EMAIL_MESSAGE); } if (!Settings.noConsoleSpam) { @@ -191,7 +178,8 @@ public class AsynchronousLogin { // task, we schedule it in the end // so that we can be sure, and have not to care if it might be // processed in other order. - ProcessSyncPlayerLogin syncPlayerLogin = new ProcessSyncPlayerLogin(player, plugin, database, settings); + ProcessSyncPlayerLogin syncPlayerLogin = new ProcessSyncPlayerLogin( + player, plugin, database, service.getSettings()); if (syncPlayerLogin.getLimbo() != null) { if (syncPlayerLogin.getLimbo().getTimeoutTaskId() != null) { syncPlayerLogin.getLimbo().getTimeoutTaskId().cancel(); @@ -206,14 +194,13 @@ public class AsynchronousLogin { ConsoleLogger.info(realName + " used the wrong password"); if (Settings.isKickOnWrongPasswordEnabled) { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override public void run() { - player.kickPlayer(m.retrieveSingle(MessageKey.WRONG_PASSWORD)); + player.kickPlayer(service.retrieveSingleMessage(MessageKey.WRONG_PASSWORD)); } }); } else { - m.send(player, MessageKey.WRONG_PASSWORD); + service.send(player, MessageKey.WRONG_PASSWORD); } } else { ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... "); diff --git a/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java b/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java index 7f716e7e6..3f930e44f 100644 --- a/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java +++ b/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java @@ -7,7 +7,10 @@ import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.datasource.CacheDataSource; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.process.Process; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.util.StringUtils; import fr.xephi.authme.util.Utils; import org.bukkit.Bukkit; @@ -15,7 +18,7 @@ import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; -public class AsynchronousQuit { +public class AsynchronousQuit implements Process { private final AuthMe plugin; private final DataSource database; @@ -23,26 +26,28 @@ public class AsynchronousQuit { private final String name; private boolean isOp = false; private boolean needToChange = false; - private boolean isKick = false; + private final boolean isKick; + private final ProcessService service; - public AsynchronousQuit(Player p, AuthMe plugin, DataSource database, - boolean isKick) { + public AsynchronousQuit(Player p, AuthMe plugin, DataSource database, boolean isKick, ProcessService service) { this.player = p; this.plugin = plugin; this.database = database; this.name = p.getName().toLowerCase(); this.isKick = isKick; + this.service = service; } - public void process() { + @Override + public void run() { if (player == null || Utils.isUnrestricted(player)) { return; } - String ip = plugin.getIP(player); + String ip = service.getIpAddressManager().getPlayerIp(player); if (PlayerCache.getInstance().isAuthenticated(name)) { - if (Settings.isSaveQuitLocationEnabled) { + if (service.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)) { Location loc = player.getLocation(); PlayerAuth auth = PlayerAuth.builder() .name(name).location(loc) @@ -76,7 +81,7 @@ public class AsynchronousQuit { plugin.sessions.put(name, task); } else { - //plugin is disable we canno schedule more tasks so run it directly here + //plugin is disabled; we cannot schedule more tasks so run it directly here postLogout(); } } @@ -85,7 +90,7 @@ public class AsynchronousQuit { database.setUnlogged(name); } - plugin.realIp.remove(name); + service.getIpAddressManager().removeCache(player.getName()); if (plugin.isEnabled()) { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerQuit(plugin, player, isOp, needToChange)); } diff --git a/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java b/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java index 97344ba04..fc7407382 100644 --- a/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java @@ -1,25 +1,25 @@ package fr.xephi.authme.process.register; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.PlayerStatePermission; +import fr.xephi.authme.process.Process; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.TwoFactor; -import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; /** */ -public class AsyncRegister { +public class AsyncRegister implements Process { private final Player player; private final String name; @@ -28,66 +28,65 @@ public class AsyncRegister { private final String email; private final AuthMe plugin; private final DataSource database; - private final Messages m; - private final NewSetting settings; + private final ProcessService service; public AsyncRegister(Player player, String password, String email, AuthMe plugin, DataSource data, - NewSetting settings) { - this.m = plugin.getMessages(); + ProcessService service) { this.player = player; this.password = password; this.name = player.getName().toLowerCase(); this.email = email; this.plugin = plugin; this.database = data; - this.ip = plugin.getIP(player); - this.settings = settings; + this.ip = service.getIpAddressManager().getPlayerIp(player); + this.service = service; } private boolean preRegisterCheck() { String passLow = password.toLowerCase(); if (PlayerCache.getInstance().isAuthenticated(name)) { - m.send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); + service.send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); return false; } else if (!Settings.isRegistrationEnabled) { - m.send(player, MessageKey.REGISTRATION_DISABLED); + service.send(player, MessageKey.REGISTRATION_DISABLED); return false; } //check the password safety only if it's not a automatically generated password - if (Settings.getPasswordHash != HashAlgorithm.TWO_FACTOR) { + if (service.getProperty(SecuritySettings.PASSWORD_HASH) != HashAlgorithm.TWO_FACTOR) { if (!passLow.matches(Settings.getPassRegex)) { - m.send(player, MessageKey.PASSWORD_MATCH_ERROR); + service.send(player, MessageKey.PASSWORD_MATCH_ERROR); return false; } else if (passLow.equalsIgnoreCase(player.getName())) { - m.send(player, MessageKey.PASSWORD_IS_USERNAME_ERROR); + service.send(player, MessageKey.PASSWORD_IS_USERNAME_ERROR); return false; } else if (password.length() < Settings.getPasswordMinLen || password.length() > Settings.passwordMaxLength) { - m.send(player, MessageKey.INVALID_PASSWORD_LENGTH); + service.send(player, MessageKey.INVALID_PASSWORD_LENGTH); return false; } else if (!Settings.unsafePasswords.isEmpty() && Settings.unsafePasswords.contains(password.toLowerCase())) { - m.send(player, MessageKey.PASSWORD_UNSAFE_ERROR); + service.send(player, MessageKey.PASSWORD_UNSAFE_ERROR); return false; } } - //check this in both possiblities so don't use 'else if' - Integer size = 0; + //check this in both possibilities so don't use 'else if' + int size; if (database.isAuthAvailable(name)) { - m.send(player, MessageKey.NAME_ALREADY_REGISTERED); + service.send(player, MessageKey.NAME_ALREADY_REGISTERED); return false; } else if (Settings.getmaxRegPerIp > 0 && !plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS) && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost") && (size = database.getAllAuthsByIp(ip).size()) >= Settings.getmaxRegPerIp) { - m.send(player, MessageKey.MAX_REGISTER_EXCEEDED, size.toString()); + service.send(player, MessageKey.MAX_REGISTER_EXCEEDED, Integer.toString(size)); return false; } return true; } - public void process() { + @Override + public void run() { if (preRegisterCheck()) { if (!StringUtils.isEmpty(email)) { emailRegister(); @@ -98,11 +97,11 @@ public class AsyncRegister { } private void emailRegister() { - Integer size = 0; + int size; if (Settings.getmaxRegPerEmail > 0 && !plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS) && (size = database.countAuthsByEmail(email)) >= Settings.getmaxRegPerEmail) { - m.send(player, MessageKey.MAX_REGISTER_EXCEEDED, size.toString()); + service.send(player, MessageKey.MAX_REGISTER_EXCEEDED, Integer.toString(size)); return; } final HashedPassword hashedPassword = plugin.getPasswordSecurity().computeHash(password, name); @@ -116,13 +115,13 @@ public class AsyncRegister { .build(); if (!database.saveAuth(auth)) { - m.send(player, MessageKey.ERROR); + service.send(player, MessageKey.ERROR); return; } database.updateEmail(auth); database.updateSession(auth); plugin.mail.main(auth, password); - ProcessSyncEmailRegister sync = new ProcessSyncEmailRegister(player, plugin); + ProcessSyncEmailRegister sync = new ProcessSyncEmailRegister(player, service); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, sync); } @@ -138,7 +137,7 @@ public class AsyncRegister { .build(); if (!database.saveAuth(auth)) { - m.send(player, MessageKey.ERROR); + service.send(player, MessageKey.ERROR); return; } @@ -150,13 +149,13 @@ public class AsyncRegister { } plugin.otherAccounts.addPlayer(player.getUniqueId()); - ProcessSyncPasswordRegister sync = new ProcessSyncPasswordRegister(player, plugin, settings); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, sync); + ProcessSyncPasswordRegister sync = new ProcessSyncPasswordRegister(player, plugin, service); + service.scheduleSyncDelayedTask(sync); //give the user the secret code to setup their app code generation if (Settings.getPasswordHash == HashAlgorithm.TWO_FACTOR) { String qrCodeUrl = TwoFactor.getQRBarcodeURL(player.getName(), Bukkit.getIp(), hashedPassword.getHash()); - m.send(player, MessageKey.TWO_FACTOR_CREATE, hashedPassword.getHash(), qrCodeUrl); + service.send(player, MessageKey.TWO_FACTOR_CREATE, hashedPassword.getHash(), qrCodeUrl); } } } diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java index 47264c0f1..1c2ac25c1 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java @@ -1,17 +1,18 @@ package fr.xephi.authme.process.register; -import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.RegistrationSettings; +import fr.xephi.authme.settings.properties.RestrictionSettings; +import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.util.Utils; import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; /** @@ -20,51 +21,43 @@ public class ProcessSyncEmailRegister implements Runnable { protected final Player player; protected final String name; - private final AuthMe plugin; - private final Messages m; + private final ProcessService service; /** * Constructor for ProcessSyncEmailRegister. * - * @param player Player - * @param plugin AuthMe + * @param player The player to process an email registration for + * @param service The process service */ - public ProcessSyncEmailRegister(Player player, AuthMe plugin) { - this.m = plugin.getMessages(); + public ProcessSyncEmailRegister(Player player, ProcessService service) { this.player = player; this.name = player.getName().toLowerCase(); - this.plugin = plugin; + this.service = service; } - /** - * Method run. - * - * @see java.lang.Runnable#run() - */ @Override public void run() { LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); if (!Settings.getRegisteredGroup.isEmpty()) { Utils.setGroup(player, Utils.GroupType.REGISTERED); } - m.send(player, MessageKey.ACCOUNT_NOT_ACTIVATED); - int time = Settings.getRegistrationTimeout * 20; - int msgInterval = Settings.getWarnMessageInterval; - - BukkitScheduler sched = plugin.getServer().getScheduler(); + service.send(player, MessageKey.ACCOUNT_NOT_ACTIVATED); + int time = service.getProperty(RestrictionSettings.TIMEOUT) * 20; + int msgInterval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); if (limbo != null) { if (time != 0) { - BukkitTask id = sched.runTaskLater(plugin, new TimeoutTask(plugin, name, player), time); + BukkitTask id = service.runTaskLater(new TimeoutTask(service.getAuthMe(), name, player), time); limbo.setTimeoutTaskId(id); } - BukkitTask nwMsg = sched.runTask(plugin, new MessageTask(plugin, name, m.retrieve(MessageKey.LOGIN_MESSAGE), msgInterval)); - limbo.setMessageTaskId(nwMsg); + BukkitTask messageTask = service.runTask(new MessageTask( + service.getAuthMe(), name, service.retrieveMessage(MessageKey.LOGIN_MESSAGE), msgInterval)); + limbo.setMessageTaskId(messageTask); } player.saveData(); - if (!Settings.noConsoleSpam) { - ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player)); + if (!service.getProperty(SecuritySettings.REMOVE_SPAM_FROM_CONSOLE)) { + ConsoleLogger.info(player.getName() + " registered " + service.getIpAddressManager().getPlayerIp(player)); } } diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java index 9f9f8919a..5efc09b55 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java @@ -9,42 +9,34 @@ import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.events.LoginEvent; import fr.xephi.authme.events.RestoreInventoryEvent; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; -import fr.xephi.authme.settings.NewSetting; +import fr.xephi.authme.process.Process; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.HooksSettings; +import fr.xephi.authme.settings.properties.RegistrationSettings; +import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.util.Utils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; /** */ -public class ProcessSyncPasswordRegister implements Runnable { +public class ProcessSyncPasswordRegister implements Process { protected final Player player; protected final String name; private final AuthMe plugin; - private final Messages m; - private final NewSetting settings; + private final ProcessService service; - /** - * Constructor for ProcessSyncPasswordRegister. - * - * @param player Player - * @param plugin AuthMe - * @param settings The plugin settings - */ - public ProcessSyncPasswordRegister(Player player, AuthMe plugin, NewSetting settings) { - this.m = plugin.getMessages(); + public ProcessSyncPasswordRegister(Player player, AuthMe plugin, ProcessService service) { this.player = player; this.name = player.getName().toLowerCase(); this.plugin = plugin; - this.settings = settings; + this.service = service; } private void sendBungeeMessage() { @@ -70,15 +62,14 @@ public class ProcessSyncPasswordRegister implements Runnable { Utils.teleportToSpawn(player); LimboCache cache = LimboCache.getInstance(); cache.updateLimboPlayer(player); - int delay = Settings.getRegistrationTimeout * 20; - int interval = Settings.getWarnMessageInterval; - BukkitScheduler sched = plugin.getServer().getScheduler(); + int delay = service.getProperty(RestrictionSettings.TIMEOUT) * 20; + int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); BukkitTask task; if (delay != 0) { - task = sched.runTaskLater(plugin, new TimeoutTask(plugin, name, player), delay); + task = service.runTaskLater(new TimeoutTask(service.getAuthMe(), name, player), delay); cache.getLimboPlayer(name).setTimeoutTaskId(task); } - task = sched.runTask(plugin, new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); + task = service.runTask(new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); cache.getLimboPlayer(name).setMessageTaskId(task); if (player.isInsideVehicle() && player.getVehicle() != null) { player.getVehicle().eject(); @@ -106,13 +97,13 @@ public class ProcessSyncPasswordRegister implements Runnable { Utils.setGroup(player, Utils.GroupType.REGISTERED); } - m.send(player, MessageKey.REGISTER_SUCCESS); + service.send(player, MessageKey.REGISTER_SUCCESS); if (!Settings.getmailAccount.isEmpty()) { - m.send(player, MessageKey.ADD_EMAIL_MESSAGE); + service.send(player, MessageKey.ADD_EMAIL_MESSAGE); } - if (Settings.applyBlindEffect) { + if (service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { player.removePotionEffect(PotionEffectType.BLINDNESS); } @@ -121,23 +112,23 @@ public class ProcessSyncPasswordRegister implements Runnable { player.saveData(); if (!Settings.noConsoleSpam) { - ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player)); + ConsoleLogger.info(player.getName() + " registered " + service.getIpAddressManager().getPlayerIp(player)); } // Kick Player after Registration is enabled, kick the player if (Settings.forceRegKick) { - player.kickPlayer(m.retrieveSingle(MessageKey.REGISTER_SUCCESS)); + player.kickPlayer(service.retrieveSingleMessage(MessageKey.REGISTER_SUCCESS)); return; } // Register is finish and player is logged, display welcome message - if (Settings.useWelcomeMessage) { - if (Settings.broadcastWelcomeMessage) { - for (String s : settings.getWelcomeMessage()) { + if (service.getProperty(RegistrationSettings.USE_WELCOME_MESSAGE)) { + if (service.getProperty(RegistrationSettings.BROADCAST_WELCOME_MESSAGE)) { + for (String s : service.getSettings().getWelcomeMessage()) { plugin.getServer().broadcastMessage(plugin.replaceAllInfo(s, player)); } } else { - for (String s : settings.getWelcomeMessage()) { + for (String s : service.getSettings().getWelcomeMessage()) { player.sendMessage(plugin.replaceAllInfo(s, player)); } } @@ -160,10 +151,10 @@ public class ProcessSyncPasswordRegister implements Runnable { } private void sendTo() { - if (!settings.getProperty(HooksSettings.BUNGEECORD_SERVER).isEmpty()) { + if (!service.getProperty(HooksSettings.BUNGEECORD_SERVER).isEmpty()) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect"); - out.writeUTF(settings.getProperty(HooksSettings.BUNGEECORD_SERVER)); + out.writeUTF(service.getProperty(HooksSettings.BUNGEECORD_SERVER)); player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); } } diff --git a/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java b/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java index 7da80c390..13353a80b 100644 --- a/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java +++ b/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java @@ -8,8 +8,11 @@ import fr.xephi.authme.cache.backup.JsonCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; +import fr.xephi.authme.process.Process; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.RegistrationSettings; +import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.util.Utils; @@ -20,15 +23,15 @@ import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; -public class AsynchronousUnregister { +public class AsynchronousUnregister implements Process { private final Player player; private final String name; private final String password; private final boolean force; private final AuthMe plugin; - private final Messages m; private final JsonCache playerCache; + private final ProcessService service; /** * Constructor for AsynchronousUnregister. @@ -38,29 +41,27 @@ public class AsynchronousUnregister { * @param force boolean * @param plugin AuthMe */ - public AsynchronousUnregister(Player player, String password, boolean force, AuthMe plugin) { - this.m = plugin.getMessages(); + public AsynchronousUnregister(Player player, String password, boolean force, AuthMe plugin, + ProcessService service) { this.player = player; this.name = player.getName().toLowerCase(); this.password = password; this.force = force; this.plugin = plugin; this.playerCache = new JsonCache(); + this.service = service; } - protected String getIp() { - return plugin.getIP(player); - } - - public void process() { + @Override + public void run() { PlayerAuth cachedAuth = PlayerCache.getInstance().getAuth(name); if (force || plugin.getPasswordSecurity().comparePassword( password, cachedAuth.getPassword(), player.getName())) { if (!plugin.getDataSource().removeAuth(name)) { - m.send(player, MessageKey.ERROR); + service.send(player, MessageKey.ERROR); return; } - int timeOut = Settings.getRegistrationTimeout * 20; + int timeOut = service.getProperty(RestrictionSettings.TIMEOUT) * 20; if (Settings.isForcedRegistrationEnabled) { Utils.teleportToSpawn(player); player.saveData(); @@ -70,7 +71,7 @@ public class AsynchronousUnregister { } LimboCache.getInstance().addLimboPlayer(player); LimboPlayer limboPlayer = LimboCache.getInstance().getLimboPlayer(name); - int interval = Settings.getWarnMessageInterval; + int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); BukkitScheduler scheduler = plugin.getServer().getScheduler(); if (timeOut != 0) { BukkitTask id = scheduler.runTaskLater(plugin, new TimeoutTask(plugin, name, player), timeOut); @@ -78,7 +79,7 @@ public class AsynchronousUnregister { } limboPlayer.setMessageTaskId(scheduler.runTask(plugin, new MessageTask(plugin, name, MessageKey.REGISTER_MESSAGE, interval))); - m.send(player, MessageKey.UNREGISTERED_SUCCESS); + service.send(player, MessageKey.UNREGISTERED_SUCCESS); ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); return; } @@ -92,14 +93,14 @@ public class AsynchronousUnregister { playerCache.removeCache(player); } // Apply blind effect - if (Settings.applyBlindEffect) { + if (service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, timeOut, 2)); } - m.send(player, MessageKey.UNREGISTERED_SUCCESS); + service.send(player, MessageKey.UNREGISTERED_SUCCESS); ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); Utils.teleportToSpawn(player); } else { - m.send(player, MessageKey.WRONG_PASSWORD); + service.send(player, MessageKey.WRONG_PASSWORD); } } } diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index 591e55a0c..4439bd255 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -158,7 +158,7 @@ public final class Settings { rakamakUsers = configFile.getString("Converter.Rakamak.fileName", "users.rak"); rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName", "UsersIp.rak"); rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false); - noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", false); + noConsoleSpam = load(SecuritySettings.REMOVE_SPAM_FROM_CONSOLE); removePassword = configFile.getBoolean("Security.console.removePassword", true); getmailAccount = configFile.getString("Email.mailAccount", ""); getMailPort = configFile.getInt("Email.mailPort", 465); @@ -197,10 +197,10 @@ public final class Settings { forceCommandsAsConsole = configFile.getStringList("settings.forceCommandsAsConsole"); recallEmail = configFile.getBoolean("Email.recallPlayers", false); delayRecall = configFile.getInt("Email.delayRecall", 5); - useWelcomeMessage = configFile.getBoolean("settings.useWelcomeMessage", true); + useWelcomeMessage = load(RegistrationSettings.USE_WELCOME_MESSAGE); unsafePasswords = configFile.getStringList("settings.security.unsafePasswords"); countriesBlacklist = configFile.getStringList("Protection.countriesBlacklist"); - broadcastWelcomeMessage = configFile.getBoolean("settings.broadcastWelcomeMessage", false); + broadcastWelcomeMessage = load(RegistrationSettings.BROADCAST_WELCOME_MESSAGE); forceRegKick = configFile.getBoolean("settings.registration.forceKickAfterRegister", false); forceRegLogin = load(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER); spawnPriority = load(RestrictionSettings.SPAWN_PRIORITY); diff --git a/src/main/java/fr/xephi/authme/task/MessageTask.java b/src/main/java/fr/xephi/authme/task/MessageTask.java index 92310f376..0c035183d 100644 --- a/src/main/java/fr/xephi/authme/task/MessageTask.java +++ b/src/main/java/fr/xephi/authme/task/MessageTask.java @@ -22,13 +22,13 @@ public class MessageTask implements Runnable { * * @param plugin AuthMe * @param name String - * @param strings String[] + * @param lines String[] * @param interval int */ - public MessageTask(AuthMe plugin, String name, String[] strings, int interval) { + public MessageTask(AuthMe plugin, String name, String[] lines, int interval) { this.plugin = plugin; this.name = name; - this.msg = strings; + this.msg = lines; this.interval = interval; } diff --git a/src/main/java/fr/xephi/authme/util/GeoLiteAPI.java b/src/main/java/fr/xephi/authme/util/GeoLiteAPI.java index f878d85a7..16ed81a96 100644 --- a/src/main/java/fr/xephi/authme/util/GeoLiteAPI.java +++ b/src/main/java/fr/xephi/authme/util/GeoLiteAPI.java @@ -22,6 +22,9 @@ public class GeoLiteAPI { private static LookupService lookupService; private static Thread downloadTask; + private GeoLiteAPI() { + } + /** * Download (if absent) the GeoIpLite data file and then try to load it. * diff --git a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java index 929fd26a1..72d949d5a 100644 --- a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java @@ -3,6 +3,7 @@ package fr.xephi.authme.command; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.manager.IpAddressManager; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.PermissionsManager; @@ -41,6 +42,7 @@ public class CommandServiceTest { private CommandService commandService; private PermissionsManager permissionsManager; private NewSetting settings; + private IpAddressManager ipAddressManager; @Before public void setUpService() { @@ -51,8 +53,9 @@ public class CommandServiceTest { passwordSecurity = mock(PasswordSecurity.class); permissionsManager = mock(PermissionsManager.class); settings = mock(NewSetting.class); - commandService = new CommandService( - authMe, commandMapper, helpProvider, messages, passwordSecurity, permissionsManager, settings); + ipAddressManager = mock(IpAddressManager.class); + commandService = new CommandService(authMe, commandMapper, helpProvider, messages, passwordSecurity, + permissionsManager, settings, ipAddressManager); } @Test @@ -216,4 +219,13 @@ public class CommandServiceTest { // then assertThat(result, equalTo(authMe)); } + + @Test + public void shouldReturnIpAddressManager() { + // given/when + IpAddressManager ipManager = commandService.getIpAddressManager(); + + // then + assertThat(ipManager, equalTo(ipAddressManager)); + } } diff --git a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java index 041b58d2a..b6e9f65e5 100644 --- a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java +++ b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java @@ -57,7 +57,7 @@ public class AsyncChangeEmailTest { given(dataSource.updateEmail(auth)).willReturn(true); // when - process.process(); + process.run(); // then verify(dataSource).updateEmail(auth); @@ -76,7 +76,7 @@ public class AsyncChangeEmailTest { given(dataSource.updateEmail(auth)).willReturn(false); // when - process.process(); + process.run(); // then verify(dataSource).updateEmail(auth); @@ -94,7 +94,7 @@ public class AsyncChangeEmailTest { given(playerCache.getAuth("bobby")).willReturn(auth); // when - process.process(); + process.run(); // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); @@ -112,7 +112,7 @@ public class AsyncChangeEmailTest { given(playerCache.getAuth("bobby")).willReturn(auth); // when - process.process(); + process.run(); // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); @@ -130,7 +130,7 @@ public class AsyncChangeEmailTest { given(playerCache.getAuth("bobby")).willReturn(auth); // when - process.process(); + process.run(); // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); @@ -149,7 +149,7 @@ public class AsyncChangeEmailTest { given(dataSource.isEmailStored("new@example.com")).willReturn(true); // when - process.process(); + process.run(); // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); @@ -166,7 +166,7 @@ public class AsyncChangeEmailTest { given(dataSource.isAuthAvailable("Bobby")).willReturn(true); // when - process.process(); + process.run(); // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); @@ -184,7 +184,7 @@ public class AsyncChangeEmailTest { Settings.emailRegistration = true; // when - process.process(); + process.run(); // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); @@ -202,7 +202,7 @@ public class AsyncChangeEmailTest { Settings.emailRegistration = false; // when - process.process(); + process.run(); // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); From fd8db2cd51b5e26b7a7330172ae0fd3a994188b0 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 3 Mar 2016 09:32:25 +0100 Subject: [PATCH 2/6] Add test for IP manager + create captcha manager (still unused) --- .../xephi/authme/manager/CaptchaManager.java | 81 +++++++++++++++++++ .../authme/manager/IpAddressManager.java | 2 +- .../authme/manager/CaptchaManagerTest.java | 63 +++++++++++++++ .../authme/manager/IpAddressManagerTest.java | 64 +++++++++++++++ 4 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 src/main/java/fr/xephi/authme/manager/CaptchaManager.java create mode 100644 src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java create mode 100644 src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java diff --git a/src/main/java/fr/xephi/authme/manager/CaptchaManager.java b/src/main/java/fr/xephi/authme/manager/CaptchaManager.java new file mode 100644 index 000000000..e89e9d497 --- /dev/null +++ b/src/main/java/fr/xephi/authme/manager/CaptchaManager.java @@ -0,0 +1,81 @@ +package fr.xephi.authme.manager; + +import fr.xephi.authme.security.RandomString; +import fr.xephi.authme.settings.NewSetting; +import fr.xephi.authme.settings.properties.SecuritySettings; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * Manager for the handling of captchas. + */ +public class CaptchaManager { + + private final int threshold; + private final int captchaLength; + private final ConcurrentHashMap playerCounts; + private final ConcurrentHashMap captchaCodes; + + public CaptchaManager(NewSetting settings) { + this.playerCounts = new ConcurrentHashMap<>(); + this.captchaCodes = new ConcurrentHashMap<>(); + this.threshold = settings.getProperty(SecuritySettings.MAX_LOGIN_TRIES_BEFORE_CAPTCHA); + this.captchaLength = settings.getProperty(SecuritySettings.CAPTCHA_LENGTH); + } + + public void increaseCount(String player) { + String playerLower = player.toLowerCase(); + Integer currentCount = playerCounts.get(playerLower); + if (currentCount == null) { + playerCounts.put(playerLower, 1); + } else { + playerCounts.put(playerLower, currentCount + 1); + } + } + + /** + * Return whether the given player is required to solve a captcha. + * + * @param player The player to verify + * @return True if the player has to solve a captcha, false otherwise + */ + public boolean isCaptchaRequired(String player) { + Integer count = playerCounts.get(player.toLowerCase()); + return count != null && count >= threshold; + } + + /** + * Return the captcha code for the player. Creates one if none present, so call only after + * checking with {@link #isCaptchaRequired}. + * + * @param player The player + * @return The code required for the player + */ + public String getCaptchaCode(String player) { + String code = captchaCodes.get(player.toLowerCase()); + if (code == null) { + code = RandomString.generate(captchaLength); + captchaCodes.put(player.toLowerCase(), code); + } + return code; + } + + /** + * Return whether the supplied code is correct for the given player. + * + * @param player The player to check + * @param code The supplied code + * @return True if the code matches or if no captcha is required for the player, false otherwise + */ + public boolean checkCode(String player, String code) { + String savedCode = captchaCodes.get(player.toLowerCase()); + if (savedCode == null) { + return true; + } else if (savedCode.equalsIgnoreCase(code)) { + captchaCodes.remove(player.toLowerCase()); + return true; + } + return false; + } + +} diff --git a/src/main/java/fr/xephi/authme/manager/IpAddressManager.java b/src/main/java/fr/xephi/authme/manager/IpAddressManager.java index b8be8db3c..951e3c8ff 100644 --- a/src/main/java/fr/xephi/authme/manager/IpAddressManager.java +++ b/src/main/java/fr/xephi/authme/manager/IpAddressManager.java @@ -60,7 +60,7 @@ public class IpAddressManager { ipCache.remove(player.toLowerCase()); } - // returns null if IP could not be looked up --> expect that it won't be cached + // returns null if IP could not be looked up private String getVeryGamesIp(final String plainIp, final int port) { final String sUrl = String.format("http://monitor-1.verygames.net/api/?action=ipclean-real-ip" + "&out=raw&ip=%s&port=%d", plainIp, port); diff --git a/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java b/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java new file mode 100644 index 000000000..62fee9bb7 --- /dev/null +++ b/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java @@ -0,0 +1,63 @@ +package fr.xephi.authme.manager; + +import fr.xephi.authme.settings.NewSetting; +import fr.xephi.authme.settings.properties.SecuritySettings; +import org.junit.Test; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * Test for {@link CaptchaManager}. + */ +public class CaptchaManagerTest { + + @Test + public void shouldAddCounts() { + // given + NewSetting settings = mockSettings(3, 4); + CaptchaManager manager = new CaptchaManager(settings); + String player = "tester"; + + // when + for (int i = 0; i < 2; ++i) { + manager.increaseCount(player); + } + + // then + assertThat(manager.isCaptchaRequired(player), equalTo(false)); + manager.increaseCount(player); + assertThat(manager.isCaptchaRequired(player.toUpperCase()), equalTo(true)); + assertThat(manager.isCaptchaRequired("otherPlayer"), equalTo(false)); + } + + @Test + public void shouldCreateAndCheckCaptcha() { + // given + String player = "Miner"; + NewSetting settings = mockSettings(1, 4); + CaptchaManager manager = new CaptchaManager(settings); + String captchaCode = manager.getCaptchaCode(player); + + // when + boolean badResult = manager.checkCode(player, "wrong_code"); + boolean goodResult = manager.checkCode(player, captchaCode); + + // then + assertThat(captchaCode.length(), equalTo(4)); + assertThat(badResult, equalTo(false)); + assertThat(goodResult, equalTo(true)); + // Supplying correct code should clear the entry, and any code should be valid if no entry is present + assertThat(manager.checkCode(player, "bogus"), equalTo(true)); + } + + + private static NewSetting mockSettings(int maxTries, int captchaLength) { + NewSetting settings = mock(NewSetting.class); + given(settings.getProperty(SecuritySettings.MAX_LOGIN_TRIES_BEFORE_CAPTCHA)).willReturn(maxTries); + given(settings.getProperty(SecuritySettings.CAPTCHA_LENGTH)).willReturn(captchaLength); + return settings; + } +} diff --git a/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java b/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java new file mode 100644 index 000000000..b5a1d7435 --- /dev/null +++ b/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java @@ -0,0 +1,64 @@ +package fr.xephi.authme.manager; + +import fr.xephi.authme.settings.NewSetting; +import fr.xephi.authme.settings.properties.HooksSettings; +import org.bukkit.entity.Player; +import org.junit.Test; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * Test for {@link IpAddressManager}. + */ +public class IpAddressManagerTest { + + @Test + public void shouldRetrieveFromCache() { + // given + IpAddressManager ipAddressManager = new IpAddressManager(mockSettings(false)); + ipAddressManager.addCache("Test", "my test IP"); + + // when + String result = ipAddressManager.getPlayerIp(mockPlayer("test", "123.123.123.123")); + + // then + assertThat(result, equalTo("my test IP")); + } + + @Test + public void shouldReturnPlainIp() { + // given + IpAddressManager ipAddressManager = new IpAddressManager(mockSettings(false)); + + // when + String result = ipAddressManager.getPlayerIp(mockPlayer("bobby", "8.8.8.8")); + + // then + assertThat(result, equalTo("8.8.8.8")); + } + + + + private static NewSetting mockSettings(boolean useVeryGames) { + NewSetting settings = mock(NewSetting.class); + given(settings.getProperty(HooksSettings.ENABLE_VERYGAMES_IP_CHECK)).willReturn(useVeryGames); + return settings; + } + + private static Player mockPlayer(String name, String ip) { + Player player = mock(Player.class); + given(player.getName()).willReturn(name); + InetAddress inetAddress = mock(InetAddress.class); + given(inetAddress.getHostAddress()).willReturn(ip); + InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 8093); + given(player.getAddress()).willReturn(inetSocketAddress); + return player; + } + +} From 19adcdcceb292a7abea56de6b2d1808d27d4dd07 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 5 Mar 2016 16:03:00 +0100 Subject: [PATCH 3/6] Move managers to the cache package - Not entirely accurate name but not really worth to have a separate package for managers --- src/main/java/fr/xephi/authme/AuthMe.java | 2 +- .../java/fr/xephi/authme/{manager => cache}/CaptchaManager.java | 2 +- .../fr/xephi/authme/{manager => cache}/IpAddressManager.java | 2 +- src/main/java/fr/xephi/authme/command/CommandService.java | 2 +- src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java | 2 +- src/main/java/fr/xephi/authme/process/ProcessService.java | 2 +- src/test/java/fr/xephi/authme/command/CommandServiceTest.java | 2 +- src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java | 1 + src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java | 1 + 9 files changed, 9 insertions(+), 7 deletions(-) rename src/main/java/fr/xephi/authme/{manager => cache}/CaptchaManager.java (98%) rename src/main/java/fr/xephi/authme/{manager => cache}/IpAddressManager.java (98%) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index ceca76be9..bdac0cecd 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -33,7 +33,7 @@ import fr.xephi.authme.listener.AuthMeServerListener; import fr.xephi.authme.listener.AuthMeTabCompletePacketAdapter; import fr.xephi.authme.listener.AuthMeTablistPacketAdapter; import fr.xephi.authme.mail.SendMailSSL; -import fr.xephi.authme.manager.IpAddressManager; +import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.output.ConsoleFilter; import fr.xephi.authme.output.Log4JFilter; import fr.xephi.authme.output.MessageKey; diff --git a/src/main/java/fr/xephi/authme/manager/CaptchaManager.java b/src/main/java/fr/xephi/authme/cache/CaptchaManager.java similarity index 98% rename from src/main/java/fr/xephi/authme/manager/CaptchaManager.java rename to src/main/java/fr/xephi/authme/cache/CaptchaManager.java index e89e9d497..342ad7c3d 100644 --- a/src/main/java/fr/xephi/authme/manager/CaptchaManager.java +++ b/src/main/java/fr/xephi/authme/cache/CaptchaManager.java @@ -1,4 +1,4 @@ -package fr.xephi.authme.manager; +package fr.xephi.authme.cache; import fr.xephi.authme.security.RandomString; import fr.xephi.authme.settings.NewSetting; diff --git a/src/main/java/fr/xephi/authme/manager/IpAddressManager.java b/src/main/java/fr/xephi/authme/cache/IpAddressManager.java similarity index 98% rename from src/main/java/fr/xephi/authme/manager/IpAddressManager.java rename to src/main/java/fr/xephi/authme/cache/IpAddressManager.java index 951e3c8ff..40b9cf865 100644 --- a/src/main/java/fr/xephi/authme/manager/IpAddressManager.java +++ b/src/main/java/fr/xephi/authme/cache/IpAddressManager.java @@ -1,4 +1,4 @@ -package fr.xephi.authme.manager; +package fr.xephi.authme.cache; import com.google.common.base.Charsets; import com.google.common.io.Resources; diff --git a/src/main/java/fr/xephi/authme/command/CommandService.java b/src/main/java/fr/xephi/authme/command/CommandService.java index 7c348ced0..ab03ceedc 100644 --- a/src/main/java/fr/xephi/authme/command/CommandService.java +++ b/src/main/java/fr/xephi/authme/command/CommandService.java @@ -3,7 +3,7 @@ package fr.xephi.authme.command; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.manager.IpAddressManager; +import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.PermissionsManager; diff --git a/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java b/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java index e29743558..72f39b807 100644 --- a/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java +++ b/src/main/java/fr/xephi/authme/hooks/BungeeCordMessage.java @@ -7,7 +7,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.manager.IpAddressManager; +import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.security.crypts.HashedPassword; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; diff --git a/src/main/java/fr/xephi/authme/process/ProcessService.java b/src/main/java/fr/xephi/authme/process/ProcessService.java index 621cdf8fa..66e45d9b3 100644 --- a/src/main/java/fr/xephi/authme/process/ProcessService.java +++ b/src/main/java/fr/xephi/authme/process/ProcessService.java @@ -1,7 +1,7 @@ package fr.xephi.authme.process; import fr.xephi.authme.AuthMe; -import fr.xephi.authme.manager.IpAddressManager; +import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.NewSetting; diff --git a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java index 72d949d5a..d237c452b 100644 --- a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java @@ -3,7 +3,7 @@ package fr.xephi.authme.command; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.manager.IpAddressManager; +import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.PermissionsManager; diff --git a/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java b/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java index 62fee9bb7..2f9d241f6 100644 --- a/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java +++ b/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java @@ -1,5 +1,6 @@ package fr.xephi.authme.manager; +import fr.xephi.authme.cache.CaptchaManager; import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.properties.SecuritySettings; import org.junit.Test; diff --git a/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java b/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java index b5a1d7435..9dc97fc9e 100644 --- a/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java +++ b/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java @@ -1,5 +1,6 @@ package fr.xephi.authme.manager; +import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.properties.HooksSettings; import org.bukkit.entity.Player; From 31bac6964f698db8e35965f945e91aa9ec10de50 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sun, 6 Mar 2016 14:42:19 +0100 Subject: [PATCH 4/6] Various code householding - Adjust javadoc - Remove unused PlayerAuth constructor - Replace legacy Settings with NewSetting calls - Add process service to all (a)sync processes - Change IP manager to only cache the calls to the VeryGames API --- src/main/java/fr/xephi/authme/AuthMe.java | 18 +++---- .../xephi/authme/cache/IpAddressManager.java | 48 +++++++++++++------ .../xephi/authme/cache/auth/PlayerAuth.java | 12 ----- .../xephi/authme/command/CommandService.java | 1 + .../fr/xephi/authme/command/CommandUtils.java | 3 ++ .../authme/PurgeBannedPlayersCommand.java | 12 ++--- .../executable/authme/PurgeCommand.java | 12 ++--- .../authme/UnregisterAdminCommand.java | 3 +- .../executable/authme/VersionCommand.java | 10 ++-- .../executable/register/RegisterCommand.java | 3 +- .../authme/permission/PlayerPermission.java | 8 ++-- .../fr/xephi/authme/process/Management.java | 20 +------- .../xephi/authme/process/ProcessService.java | 11 ++++- .../process/email/AsyncChangeEmail.java | 38 +++++++-------- .../process/login/AsynchronousLogin.java | 5 +- .../process/logout/AsynchronousLogout.java | 33 ++++++------- ...va => ProcessSynchronousPlayerLogout.java} | 41 ++++++++-------- .../authme/process/quit/AsynchronousQuit.java | 10 ++-- .../process/register/AsyncRegister.java | 27 +++++------ .../register/ProcessSyncEmailRegister.java | 7 +-- .../fr/xephi/authme/settings/Settings.java | 35 +++----------- .../settings/properties/PurgeSettings.java | 19 ++++---- .../AbstractResourceClosingTest.java | 2 +- .../authme/manager/IpAddressManagerTest.java | 2 +- .../process/email/AsyncChangeEmailTest.java | 39 ++++++++------- 25 files changed, 199 insertions(+), 220 deletions(-) rename src/main/java/fr/xephi/authme/process/logout/{ProcessSyncronousPlayerLogout.java => ProcessSynchronousPlayerLogout.java} (68%) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index e511d1d9e..28dce1e8f 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -52,6 +52,7 @@ import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.PluginSettings; +import fr.xephi.authme.settings.properties.PurgeSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.CollectionUtils; @@ -301,7 +302,8 @@ public class AuthMe extends JavaPlugin { setupApi(); // Set up the management - ProcessService processService = new ProcessService(newSettings, messages, this, ipAddressManager); + ProcessService processService = new ProcessService(newSettings, messages, this, ipAddressManager, + passwordSecurity); management = new Management(this, processService, database, PlayerCache.getInstance()); // Set up the BungeeCord hook @@ -751,26 +753,26 @@ public class AuthMe extends JavaPlugin { // Purge inactive players from the database, as defined in the configuration private void autoPurge() { - if (!Settings.usePurge) { + if (!newSettings.getProperty(PurgeSettings.USE_AUTO_PURGE)) { return; } Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DATE, -(Settings.purgeDelay)); + calendar.add(Calendar.DATE, -newSettings.getProperty(PurgeSettings.DAYS_BEFORE_REMOVE_PLAYER)); long until = calendar.getTimeInMillis(); List cleared = database.autoPurgeDatabase(until); if (CollectionUtils.isEmpty(cleared)) { return; } ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!"); - if (Settings.purgeEssentialsFile && this.ess != null) + if (newSettings.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) && this.ess != null) dataManager.purgeEssentials(cleared); - if (Settings.purgePlayerDat) + if (newSettings.getProperty(PurgeSettings.REMOVE_PLAYER_DAT)) dataManager.purgeDat(cleared); - if (Settings.purgeLimitedCreative) + if (newSettings.getProperty(PurgeSettings.REMOVE_LIMITED_CREATIVE_INVENTORIES)) dataManager.purgeLimitedCreative(cleared); - if (Settings.purgeAntiXray) + if (newSettings.getProperty(PurgeSettings.REMOVE_ANTI_XRAY_FILE)) dataManager.purgeAntiXray(cleared); - if (Settings.purgePermissions) + if (newSettings.getProperty(PurgeSettings.REMOVE_PERMISSIONS)) dataManager.purgePermissions(cleared); } diff --git a/src/main/java/fr/xephi/authme/cache/IpAddressManager.java b/src/main/java/fr/xephi/authme/cache/IpAddressManager.java index 40b9cf865..41d1d77fe 100644 --- a/src/main/java/fr/xephi/authme/cache/IpAddressManager.java +++ b/src/main/java/fr/xephi/authme/cache/IpAddressManager.java @@ -17,10 +17,10 @@ import java.util.concurrent.ConcurrentHashMap; */ public class IpAddressManager { - /** Cache for IP lookups per player. */ - private final ConcurrentHashMap ipCache; /** Whether or not to use the VeryGames API for IP lookups. */ private final boolean useVeryGamesIpCheck; + /** Cache for lookups via the VeryGames API. */ + private final ConcurrentHashMap ipCache; /** * Constructor. @@ -32,32 +32,52 @@ public class IpAddressManager { this.ipCache = new ConcurrentHashMap<>(); } + /** + * Return the player's IP address. If enabled in the settings, the IP address returned by the + * VeryGames API will be returned. + * + * @param player The player to look up + * @return The IP address of the player + */ public String getPlayerIp(Player player) { - final String playerName = player.getName().toLowerCase(); - final String cachedValue = ipCache.get(playerName); - if (cachedValue != null) { - return cachedValue; - } - - final String plainIp = player.getAddress().getAddress().getHostAddress(); if (useVeryGamesIpCheck) { + final String playerName = player.getName().toLowerCase(); + final String cachedValue = ipCache.get(playerName); + if (cachedValue != null) { + return cachedValue; + } + + final String plainIp = player.getAddress().getAddress().getHostAddress(); String veryGamesResult = getVeryGamesIp(plainIp, player.getAddress().getPort()); if (veryGamesResult != null) { ipCache.put(playerName, veryGamesResult); return veryGamesResult; } - } else { - ipCache.put(playerName, plainIp); } - return plainIp; + return player.getAddress().getAddress().getHostAddress(); } + /** + * Add a player to the IP address cache. + * + * @param player The player to add or update the cache entry for + * @param ip The IP address to add + */ public void addCache(String player, String ip) { - ipCache.put(player.toLowerCase(), ip); + if (useVeryGamesIpCheck) { + ipCache.put(player.toLowerCase(), ip); + } } + /** + * Remove a player's cache entry. + * + * @param player The player to remove + */ public void removeCache(String player) { - ipCache.remove(player.toLowerCase()); + if (useVeryGamesIpCheck) { + ipCache.remove(player.toLowerCase()); + } } // returns null if IP could not be looked up diff --git a/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java b/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java index c2bb4f704..c8b4c6b5a 100644 --- a/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java +++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java @@ -30,18 +30,6 @@ public class PlayerAuth { this.deserialize(serialized); } - /** - * Constructor for PlayerAuth. - * - * @param nickname String - * @param ip String - * @param lastLogin long - * @param realName String - */ - public PlayerAuth(String nickname, String ip, long lastLogin, String realName) { - this(nickname, new HashedPassword(""), -1, ip, lastLogin, 0, 0, 0, "world", "your@email.com", realName); - } - /** * Constructor for PlayerAuth. * diff --git a/src/main/java/fr/xephi/authme/command/CommandService.java b/src/main/java/fr/xephi/authme/command/CommandService.java index ab03ceedc..a23acd10c 100644 --- a/src/main/java/fr/xephi/authme/command/CommandService.java +++ b/src/main/java/fr/xephi/authme/command/CommandService.java @@ -41,6 +41,7 @@ public class CommandService { * @param passwordSecurity The Password Security instance * @param permissionsManager The permissions manager * @param settings The settings manager + * @param ipAddressManager The IP address manager */ public CommandService(AuthMe authMe, CommandMapper commandMapper, HelpProvider helpProvider, Messages messages, PasswordSecurity passwordSecurity, PermissionsManager permissionsManager, NewSetting settings, diff --git a/src/main/java/fr/xephi/authme/command/CommandUtils.java b/src/main/java/fr/xephi/authme/command/CommandUtils.java index 905e8922e..016cbce13 100644 --- a/src/main/java/fr/xephi/authme/command/CommandUtils.java +++ b/src/main/java/fr/xephi/authme/command/CommandUtils.java @@ -8,6 +8,9 @@ import java.util.List; public final class CommandUtils { + private CommandUtils() { + } + public static int getMinNumberOfArguments(CommandDescription command) { int mandatoryArguments = 0; for (CommandArgumentDescription argument : command.getArguments()) { diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java index b94ce2608..9ac24be5d 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java @@ -3,7 +3,7 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.PurgeSettings; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; @@ -15,7 +15,7 @@ public class PurgeBannedPlayersCommand implements ExecutableCommand { @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { // AuthMe plugin instance - final AuthMe plugin = AuthMe.getInstance(); + final AuthMe plugin = commandService.getAuthMe(); // Get the list of banned players List bannedPlayers = new ArrayList<>(); @@ -25,13 +25,13 @@ public class PurgeBannedPlayersCommand implements ExecutableCommand { // Purge the banned players plugin.getDataSource().purgeBanned(bannedPlayers); - if (Settings.purgeEssentialsFile && plugin.ess != null) + if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) && plugin.ess != null) plugin.dataManager.purgeEssentials(bannedPlayers); - if (Settings.purgePlayerDat) + if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT)) plugin.dataManager.purgeDat(bannedPlayers); - if (Settings.purgeLimitedCreative) + if (commandService.getProperty(PurgeSettings.REMOVE_LIMITED_CREATIVE_INVENTORIES)) plugin.dataManager.purgeLimitedCreative(bannedPlayers); - if (Settings.purgeAntiXray) + if (commandService.getProperty(PurgeSettings.REMOVE_ANTI_XRAY_FILE)) plugin.dataManager.purgeAntiXray(bannedPlayers); // Show a status message diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java index 8797145b2..361710315 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java @@ -3,7 +3,7 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.PurgeSettings; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; @@ -15,7 +15,7 @@ public class PurgeCommand implements ExecutableCommand { @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { // AuthMe plugin instance - AuthMe plugin = AuthMe.getInstance(); + AuthMe plugin = commandService.getAuthMe(); // Get the days parameter String daysStr = arguments.get(0); @@ -47,13 +47,13 @@ public class PurgeCommand implements ExecutableCommand { sender.sendMessage(ChatColor.GOLD + "Deleted " + purged.size() + " user accounts"); // Purge other data - if (Settings.purgeEssentialsFile && plugin.ess != null) + if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) && plugin.ess != null) plugin.dataManager.purgeEssentials(purged); - if (Settings.purgePlayerDat) + if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT)) plugin.dataManager.purgeDat(purged); - if (Settings.purgeLimitedCreative) + if (commandService.getProperty(PurgeSettings.REMOVE_LIMITED_CREATIVE_INVENTORIES)) plugin.dataManager.purgeLimitedCreative(purged); - if (Settings.purgeAntiXray) + if (commandService.getProperty(PurgeSettings.REMOVE_ANTI_XRAY_FILE)) plugin.dataManager.purgeAntiXray(purged); // Show a status message diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java index 9ed65b0bc..eacdd0593 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java @@ -8,6 +8,7 @@ import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.util.Utils; @@ -66,7 +67,7 @@ public class UnregisterAdminCommand implements ExecutableCommand { plugin, new MessageTask(plugin, playerNameLowerCase, MessageKey.REGISTER_MESSAGE, interval) ) ); - if (Settings.applyBlindEffect) { + if (commandService.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, timeOut, 2)); } commandService.send(target, MessageKey.UNREGISTERED_SUCCESS); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java index 4a7b629cd..7b99521d4 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java @@ -3,15 +3,15 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.ExecutableCommand; -import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER; import fr.xephi.authme.util.Utils; - -import java.util.List; - import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.util.List; + +import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER; + public class VersionCommand implements ExecutableCommand { @Override @@ -71,8 +71,6 @@ public class VersionCommand implements ExecutableCommand { * @return True if the player is online, false otherwise. */ private static boolean isPlayerOnline(String minecraftName) { - // Note ljacqu 20151121: Generally you should use Utils#getOnlinePlayers to retrieve the list of online players. - // If it's only used in a for-each loop such as here, it's fine. For other purposes, go through the Utils class. for (Player player : Utils.getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(minecraftName)) { return true; diff --git a/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java index c7d8e8229..48a1c3f02 100644 --- a/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java @@ -7,6 +7,7 @@ import fr.xephi.authme.process.Management; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.RandomString; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.Utils; import org.bukkit.entity.Player; @@ -17,7 +18,7 @@ public class RegisterCommand extends PlayerCommand { @Override public void runCommand(Player player, List arguments, CommandService commandService) { - if (Settings.getPasswordHash == HashAlgorithm.TWO_FACTOR) { + if (commandService.getProperty(SecuritySettings.PASSWORD_HASH) == HashAlgorithm.TWO_FACTOR) { //for two factor auth we don't need to check the usage commandService.getManagement().performRegister(player, "", ""); return; diff --git a/src/main/java/fr/xephi/authme/permission/PlayerPermission.java b/src/main/java/fr/xephi/authme/permission/PlayerPermission.java index 7d00aff7f..210cbce93 100644 --- a/src/main/java/fr/xephi/authme/permission/PlayerPermission.java +++ b/src/main/java/fr/xephi/authme/permission/PlayerPermission.java @@ -55,10 +55,10 @@ public enum PlayerPermission implements PermissionNode { */ CAN_LOGIN_BE_FORCED("authme.player.canbeforced"), - /** - * Permission to use to see own other accounts. - */ - SEE_OWN_ACCOUNTS("authme.player.seeownaccounts"); + /** + * Permission to use to see own other accounts. + */ + SEE_OWN_ACCOUNTS("authme.player.seeownaccounts"); /** * The permission node. diff --git a/src/main/java/fr/xephi/authme/process/Management.java b/src/main/java/fr/xephi/authme/process/Management.java index c981e0c00..4cea16fc4 100644 --- a/src/main/java/fr/xephi/authme/process/Management.java +++ b/src/main/java/fr/xephi/authme/process/Management.java @@ -11,7 +11,6 @@ import fr.xephi.authme.process.logout.AsynchronousLogout; import fr.xephi.authme.process.quit.AsynchronousQuit; import fr.xephi.authme.process.register.AsyncRegister; import fr.xephi.authme.process.unregister.AsynchronousUnregister; -import fr.xephi.authme.settings.NewSetting; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; @@ -24,22 +23,13 @@ public class Management { private final ProcessService processService; private final DataSource dataSource; private final PlayerCache playerCache; - private final NewSetting settings; - /** - * Constructor for Management. - * - * @param plugin AuthMe - */ public Management(AuthMe plugin, ProcessService processService, DataSource dataSource, PlayerCache playerCache) { this.plugin = plugin; this.sched = this.plugin.getServer().getScheduler(); this.processService = processService; this.dataSource = dataSource; this.playerCache = playerCache; - - // FIXME don't pass settings anymore -> go through the service in the processes - this.settings = processService.getSettings(); } public void performLogin(final Player player, final String password, final boolean forceLogin) { @@ -47,13 +37,7 @@ public class Management { } public void performLogout(final Player player) { - sched.runTaskAsynchronously(plugin, new Runnable() { - - @Override - public void run() { - new AsynchronousLogout(player, plugin, plugin.getDataSource()).process(); - } - }); + runTask(new AsynchronousLogout(player, plugin, dataSource, processService)); } public void performRegister(final Player player, final String password, final String email) { @@ -77,7 +61,7 @@ public class Management { } public void performChangeEmail(final Player player, final String oldEmail, final String newEmail) { - runTask(new AsyncChangeEmail(player, plugin, oldEmail, newEmail, dataSource, playerCache, settings)); + runTask(new AsyncChangeEmail(player, oldEmail, newEmail, dataSource, playerCache, processService)); } private void runTask(Process process) { diff --git a/src/main/java/fr/xephi/authme/process/ProcessService.java b/src/main/java/fr/xephi/authme/process/ProcessService.java index 66e45d9b3..9bc20878a 100644 --- a/src/main/java/fr/xephi/authme/process/ProcessService.java +++ b/src/main/java/fr/xephi/authme/process/ProcessService.java @@ -4,6 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.domain.Property; import org.bukkit.command.CommandSender; @@ -19,12 +21,15 @@ public class ProcessService { private final Messages messages; private final AuthMe authMe; private final IpAddressManager ipAddressManager; + private final PasswordSecurity passwordSecurity; - public ProcessService(NewSetting settings, Messages messages, AuthMe authMe, IpAddressManager ipAddressManager) { + public ProcessService(NewSetting settings, Messages messages, AuthMe authMe, IpAddressManager ipAddressManager, + PasswordSecurity passwordSecurity) { this.settings = settings; this.messages = messages; this.authMe = authMe; this.ipAddressManager = ipAddressManager; + this.passwordSecurity = passwordSecurity; } public T getProperty(Property property) { @@ -75,4 +80,8 @@ public class ProcessService { return ipAddressManager; } + public HashedPassword computeHash(String password, String username) { + return passwordSecurity.computeHash(password, username); + } + } diff --git a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java index 22833a202..132decd5e 100644 --- a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java +++ b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java @@ -1,14 +1,12 @@ package fr.xephi.authme.process.email; -import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; import fr.xephi.authme.process.Process; -import fr.xephi.authme.settings.NewSetting; -import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.process.ProcessService; +import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.util.Utils; import org.bukkit.entity.Player; @@ -20,20 +18,18 @@ public class AsyncChangeEmail implements Process { private final Player player; private final String oldEmail; private final String newEmail; - private final Messages m; - private final NewSetting settings; + private final ProcessService service; private final PlayerCache playerCache; private final DataSource dataSource; - public AsyncChangeEmail(Player player, AuthMe plugin, String oldEmail, String newEmail, DataSource dataSource, - PlayerCache playerCache, NewSetting settings) { - this.m = plugin.getMessages(); + public AsyncChangeEmail(Player player, String oldEmail, String newEmail, DataSource dataSource, + PlayerCache playerCache, ProcessService service) { this.player = player; this.oldEmail = oldEmail; this.newEmail = newEmail; this.playerCache = playerCache; this.dataSource = dataSource; - this.settings = settings; + this.service = service; } @Override @@ -44,13 +40,13 @@ public class AsyncChangeEmail implements Process { final String currentEmail = auth.getEmail(); if (currentEmail == null) { - m.send(player, MessageKey.USAGE_ADD_EMAIL); - } else if (newEmail == null || !Utils.isEmailCorrect(newEmail, settings)) { - m.send(player, MessageKey.INVALID_NEW_EMAIL); + service.send(player, MessageKey.USAGE_ADD_EMAIL); + } else if (newEmail == null || !Utils.isEmailCorrect(newEmail, service.getSettings())) { + service.send(player, MessageKey.INVALID_NEW_EMAIL); } else if (!oldEmail.equals(currentEmail)) { - m.send(player, MessageKey.INVALID_OLD_EMAIL); + service.send(player, MessageKey.INVALID_OLD_EMAIL); } else if (dataSource.isEmailStored(newEmail)) { - m.send(player, MessageKey.EMAIL_ALREADY_USED_ERROR); + service.send(player, MessageKey.EMAIL_ALREADY_USED_ERROR); } else { saveNewEmail(auth); } @@ -63,20 +59,20 @@ public class AsyncChangeEmail implements Process { auth.setEmail(newEmail); if (dataSource.updateEmail(auth)) { playerCache.updatePlayer(auth); - m.send(player, MessageKey.EMAIL_CHANGED_SUCCESS); + service.send(player, MessageKey.EMAIL_CHANGED_SUCCESS); } else { - m.send(player, MessageKey.ERROR); + service.send(player, MessageKey.ERROR); auth.setEmail(newEmail); } } private void outputUnloggedMessage() { if (dataSource.isAuthAvailable(player.getName())) { - m.send(player, MessageKey.LOGIN_MESSAGE); - } else if (Settings.emailRegistration) { - m.send(player, MessageKey.REGISTER_EMAIL_MESSAGE); + service.send(player, MessageKey.LOGIN_MESSAGE); + } else if (service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)) { + service.send(player, MessageKey.REGISTER_EMAIL_MESSAGE); } else { - m.send(player, MessageKey.REGISTER_MESSAGE); + service.send(player, MessageKey.REGISTER_MESSAGE); } } } diff --git a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java index e1ef5df88..8c5c36750 100644 --- a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java @@ -15,6 +15,7 @@ import fr.xephi.authme.process.Process; import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.security.RandomString; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.task.MessageTask; @@ -98,7 +99,7 @@ public class AsynchronousLogin implements Process { return null; } - if (!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) { + if (!service.getProperty(DatabaseSettings.MYSQL_COL_GROUP).isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) { service.send(player, MessageKey.ACCOUNT_NOT_ACTIVATED); return null; } @@ -146,7 +147,7 @@ public class AsynchronousLogin implements Process { .build(); database.updateSession(auth); - if (Settings.useCaptcha) { + if (service.getProperty(SecuritySettings.USE_CAPTCHA)) { if (plugin.captcha.containsKey(name)) { plugin.captcha.remove(name); } diff --git a/src/main/java/fr/xephi/authme/process/logout/AsynchronousLogout.java b/src/main/java/fr/xephi/authme/process/logout/AsynchronousLogout.java index 3e719060a..a882ab30b 100644 --- a/src/main/java/fr/xephi/authme/process/logout/AsynchronousLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/AsynchronousLogout.java @@ -6,22 +6,22 @@ import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; +import fr.xephi.authme.process.Process; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils.GroupType; import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitScheduler; /** */ -public class AsynchronousLogout { +public class AsynchronousLogout implements Process { - protected final Player player; - protected final String name; - protected final AuthMe plugin; - protected final DataSource database; - protected boolean canLogout = true; - private final Messages m; + private final Player player; + private final String name; + private final AuthMe plugin; + private final DataSource database; + private boolean canLogout = true; + private final ProcessService service; /** * Constructor for AsynchronousLogout. @@ -29,29 +29,30 @@ public class AsynchronousLogout { * @param player Player * @param plugin AuthMe * @param database DataSource + * @param service The process service */ - public AsynchronousLogout(Player player, AuthMe plugin, DataSource database) { - this.m = plugin.getMessages(); + public AsynchronousLogout(Player player, AuthMe plugin, DataSource database, ProcessService service) { this.player = player; this.plugin = plugin; this.database = database; this.name = player.getName().toLowerCase(); + this.service = service; } private void preLogout() { if (!PlayerCache.getInstance().isAuthenticated(name)) { - m.send(player, MessageKey.NOT_LOGGED_IN); + service.send(player, MessageKey.NOT_LOGGED_IN); canLogout = false; } } - public void process() { + @Override + public void run() { preLogout(); if (!canLogout) { return; } final Player p = player; - BukkitScheduler scheduler = p.getServer().getScheduler(); PlayerAuth auth = PlayerCache.getInstance().getAuth(name); database.updateSession(auth); auth.setQuitLocX(p.getLocation().getX()); @@ -62,7 +63,7 @@ public class AsynchronousLogout { PlayerCache.getInstance().removePlayer(name); database.setUnlogged(name); - scheduler.scheduleSyncDelayedTask(plugin, new Runnable() { + service.scheduleSyncDelayedTask(new Runnable() { @Override public void run() { Utils.teleportToSpawn(p); @@ -73,6 +74,6 @@ public class AsynchronousLogout { } LimboCache.getInstance().addLimboPlayer(player); Utils.setGroup(player, GroupType.NOTLOGGEDIN); - scheduler.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin)); + service.scheduleSyncDelayedTask(new ProcessSynchronousPlayerLogout(p, plugin, service)); } } diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSynchronousPlayerLogout.java similarity index 68% rename from src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java rename to src/main/java/fr/xephi/authme/process/logout/ProcessSynchronousPlayerLogout.java index 64c300ef0..7b8e53ed8 100644 --- a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSynchronousPlayerLogout.java @@ -7,37 +7,40 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.events.LogoutEvent; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; +import fr.xephi.authme.process.Process; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.RegistrationSettings; +import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; /** */ -public class ProcessSyncronousPlayerLogout implements Runnable { +public class ProcessSynchronousPlayerLogout implements Process { - protected final Player player; - protected final AuthMe plugin; - protected final String name; - private final Messages m; + private final Player player; + private final AuthMe plugin; + private final String name; + private final ProcessService service; /** - * Constructor for ProcessSyncronousPlayerLogout. + * Constructor for ProcessSynchronousPlayerLogout. * * @param player Player * @param plugin AuthMe + * @param service The process service */ - public ProcessSyncronousPlayerLogout(Player player, AuthMe plugin) { - this.m = plugin.getMessages(); + public ProcessSynchronousPlayerLogout(Player player, AuthMe plugin, ProcessService service) { this.player = player; this.plugin = plugin; this.name = player.getName().toLowerCase(); + this.service = service; } protected void sendBungeeMessage() { @@ -56,11 +59,6 @@ public class ProcessSyncronousPlayerLogout implements Runnable { } } - /** - * Method run. - * - * @see java.lang.Runnable#run() - */ @Override public void run() { if (plugin.sessions.containsKey(name)) { @@ -70,19 +68,18 @@ public class ProcessSyncronousPlayerLogout implements Runnable { if (Settings.protectInventoryBeforeLogInEnabled) { plugin.inventoryProtector.sendBlankInventoryPacket(player); } - int timeOut = Settings.getRegistrationTimeout * 20; - int interval = Settings.getWarnMessageInterval; - BukkitScheduler sched = player.getServer().getScheduler(); + int timeOut = service.getProperty(RestrictionSettings.TIMEOUT) * 20; + int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); if (timeOut != 0) { - BukkitTask id = sched.runTaskLater(plugin, new TimeoutTask(plugin, name, player), timeOut); + BukkitTask id = service.runTaskLater(new TimeoutTask(plugin, name, player), timeOut); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); } - BukkitTask msgT = sched.runTask(plugin, new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); + BukkitTask msgT = service.runTask(new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); if (player.isInsideVehicle() && player.getVehicle() != null) { player.getVehicle().eject(); } - if (Settings.applyBlindEffect) { + if (service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, timeOut, 2)); } player.setOp(false); @@ -92,7 +89,7 @@ public class ProcessSyncronousPlayerLogout implements Runnable { if (Settings.bungee) { sendBungeeMessage(); } - m.send(player, MessageKey.LOGOUT_SUCCESS); + service.send(player, MessageKey.LOGOUT_SUCCESS); ConsoleLogger.info(player.getName() + " logged out"); } diff --git a/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java b/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java index 3f930e44f..7638ce18e 100644 --- a/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java +++ b/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java @@ -13,7 +13,6 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.util.StringUtils; import fr.xephi.authme.util.Utils; -import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; @@ -54,7 +53,12 @@ public class AsynchronousQuit implements Process { .realName(player.getName()).build(); database.updateQuitLoc(auth); } - PlayerAuth auth = new PlayerAuth(name, ip, System.currentTimeMillis(), player.getName()); + PlayerAuth auth = PlayerAuth.builder() + .name(name) + .realName(player.getName()) + .ip(ip) + .lastLogin(System.currentTimeMillis()) + .build(); database.updateSession(auth); } @@ -92,7 +96,7 @@ public class AsynchronousQuit implements Process { service.getIpAddressManager().removeCache(player.getName()); if (plugin.isEnabled()) { - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerQuit(plugin, player, isOp, needToChange)); + service.scheduleSyncDelayedTask(new ProcessSyncronousPlayerQuit(plugin, player, isOp, needToChange)); } // remove player from cache if (database instanceof CacheDataSource) { diff --git a/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java b/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java index 6b14bbece..717ab58be 100644 --- a/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java @@ -1,10 +1,5 @@ package fr.xephi.authme.process.register; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; @@ -22,6 +17,8 @@ import fr.xephi.authme.util.StringUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import java.util.List; + /** */ public class AsyncRegister implements Process { @@ -82,10 +79,11 @@ public class AsyncRegister implements Process { && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost") && !plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) { - Integer maxReg = Settings.getmaxRegPerIp; + int maxReg = Settings.getmaxRegPerIp; List otherAccounts = database.getAllAuthsByIp(ip); if (otherAccounts.size() >= maxReg) { - m.send(player, MessageKey.MAX_REGISTER_EXCEEDED, maxReg.toString(), Integer.toString(otherAccounts.size()), otherAccounts.toString()); + service.send(player, MessageKey.MAX_REGISTER_EXCEEDED, Integer.toString(maxReg), + Integer.toString(otherAccounts.size()), StringUtils.join(", ", otherAccounts.toString())); return false; } } @@ -104,18 +102,19 @@ public class AsyncRegister implements Process { } private void emailRegister() { - if(Settings.getmaxRegPerEmail > 0 + if (Settings.getmaxRegPerEmail > 0 && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost") && !plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) { - Integer maxReg = Settings.getmaxRegPerIp; + int maxReg = Settings.getmaxRegPerIp; List otherAccounts = database.getAllAuthsByIp(ip); if (otherAccounts.size() >= maxReg) { - m.send(player, MessageKey.MAX_REGISTER_EXCEEDED, maxReg.toString(), Integer.toString(otherAccounts.size()), otherAccounts.toString()); + service.send(player, MessageKey.MAX_REGISTER_EXCEEDED, Integer.toString(maxReg), + Integer.toString(otherAccounts.size()), StringUtils.join(", ", otherAccounts.toString())); return; } } - final HashedPassword hashedPassword = plugin.getPasswordSecurity().computeHash(password, name); + final HashedPassword hashedPassword = service.computeHash(password, name); PlayerAuth auth = PlayerAuth.builder() .name(name) .realName(player.getName()) @@ -133,12 +132,12 @@ public class AsyncRegister implements Process { database.updateSession(auth); plugin.mail.main(auth, password); ProcessSyncEmailRegister sync = new ProcessSyncEmailRegister(player, service); - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, sync); + service.scheduleSyncDelayedTask(sync); } private void passwordRegister() { - final HashedPassword hashedPassword = plugin.getPasswordSecurity().computeHash(password, name); + final HashedPassword hashedPassword = service.computeHash(password, name); PlayerAuth auth = PlayerAuth.builder() .name(name) .realName(player.getName()) @@ -163,7 +162,7 @@ public class AsyncRegister implements Process { service.scheduleSyncDelayedTask(sync); //give the user the secret code to setup their app code generation - if (Settings.getPasswordHash == HashAlgorithm.TWO_FACTOR) { + if (service.getProperty(SecuritySettings.PASSWORD_HASH) == HashAlgorithm.TWO_FACTOR) { String qrCodeUrl = TwoFactor.getQRBarcodeURL(player.getName(), Bukkit.getIp(), hashedPassword.getHash()); service.send(player, MessageKey.TWO_FACTOR_CREATE, hashedPassword.getHash(), qrCodeUrl); } diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java index 1c2ac25c1..bee6576fb 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.process.Process; import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.RegistrationSettings; @@ -17,10 +18,10 @@ import org.bukkit.scheduler.BukkitTask; /** */ -public class ProcessSyncEmailRegister implements Runnable { +public class ProcessSyncEmailRegister implements Process { - protected final Player player; - protected final String name; + private final Player player; + private final String name; private final ProcessService service; /** diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index 4439bd255..fdf77375f 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -1,10 +1,8 @@ package fr.xephi.authme.settings; import fr.xephi.authme.AuthMe; -import fr.xephi.authme.datasource.DataSourceType; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.settings.domain.Property; -import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; @@ -41,13 +39,9 @@ public final class Settings { public static List forceRegisterCommands; public static List forceRegisterCommandsAsConsole; public static List unsafePasswords; - public static List emailBlacklist; - public static List emailWhitelist; - public static DataSourceType getDataSource; public static HashAlgorithm getPasswordHash; public static Pattern nickPattern; public static boolean useLogging = false; - public static int purgeDelay = 60; public static boolean isChatAllowed, isPermissionCheckEnabled, isRegistrationEnabled, isForcedRegistrationEnabled, isTeleportToSpawnEnabled, isSessionsEnabled, isAllowRestrictedIp, @@ -57,19 +51,17 @@ public final class Settings { isKickOnWrongPasswordEnabled, enablePasswordConfirmation, protectInventoryBeforeLogInEnabled, isStopEnabled, reloadSupport, rakamakUseIp, noConsoleSpam, removePassword, displayOtherAccounts, - useCaptcha, emailRegistration, multiverse, bungee, + emailRegistration, multiverse, bungee, banUnsafeIp, doubleEmailCheck, sessionExpireOnIpChange, - disableSocialSpy, useEssentialsMotd, usePurge, - purgePlayerDat, purgeEssentialsFile, - purgeLimitedCreative, purgeAntiXray, purgePermissions, + disableSocialSpy, useEssentialsMotd, enableProtection, enableAntiBot, recallEmail, useWelcomeMessage, broadcastWelcomeMessage, forceRegKick, forceRegLogin, checkVeryGames, removeJoinMessage, removeLeaveMessage, delayJoinMessage, - noTeleport, applyBlindEffect, hideTablistBeforeLogin, denyTabcompleteBeforeLogin, + noTeleport, hideTablistBeforeLogin, denyTabcompleteBeforeLogin, kickPlayersBeforeStopping, allowAllCommandsIfRegIsOptional, - customAttributes, generateImage, isRemoveSpeedEnabled, preventOtherCase; + customAttributes, isRemoveSpeedEnabled, preventOtherCase; public static String getNickRegex, getUnloggedinGroup, - getMySQLColumnGroup, unRegisteredGroup, + unRegisteredGroup, backupWindowsPath, getRegisteredGroup, rakamakUsers, rakamakUsersIp, getmailAccount, defaultWorld, spawnPriority, crazyloginFileName, getPassRegex, sendPlayerTo; @@ -79,7 +71,7 @@ public final class Settings { getNonActivatedGroup, passwordMaxLength, getRecoveryPassLength, getMailPort, maxLoginTry, captchaLength, saltLength, getmaxRegPerEmail, bCryptLog2Rounds, - antiBotSensibility, antiBotDuration, delayRecall, getMaxLoginPerIp, + antiBotSensibility, antiBotDuration, getMaxLoginPerIp, getMaxJoinPerIp; protected static FileConfiguration configFile; @@ -123,8 +115,6 @@ public final class Settings { getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp", 1); getPasswordHash = load(SecuritySettings.PASSWORD_HASH); getUnloggedinGroup = load(SecuritySettings.UNLOGGEDIN_GROUP); - getDataSource = load(DatabaseSettings.BACKEND); - getMySQLColumnGroup = configFile.getString("ExternalBoardOptions.mySQLColumnGroup", ""); getNonActivatedGroup = configFile.getInt("ExternalBoardOptions.nonActivedUserGroup", -1); unRegisteredGroup = configFile.getString("GroupOptions.UnregisteredPlayerGroup", ""); @@ -164,7 +154,6 @@ public final class Settings { getMailPort = configFile.getInt("Email.mailPort", 465); getRecoveryPassLength = configFile.getInt("Email.RecoveryPasswordLength", 8); displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true); - useCaptcha = configFile.getBoolean("Security.captcha.useCaptcha", false); maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5); captchaLength = configFile.getInt("Security.captcha.captchaLength", 5); emailRegistration = load(RegistrationSettings.USE_EMAIL_REGISTRATION); @@ -180,14 +169,7 @@ public final class Settings { disableSocialSpy = configFile.getBoolean("Hooks.disableSocialSpy", true); bCryptLog2Rounds = configFile.getInt("ExternalBoardOptions.bCryptLog2Round", 10); useEssentialsMotd = configFile.getBoolean("Hooks.useEssentialsMotd", false); - usePurge = configFile.getBoolean("Purge.useAutoPurge", false); - purgeDelay = configFile.getInt("Purge.daysBeforeRemovePlayer", 60); - purgePlayerDat = configFile.getBoolean("Purge.removePlayerDat", false); - purgeEssentialsFile = configFile.getBoolean("Purge.removeEssentialsFile", false); defaultWorld = configFile.getString("Purge.defaultWorld", "world"); - purgeLimitedCreative = configFile.getBoolean("Purge.removeLimitedCreativesInventories", false); - purgeAntiXray = configFile.getBoolean("Purge.removeAntiXRayFile", false); - purgePermissions = configFile.getBoolean("Purge.removePermissions", false); enableProtection = configFile.getBoolean("Protection.enableProtection", false); countries = configFile.getStringList("Protection.countries"); enableAntiBot = configFile.getBoolean("Protection.enableAntiBot", false); @@ -196,7 +178,6 @@ public final class Settings { forceCommands = configFile.getStringList("settings.forceCommands"); forceCommandsAsConsole = configFile.getStringList("settings.forceCommandsAsConsole"); recallEmail = configFile.getBoolean("Email.recallPlayers", false); - delayRecall = configFile.getInt("Email.delayRecall", 5); useWelcomeMessage = load(RegistrationSettings.USE_WELCOME_MESSAGE); unsafePasswords = configFile.getStringList("settings.security.unsafePasswords"); countriesBlacklist = configFile.getStringList("Protection.countriesBlacklist"); @@ -213,13 +194,9 @@ public final class Settings { noTeleport = load(RestrictionSettings.NO_TELEPORT); crazyloginFileName = configFile.getString("Converter.CrazyLogin.fileName", "accounts.db"); getPassRegex = configFile.getString("settings.restrictions.allowedPasswordCharacters", "[\\x21-\\x7E]*"); - applyBlindEffect = configFile.getBoolean("settings.applyBlindEffect", false); - emailBlacklist = configFile.getStringList("Email.emailBlacklisted"); - emailWhitelist = configFile.getStringList("Email.emailWhitelisted"); forceRegisterCommands = configFile.getStringList("settings.forceRegisterCommands"); forceRegisterCommandsAsConsole = configFile.getStringList("settings.forceRegisterCommandsAsConsole"); customAttributes = configFile.getBoolean("Hooks.customAttributes"); - generateImage = configFile.getBoolean("Email.generateImage", false); preventOtherCase = configFile.getBoolean("settings.preventOtherCase", false); kickPlayersBeforeStopping = configFile.getBoolean("Security.stop.kickPlayersBeforeStopping", true); sendPlayerTo = configFile.getString("Hooks.sendPlayerTo", ""); diff --git a/src/main/java/fr/xephi/authme/settings/properties/PurgeSettings.java b/src/main/java/fr/xephi/authme/settings/properties/PurgeSettings.java index b4de9abfc..2ec557997 100644 --- a/src/main/java/fr/xephi/authme/settings/properties/PurgeSettings.java +++ b/src/main/java/fr/xephi/authme/settings/properties/PurgeSettings.java @@ -5,43 +5,40 @@ import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.settings.domain.SettingsClass; import static fr.xephi.authme.settings.domain.Property.newProperty; -import static fr.xephi.authme.settings.domain.PropertyType.BOOLEAN; -import static fr.xephi.authme.settings.domain.PropertyType.INTEGER; -import static fr.xephi.authme.settings.domain.PropertyType.STRING; public class PurgeSettings implements SettingsClass { @Comment("If enabled, AuthMe automatically purges old, unused accounts") public static final Property USE_AUTO_PURGE = - newProperty(BOOLEAN, "Purge.useAutoPurge", false); + newProperty("Purge.useAutoPurge", false); @Comment("Number of Days an account become Unused") public static final Property DAYS_BEFORE_REMOVE_PLAYER = - newProperty(INTEGER, "Purge.daysBeforeRemovePlayer", 60); + newProperty("Purge.daysBeforeRemovePlayer", 60); @Comment("Do we need to remove the player.dat file during purge process?") public static final Property REMOVE_PLAYER_DAT = - newProperty(BOOLEAN, "Purge.removePlayerDat", false); + newProperty("Purge.removePlayerDat", false); @Comment("Do we need to remove the Essentials/users/player.yml file during purge process?") public static final Property REMOVE_ESSENTIALS_FILES = - newProperty(BOOLEAN, "Purge.removeEssentialsFile", false); + newProperty("Purge.removeEssentialsFile", false); @Comment("World where are players.dat stores") public static final Property DEFAULT_WORLD = - newProperty(STRING, "Purge.defaultWorld", "world"); + newProperty("Purge.defaultWorld", "world"); @Comment("Do we need to remove LimitedCreative/inventories/player.yml, player_creative.yml files during purge process ?") public static final Property REMOVE_LIMITED_CREATIVE_INVENTORIES = - newProperty(BOOLEAN, "Purge.removeLimitedCreativesInventories", false); + newProperty("Purge.removeLimitedCreativesInventories", false); @Comment("Do we need to remove the AntiXRayData/PlayerData/player file during purge process?") public static final Property REMOVE_ANTI_XRAY_FILE = - newProperty(BOOLEAN, "Purge.removeAntiXRayFile", false); + newProperty("Purge.removeAntiXRayFile", false); @Comment("Do we need to remove permissions?") public static final Property REMOVE_PERMISSIONS = - newProperty(BOOLEAN, "Purge.removePermissions", false); + newProperty("Purge.removePermissions", false); private PurgeSettings() { } diff --git a/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java index f5ba58e85..328dfc6d5 100644 --- a/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java @@ -58,7 +58,7 @@ import static org.mockito.Mockito.verify; public abstract class AbstractResourceClosingTest { /** List of DataSource method names not to test. */ - private static final Set IGNORED_METHODS = ImmutableSet.of("reload", "close", "getType"); + private static final Set IGNORED_METHODS = ImmutableSet.of("close", "getType"); /** Collection of values to use to call methods with the parameters they expect. */ private static final Map, Object> PARAM_VALUES = getDefaultParameters(); diff --git a/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java b/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java index 9dc97fc9e..873e84e5f 100644 --- a/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java +++ b/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java @@ -22,7 +22,7 @@ public class IpAddressManagerTest { @Test public void shouldRetrieveFromCache() { // given - IpAddressManager ipAddressManager = new IpAddressManager(mockSettings(false)); + IpAddressManager ipAddressManager = new IpAddressManager(mockSettings(true)); ipAddressManager.addCache("Test", "my test IP"); // when diff --git a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java index b6e9f65e5..bddd0122d 100644 --- a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java +++ b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java @@ -1,13 +1,12 @@ package fr.xephi.authme.process.email; -import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.output.MessageKey; -import fr.xephi.authme.output.Messages; +import fr.xephi.authme.process.ProcessService; import fr.xephi.authme.settings.NewSetting; -import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.util.WrapperMock; import org.bukkit.entity.Player; import org.junit.After; @@ -27,9 +26,9 @@ import static org.mockito.Mockito.when; public class AsyncChangeEmailTest { private Player player; - private Messages messages; private PlayerCache playerCache; private DataSource dataSource; + private ProcessService service; private NewSetting settings; @BeforeClass @@ -41,9 +40,10 @@ public class AsyncChangeEmailTest { @After public void cleanFields() { player = null; - messages = null; playerCache = null; dataSource = null; + service = null; + settings = null; } @Test @@ -62,7 +62,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource).updateEmail(auth); verify(playerCache).updatePlayer(auth); - verify(messages).send(player, MessageKey.EMAIL_CHANGED_SUCCESS); + verify(service).send(player, MessageKey.EMAIL_CHANGED_SUCCESS); } @Test @@ -81,7 +81,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource).updateEmail(auth); verify(playerCache, never()).updatePlayer(auth); - verify(messages).send(player, MessageKey.ERROR); + verify(service).send(player, MessageKey.ERROR); } @Test @@ -99,7 +99,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); - verify(messages).send(player, MessageKey.USAGE_ADD_EMAIL); + verify(service).send(player, MessageKey.USAGE_ADD_EMAIL); } @Test @@ -117,7 +117,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); - verify(messages).send(player, MessageKey.INVALID_NEW_EMAIL); + verify(service).send(player, MessageKey.INVALID_NEW_EMAIL); } @Test @@ -135,7 +135,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); - verify(messages).send(player, MessageKey.INVALID_OLD_EMAIL); + verify(service).send(player, MessageKey.INVALID_OLD_EMAIL); } @Test @@ -154,7 +154,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); - verify(messages).send(player, MessageKey.EMAIL_ALREADY_USED_ERROR); + verify(service).send(player, MessageKey.EMAIL_ALREADY_USED_ERROR); } @Test @@ -171,7 +171,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); - verify(messages).send(player, MessageKey.LOGIN_MESSAGE); + verify(service).send(player, MessageKey.LOGIN_MESSAGE); } @Test @@ -181,7 +181,7 @@ public class AsyncChangeEmailTest { given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(false); given(dataSource.isAuthAvailable("Bobby")).willReturn(false); - Settings.emailRegistration = true; + given(service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(true); // when process.run(); @@ -189,7 +189,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); - verify(messages).send(player, MessageKey.REGISTER_EMAIL_MESSAGE); + verify(service).send(player, MessageKey.REGISTER_EMAIL_MESSAGE); } @Test @@ -199,7 +199,7 @@ public class AsyncChangeEmailTest { given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(false); given(dataSource.isAuthAvailable("Bobby")).willReturn(false); - Settings.emailRegistration = false; + given(service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(false); // when process.run(); @@ -207,7 +207,7 @@ public class AsyncChangeEmailTest { // then verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); - verify(messages).send(player, MessageKey.REGISTER_MESSAGE); + verify(service).send(player, MessageKey.REGISTER_MESSAGE); } private static PlayerAuth authWithMail(String email) { @@ -218,12 +218,11 @@ public class AsyncChangeEmailTest { private AsyncChangeEmail createProcess(String oldEmail, String newEmail) { player = mock(Player.class); - messages = mock(Messages.class); - AuthMe authMe = mock(AuthMe.class); - when(authMe.getMessages()).thenReturn(messages); playerCache = mock(PlayerCache.class); dataSource = mock(DataSource.class); + service = mock(ProcessService.class); settings = mock(NewSetting.class); - return new AsyncChangeEmail(player, authMe, oldEmail, newEmail, dataSource, playerCache, settings); + given(service.getSettings()).willReturn(settings); + return new AsyncChangeEmail(player, oldEmail, newEmail, dataSource, playerCache, service); } } From 3f4681c5ed16f9ee5db690f78fa88b32587ee481 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sun, 6 Mar 2016 14:45:28 +0100 Subject: [PATCH 5/6] Minor - fix merge conflicts --- src/main/java/fr/xephi/authme/AuthMe.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 047fe099e..9a16c4655 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -376,7 +376,7 @@ public class AuthMe extends JavaPlugin { // Set up the permissions manager and command handler permsMan = initializePermissionsManager(); - commandHandler = initializeCommandHandler(permsMan, messages, passwordSecurity, newSettings); + commandHandler = initializeCommandHandler(permsMan, messages, passwordSecurity, newSettings, ipAddressManager); // Download and load GeoIp.dat file if absent GeoLiteAPI.isDataAvailable(); @@ -401,11 +401,12 @@ public class AuthMe extends JavaPlugin { dataManager = new DataManager(this); - ProcessService processService = new ProcessService(newSettings, messages, this); + ProcessService processService = new ProcessService(newSettings, messages, this, + ipAddressManager, passwordSecurity); management = new Management(this, processService, database, PlayerCache.getInstance()); // Set up the BungeeCord hook - setupBungeeCordHook(); + setupBungeeCordHook(newSettings, ipAddressManager); // Reload support hook reloadSupportHook(); From 654cebd5a7098c2c9e25d9d86e9919d3c913c7f8 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sun, 6 Mar 2016 15:38:08 +0100 Subject: [PATCH 6/6] Minor - rename LimboPlayer methods + code householding - Rename *taskId methods to *task to reflect what they handle - Remove usages of Wrapper where applicable - Replace some uses of legacy Settings with NewSetting calls --- src/main/java/fr/xephi/authme/AuthMe.java | 4 +- .../xephi/authme/cache/limbo/LimboCache.java | 6 +- .../xephi/authme/cache/limbo/LimboPlayer.java | 91 ++++++++++--------- .../xephi/authme/command/CommandService.java | 5 + .../authme/UnregisterAdminCommand.java | 4 +- .../executable/captcha/CaptchaCommand.java | 6 +- .../changepassword/ChangePasswordCommand.java | 4 +- .../authme/process/join/AsynchronousJoin.java | 6 +- .../process/login/AsynchronousLogin.java | 22 +++-- .../process/login/ProcessSyncPlayerLogin.java | 2 +- .../ProcessSynchronousPlayerLogout.java | 4 +- .../authme/process/quit/AsynchronousQuit.java | 2 +- .../register/ProcessSyncEmailRegister.java | 4 +- .../register/ProcessSyncPasswordRegister.java | 4 +- .../unregister/AsynchronousUnregister.java | 4 +- .../fr/xephi/authme/task/MessageTask.java | 2 +- .../java/fr/xephi/authme/util/Wrapper.java | 5 - .../CaptchaManagerTest.java | 3 +- .../IpAddressManagerTest.java | 3 +- .../ChangePasswordCommandTest.java | 21 ++--- .../fr/xephi/authme/util/WrapperMock.java | 6 -- 21 files changed, 99 insertions(+), 109 deletions(-) rename src/test/java/fr/xephi/authme/{manager => cache}/CaptchaManagerTest.java (96%) rename src/test/java/fr/xephi/authme/{manager => cache}/IpAddressManagerTest.java (96%) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 9a16c4655..cfd2b506b 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -815,8 +815,8 @@ public class AuthMe extends JavaPlugin { } Utils.addNormal(player, limbo.getGroup()); - player.setOp(limbo.getOperator()); - limbo.getTimeoutTaskId().cancel(); + player.setOp(limbo.isOperator()); + limbo.getTimeoutTask().cancel(); LimboCache.getInstance().deleteLimboPlayer(name); if (this.playerBackup.doesCacheExist(player)) { this.playerBackup.removeCache(player); diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java index 2679df641..49eaf9eee 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java @@ -16,8 +16,8 @@ import static com.google.common.base.Preconditions.checkNotNull; public class LimboCache { private volatile static LimboCache singleton; - public final ConcurrentHashMap cache; - public final AuthMe plugin; + private final ConcurrentHashMap cache; + private final AuthMe plugin; private final JsonCache jsonCache; /** @@ -84,7 +84,7 @@ public class LimboCache { checkNotNull(name); name = name.toLowerCase(); if (cache.containsKey(name)) { - cache.get(name).clearTask(); + cache.get(name).clearTasks(); cache.remove(name); } } diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java index 917a22bc1..6295bbb7d 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java @@ -4,14 +4,16 @@ import org.bukkit.Location; import org.bukkit.scheduler.BukkitTask; /** + * Represents a player which is not logged in and keeps track of certain states (like OP status, flying) + * which may be revoked from the player until he has logged in or registered. */ public class LimboPlayer { private final String name; private final boolean fly; private Location loc = null; - private BukkitTask timeoutTaskId = null; - private BukkitTask messageTaskId = null; + private BukkitTask timeoutTask = null; + private BukkitTask messageTask = null; private boolean operator = false; private String group; @@ -25,36 +27,36 @@ public class LimboPlayer { } /** - * Method getName. + * Return the name of the player. * - * @return String + * @return The player's name */ public String getName() { return name; } /** - * Method getLoc. + * Return the player's original location. * - * @return Location + * @return The player's location */ public Location getLoc() { return loc; } /** - * Method getOperator. + * Return whether the player is an operator or not (i.e. whether he is an OP). * - * @return boolean + * @return True if the player has OP status, false otherwise */ - public boolean getOperator() { + public boolean isOperator() { return operator; } /** - * Method getGroup. + * Return the player's permissions group. * - * @return String + * @return The permissions group the player belongs to */ public String getGroup() { return group; @@ -64,54 +66,61 @@ public class LimboPlayer { return fly; } - public BukkitTask getTimeoutTaskId() { - return timeoutTaskId; - } - /** - * Method setTimeoutTaskId. + * Return the timeout task, which kicks the player if he hasn't registered or logged in + * after a configurable amount of time. * - * @param i BukkitTask + * @return The timeout task associated to the player */ - public void setTimeoutTaskId(BukkitTask i) { - if (this.timeoutTaskId != null) { - this.timeoutTaskId.cancel(); - } - this.timeoutTaskId = i; + public BukkitTask getTimeoutTask() { + return timeoutTask; } /** - * Method getMessageTaskId. + * Set the timeout task of the player. The timeout task kicks the player after a configurable + * amount of time if he hasn't logged in or registered. * - * @return BukkitTask + * @param timeoutTask The task to set */ - public BukkitTask getMessageTaskId() { - return messageTaskId; + public void setTimeoutTask(BukkitTask timeoutTask) { + if (this.timeoutTask != null) { + this.timeoutTask.cancel(); + } + this.timeoutTask = timeoutTask; } /** - * Method setMessageTaskId. + * Return the message task reminding the player to log in or register. * - * @param messageTaskId BukkitTask + * @return The task responsible for sending the message regularly */ - public void setMessageTaskId(BukkitTask messageTaskId) { - if (this.messageTaskId != null) { - this.messageTaskId.cancel(); - } - this.messageTaskId = messageTaskId; + public BukkitTask getMessageTask() { + return messageTask; } /** - * Method clearTask. + * Set the messages task responsible for telling the player to log in or register. + * + * @param messageTask The message task to set */ - public void clearTask() { - if (messageTaskId != null) { - messageTaskId.cancel(); + public void setMessageTask(BukkitTask messageTask) { + if (this.messageTask != null) { + this.messageTask.cancel(); } - messageTaskId = null; - if (timeoutTaskId != null) { - timeoutTaskId.cancel(); + this.messageTask = messageTask; + } + + /** + * Clears all tasks associated to the player. + */ + public void clearTasks() { + if (messageTask != null) { + messageTask.cancel(); } - timeoutTaskId = null; + messageTask = null; + if (timeoutTask != null) { + timeoutTask.cancel(); + } + timeoutTask = null; } } diff --git a/src/main/java/fr/xephi/authme/command/CommandService.java b/src/main/java/fr/xephi/authme/command/CommandService.java index b7e6b91ec..0d782882e 100644 --- a/src/main/java/fr/xephi/authme/command/CommandService.java +++ b/src/main/java/fr/xephi/authme/command/CommandService.java @@ -1,6 +1,7 @@ package fr.xephi.authme.command; import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.cache.IpAddressManager; @@ -190,4 +191,8 @@ public class CommandService { return ipAddressManager; } + public PlayerCache getPlayerCache() { + return PlayerCache.getInstance(); + } + } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java index eacdd0593..03cf400d9 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java @@ -60,9 +60,9 @@ public class UnregisterAdminCommand implements ExecutableCommand { BukkitScheduler scheduler = sender.getServer().getScheduler(); if (timeOut != 0) { BukkitTask id = scheduler.runTaskLater(plugin, new TimeoutTask(plugin, playerNameLowerCase, target), timeOut); - LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setTimeoutTaskId(id); + LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setTimeoutTask(id); } - LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTaskId( + LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTask( scheduler.runTask( plugin, new MessageTask(plugin, playerNameLowerCase, MessageKey.REGISTER_MESSAGE, interval) ) diff --git a/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java b/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java index 8c5a0764a..aba0a950a 100644 --- a/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java @@ -7,7 +7,6 @@ import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.security.RandomString; import fr.xephi.authme.settings.properties.SecuritySettings; -import fr.xephi.authme.util.Wrapper; import org.bukkit.entity.Player; import java.util.List; @@ -18,9 +17,8 @@ public class CaptchaCommand extends PlayerCommand { public void runCommand(Player player, List arguments, CommandService commandService) { final String playerNameLowerCase = player.getName().toLowerCase(); final String captcha = arguments.get(0); - Wrapper wrapper = Wrapper.getInstance(); - final AuthMe plugin = wrapper.getAuthMe(); - PlayerCache playerCache = wrapper.getPlayerCache(); + final AuthMe plugin = commandService.getAuthMe(); + PlayerCache playerCache = PlayerCache.getInstance(); // Command logic if (playerCache.isAuthenticated(playerNameLowerCase)) { diff --git a/src/main/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommand.java index d27ff2987..336df1529 100644 --- a/src/main/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommand.java @@ -8,7 +8,6 @@ import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.task.ChangePasswordTask; -import fr.xephi.authme.util.Wrapper; import org.bukkit.entity.Player; import java.util.List; @@ -24,8 +23,7 @@ public class ChangePasswordCommand extends PlayerCommand { String newPassword = arguments.get(1); String name = player.getName().toLowerCase(); - Wrapper wrapper = Wrapper.getInstance(); - final PlayerCache playerCache = wrapper.getPlayerCache(); + final PlayerCache playerCache = commandService.getPlayerCache(); if (!playerCache.isAuthenticated(name)) { commandService.send(player, MessageKey.NOT_LOGGED_IN); return; diff --git a/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java b/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java index 04377825d..a8b91895a 100644 --- a/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java +++ b/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java @@ -64,8 +64,6 @@ public class AsynchronousJoin implements Process { } final String ip = service.getIpAddressManager().getPlayerIp(player); - - if (isNameRestricted(name, ip, player.getAddress().getHostName(), service.getSettings())) { service.scheduleSyncDelayedTask(new Runnable() { @Override @@ -196,7 +194,7 @@ public class AsynchronousJoin implements Process { int msgInterval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); if (registrationTimeout > 0) { BukkitTask id = service.runTaskLater(new TimeoutTask(plugin, name, player), registrationTimeout); - LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTask(id); } MessageKey msg; @@ -209,7 +207,7 @@ public class AsynchronousJoin implements Process { } if (msgInterval > 0 && LimboCache.getInstance().getLimboPlayer(name) != null) { BukkitTask msgTask = service.runTask(new MessageTask(plugin, name, msg, msgInterval)); - LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgTask); + LimboCache.getInstance().getLimboPlayer(name).setMessageTask(msgTask); } } diff --git a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java index 8c5c36750..45bc3fe0b 100644 --- a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java @@ -17,6 +17,7 @@ import fr.xephi.authme.security.RandomString; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; +import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.util.StringUtils; @@ -88,13 +89,13 @@ public class AsynchronousLogin implements Process { if (pAuth == null) { service.send(player, MessageKey.USER_NOT_REGISTERED); if (LimboCache.getInstance().hasLimboPlayer(name)) { - LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId().cancel(); + LimboCache.getInstance().getLimboPlayer(name).getMessageTask().cancel(); String[] msg = service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION) ? service.retrieveMessage(MessageKey.REGISTER_EMAIL_MESSAGE) : service.retrieveMessage(MessageKey.REGISTER_MESSAGE); BukkitTask messageTask = service.runTask( new MessageTask(plugin, name, msg, service.getProperty(RegistrationSettings.MESSAGE_INTERVAL))); - LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(messageTask); + LimboCache.getInstance().getLimboPlayer(name).setMessageTask(messageTask); } return null; } @@ -128,7 +129,7 @@ public class AsynchronousLogin implements Process { return; } - if (pAuth.getIp().equals("127.0.0.1") && !pAuth.getIp().equals(ip)) { + if ("127.0.0.1".equals(pAuth.getIp()) && !pAuth.getIp().equals(ip)) { pAuth.setIp(ip); database.updateIp(pAuth.getNickname(), ip); } @@ -181,19 +182,20 @@ public class AsynchronousLogin implements Process { ProcessSyncPlayerLogin syncPlayerLogin = new ProcessSyncPlayerLogin( player, plugin, database, service.getSettings()); if (syncPlayerLogin.getLimbo() != null) { - if (syncPlayerLogin.getLimbo().getTimeoutTaskId() != null) { - syncPlayerLogin.getLimbo().getTimeoutTaskId().cancel(); + if (syncPlayerLogin.getLimbo().getTimeoutTask() != null) { + syncPlayerLogin.getLimbo().getTimeoutTask().cancel(); } - if (syncPlayerLogin.getLimbo().getMessageTaskId() != null) { - syncPlayerLogin.getLimbo().getMessageTaskId().cancel(); + if (syncPlayerLogin.getLimbo().getMessageTask() != null) { + syncPlayerLogin.getLimbo().getMessageTask().cancel(); } } Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, syncPlayerLogin); } else if (player.isOnline()) { - if (!Settings.noConsoleSpam) + if (!service.getProperty(SecuritySettings.REMOVE_SPAM_FROM_CONSOLE)) { ConsoleLogger.info(realName + " used the wrong password"); - if (Settings.isKickOnWrongPasswordEnabled) { - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + } + if (service.getProperty(RestrictionSettings.KICK_ON_WRONG_PASSWORD)) { + service.scheduleSyncDelayedTask(new Runnable() { @Override public void run() { player.kickPlayer(service.retrieveSingleMessage(MessageKey.WRONG_PASSWORD)); diff --git a/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java b/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java index 78995cb1c..b454f3700 100644 --- a/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java @@ -67,7 +67,7 @@ public class ProcessSyncPlayerLogin implements Runnable { } private void restoreOpState() { - player.setOp(limbo.getOperator()); + player.setOp(limbo.isOperator()); } private void packQuitLocation() { diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSynchronousPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSynchronousPlayerLogout.java index 7b8e53ed8..bc2ea16d7 100644 --- a/src/main/java/fr/xephi/authme/process/logout/ProcessSynchronousPlayerLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSynchronousPlayerLogout.java @@ -72,10 +72,10 @@ public class ProcessSynchronousPlayerLogout implements Process { int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); if (timeOut != 0) { BukkitTask id = service.runTaskLater(new TimeoutTask(plugin, name, player), timeOut); - LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTask(id); } BukkitTask msgT = service.runTask(new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); - LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); + LimboCache.getInstance().getLimboPlayer(name).setMessageTask(msgT); if (player.isInsideVehicle() && player.getVehicle() != null) { player.getVehicle().eject(); } diff --git a/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java b/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java index 7638ce18e..cb2a79a95 100644 --- a/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java +++ b/src/main/java/fr/xephi/authme/process/quit/AsynchronousQuit.java @@ -68,7 +68,7 @@ public class AsynchronousQuit implements Process { Utils.addNormal(player, limbo.getGroup()); } needToChange = true; - isOp = limbo.getOperator(); + isOp = limbo.isOperator(); LimboCache.getInstance().deleteLimboPlayer(name); } if (Settings.isSessionsEnabled && !isKick) { diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java index bee6576fb..a58fddeda 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java @@ -49,11 +49,11 @@ public class ProcessSyncEmailRegister implements Process { if (limbo != null) { if (time != 0) { BukkitTask id = service.runTaskLater(new TimeoutTask(service.getAuthMe(), name, player), time); - limbo.setTimeoutTaskId(id); + limbo.setTimeoutTask(id); } BukkitTask messageTask = service.runTask(new MessageTask( service.getAuthMe(), name, service.retrieveMessage(MessageKey.LOGIN_MESSAGE), msgInterval)); - limbo.setMessageTaskId(messageTask); + limbo.setMessageTask(messageTask); } player.saveData(); diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java index 5efc09b55..c77a7d037 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java @@ -67,10 +67,10 @@ public class ProcessSyncPasswordRegister implements Process { BukkitTask task; if (delay != 0) { task = service.runTaskLater(new TimeoutTask(service.getAuthMe(), name, player), delay); - cache.getLimboPlayer(name).setTimeoutTaskId(task); + cache.getLimboPlayer(name).setTimeoutTask(task); } task = service.runTask(new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); - cache.getLimboPlayer(name).setMessageTaskId(task); + cache.getLimboPlayer(name).setMessageTask(task); if (player.isInsideVehicle() && player.getVehicle() != null) { player.getVehicle().eject(); } diff --git a/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java b/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java index 13353a80b..2e032cea3 100644 --- a/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java +++ b/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java @@ -75,9 +75,9 @@ public class AsynchronousUnregister implements Process { BukkitScheduler scheduler = plugin.getServer().getScheduler(); if (timeOut != 0) { BukkitTask id = scheduler.runTaskLater(plugin, new TimeoutTask(plugin, name, player), timeOut); - limboPlayer.setTimeoutTaskId(id); + limboPlayer.setTimeoutTask(id); } - limboPlayer.setMessageTaskId(scheduler.runTask(plugin, + limboPlayer.setMessageTask(scheduler.runTask(plugin, new MessageTask(plugin, name, MessageKey.REGISTER_MESSAGE, interval))); service.send(player, MessageKey.UNREGISTERED_SUCCESS); ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); diff --git a/src/main/java/fr/xephi/authme/task/MessageTask.java b/src/main/java/fr/xephi/authme/task/MessageTask.java index 0c035183d..56d1493d3 100644 --- a/src/main/java/fr/xephi/authme/task/MessageTask.java +++ b/src/main/java/fr/xephi/authme/task/MessageTask.java @@ -49,7 +49,7 @@ public class MessageTask implements Runnable { } BukkitTask nextTask = plugin.getServer().getScheduler().runTaskLater(plugin, this, interval * 20); if (LimboCache.getInstance().hasLimboPlayer(name)) { - LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(nextTask); + LimboCache.getInstance().getLimboPlayer(name).setMessageTask(nextTask); } return; } diff --git a/src/main/java/fr/xephi/authme/util/Wrapper.java b/src/main/java/fr/xephi/authme/util/Wrapper.java index 77f65cff5..bdd1d5a2d 100644 --- a/src/main/java/fr/xephi/authme/util/Wrapper.java +++ b/src/main/java/fr/xephi/authme/util/Wrapper.java @@ -8,7 +8,6 @@ import org.bukkit.Server; import org.bukkit.scheduler.BukkitScheduler; import java.io.File; -import java.util.logging.Logger; /** * Wrapper for the retrieval of common singletons used throughout the application. @@ -48,10 +47,6 @@ public class Wrapper { return getAuthMe().getServer(); } - public Logger getLogger() { - return getAuthMe().getLogger(); - } - public Messages getMessages() { return getAuthMe().getMessages(); } diff --git a/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java b/src/test/java/fr/xephi/authme/cache/CaptchaManagerTest.java similarity index 96% rename from src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java rename to src/test/java/fr/xephi/authme/cache/CaptchaManagerTest.java index 2f9d241f6..964891552 100644 --- a/src/test/java/fr/xephi/authme/manager/CaptchaManagerTest.java +++ b/src/test/java/fr/xephi/authme/cache/CaptchaManagerTest.java @@ -1,6 +1,5 @@ -package fr.xephi.authme.manager; +package fr.xephi.authme.cache; -import fr.xephi.authme.cache.CaptchaManager; import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.properties.SecuritySettings; import org.junit.Test; diff --git a/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java b/src/test/java/fr/xephi/authme/cache/IpAddressManagerTest.java similarity index 96% rename from src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java rename to src/test/java/fr/xephi/authme/cache/IpAddressManagerTest.java index 873e84e5f..50c73d300 100644 --- a/src/test/java/fr/xephi/authme/manager/IpAddressManagerTest.java +++ b/src/test/java/fr/xephi/authme/cache/IpAddressManagerTest.java @@ -1,6 +1,5 @@ -package fr.xephi.authme.manager; +package fr.xephi.authme.cache; -import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.properties.HooksSettings; import org.bukkit.entity.Player; diff --git a/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java index 3936e5069..31fb30f15 100644 --- a/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java @@ -7,8 +7,6 @@ import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.task.ChangePasswordTask; -import fr.xephi.authme.util.WrapperMock; -import org.bukkit.Server; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -21,6 +19,7 @@ import java.util.Arrays; import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.any; @@ -35,14 +34,10 @@ import static org.mockito.Mockito.when; */ public class ChangePasswordCommandTest { - private WrapperMock wrapperMock; - private PlayerCache cacheMock; private CommandService commandService; @Before public void setUpMocks() { - wrapperMock = WrapperMock.createInstance(); - cacheMock = wrapperMock.getPlayerCache(); commandService = mock(CommandService.class); when(commandService.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).thenReturn(2); @@ -62,7 +57,9 @@ public class ChangePasswordCommandTest { command.executeCommand(sender, new ArrayList(), commandService); // then - assertThat(wrapperMock.wasMockCalled(Server.class), equalTo(false)); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); + verify(sender).sendMessage(captor.capture()); + assertThat(captor.getValue(), containsString("only for players")); } @Test @@ -76,7 +73,6 @@ public class ChangePasswordCommandTest { // then verify(commandService).send(sender, MessageKey.NOT_LOGGED_IN); - assertThat(wrapperMock.wasMockCalled(Server.class), equalTo(false)); } @Test @@ -90,7 +86,6 @@ public class ChangePasswordCommandTest { // then verify(commandService).send(sender, MessageKey.PASSWORD_MATCH_ERROR); - assertThat(wrapperMock.wasMockCalled(Server.class), equalTo(false)); } @@ -105,7 +100,6 @@ public class ChangePasswordCommandTest { // then verify(commandService).send(sender, MessageKey.PASSWORD_IS_USERNAME_ERROR); - assertThat(wrapperMock.wasMockCalled(Server.class), equalTo(false)); } @Test @@ -120,7 +114,6 @@ public class ChangePasswordCommandTest { // then verify(commandService).send(sender, MessageKey.INVALID_PASSWORD_LENGTH); - assertThat(wrapperMock.wasMockCalled(Server.class), equalTo(false)); } @Test @@ -135,7 +128,6 @@ public class ChangePasswordCommandTest { // then verify(commandService).send(sender, MessageKey.INVALID_PASSWORD_LENGTH); - assertThat(wrapperMock.wasMockCalled(Server.class), equalTo(false)); } @Test @@ -151,7 +143,6 @@ public class ChangePasswordCommandTest { // then verify(commandService).send(sender, MessageKey.PASSWORD_UNSAFE_ERROR); - assertThat(wrapperMock.wasMockCalled(Server.class), equalTo(false)); } @Test @@ -175,7 +166,9 @@ public class ChangePasswordCommandTest { private Player initPlayerWithName(String name, boolean loggedIn) { Player player = mock(Player.class); when(player.getName()).thenReturn(name); - when(cacheMock.isAuthenticated(name)).thenReturn(loggedIn); + PlayerCache playerCache = mock(PlayerCache.class); + when(playerCache.isAuthenticated(name)).thenReturn(loggedIn); + when(commandService.getPlayerCache()).thenReturn(playerCache); return player; } diff --git a/src/test/java/fr/xephi/authme/util/WrapperMock.java b/src/test/java/fr/xephi/authme/util/WrapperMock.java index 057f38bdb..fbf880ba5 100644 --- a/src/test/java/fr/xephi/authme/util/WrapperMock.java +++ b/src/test/java/fr/xephi/authme/util/WrapperMock.java @@ -10,7 +10,6 @@ import org.mockito.Mockito; import java.io.File; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; /** * Class returning mocks for all calls in {@link Wrapper}. @@ -36,11 +35,6 @@ public class WrapperMock extends Wrapper { return instance; } - @Override - public Logger getLogger() { - return getMock(Logger.class); - } - @Override public Server getServer() { return getMock(Server.class);