diff --git a/pom.xml b/pom.xml index ceeaefcaf..c928c9a6f 100644 --- a/pom.xml +++ b/pom.xml @@ -285,7 +285,7 @@ com.zaxxer HikariCP - 2.4.1 + 2.4.2 compile @@ -298,7 +298,7 @@ org.slf4j slf4j-jdk14 - 1.7.12 + 1.7.13 compile true @@ -502,6 +502,10 @@ AllPay com.fernferret.allpay + + Vault + net.milkbowl.vault + VaultAPI net.milkbowl.vault diff --git a/src/main/java/fr/xephi/authme/AntiBot.java b/src/main/java/fr/xephi/authme/AntiBot.java index 194e4cdf6..2ca1a8a0e 100644 --- a/src/main/java/fr/xephi/authme/AntiBot.java +++ b/src/main/java/fr/xephi/authme/AntiBot.java @@ -1,8 +1,8 @@ package fr.xephi.authme; -import fr.xephi.authme.permission.UserPermission; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.permission.PlayerPermission; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.Wrapper; import org.bukkit.Bukkit; @@ -73,7 +73,7 @@ public class AntiBot { if (antiBotStatus == AntiBotStatus.ACTIVE || antiBotStatus == AntiBotStatus.DISABLED) { return; } - if (plugin.getPermissionsManager().hasPermission(player, UserPermission.BYPASS_ANTIBOT)) { + if (plugin.getPermissionsManager().hasPermission(player, PlayerPermission.BYPASS_ANTIBOT)) { return; } diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 4f1886fcd..775b22aa2 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -17,8 +17,12 @@ import fr.xephi.authme.hooks.BungeeCordMessage; import fr.xephi.authme.hooks.EssSpawn; import fr.xephi.authme.listener.*; import fr.xephi.authme.modules.ModuleManager; +import fr.xephi.authme.output.ConsoleFilter; +import fr.xephi.authme.output.Log4JFilter; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.PermissionsManager; -import fr.xephi.authme.permission.UserPermission; +import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.process.Management; import fr.xephi.authme.settings.*; import fr.xephi.authme.util.GeoLiteAPI; @@ -227,7 +231,7 @@ public class AuthMe extends JavaPlugin { this.otherAccounts = OtherAccounts.getInstance(); // Setup messages - this.messages = new Messages(Settings.messageFile, Settings.messagesLanguage); + this.messages = Messages.getInstance(); // Set up Metrics setupMetrics(); @@ -735,7 +739,7 @@ public class AuthMe extends JavaPlugin { public Player generateKickPlayer(Collection collection) { Player player = null; for (Player p : collection) { - if (!getPermissionsManager().hasPermission(p, UserPermission.IS_VIP)) { + if (!getPermissionsManager().hasPermission(p, PlayerPermission.IS_VIP)) { player = p; break; } diff --git a/src/main/java/fr/xephi/authme/ConsoleFilter.java b/src/main/java/fr/xephi/authme/ConsoleFilter.java deleted file mode 100644 index 7e12ef10e..000000000 --- a/src/main/java/fr/xephi/authme/ConsoleFilter.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.xephi.authme; - -import java.util.logging.Filter; -import java.util.logging.LogRecord; - -/** - * Console filter Class - * - * @author Xephi59 - * @version $Revision: 1.0 $ - */ -public class ConsoleFilter implements Filter { - - public ConsoleFilter() { - } - - /** - * Method isLoggable. - * - * @param record LogRecord - * - * @return boolean * @see java.util.logging.Filter#isLoggable(LogRecord) - */ - @Override - public boolean isLoggable(LogRecord record) { - try { - if (record == null || record.getMessage() == null) - return true; - String logM = record.getMessage().toLowerCase(); - if (!logM.contains("issued server command:")) - return true; - if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") && !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ") && !logM.contains("/register ")) - return true; - String playerName = record.getMessage().split(" ")[0]; - record.setMessage(playerName + " issued an AuthMe command!"); - return true; - } catch (NullPointerException npe) { - return true; - } - } - -} diff --git a/src/main/java/fr/xephi/authme/SendMailSSL.java b/src/main/java/fr/xephi/authme/SendMailSSL.java index 397ddac91..8eb1a92be 100644 --- a/src/main/java/fr/xephi/authme/SendMailSSL.java +++ b/src/main/java/fr/xephi/authme/SendMailSSL.java @@ -48,7 +48,7 @@ public class SendMailSSL { final String subject = Settings.getMailSubject; final String smtp = Settings.getmailSMTP; final String password = Settings.getmailPassword; - final String mailText = Settings.getMailText.replace("", auth.getNickname()).replace("", plugin.getServer().getServerName()).replace("", newPass); + final String mailText = Settings.getMailText.replace("%playername%", auth.getNickname()).replace("%servername%", plugin.getServer().getServerName()).replace("%generatedpass%", newPass); final String mail = auth.getEmail(); Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @@ -76,7 +76,7 @@ public class SendMailSSL { ImageIO.write(gen.generateImage(), "jpg", file); DataSource source = new FileDataSource(file); String tag = email.embed(source, auth.getNickname() + "_new_pass.jpg"); - content = content.replace("", ""); + content = content.replace("%image%", ""); } catch (Exception e) { ConsoleLogger.showError("Unable to send new password as image! Using normal text! Dest: " + mail); } @@ -86,8 +86,7 @@ public class SendMailSSL { try { email.send(); } catch (Exception e) { - e.printStackTrace(); - ConsoleLogger.showError("Fail to send a mail to " + mail); + ConsoleLogger.showError("Fail to send a mail to " + mail + " cause " + e.getLocalizedMessage()); } if (file != null) //noinspection ResultOfMethodCallIgnored 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 5339ac3a3..27ce38d84 100644 --- a/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java +++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java @@ -162,8 +162,10 @@ public class PlayerAuth { * @param email String * @param realName String */ - public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { - this.nickname = nickname; + public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, + long lastLogin, double x, double y, double z, String world, String email, + String realName) { + this.nickname = nickname.toLowerCase(); this.hash = hash; this.ip = ip; this.lastLogin = lastLogin; @@ -202,7 +204,7 @@ public class PlayerAuth { * @param nickname String */ public void setName(String nickname) { - this.nickname = nickname; + this.nickname = nickname.toLowerCase(); } /** 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 33cef3ded..2495d68b6 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java @@ -117,10 +117,9 @@ public class LimboCache { * @param name String */ public void deleteLimboPlayer(String name) { - if(cache.containsKey(name)) { - cache.get(name).clearTask(); - cache.remove(name); - } + if (name == null) + return; + cache.remove(name); } /** @@ -131,6 +130,8 @@ public class LimboCache { * @return LimboPlayer */ public LimboPlayer getLimboPlayer(String name) { + if (name == null) + return null; return cache.get(name); } @@ -142,6 +143,8 @@ public class LimboCache { * @return boolean */ public boolean hasLimboPlayer(String name) { + if (name == null) + return false; return cache.containsKey(name); } @@ -151,9 +154,8 @@ public class LimboCache { * @param player Player */ public void updateLimboPlayer(Player player) { - String name = player.getName().toLowerCase(); - if (hasLimboPlayer(name)) { - deleteLimboPlayer(name); + if (this.hasLimboPlayer(player.getName().toLowerCase())) { + this.deleteLimboPlayer(player.getName().toLowerCase()); } addLimboPlayer(player); } diff --git a/src/main/java/fr/xephi/authme/command/CommandDescription.java b/src/main/java/fr/xephi/authme/command/CommandDescription.java index 3a5342461..44989a20b 100644 --- a/src/main/java/fr/xephi/authme/command/CommandDescription.java +++ b/src/main/java/fr/xephi/authme/command/CommandDescription.java @@ -735,11 +735,11 @@ public class CommandDescription { this.permissions = new CommandPermissions(permissionNode, defaultPermission); } - public static Builder builder() { - return new Builder(); + public static CommandBuilder builder() { + return new CommandBuilder(); } - public static final class Builder { + public static final class CommandBuilder { private List labels; private String description; private String detailedDescription; @@ -767,47 +767,47 @@ public class CommandDescription { ); } - public Builder labels(List labels) { + public CommandBuilder labels(List labels) { this.labels = labels; return this; } - public Builder labels(String... labels) { + public CommandBuilder labels(String... labels) { return labels(asMutableList(labels)); } - public Builder description(String description) { + public CommandBuilder description(String description) { this.description = description; return this; } - public Builder detailedDescription(String detailedDescription) { + public CommandBuilder detailedDescription(String detailedDescription) { this.detailedDescription = detailedDescription; return this; } - public Builder executableCommand(ExecutableCommand executableCommand) { + public CommandBuilder executableCommand(ExecutableCommand executableCommand) { this.executableCommand = executableCommand; return this; } - public Builder parent(CommandDescription parent) { + public CommandBuilder parent(CommandDescription parent) { this.parent = parent; return this; } - public Builder withArgument(String label, String description, boolean isOptional) { + public CommandBuilder withArgument(String label, String description, boolean isOptional) { arguments.add(new CommandArgumentDescription(label, description, isOptional)); return this; } - public Builder noArgumentMaximum(boolean noArgumentMaximum) { + public CommandBuilder noArgumentMaximum(boolean noArgumentMaximum) { this.noArgumentMaximum = noArgumentMaximum; return this; } - public Builder permissions(CommandPermissions.DefaultPermission defaultPermission, - PermissionNode... permissionNodes) { + public CommandBuilder permissions(CommandPermissions.DefaultPermission defaultPermission, + PermissionNode... permissionNodes) { this.permissions = new CommandPermissions(asMutableList(permissionNodes), defaultPermission); return this; } diff --git a/src/main/java/fr/xephi/authme/command/CommandManager.java b/src/main/java/fr/xephi/authme/command/CommandManager.java index cc335561c..6c2f1c845 100644 --- a/src/main/java/fr/xephi/authme/command/CommandManager.java +++ b/src/main/java/fr/xephi/authme/command/CommandManager.java @@ -10,7 +10,7 @@ import fr.xephi.authme.command.executable.email.RecoverEmailCommand; import fr.xephi.authme.command.executable.login.LoginCommand; import fr.xephi.authme.command.executable.logout.LogoutCommand; import fr.xephi.authme.permission.AdminPermission; -import fr.xephi.authme.permission.UserPermission; +import fr.xephi.authme.permission.PlayerPermission; import java.util.ArrayList; import java.util.Arrays; @@ -73,7 +73,7 @@ public class CommandManager { .description("Register a player") .detailedDescription("Register the specified player with the specified password.") .parent(authMeBaseCommand) - .permissions(OP_ONLY, UserPermission.REGISTER) + .permissions(OP_ONLY, PlayerPermission.REGISTER) .withArgument("player", "Player name", false) .withArgument("password", "Password", false) .build(); @@ -85,7 +85,7 @@ public class CommandManager { .description("Unregister a player") .detailedDescription("Unregister the specified player.") .parent(authMeBaseCommand) - .permissions(OP_ONLY, UserPermission.UNREGISTER) + .permissions(OP_ONLY, PlayerPermission.UNREGISTER) .withArgument("player", "Player name", false) .build(); @@ -96,7 +96,7 @@ public class CommandManager { .description("Enforce login player") .detailedDescription("Enforce the specified player to login.") .parent(authMeBaseCommand) - .permissions(OP_ONLY, UserPermission.CAN_LOGIN_BE_FORCED) + .permissions(OP_ONLY, PlayerPermission.CAN_LOGIN_BE_FORCED) .withArgument("player", "Online player name", true) .build(); @@ -107,7 +107,7 @@ public class CommandManager { .description("Change a player's password") .detailedDescription("Change the password of a player.") .parent(authMeBaseCommand) - .permissions(OP_ONLY, UserPermission.CHANGE_PASSWORD) + .permissions(OP_ONLY, AdminPermission.CHANGE_PASSWORD) .withArgument("player", "Player name", false) .withArgument("pwd", "New password", false) .build(); @@ -135,35 +135,30 @@ public class CommandManager { .build(); // Register the getemail command - CommandDescription getEmailCommand = new CommandDescription(new GetEmailCommand(), new ArrayList() { - - { - add("getemail"); - add("getmail"); - add("email"); - add("mail"); - } - }, "Display player's email", "Display the email address of the specified player if set.", authMeBaseCommand); - getEmailCommand.setCommandPermissions(AdminPermission.GET_EMAIL, OP_ONLY); - getEmailCommand.addArgument(new CommandArgumentDescription("player", "Player name", true)); + CommandDescription getEmailCommand = CommandDescription.builder() + .executableCommand(new GetEmailCommand()) + .labels("getemail", "getmail", "email", "mail") + .description("Display player's email") + .detailedDescription("Display the email address of the specified player if set.") + .parent(authMeBaseCommand) + .permissions(OP_ONLY, AdminPermission.GET_EMAIL) + .withArgument("player", "Player name", true) + .build(); // Register the setemail command - CommandDescription setEmailCommand = new CommandDescription(new SetEmailCommand(), new ArrayList() { - - { - add("chgemail"); - add("chgmail"); - add("setemail"); - add("setmail"); - } - }, "Change player's email", "Change the email address of the specified player.", authMeBaseCommand); - setEmailCommand.setCommandPermissions(AdminPermission.CHANGE_EMAIL, OP_ONLY); - setEmailCommand.addArgument(new CommandArgumentDescription("player", "Player name", false)); - setEmailCommand.addArgument(new CommandArgumentDescription("email", "Player email", false)); + CommandDescription setEmailCommand = CommandDescription.builder() + .executableCommand(new SetEmailCommand()) + .labels("chgemail", "chgmail", "setemail", "setmail") + .description("Change player's email") + .detailedDescription("Change the email address of the specified player.") + .parent(authMeBaseCommand) + .permissions(OP_ONLY, AdminPermission.CHANGE_EMAIL) + .withArgument("player", "Player name", false) + .withArgument("email", "Player email", false) + .build(); // Register the getip command CommandDescription getIpCommand = new CommandDescription(new GetIpCommand(), new ArrayList() { - { add("getip"); add("ip"); @@ -174,7 +169,6 @@ public class CommandManager { // Register the spawn command CommandDescription spawnCommand = new CommandDescription(new SpawnCommand(), new ArrayList() { - { add("spawn"); add("home"); @@ -184,7 +178,6 @@ public class CommandManager { // Register the setspawn command CommandDescription setSpawnCommand = new CommandDescription(new SetSpawnCommand(), new ArrayList() { - { add("setspawn"); add("chgspawn"); @@ -194,7 +187,6 @@ public class CommandManager { // Register the firstspawn command CommandDescription firstSpawnCommand = new CommandDescription(new FirstSpawnCommand(), new ArrayList() { - { add("firstspawn"); add("firsthome"); @@ -204,7 +196,6 @@ public class CommandManager { // Register the setfirstspawn command CommandDescription setFirstSpawnCommand = new CommandDescription(new SetFirstSpawnCommand(), new ArrayList() { - { add("setfirstspawn"); add("chgfirstspawn"); @@ -214,7 +205,6 @@ public class CommandManager { // Register the purge command CommandDescription purgeCommand = new CommandDescription(new PurgeCommand(), new ArrayList() { - { add("purge"); add("delete"); @@ -225,7 +215,6 @@ public class CommandManager { // Register the purgelastposition command CommandDescription purgeLastPositionCommand = new CommandDescription(new PurgeLastPositionCommand(), new ArrayList() { - { add("resetpos"); add("purgelastposition"); @@ -240,7 +229,6 @@ public class CommandManager { // Register the purgebannedplayers command CommandDescription purgeBannedPlayersCommand = new CommandDescription(new PurgeBannedPlayersCommand(), new ArrayList() { - { add("purgebannedplayers"); add("purgebannedplayer"); @@ -252,7 +240,6 @@ public class CommandManager { // Register the switchantibot command CommandDescription switchAntiBotCommand = new CommandDescription(new SwitchAntiBotCommand(), new ArrayList() { - { add("switchantibot"); add("toggleantibot"); @@ -277,7 +264,6 @@ public class CommandManager { // Register the reload command CommandDescription reloadCommand = new CommandDescription(new ReloadCommand(), new ArrayList() { - { add("reload"); add("rld"); @@ -302,7 +288,7 @@ public class CommandManager { .description("Login command") .detailedDescription("Command to log in using AuthMeReloaded.") .parent(null) - .permissions(ALLOWED, UserPermission.LOGIN) + .permissions(ALLOWED, PlayerPermission.LOGIN) .withArgument("password", "Login password", false) .build(); @@ -313,12 +299,11 @@ public class CommandManager { // Register the base logout command CommandDescription logoutBaseCommand = new CommandDescription(new LogoutCommand(), new ArrayList() { - { add("logout"); } }, "Logout command", "Command to logout using AuthMeReloaded.", null); - logoutBaseCommand.setCommandPermissions(UserPermission.LOGOUT, CommandPermissions.DefaultPermission.ALLOWED); + logoutBaseCommand.setCommandPermissions(PlayerPermission.LOGOUT, CommandPermissions.DefaultPermission.ALLOWED); // Register the help command CommandDescription logoutHelpCommand = new CommandDescription(helpCommandExecutable, helpCommandLabels, @@ -327,13 +312,12 @@ public class CommandManager { // Register the base register command CommandDescription registerBaseCommand = new CommandDescription(new fr.xephi.authme.command.executable.register.RegisterCommand(), new ArrayList() { - { add("register"); add("reg"); } }, "Registration command", "Command to register using AuthMeReloaded.", null); - registerBaseCommand.setCommandPermissions(UserPermission.REGISTER, CommandPermissions.DefaultPermission.ALLOWED); + registerBaseCommand.setCommandPermissions(PlayerPermission.REGISTER, CommandPermissions.DefaultPermission.ALLOWED); registerBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false)); registerBaseCommand.addArgument(new CommandArgumentDescription("verifyPassword", "Verify password", false)); @@ -344,13 +328,12 @@ public class CommandManager { // Register the base unregister command CommandDescription unregisterBaseCommand = new CommandDescription(new fr.xephi.authme.command.executable.unregister.UnregisterCommand(), new ArrayList() { - { add("unregister"); add("unreg"); } }, "Unregistration command", "Command to unregister using AuthMeReloaded.", null); - unregisterBaseCommand.setCommandPermissions(UserPermission.UNREGISTER, CommandPermissions.DefaultPermission.ALLOWED); + unregisterBaseCommand.setCommandPermissions(PlayerPermission.UNREGISTER, CommandPermissions.DefaultPermission.ALLOWED); unregisterBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false)); // Register the help command @@ -359,13 +342,12 @@ public class CommandManager { // Register the base changepassword command CommandDescription changePasswordBaseCommand = new CommandDescription(new fr.xephi.authme.command.executable.changepassword.ChangePasswordCommand(), new ArrayList() { - { add("changepassword"); add("changepass"); } }, "Change password command", "Command to change your password using AuthMeReloaded.", null); - changePasswordBaseCommand.setCommandPermissions(UserPermission.CHANGE_PASSWORD, CommandPermissions.DefaultPermission.ALLOWED); + changePasswordBaseCommand.setCommandPermissions(PlayerPermission.CHANGE_PASSWORD, CommandPermissions.DefaultPermission.ALLOWED); changePasswordBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false)); changePasswordBaseCommand.addArgument(new CommandArgumentDescription("verifyPassword", "Verify password", false)); @@ -376,7 +358,6 @@ public class CommandManager { // Register the base Dungeon Maze command CommandDescription emailBaseCommand = new CommandDescription(helpCommandExecutable, new ArrayList() { - { add("email"); add("mail"); @@ -390,33 +371,30 @@ public class CommandManager { // Register the add command CommandDescription addEmailCommand = new CommandDescription(new AddEmailCommand(), new ArrayList() { - { add("add"); add("addemail"); add("addmail"); } }, "Add E-mail", "Add an new E-Mail address to your account.", emailBaseCommand); - addEmailCommand.setCommandPermissions(UserPermission.ADD_EMAIL, CommandPermissions.DefaultPermission.ALLOWED); + addEmailCommand.setCommandPermissions(PlayerPermission.ADD_EMAIL, CommandPermissions.DefaultPermission.ALLOWED); addEmailCommand.addArgument(new CommandArgumentDescription("email", "Email address", false)); addEmailCommand.addArgument(new CommandArgumentDescription("verifyEmail", "Email address verification", false)); // Register the change command CommandDescription changeEmailCommand = new CommandDescription(new ChangeEmailCommand(), new ArrayList() { - { add("change"); add("changeemail"); add("changemail"); } }, "Change E-mail", "Change an E-Mail address of your account.", emailBaseCommand); - changeEmailCommand.setCommandPermissions(UserPermission.CHANGE_EMAIL, CommandPermissions.DefaultPermission.ALLOWED); + changeEmailCommand.setCommandPermissions(PlayerPermission.CHANGE_EMAIL, CommandPermissions.DefaultPermission.ALLOWED); changeEmailCommand.addArgument(new CommandArgumentDescription("oldEmail", "Old email address", false)); changeEmailCommand.addArgument(new CommandArgumentDescription("newEmail", "New email address", false)); // Register the recover command CommandDescription recoverEmailCommand = new CommandDescription(new RecoverEmailCommand(), new ArrayList() { - { add("recover"); add("recovery"); @@ -424,18 +402,17 @@ public class CommandManager { add("recovermail"); } }, "Recover using E-mail", "Recover your account using an E-mail address.", emailBaseCommand); - recoverEmailCommand.setCommandPermissions(UserPermission.RECOVER_EMAIL, CommandPermissions.DefaultPermission.ALLOWED); + recoverEmailCommand.setCommandPermissions(PlayerPermission.RECOVER_EMAIL, CommandPermissions.DefaultPermission.ALLOWED); recoverEmailCommand.addArgument(new CommandArgumentDescription("email", "Email address", false)); // Register the base captcha command CommandDescription captchaBaseCommand = new CommandDescription(new CaptchaCommand(), new ArrayList() { - { add("captcha"); add("capt"); } }, "Captcha command", "Captcha command for AuthMeReloaded.", null); - captchaBaseCommand.setCommandPermissions(UserPermission.CAPTCHA, CommandPermissions.DefaultPermission.ALLOWED); + captchaBaseCommand.setCommandPermissions(PlayerPermission.CAPTCHA, CommandPermissions.DefaultPermission.ALLOWED); captchaBaseCommand.addArgument(new CommandArgumentDescription("captcha", "The captcha", false)); // Register the help command @@ -445,14 +422,13 @@ public class CommandManager { // Register the base converter command CommandDescription converterBaseCommand = new CommandDescription(new ConverterCommand(), new ArrayList() { - { add("converter"); add("convert"); add("conv"); } }, "Convert command", "Convert command for AuthMeReloaded.", null); - converterBaseCommand.setCommandPermissions(UserPermission.CONVERTER, OP_ONLY); + converterBaseCommand.setCommandPermissions(AdminPermission.CONVERTER, OP_ONLY); converterBaseCommand.addArgument(new CommandArgumentDescription("job", "Conversion job: flattosql / flattosqlite /| xauth / crazylogin / rakamak / royalauth / vauth / sqltoflat", false)); // Register the help command diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/AccountsCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/AccountsCommand.java index b5f07d1af..ba34491a6 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/AccountsCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/AccountsCommand.java @@ -5,8 +5,8 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ChangePasswordCommand.java index 83ea810f5..06255128f 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ChangePasswordCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ChangePasswordCommand.java @@ -7,8 +7,8 @@ import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.security.PasswordSecurity; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -16,6 +16,7 @@ import org.bukkit.command.CommandSender; import java.security.NoSuchAlgorithmException; /** + * Admin command for changing a player's password. */ public class ChangePasswordCommand extends ExecutableCommand { @@ -31,23 +32,26 @@ public class ChangePasswordCommand extends ExecutableCommand { // Validate the password String playerPassLowerCase = playerPass.toLowerCase(); - if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") || !playerPassLowerCase.matches(Settings.getPassRegex)) { - m.send(sender, MessageKey.PASSWORD_IS_USERNAME_ERROR); + if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") + || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") + || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") + || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") + || !playerPassLowerCase.matches(Settings.getPassRegex)) { + m.send(sender, MessageKey.PASSWORD_MATCH_ERROR); return true; } if (playerPassLowerCase.equalsIgnoreCase(playerName)) { m.send(sender, MessageKey.PASSWORD_IS_USERNAME_ERROR); return true; } - if (playerPassLowerCase.length() < Settings.getPasswordMinLen || playerPassLowerCase.length() > Settings.passwordMaxLength) { + if (playerPassLowerCase.length() < Settings.getPasswordMinLen + || playerPassLowerCase.length() > Settings.passwordMaxLength) { m.send(sender, MessageKey.INVALID_PASSWORD_LENGTH); return true; } - if (!Settings.unsafePasswords.isEmpty()) { - if (Settings.unsafePasswords.contains(playerPassLowerCase)) { - m.send(sender, MessageKey.PASSWORD_UNSAFE_ERROR); - return true; - } + if (!Settings.unsafePasswords.isEmpty() && Settings.unsafePasswords.contains(playerPassLowerCase)) { + m.send(sender, MessageKey.PASSWORD_UNSAFE_ERROR); + return true; } // Set the password final String playerNameLowerCase = playerName.toLowerCase(); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java index 7d8c99792..b5fa337eb 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java @@ -3,7 +3,7 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.permission.UserPermission; +import fr.xephi.authme.permission.PlayerPermission; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -30,7 +30,7 @@ public class ForceLoginCommand extends ExecutableCommand { sender.sendMessage("Player needs to be online!"); return true; } - if (!plugin.getPermissionsManager().hasPermission(player, UserPermission.CAN_LOGIN_BE_FORCED)) { + if (!plugin.getPermissionsManager().hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)) { sender.sendMessage("You cannot force login for the player " + playerName + "!"); return true; } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/GetEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/GetEmailCommand.java index 94db21cec..cc0ac9b86 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/GetEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/GetEmailCommand.java @@ -4,8 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import org.bukkit.command.CommandSender; /** diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/LastLoginCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/LastLoginCommand.java index 3f3835f35..ecae052b9 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/LastLoginCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/LastLoginCommand.java @@ -4,8 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import org.bukkit.command.CommandSender; import java.util.Date; diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommand.java index dc4172638..e9e3c9ad3 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommand.java @@ -5,8 +5,8 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/RegisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/RegisterCommand.java index 8ddbfefdf..38e73d017 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/RegisterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/RegisterCommand.java @@ -6,8 +6,8 @@ import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.security.PasswordSecurity; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java index e94b5b72f..1eaf3717e 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java @@ -6,8 +6,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.Profiler; import org.bukkit.command.CommandSender; @@ -41,7 +41,7 @@ public class ReloadCommand extends ExecutableCommand { try { Settings.reload(); - plugin.setMessages(new Messages(Settings.messageFile, Settings.messagesLanguage)); + Messages.getInstance().reloadManager(); plugin.getModuleManager().reloadModules(); plugin.setupDatabase(); } catch (Exception e) { diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SetEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SetEmailCommand.java index 35816fbf5..278bf13c4 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/SetEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/SetEmailCommand.java @@ -5,8 +5,8 @@ import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.command.CommandSender; diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterCommand.java index f10116205..e5a8396fd 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterCommand.java @@ -6,8 +6,8 @@ import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; 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 a5a194c62..4fa2bbef9 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 @@ -5,8 +5,8 @@ import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.security.RandomString; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; 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 45d05ee32..f9219aba6 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 @@ -4,8 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.ChangePasswordTask; import fr.xephi.authme.util.Wrapper; @@ -13,6 +13,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** + * The command for a player to change his password with. */ public class ChangePasswordCommand extends ExecutableCommand { @@ -27,10 +28,10 @@ public class ChangePasswordCommand extends ExecutableCommand { final Messages m = wrapper.getMessages(); // Get the passwords - String playerPass = commandArguments.get(0); - String playerPassVerify = commandArguments.get(1); + String oldPassword = commandArguments.get(0); + String newPassword = commandArguments.get(1); - // Get the player instance and make sure it's authenticated + // Get the player instance and make sure he's authenticated Player player = (Player) sender; String name = player.getName().toLowerCase(); final PlayerCache playerCache = wrapper.getPlayerCache(); @@ -40,8 +41,7 @@ public class ChangePasswordCommand extends ExecutableCommand { } // Make sure the password is allowed - // TODO ljacqu 20151121: The password confirmation appears to be never verified - String playerPassLowerCase = playerPass.toLowerCase(); + String playerPassLowerCase = newPassword.toLowerCase(); if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") @@ -66,8 +66,8 @@ public class ChangePasswordCommand extends ExecutableCommand { // Set the password final AuthMe plugin = wrapper.getAuthMe(); - wrapper.getServer().getScheduler().runTaskAsynchronously(plugin, - new ChangePasswordTask(plugin, player, playerPass, playerPassVerify)); + wrapper.getScheduler().runTaskAsynchronously(plugin, + new ChangePasswordTask(plugin, player, oldPassword, newPassword)); return true; } } diff --git a/src/main/java/fr/xephi/authme/command/executable/converter/ConverterCommand.java b/src/main/java/fr/xephi/authme/command/executable/converter/ConverterCommand.java index a2da7b376..883149973 100644 --- a/src/main/java/fr/xephi/authme/command/executable/converter/ConverterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/converter/ConverterCommand.java @@ -4,8 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.converter.*; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; diff --git a/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java index ab50cdb10..2af4f65a7 100644 --- a/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java @@ -8,8 +8,8 @@ import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.RandomString; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.Wrapper; import org.bukkit.command.CommandSender; 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 a36443b7b..1f366deaa 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 @@ -5,8 +5,8 @@ import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.process.Management; import fr.xephi.authme.security.RandomString; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.Wrapper; import org.bukkit.command.CommandSender; @@ -55,7 +55,7 @@ public class RegisterCommand extends ExecutableCommand { } if (commandArguments.getCount() > 1 && Settings.getEnablePasswordVerifier) { if (!commandArguments.get(0).equals(commandArguments.get(1))) { - m.send(player, MessageKey.PASSWORD_IS_USERNAME_ERROR); + m.send(player, MessageKey.PASSWORD_MATCH_ERROR); return true; } } diff --git a/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java index 96c8b3cfc..22ef35661 100644 --- a/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java @@ -4,8 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/src/main/java/fr/xephi/authme/converter/SqlToFlat.java b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java index ee1375084..1af5594cf 100644 --- a/src/main/java/fr/xephi/authme/converter/SqlToFlat.java +++ b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java @@ -5,7 +5,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.FlatFile; -import fr.xephi.authme.settings.MessageKey; +import fr.xephi.authme.output.MessageKey; import org.bukkit.command.CommandSender; import java.util.List; diff --git a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java index a61d93e37..bca9af2cf 100644 --- a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java +++ b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java @@ -42,16 +42,16 @@ public class vAuthFileReader { String name = line.split(": ")[0]; String password = line.split(": ")[1]; PlayerAuth auth; - if (isUUIDinstance(password)) { - String playerName; + if (isUuidInstance(password)) { + String pname; try { - playerName = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName(); + pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName(); } catch (Exception | NoSuchMethodError e) { - playerName = getName(UUID.fromString(name)); + pname = getName(UUID.fromString(name)); } - if (playerName == null) + if (pname == null) continue; - auth = new PlayerAuth(playerName.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", playerName); + auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname); } else { auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", name); } @@ -64,17 +64,8 @@ public class vAuthFileReader { } - /** - * Method isUUIDinstance. - * - * @param s String - * - * @return boolean - */ - private boolean isUUIDinstance(String s) { - if (String.valueOf(s.charAt(8)).equalsIgnoreCase("-")) - return true; - return true; + private static boolean isUuidInstance(String s) { + return s.length() > 8 && s.charAt(8) == '-'; } /** diff --git a/src/main/java/fr/xephi/authme/datasource/MySQL.java b/src/main/java/fr/xephi/authme/datasource/MySQL.java index 455361a49..69c10e824 100644 --- a/src/main/java/fr/xephi/authme/datasource/MySQL.java +++ b/src/main/java/fr/xephi/authme/datasource/MySQL.java @@ -1,8 +1,7 @@ package fr.xephi.authme.datasource; -import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; -import com.zaxxer.hikari.pool.PoolInitializationException; +import com.zaxxer.hikari.pool.HikariPool.PoolInitializationException; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; @@ -36,10 +35,9 @@ public class MySQL implements DataSource { private final String columnEmail; private final String columnID; private final String columnLogged; + private final String columnRealName; private final List columnOthers; private HikariDataSource ds; - private final String columnRealName; - private final int maxConnections; /** * Constructor for MySQL. @@ -68,7 +66,6 @@ public class MySQL implements DataSource { this.columnID = Settings.getMySQLColumnId; this.columnLogged = Settings.getMySQLColumnLogged; this.columnRealName = Settings.getMySQLColumnRealName; - this.maxConnections = Settings.getMySQLMaxConnections; // Set the connection arguments (and check if connection is ok) try { @@ -76,15 +73,15 @@ public class MySQL implements DataSource { } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { ConsoleLogger.showError("Invalid database arguments! Please check your configuration!"); - ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN..."); + ConsoleLogger.showError("If this error persists, please report it to the developer!"); throw new IllegalArgumentException(e); } if (e instanceof PoolInitializationException) { ConsoleLogger.showError("Can't initialize database connection! Please check your configuration!"); - ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN..."); + ConsoleLogger.showError("If this error persists, please report it to the developer!"); throw new PoolInitializationException(e); } - ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer! SHUTDOWN..."); + ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer!"); throw e; } @@ -94,7 +91,7 @@ public class MySQL implements DataSource { } catch (SQLException e) { this.close(); ConsoleLogger.showError("Can't initialize the MySQL database... Please check your database settings in the config.yml file! SHUTDOWN..."); - ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN..."); + ConsoleLogger.showError("If this error persists, please report it to the developer!"); throw e; } } @@ -102,34 +99,29 @@ public class MySQL implements DataSource { /** * Method setConnectionArguments. * - * @throws ClassNotFoundException * @throws IllegalArgumentException + * @throws RuntimeException */ - private synchronized void setConnectionArguments() - throws IllegalArgumentException { - HikariConfig config = new HikariConfig(); - config.setPoolName("AuthMeMYSQLPool"); - config.setDriverClassName("com.mysql.jdbc.Driver"); - config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database); - config.setUsername(this.username); - config.setPassword(this.password); - config.addDataSourceProperty("cachePrepStmts", "false"); - config.addDataSourceProperty("autoReconnect", false); - config.setInitializationFailFast(true); // Don't start the plugin if the database is unavailable - config.setMaxLifetime(180000); // 3 Min - config.setIdleTimeout(60000); // 1 Min - config.setMinimumIdle(2); - config.setMaximumPoolSize(maxConnections); - ds = new HikariDataSource(config); + private synchronized void setConnectionArguments() throws RuntimeException { + ds = new HikariDataSource(); + ds.setPoolName("AuthMeMYSQLPool"); + ds.setDriverClassName("com.mysql.jdbc.Driver"); + ds.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database + "?rewriteBatchedStatements=true"); + ds.setUsername(this.username); + ds.setPassword(this.password); + ds.setInitializationFailFast(true); // Don't start the plugin if the database is unavailable + ds.setMaxLifetime(180000); // 3 Min + ds.setIdleTimeout(60000); // 1 Min + ds.setMinimumIdle(2); + ds.setMaximumPoolSize((Runtime.getRuntime().availableProcessors() * 2) + 1); ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!"); } /** * Method reloadArguments. * - * @throws ClassNotFoundException * @throws IllegalArgumentException + * @throws RuntimeException */ - private synchronized void reloadArguments() - throws ClassNotFoundException, IllegalArgumentException { + private synchronized void reloadArguments() throws RuntimeException { if (ds != null) { ds.close(); } @@ -152,64 +144,102 @@ public class MySQL implements DataSource { * @throws SQLException */ private synchronized void setupConnection() throws SQLException { - Connection con = null; - Statement st = null; - ResultSet rs = null; - try { - if ((con = getConnection()) == null) - return; - st = con.createStatement(); - st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword + " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); - rs = con.getMetaData().getColumns(null, null, tableName, columnPassword); + try (Connection con = getConnection()) { + Statement st = con.createStatement(); + DatabaseMetaData md = con.getMetaData(); + // Create table if not exists. + String sql = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + + columnID + " INTEGER AUTO_INCREMENT," + + columnName + " VARCHAR(255) NOT NULL UNIQUE," + + columnRealName + " VARCHAR(255) NOT NULL," + + columnPassword + " VARCHAR(255) NOT NULL," + + columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + + columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + ")" + + ");"; + st.executeUpdate(sql); + + ResultSet rs = md.getColumns(null, null, tableName, columnName); if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;"); + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + columnName + " VARCHAR(255) NOT NULL UNIQUE AFTER " + columnID + ";"); } rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, columnIp); + + rs = md.getColumns(null, null, tableName, columnRealName); if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;"); + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + columnRealName + " VARCHAR(255) NOT NULL AFTER " + columnName + ";"); } rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin); + + rs = md.getColumns(null, null, tableName, columnPassword); if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT;"); + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;"); } rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); + + rs = md.getColumns(null, null, tableName, columnIp); if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + columnLastLogin + " , ADD " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocX + " , ADD " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocY + ";"); + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;"); } rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld); + + rs = md.getColumns(null, null, tableName, columnLastLogin); if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER " + lastlocZ + ";"); + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + columnLastLogin + " BIGINT;"); } rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, columnEmail); + + rs = md.getColumns(null, null, tableName, lastlocX); if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com' AFTER " + lastlocWorld + ";"); + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + columnLastLogin + " , ADD " + + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocX + " , ADD " + + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocY); } rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, columnLogged); - if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLogged + " SMALLINT NOT NULL DEFAULT '0' AFTER " + columnEmail + ";"); - } - rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); + + rs = md.getColumns(null, null, tableName, lastlocX); if (rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " MODIFY " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';"); + st.executeUpdate("ALTER TABLE " + tableName + " MODIFY " + + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';"); } rs.close(); - rs = con.getMetaData().getColumns(null, null, tableName, columnRealName); + + rs = md.getColumns(null, null, tableName, lastlocWorld); if (!rs.next()) { - st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnRealName + " VARCHAR(255) NOT NULL DEFAULT 'Player' AFTER " + columnLogged + ";"); + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER " + lastlocZ); } - if (Settings.isMySQLWebsite) - st.execute("SET GLOBAL query_cache_size = 0; SET GLOBAL query_cache_type = 0;"); - } finally { - close(rs); - close(st); - close(con); + rs.close(); + + rs = md.getColumns(null, null, tableName, columnEmail); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com' AFTER " + lastlocWorld); + } + rs.close(); + + rs = md.getColumns(null, null, tableName, columnLogged); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + columnLogged + " SMALLINT NOT NULL DEFAULT '0' AFTER " + columnEmail); + } + rs.close(); + + st.close(); } ConsoleLogger.info("MySQL Setup finished"); } @@ -223,24 +253,16 @@ public class MySQL implements DataSource { */ @Override public synchronized boolean isAuthAvailable(String user) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - try { - if ((con = getConnection()) == null) - return true; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); - pst.setString(1, user); - rs = pst.executeQuery(); + try (Connection con = getConnection()) { + String sql = "SELECT " + columnName + " FROM " + tableName + " WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); + pst.setString(1, user.toLowerCase()); + ResultSet rs = pst.executeQuery(); return rs.next(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(rs); - close(pst); - close(con); } + return false; } /** @@ -252,53 +274,47 @@ public class MySQL implements DataSource { */ @Override public synchronized PlayerAuth getAuth(String user) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - PlayerAuth pAuth = null; - int id; - try { - if ((con = getConnection()) == null) + PlayerAuth pAuth; + try (Connection con = getConnection()) { + String sql = "SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); + pst.setString(1, user.toLowerCase()); + ResultSet rs = pst.executeQuery(); + if (!rs.next()) { return null; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); - pst.setString(1, user); - rs = pst.executeQuery(); - if (rs.next()) { - id = rs.getInt(columnID); - if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { - pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } else { - if (!columnSalt.isEmpty()) { - if (!columnGroup.isEmpty()) - pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - else - pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } else { - pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } + } + String salt = !columnSalt.isEmpty() ? rs.getString(columnSalt) : ""; + int group = !salt.isEmpty() && !columnGroup.isEmpty() ? rs.getInt(columnGroup) : -1; + int id = rs.getInt(columnID); + pAuth = PlayerAuth.builder() + .name(rs.getString(columnName)) + .realName(rs.getString(columnRealName)) + .hash(rs.getString(columnPassword)) + .lastLogin(rs.getLong(columnLastLogin)) + .ip(rs.getString(columnIp)) + .locWorld(rs.getString(lastlocWorld)) + .locX(rs.getDouble(lastlocX)) + .locY(rs.getDouble(lastlocY)) + .locZ(rs.getDouble(lastlocZ)) + .email(rs.getString(columnEmail)) + .salt(salt) + .groupId(group) + .build(); + rs.close(); + pst.close(); + if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { + pst = con.prepareStatement("SELECT data FROM xf_user_authenticate WHERE " + columnID + "=?;"); + pst.setInt(1, id); + rs = pst.executeQuery(); + if (rs.next()) { + Blob blob = rs.getBlob("data"); + byte[] bytes = blob.getBytes(1, (int) blob.length()); + pAuth.setHash(new String(bytes)); } - if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { - rs.close(); - pst.close(); - pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); - pst.setInt(1, id); - rs = pst.executeQuery(); - if (rs.next()) { - Blob blob = rs.getBlob("data"); - byte[] bytes = blob.getBytes(1, (int) blob.length()); - pAuth.setHash(new String(bytes)); - } - } - } else { - return null; } } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); return null; - } finally { - close(rs); - close(pst); - close(con); } return pAuth; } @@ -308,36 +324,36 @@ public class MySQL implements DataSource { * * @param auth PlayerAuth * - * @return boolean * @see fr.xephi.authme.datasource.DataSource#saveAuth(PlayerAuth) + * @return boolean + * + * @see fr.xephi.authme.datasource.DataSource#saveAuth(PlayerAuth) */ @Override public synchronized boolean saveAuth(PlayerAuth auth) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - try { - if ((con = getConnection()) == null) - return false; - if ((columnSalt == null || columnSalt.isEmpty()) || (auth.getSalt() == null || auth.getSalt().isEmpty())) { - pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnRealName + ") VALUES (?,?,?,?,?);"); - pst.setString(1, auth.getNickname()); - pst.setString(2, auth.getHash()); - pst.setString(3, auth.getIp()); - pst.setLong(4, auth.getLastLogin()); - pst.setString(5, auth.getRealName()); - pst.executeUpdate(); - pst.close(); - } else { - pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + "," + columnRealName + ") VALUES (?,?,?,?,?,?);"); - pst.setString(1, auth.getNickname()); - pst.setString(2, auth.getHash()); - pst.setString(3, auth.getIp()); - pst.setLong(4, auth.getLastLogin()); - pst.setString(5, auth.getSalt()); - pst.setString(6, auth.getRealName()); - pst.executeUpdate(); - pst.close(); + try (Connection con = getConnection()) { + PreparedStatement pst; + PreparedStatement pst2; + ResultSet rs; + String sql; + + boolean useSalt = !columnSalt.isEmpty() || !auth.getSalt().isEmpty(); + sql = "INSERT INTO " + tableName + "(" + + columnName + "," + columnPassword + "," + columnIp + "," + + columnLastLogin + "," + columnRealName + + (useSalt ? "," + columnSalt : "") + + ") VALUES (?,?,?,?,?" + (useSalt ? ",?" : "") + ");"; + pst = con.prepareStatement(sql); + pst.setString(1, auth.getNickname()); + pst.setString(2, auth.getHash()); + pst.setString(3, auth.getIp()); + pst.setLong(4, auth.getLastLogin()); + pst.setString(5, auth.getRealName()); + if (useSalt) { + pst.setString(6, auth.getSalt()); } + pst.executeUpdate(); + pst.close(); + if (!columnOthers.isEmpty()) { for (String column : columnOthers) { pst = con.prepareStatement("UPDATE " + tableName + " SET " + column + "=? WHERE " + columnName + "=?;"); @@ -347,174 +363,168 @@ public class MySQL implements DataSource { pst.close(); } } + if (Settings.getPasswordHash == HashAlgorithm.PHPBB) { - PreparedStatement pst2 = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); - pst2.setString(1, auth.getNickname()); - rs = pst2.executeQuery(); - if (rs.next()) { - int id = rs.getInt(columnID); - // Insert player in phpbb_user_group - pst = con.prepareStatement("INSERT INTO " + Settings.getPhpbbPrefix + "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);"); - pst.setInt(1, Settings.getPhpbbGroup); - pst.setInt(2, id); - pst.setInt(3, 0); - pst.setInt(4, 0); - pst.executeUpdate(); - pst.close(); - // Update username_clean in phpbb_users - pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".username_clean=? WHERE " + columnName + "=?;"); - pst.setString(1, auth.getNickname().toLowerCase()); - pst.setString(2, auth.getNickname()); - pst.executeUpdate(); - pst.close(); - // Update player group in phpbb_users - pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".group_id=? WHERE " + columnName + "=?;"); - pst.setInt(1, Settings.getPhpbbGroup); - pst.setString(2, auth.getNickname()); - pst.executeUpdate(); - pst.close(); - // Get current time without ms - long time = System.currentTimeMillis() / 1000; - // Update user_regdate - pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".user_regdate=? WHERE " + columnName + "=?;"); - pst.setLong(1, time); - pst.setString(2, auth.getNickname()); - pst.executeUpdate(); - pst.close(); - // Update user_lastvisit - pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".user_lastvisit=? WHERE " + columnName + "=?;"); - pst.setLong(1, time); - pst.setString(2, auth.getNickname()); - pst.executeUpdate(); - pst.close(); - // Increment num_users - pst = con.prepareStatement("UPDATE " + Settings.getPhpbbPrefix + "config SET config_value = config_value + 1 WHERE config_name = 'num_users';"); - pst.executeUpdate(); - pst.close(); - } - rs.close(); - pst2.close(); - } - if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) { - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); + sql = "SELECT " + columnID + " FROM " + tableName + " WHERE " + columnName + "=?;"; + pst = con.prepareStatement(sql); pst.setString(1, auth.getNickname()); rs = pst.executeQuery(); if (rs.next()) { int id = rs.getInt(columnID); - // First Name - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "first_name"); - pst.setString(3, ""); - pst.executeUpdate(); - pst.close(); - // Last Name - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "last_name"); - pst.setString(3, ""); - pst.executeUpdate(); - pst.close(); - // Nick Name - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "nickname"); - pst.setString(3, auth.getNickname()); - pst.executeUpdate(); - pst.close(); - // Description - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "description"); - pst.setString(3, ""); - pst.executeUpdate(); - pst.close(); - // Rich_Editing - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "rich_editing"); - pst.setString(3, "true"); - pst.executeUpdate(); - pst.close(); - // Comments_Shortcuts - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "comment_shortcuts"); - pst.setString(3, "false"); - pst.executeUpdate(); - pst.close(); - // admin_color - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "admin_color"); - pst.setString(3, "fresh"); - pst.executeUpdate(); - pst.close(); - // use_ssl - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "use_ssl"); - pst.setString(3, "0"); - pst.executeUpdate(); - pst.close(); - // show_admin_bar_front - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "show_admin_bar_front"); - pst.setString(3, "true"); - pst.executeUpdate(); - pst.close(); - // wp_capabilities - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "wp_capabilities"); - pst.setString(3, "a:1:{s:10:\"subscriber\";b:1;}"); - pst.executeUpdate(); - pst.close(); - // wp_user_level - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "wp_user_level"); - pst.setString(3, "0"); - pst.executeUpdate(); - pst.close(); - // default_password_nag - pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "default_password_nag"); - pst.setString(3, ""); - pst.executeUpdate(); - pst.close(); + // Insert player in phpbb_user_group + sql = "INSERT INTO " + Settings.getPhpbbPrefix + + "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);"; + pst2 = con.prepareStatement(sql); + pst2.setInt(1, Settings.getPhpbbGroup); + pst2.setInt(2, id); + pst2.setInt(3, 0); + pst2.setInt(4, 0); + pst2.executeUpdate(); + pst2.close(); + // Update username_clean in phpbb_users + sql = "UPDATE " + tableName + " SET " + tableName + + ".username_clean=? WHERE " + columnName + "=?;"; + pst2 = con.prepareStatement(sql); + pst2.setString(1, auth.getNickname()); + pst2.setString(2, auth.getNickname()); + pst2.executeUpdate(); + pst2.close(); + // Update player group in phpbb_users + sql = "UPDATE " + tableName + " SET " + tableName + + ".group_id=? WHERE " + columnName + "=?;"; + pst2 = con.prepareStatement(sql); + pst2.setInt(1, Settings.getPhpbbGroup); + pst2.setString(2, auth.getNickname()); + pst2.executeUpdate(); + pst2.close(); + // Get current time without ms + long time = System.currentTimeMillis() / 1000; + // Update user_regdate + sql = "UPDATE " + tableName + " SET " + tableName + + ".user_regdate=? WHERE " + columnName + "=?;"; + pst2 = con.prepareStatement(sql); + pst2.setLong(1, time); + pst2.setString(2, auth.getNickname()); + pst2.executeUpdate(); + pst2.close(); + // Update user_lastvisit + sql = "UPDATE " + tableName + " SET " + tableName + + ".user_lastvisit=? WHERE " + columnName + "=?;"; + pst2 = con.prepareStatement(sql); + pst2.setLong(1, time); + pst2.setString(2, auth.getNickname()); + pst2.executeUpdate(); + pst2.close(); + // Increment num_users + sql = "UPDATE " + Settings.getPhpbbPrefix + + "config SET config_value = config_value + 1 WHERE config_name = 'num_users';"; + pst2 = con.prepareStatement(sql); + pst2.executeUpdate(); + pst2.close(); } rs.close(); - } - if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); + pst.close(); + } else if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) { + pst = con.prepareStatement("SELECT " + columnID + " FROM " + tableName + " WHERE " + columnName + "=?;"); + pst.setString(1, auth.getNickname()); + rs = pst.executeQuery(); + if (rs.next()) { + int id = rs.getInt(columnID); + sql = "INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"; + pst2 = con.prepareStatement(sql); + // First Name + pst2.setInt(1, id); + pst2.setString(2, "first_name"); + pst2.setString(3, ""); + pst2.addBatch(); + // Last Name + pst2.setInt(1, id); + pst2.setString(2, "last_name"); + pst2.setString(3, ""); + pst2.addBatch(); + // Nick Name + pst2.setInt(1, id); + pst2.setString(2, "nickname"); + pst2.setString(3, auth.getNickname()); + pst2.addBatch(); + // Description + pst2.setInt(1, id); + pst2.setString(2, "description"); + pst2.setString(3, ""); + pst2.addBatch(); + // Rich_Editing + pst2.setInt(1, id); + pst2.setString(2, "rich_editing"); + pst2.setString(3, "true"); + pst2.addBatch(); + // Comments_Shortcuts + pst2.setInt(1, id); + pst2.setString(2, "comment_shortcuts"); + pst2.setString(3, "false"); + pst2.addBatch(); + // admin_color + pst2.setInt(1, id); + pst2.setString(2, "admin_color"); + pst2.setString(3, "fresh"); + pst2.addBatch(); + // use_ssl + pst2.setInt(1, id); + pst2.setString(2, "use_ssl"); + pst2.setString(3, "0"); + pst2.addBatch(); + // show_admin_bar_front + pst2.setInt(1, id); + pst2.setString(2, "show_admin_bar_front"); + pst2.setString(3, "true"); + pst2.addBatch(); + // wp_capabilities + pst2.setInt(1, id); + pst2.setString(2, "wp_capabilities"); + pst2.setString(3, "a:1:{s:10:\"subscriber\";b:1;}"); + pst2.addBatch(); + // wp_user_level + pst2.setInt(1, id); + pst2.setString(2, "wp_user_level"); + pst2.setString(3, "0"); + pst2.addBatch(); + // default_password_nag + pst2.setInt(1, id); + pst2.setString(2, "default_password_nag"); + pst2.setString(3, ""); + pst2.addBatch(); + + // Execute queries + pst2.executeBatch(); + pst2.clearBatch(); + pst2.close(); + } + rs.close(); + pst.close(); + } else if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { + pst = con.prepareStatement("SELECT " + columnID + " FROM " + tableName + " WHERE " + columnName + "=?;"); pst.setString(1, auth.getNickname()); rs = pst.executeQuery(); if (rs.next()) { int id = rs.getInt(columnID); // Insert password in the correct table - pst = con.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);"); - pst.setInt(1, id); - pst.setString(2, "XenForo_Authentication_Core12"); + pst2 = con.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);"); + pst2.setInt(1, id); + pst2.setString(2, "XenForo_Authentication_Core12"); byte[] bytes = auth.getHash().getBytes(); Blob blob = con.createBlob(); blob.setBytes(1, bytes); - pst.setBlob(3, blob); - pst.executeUpdate(); + pst2.setBlob(3, blob); + pst2.executeUpdate(); + pst2.close(); } rs.close(); + pst.close(); } + return true; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(rs); - close(pst); - close(con); } - return true; + return false; } /** @@ -522,51 +532,52 @@ public class MySQL implements DataSource { * * @param auth PlayerAuth * - * @return boolean * @see fr.xephi.authme.datasource.DataSource#updatePassword(PlayerAuth) + * @return boolean + * + * @see fr.xephi.authme.datasource.DataSource#updatePassword(PlayerAuth) */ @Override public synchronized boolean updatePassword(PlayerAuth auth) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - try { - if ((con = getConnection()) == null) - return false; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE LOWER(" + columnName + ")=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, auth.getHash()); pst.setString(2, auth.getNickname()); pst.executeUpdate(); pst.close(); if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + sql = "SELECT " + columnID + " FROM " + tableName + " WHERE " + columnName + "=?;"; + pst = con.prepareStatement(sql); pst.setString(1, auth.getNickname()); - rs = pst.executeQuery(); + ResultSet rs = pst.executeQuery(); if (rs.next()) { int id = rs.getInt(columnID); // Insert password in the correct table - pst = con.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE " + columnID + "=?;"); + sql = "UPDATE xf_user_authenticate SET data=? WHERE " + columnID + "=?;"; + PreparedStatement pst2 = con.prepareStatement(sql); byte[] bytes = auth.getHash().getBytes(); Blob blob = con.createBlob(); blob.setBytes(1, bytes); - pst.setBlob(1, blob); - pst.setInt(2, id); - pst.executeUpdate(); - pst = con.prepareStatement("UPDATE xf_user_authenticate SET scheme_class=? WHERE " + columnID + "=?;"); - pst.setString(1, "XenForo_Authentication_Core12"); - pst.setInt(2, id); - pst.executeUpdate(); + pst2.setBlob(1, blob); + pst2.setInt(2, id); + pst2.executeUpdate(); + pst2.close(); + // ... + sql = "UPDATE xf_user_authenticate SET scheme_class=? WHERE " + columnID + "=?;"; + pst2 = con.prepareStatement(sql); + pst2.setString(1, "XenForo_Authentication_Core12"); + pst2.setInt(2, id); + pst2.executeUpdate(); + pst2.close(); } rs.close(); + pst.close(); } + return true; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(rs); - close(pst); - close(con); } - return true; + return false; } /** @@ -574,29 +585,27 @@ public class MySQL implements DataSource { * * @param auth PlayerAuth * - * @return boolean * @see fr.xephi.authme.datasource.DataSource#updateSession(PlayerAuth) + * @return boolean + * + * @see fr.xephi.authme.datasource.DataSource#updateSession(PlayerAuth) */ @Override public synchronized boolean updateSession(PlayerAuth auth) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return false; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=?, " + columnRealName + "=? WHERE LOWER(" + columnName + ")=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + + columnIp + "=?, " + columnLastLogin + "=?, " + columnRealName + "=? WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, auth.getIp()); pst.setLong(2, auth.getLastLogin()); pst.setString(3, auth.getRealName()); pst.setString(4, auth.getNickname()); pst.executeUpdate(); + pst.close(); + return true; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(pst); - close(con); } - return true; + return false; } /** @@ -604,25 +613,22 @@ public class MySQL implements DataSource { * * @param until long * - * @return int * @see fr.xephi.authme.datasource.DataSource#purgeDatabase(long) + * @return int + * + * @see fr.xephi.authme.datasource.DataSource#purgeDatabase(long) */ @Override public synchronized int purgeDatabase(long until) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return 0; - pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + " * @see fr.xephi.authme.datasource.DataSource#autoPurgeDatabase(long) + * @return List + * + * @see fr.xephi.authme.datasource.DataSource#autoPurgeDatabase(long) */ @Override public synchronized List autoPurgeDatabase(long until) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; List list = new ArrayList<>(); - try { - if ((con = getConnection()) == null) - return list; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "(); - } finally { - close(rs); - close(pst); - close(con); } + return list; } /** @@ -667,43 +664,39 @@ public class MySQL implements DataSource { * * @param user String * - * @return boolean * @see fr.xephi.authme.datasource.DataSource#removeAuth(String) + * @return boolean + * + * @see fr.xephi.authme.datasource.DataSource#removeAuth(String) */ @Override public synchronized boolean removeAuth(String user) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return false; + user = user.toLowerCase(); + try (Connection con = getConnection()) { + String sql; + PreparedStatement pst; if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { - int id; - ResultSet rs; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + sql = "SELECT " + columnID + " FROM " + tableName + " WHERE " + columnName + "=?;"; + pst = con.prepareStatement(sql); pst.setString(1, user); - rs = pst.executeQuery(); + ResultSet rs = pst.executeQuery(); if (rs.next()) { - id = rs.getInt(columnID); - // Remove data - PreparedStatement pst2 = con.prepareStatement("DELETE FROM xf_user_authenticate WHERE " + columnID + "=?;"); - pst2.setInt(1, id); - pst2.executeUpdate(); - pst2.close(); + int id = rs.getInt(columnID); + sql = "DELETE FROM xf_user_authenticate WHERE " + columnID + "=" + id; + Statement st = con.createStatement(); + st.executeUpdate(sql); + st.close(); } - } - if (pst != null && !pst.isClosed()) + rs.close(); pst.close(); - pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + } + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); pst.setString(1, user); pst.executeUpdate(); + return true; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(pst); - close(con); } - return true; + return false; } /** @@ -711,30 +704,29 @@ public class MySQL implements DataSource { * * @param auth PlayerAuth * - * @return boolean * @see fr.xephi.authme.datasource.DataSource#updateQuitLoc(PlayerAuth) + * @return boolean + * + * @see fr.xephi.authme.datasource.DataSource#updateQuitLoc(PlayerAuth) */ @Override public synchronized boolean updateQuitLoc(PlayerAuth auth) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return false; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE LOWER(" + columnName + ")=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + + " SET " + lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=?" + + " WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setDouble(1, auth.getQuitLocX()); pst.setDouble(2, auth.getQuitLocY()); pst.setDouble(3, auth.getQuitLocZ()); pst.setString(4, auth.getWorld()); pst.setString(5, auth.getNickname()); pst.executeUpdate(); + pst.close(); + return true; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(pst); - close(con); } - return true; + return false; } /** @@ -742,32 +734,27 @@ public class MySQL implements DataSource { * * @param ip String * - * @return int * @see fr.xephi.authme.datasource.DataSource#getIps(String) + * @return int + * + * @see fr.xephi.authme.datasource.DataSource#getIps(String) */ @Override public synchronized int getIps(String ip) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; int countIp = 0; - try { - if ((con = getConnection()) == null) - return 0; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + try (Connection con = getConnection()) { + String sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + columnIp + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, ip); - rs = pst.executeQuery(); + ResultSet rs = pst.executeQuery(); while (rs.next()) { - countIp++; + countIp = rs.getInt(1); } - return countIp; + rs.close(); + pst.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return 0; - } finally { - close(rs); - close(pst); - close(con); } + return countIp; } /** @@ -775,28 +762,25 @@ public class MySQL implements DataSource { * * @param auth PlayerAuth * - * @return boolean * @see fr.xephi.authme.datasource.DataSource#updateEmail(PlayerAuth) + * @return boolean + * + * @see fr.xephi.authme.datasource.DataSource#updateEmail(PlayerAuth) */ @Override public synchronized boolean updateEmail(PlayerAuth auth) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return false; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + " =? WHERE LOWER(" + columnName + ")=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + columnEmail + " =? WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, auth.getEmail()); pst.setString(2, auth.getNickname()); pst.executeUpdate(); + pst.close(); + return true; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.writeStackTrace(ex); - return false; - } finally { - close(pst); - close(con); } - return true; + return false; } /** @@ -804,30 +788,27 @@ public class MySQL implements DataSource { * * @param auth PlayerAuth * - * @return boolean * @see fr.xephi.authme.datasource.DataSource#updateSalt(PlayerAuth) + * @return boolean + * + * @see fr.xephi.authme.datasource.DataSource#updateSalt(PlayerAuth) */ @Override public synchronized boolean updateSalt(PlayerAuth auth) { if (columnSalt.isEmpty()) { return false; } - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return false; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + " =? WHERE LOWER(" + columnName + ")=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + columnSalt + " =? WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, auth.getSalt()); pst.setString(2, auth.getNickname()); pst.executeUpdate(); + pst.close(); + return true; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(pst); - close(con); } - return true; + return false; } /** @@ -841,12 +822,8 @@ public class MySQL implements DataSource { reloadArguments(); } catch (Exception e) { ConsoleLogger.showError(e.getMessage()); - ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN..."); - if (Settings.isStopEnabled) { - AuthMe.getInstance().getServer().shutdown(); - } - if (!Settings.isStopEnabled) - AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); + ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL configuration!"); + AuthMe.getInstance().stopOrUnload(); } } @@ -857,23 +834,8 @@ public class MySQL implements DataSource { */ @Override public synchronized void close() { - if (ds != null && !ds.isClosed()) + if (ds != null && !ds.isClosed()) { ds.close(); - } - - /** - * Method close. - * - * @param o AutoCloseable - */ - private void close(AutoCloseable o) { - if (o != null) { - try { - o.close(); - } catch (Exception ex) { - ConsoleLogger.showError(ex.getMessage()); - ConsoleLogger.writeStackTrace(ex); - } } } @@ -882,32 +844,27 @@ public class MySQL implements DataSource { * * @param auth PlayerAuth * - * @return List * @see fr.xephi.authme.datasource.DataSource#getAllAuthsByName(PlayerAuth) + * @return List + * + * @see fr.xephi.authme.datasource.DataSource#getAllAuthsByName(PlayerAuth) */ @Override public synchronized List getAllAuthsByName(PlayerAuth auth) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - List countIp = new ArrayList<>(); - try { - if ((con = getConnection()) == null) - return countIp; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + List result = new ArrayList<>(); + try (Connection con = getConnection()) { + String sql = "SELECT " + columnName + " FROM " + tableName + " WHERE " + columnIp + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, auth.getIp()); - rs = pst.executeQuery(); + ResultSet rs = pst.executeQuery(); while (rs.next()) { - countIp.add(rs.getString(columnName)); + result.add(rs.getString(columnName)); } - return countIp; + rs.close(); + pst.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return new ArrayList<>(); - } finally { - close(rs); - close(pst); - close(con); } + return result; } /** @@ -915,32 +872,27 @@ public class MySQL implements DataSource { * * @param ip String * - * @return List * @see fr.xephi.authme.datasource.DataSource#getAllAuthsByIp(String) + * @return List + * + * @see fr.xephi.authme.datasource.DataSource#getAllAuthsByIp(String) */ @Override public synchronized List getAllAuthsByIp(String ip) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - List countIp = new ArrayList<>(); - try { - if ((con = getConnection()) == null) - return countIp; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + List result = new ArrayList<>(); + try (Connection con = getConnection()) { + String sql = "SELECT " + columnName + " FROM " + tableName + " WHERE " + columnIp + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, ip); - rs = pst.executeQuery(); + ResultSet rs = pst.executeQuery(); while (rs.next()) { - countIp.add(rs.getString(columnName)); + result.add(rs.getString(columnName)); } - return countIp; + rs.close(); + pst.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return new ArrayList<>(); - } finally { - close(rs); - close(pst); - close(con); } + return result; } /** @@ -948,27 +900,25 @@ public class MySQL implements DataSource { * * @param email String * - * @return List * @throws SQLException * @see fr.xephi.authme.datasource.DataSource#getAllAuthsByEmail(String) + * @return List + * + * @throws SQLException + * @see fr.xephi.authme.datasource.DataSource#getAllAuthsByEmail(String) */ @Override public synchronized List getAllAuthsByEmail(String email) throws SQLException { - final Connection con = getConnection(); - PreparedStatement pst = null; - ResultSet rs = null; List countEmail = new ArrayList<>(); - - try { - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;"); + try (Connection con = getConnection()) { + String sql = "SELECT " + columnName + " FROM " + tableName + " WHERE " + columnEmail + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, email); - rs = pst.executeQuery(); + ResultSet rs = pst.executeQuery(); while (rs.next()) { countEmail.add(rs.getString(columnName)); } + rs.close(); + pst.close(); return countEmail; - } finally { - close(rs); - close(pst); - close(con); } } @@ -977,25 +927,19 @@ public class MySQL implements DataSource { * * @param banned List * - * @see fr.xephi.authme.datasource.DataSource#purgeBanned(List) + * @see fr.xephi.authme.datasource.DataSource#purgeBanned(List) */ @Override public synchronized void purgeBanned(List banned) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return; + try (Connection con = getConnection()) { + PreparedStatement pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); for (String name : banned) { - pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); pst.setString(1, name); pst.executeUpdate(); } + pst.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - } finally { - close(pst); - close(con); } } @@ -1018,26 +962,17 @@ public class MySQL implements DataSource { */ @Override public boolean isLogged(String user) { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - try { - if ((con = getConnection()) == null) - return false; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + boolean isLogged = false; + try (Connection con = getConnection()) { + String sql = "SELECT " + columnLogged + " FROM " + tableName + " WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, user); - rs = pst.executeQuery(); - if (rs.next()) - return (rs.getInt(columnLogged) == 1); + ResultSet rs = pst.executeQuery(); + isLogged = rs.next() && (rs.getInt(columnLogged) == 1); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - close(rs); - close(pst); - close(con); } - return false; + return isLogged; } /** @@ -1049,20 +984,15 @@ public class MySQL implements DataSource { */ @Override public void setLogged(String user) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setInt(1, 1); - pst.setString(2, user); + pst.setString(2, user.toLowerCase()); pst.executeUpdate(); + pst.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - } finally { - close(pst); - close(con); } } @@ -1075,22 +1005,16 @@ public class MySQL implements DataSource { */ @Override public void setUnlogged(String user) { - Connection con = null; - PreparedStatement pst = null; - if (user != null) - try { - if ((con = getConnection()) == null) - return; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;"); - pst.setInt(1, 0); - pst.setString(2, user); - pst.executeUpdate(); - } catch (Exception ex) { - ConsoleLogger.showError(ex.getMessage()); - } finally { - close(pst); - close(con); - } + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); + pst.setInt(1, 0); + pst.setString(2, user.toLowerCase()); + pst.executeUpdate(); + pst.close(); + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + } } /** @@ -1100,48 +1024,38 @@ public class MySQL implements DataSource { */ @Override public void purgeLogged() { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setInt(1, 0); pst.setInt(2, 1); pst.executeUpdate(); + pst.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - } finally { - close(pst); - close(con); } } /** * Method getAccountsRegistered. * - * @return int * @see fr.xephi.authme.datasource.DataSource#getAccountsRegistered() + * @return int + * + * @see fr.xephi.authme.datasource.DataSource#getAccountsRegistered() */ @Override public int getAccountsRegistered() { int result = 0; - Connection con = null; - PreparedStatement pst = null; - ResultSet rs; - try { - if ((con = getConnection()) == null) - return result; - pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); - rs = pst.executeQuery(); - if (rs != null && rs.next()) { + try (Connection con = getConnection()) { + PreparedStatement pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); + ResultSet rs = pst.executeQuery(); + if (rs.next()) { result = rs.getInt(1); } + rs.close(); + pst.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return result; - } finally { - close(pst); - close(con); } return result; } @@ -1156,75 +1070,67 @@ public class MySQL implements DataSource { */ @Override public void updateName(String oldOne, String newOne) { - Connection con = null; - PreparedStatement pst = null; - try { - if ((con = getConnection()) == null) - return; - pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE LOWER(" + columnName + ")=?;"); + try (Connection con = getConnection()) { + String sql = "UPDATE " + tableName + " SET " + columnName + "=? WHERE " + columnName + "=?;"; + PreparedStatement pst = con.prepareStatement(sql); pst.setString(1, newOne); pst.setString(2, oldOne); pst.executeUpdate(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - } finally { - close(pst); - close(con); } } /** * Method getAllAuths. * - * @return List * @see fr.xephi.authme.datasource.DataSource#getAllAuths() + * @return List + * + * @see fr.xephi.authme.datasource.DataSource#getAllAuths() */ @Override public List getAllAuths() { List auths = new ArrayList<>(); - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - try { - if ((con = getConnection()) == null) - return auths; - pst = con.prepareStatement("SELECT * FROM " + tableName + ";"); - rs = pst.executeQuery(); + try (Connection con = getConnection()) { + Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT * FROM " + tableName); + PreparedStatement pst = con.prepareStatement("SELECT data FROM xf_user_authenticate WHERE " + columnID + "=?;"); while (rs.next()) { - PlayerAuth pAuth; - int id = rs.getInt(columnID); - if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } else { - if (!columnSalt.isEmpty()) { - if (!columnGroup.isEmpty()) - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - else - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } else { - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } - } + String salt = !columnSalt.isEmpty() ? rs.getString(columnSalt) : ""; + int group = !salt.isEmpty() && !columnGroup.isEmpty() ? rs.getInt(columnGroup) : -1; + PlayerAuth pAuth = PlayerAuth.builder() + .name(rs.getString(columnName)) + .realName(rs.getString(columnRealName)) + .hash(rs.getString(columnPassword)) + .lastLogin(rs.getLong(columnLastLogin)) + .ip(rs.getString(columnIp)) + .locWorld(rs.getString(lastlocWorld)) + .locX(rs.getDouble(lastlocX)) + .locY(rs.getDouble(lastlocY)) + .locZ(rs.getDouble(lastlocZ)) + .email(rs.getString(columnEmail)) + .salt(salt) + .groupId(group) + .build(); + if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { - ResultSet rsid; - pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); + int id = rs.getInt(columnID); pst.setInt(1, id); - rsid = pst.executeQuery(); - if (rsid.next()) { - Blob blob = rsid.getBlob("data"); + ResultSet rs2 = pst.executeQuery(); + if (rs2.next()) { + Blob blob = rs2.getBlob("data"); byte[] bytes = blob.getBytes(1, (int) blob.length()); pAuth.setHash(new String(bytes)); } - rsid.close(); + rs2.close(); } auths.add(pAuth); } + pst.close(); + rs.close(); + st.close(); } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return auths; - } finally { - close(pst); - close(con); - close(rs); } return auths; } @@ -1232,55 +1138,50 @@ public class MySQL implements DataSource { /** * Method getLoggedPlayers. * - * @return List * @see fr.xephi.authme.datasource.DataSource#getLoggedPlayers() + * @return List + * + * @see fr.xephi.authme.datasource.DataSource#getLoggedPlayers() */ @Override public List getLoggedPlayers() { List auths = new ArrayList<>(); - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - try { - if ((con = getConnection()) == null) - return auths; - pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); - rs = pst.executeQuery(); + try (Connection con = getConnection()) { + Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); + PreparedStatement pst = con.prepareStatement("SELECT data FROM xf_user_authenticate WHERE " + columnID + "=?;"); while (rs.next()) { - PlayerAuth pAuth; - int id = rs.getInt(columnID); - if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } else { - if (!columnSalt.isEmpty()) { - if (!columnGroup.isEmpty()) - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - else - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } else { - pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); - } - } + String salt = !columnSalt.isEmpty() ? rs.getString(columnSalt) : ""; + int group = !salt.isEmpty() && !columnGroup.isEmpty() ? rs.getInt(columnGroup) : -1; + PlayerAuth pAuth = PlayerAuth.builder() + .name(rs.getString(columnName)) + .realName(rs.getString(columnRealName)) + .hash(rs.getString(columnPassword)) + .lastLogin(rs.getLong(columnLastLogin)) + .ip(rs.getString(columnIp)) + .locWorld(rs.getString(lastlocWorld)) + .locX(rs.getDouble(lastlocX)) + .locY(rs.getDouble(lastlocY)) + .locZ(rs.getDouble(lastlocZ)) + .email(rs.getString(columnEmail)) + .salt(salt) + .groupId(group) + .build(); + if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { - ResultSet rsid; - pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); + int id = rs.getInt(columnID); pst.setInt(1, id); - rsid = pst.executeQuery(); - if (rsid.next()) { - Blob blob = rsid.getBlob("data"); + ResultSet rs2 = pst.executeQuery(); + if (rs2.next()) { + Blob blob = rs2.getBlob("data"); byte[] bytes = blob.getBytes(1, (int) blob.length()); pAuth.setHash(new String(bytes)); } - rsid.close(); + rs2.close(); } auths.add(pAuth); } } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); - return auths; - } finally { - close(pst); - close(rs); - close(con); } return auths; } diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java index fa783ec3c..6451f270c 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java @@ -32,6 +32,8 @@ import org.bukkit.event.player.*; import java.util.concurrent.ConcurrentHashMap; +import static fr.xephi.authme.output.MessageKey.USERNAME_ALREADY_ONLINE_ERROR; + /** */ public class AuthMePlayerListener implements Listener { @@ -268,7 +270,7 @@ public class AuthMePlayerListener implements Listener { PermissionsManager permsMan = plugin.getPermissionsManager(); final Player player = event.getPlayer(); - if (event.getResult() == PlayerLoginEvent.Result.KICK_FULL && !permsMan.hasPermission(player, UserPermission.IS_VIP)) { + if (event.getResult() == PlayerLoginEvent.Result.KICK_FULL && !permsMan.hasPermission(player, PlayerPermission.IS_VIP)) { event.setKickMessage(m.retrieveSingle(MessageKey.KICK_FULL_SERVER)); event.setResult(PlayerLoginEvent.Result.KICK_FULL); return; @@ -280,7 +282,7 @@ public class AuthMePlayerListener implements Listener { // TODO: Add message to the messages file!!! if (Settings.isKickNonRegisteredEnabled && !isAuthAvailable) { if (Settings.antiBotInAction) { - event.setKickMessage("AntiBot service in action! You actually need to be registered!"); + event.setKickMessage(m.retrieveSingle(MessageKey.KICK_ANTIBOT)); event.setResult(PlayerLoginEvent.Result.KICK_OTHER); return; } else { diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java index 2866fd755..fd8279c04 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java @@ -2,8 +2,8 @@ package fr.xephi.authme.listener; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.GeoLiteAPI; import org.bukkit.event.EventHandler; diff --git a/src/main/java/fr/xephi/authme/output/ConsoleFilter.java b/src/main/java/fr/xephi/authme/output/ConsoleFilter.java new file mode 100644 index 000000000..975cc4cc3 --- /dev/null +++ b/src/main/java/fr/xephi/authme/output/ConsoleFilter.java @@ -0,0 +1,26 @@ +package fr.xephi.authme.output; + +import java.util.logging.Filter; +import java.util.logging.LogRecord; + +/** + * Console filter to replace sensitive AuthMe commands with a generic message. + * + * @author Xephi59 + */ +public class ConsoleFilter implements Filter { + + @Override + public boolean isLoggable(LogRecord record) { + if (record == null || record.getMessage() == null) { + return true; + } + + if (LogFilterHelper.isSensitiveAuthMeCommand(record.getMessage())) { + String playerName = record.getMessage().split(" ")[0]; + record.setMessage(playerName + " issued an AuthMe command"); + } + return true; + } + +} diff --git a/src/main/java/fr/xephi/authme/Log4JFilter.java b/src/main/java/fr/xephi/authme/output/Log4JFilter.java similarity index 54% rename from src/main/java/fr/xephi/authme/Log4JFilter.java rename to src/main/java/fr/xephi/authme/output/Log4JFilter.java index 581699f08..89d77ebe9 100644 --- a/src/main/java/fr/xephi/authme/Log4JFilter.java +++ b/src/main/java/fr/xephi/authme/output/Log4JFilter.java @@ -1,8 +1,8 @@ -package fr.xephi.authme; +package fr.xephi.authme.output; -import fr.xephi.authme.util.StringUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.message.Message; @@ -11,16 +11,8 @@ import org.apache.logging.log4j.message.Message; * Implements a filter for Log4j to skip sensitive AuthMe commands. * * @author Xephi59 - * @version $Revision: 1.0 $ */ -public class Log4JFilter implements org.apache.logging.log4j.core.Filter { - - /** - * List of commands (lower-case) to skip. - */ - private static final String[] COMMANDS_TO_SKIP = {"/login ", "/l ", "/reg ", "/changepassword ", - "/unregister ", "/authme register ", "/authme changepassword ", "/authme reg ", "/authme cp ", - "/register "}; +public class Log4JFilter implements Filter { /** * Constructor. @@ -29,13 +21,12 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter { } /** - * Validates a Message instance and returns the {@link Result} value - * depending depending on whether the message contains sensitive AuthMe - * data. + * Validate a Message instance and return the {@link Result} value + * depending on whether the message contains sensitive AuthMe data. * - * @param message the Message object to verify + * @param message The Message object to verify * - * @return the Result value + * @return The Result value */ private static Result validateMessage(Message message) { if (message == null) { @@ -45,24 +36,17 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter { } /** - * Validates a message and returns the {@link Result} value depending - * depending on whether the message contains sensitive AuthMe data. + * Validate a message and return the {@link Result} value depending + * on whether the message contains sensitive AuthMe data. * - * @param message the message to verify + * @param message The message to verify * - * @return the Result value + * @return The Result value */ private static Result validateMessage(String message) { - if (message == null) { - return Result.NEUTRAL; - } - - String lowerMessage = message.toLowerCase(); - if (lowerMessage.contains("issued server command:") - && StringUtils.containsAny(lowerMessage, COMMANDS_TO_SKIP)) { - return Result.DENY; - } - return Result.NEUTRAL; + return LogFilterHelper.isSensitiveAuthMeCommand(message) + ? Result.DENY + : Result.NEUTRAL; } @Override @@ -74,14 +58,12 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter { } @Override - public Result filter(Logger arg0, Level arg1, Marker arg2, String message, - Object... arg4) { + public Result filter(Logger arg0, Level arg1, Marker arg2, String message, Object... arg4) { return validateMessage(message); } @Override - public Result filter(Logger arg0, Level arg1, Marker arg2, Object message, - Throwable arg4) { + public Result filter(Logger arg0, Level arg1, Marker arg2, Object message, Throwable arg4) { if (message == null) { return Result.NEUTRAL; } @@ -89,8 +71,7 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter { } @Override - public Result filter(Logger arg0, Level arg1, Marker arg2, Message message, - Throwable arg4) { + public Result filter(Logger arg0, Level arg1, Marker arg2, Message message, Throwable arg4) { return validateMessage(message); } diff --git a/src/main/java/fr/xephi/authme/output/LogFilterHelper.java b/src/main/java/fr/xephi/authme/output/LogFilterHelper.java new file mode 100644 index 000000000..605283ac2 --- /dev/null +++ b/src/main/java/fr/xephi/authme/output/LogFilterHelper.java @@ -0,0 +1,34 @@ +package fr.xephi.authme.output; + +import fr.xephi.authme.util.StringUtils; + +/** + * Service class for the log filters. + */ +public final class LogFilterHelper { + + private static final String ISSUED_COMMAND_TEXT = "issued server command:"; + + private static final String[] COMMANDS_TO_SKIP = {"/login ", "/l ", "/reg ", "/changepassword ", + "/unregister ", "/authme register ", "/authme changepassword ", "/authme reg ", "/authme cp ", + "/register "}; + + private LogFilterHelper() { + // Util class + } + + /** + * Validate a message and return whether the message contains a sensitive AuthMe command. + * + * @param message The message to verify + * + * @return True if it is a sensitive AuthMe command, false otherwise + */ + public static boolean isSensitiveAuthMeCommand(String message) { + if (message == null) { + return false; + } + String lowerMessage = message.toLowerCase(); + return lowerMessage.contains(ISSUED_COMMAND_TEXT) && StringUtils.containsAny(lowerMessage, COMMANDS_TO_SKIP); + } +} diff --git a/src/main/java/fr/xephi/authme/settings/MessageKey.java b/src/main/java/fr/xephi/authme/output/MessageKey.java similarity index 97% rename from src/main/java/fr/xephi/authme/settings/MessageKey.java rename to src/main/java/fr/xephi/authme/output/MessageKey.java index 2fc1520ad..bc024abf7 100644 --- a/src/main/java/fr/xephi/authme/settings/MessageKey.java +++ b/src/main/java/fr/xephi/authme/output/MessageKey.java @@ -1,10 +1,12 @@ -package fr.xephi.authme.settings; +package fr.xephi.authme.output; /** * Keys for translatable messages managed by {@link Messages}. */ public enum MessageKey { + KICK_ANTIBOT("kick_antibot"), + UNKNOWN_USER("unknown_user"), UNSAFE_QUIT_LOCATION("unsafe_spawn"), diff --git a/src/main/java/fr/xephi/authme/output/Messages.java b/src/main/java/fr/xephi/authme/output/Messages.java new file mode 100644 index 000000000..ad586fd12 --- /dev/null +++ b/src/main/java/fr/xephi/authme/output/Messages.java @@ -0,0 +1,82 @@ +package fr.xephi.authme.output; + +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.util.StringUtils; +import org.bukkit.command.CommandSender; + +/** + * Class for retrieving and sending translatable messages to players. + * This class detects when the language settings have changed and will + * automatically update to use a new language file. + */ +public class Messages { + + private static Messages singleton; + private final String language; + private MessagesManager manager; + + + private Messages(String language, MessagesManager manager) { + this.language = language; + this.manager = manager; + } + + /** + * Get the instance of Messages. + * + * @return The Messages instance + */ + public static Messages getInstance() { + if (singleton == null) { + MessagesManager manager = new MessagesManager(Settings.messageFile); + singleton = new Messages(Settings.messagesLanguage, manager); + } + return singleton; + } + + /** + * Send the given message code to the player. + * + * @param sender The entity to send the message to + * @param key The key of the message to send + */ + public void send(CommandSender sender, MessageKey key) { + String[] lines = manager.retrieve(key.getKey()); + for (String line : lines) { + sender.sendMessage(line); + } + } + + /** + * Retrieve the message from the text file and return it split by new line as an array. + * + * @param key The message key to retrieve + * + * @return The message split by new lines + */ + public String[] retrieve(MessageKey key) { + if (!Settings.messagesLanguage.equalsIgnoreCase(language)) { + reloadManager(); + } + return manager.retrieve(key.getKey()); + } + + /** + * Retrieve the message from the text file. + * + * @param key The message key to retrieve + * + * @return The message from the file + */ + public String retrieveSingle(MessageKey key) { + return StringUtils.join("\n", retrieve(key)); + } + + /** + * Reload the messages manager. + */ + public void reloadManager() { + manager = new MessagesManager(Settings.messageFile); + } + +} diff --git a/src/main/java/fr/xephi/authme/output/MessagesManager.java b/src/main/java/fr/xephi/authme/output/MessagesManager.java new file mode 100644 index 000000000..3221e334f --- /dev/null +++ b/src/main/java/fr/xephi/authme/output/MessagesManager.java @@ -0,0 +1,62 @@ +package fr.xephi.authme.output; + +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.CustomConfiguration; + +import java.io.File; + +/** + * Class responsible for reading messages from a file and formatting them for Minecraft. + *

+ * This class is used within {@link Messages}, which offers a high-level interface for accessing + * or sending messages from a properties file. + */ +class MessagesManager extends CustomConfiguration { + + /** The section symbol, used in Minecraft for formatting codes. */ + private static final String SECTION_SIGN = "\u00a7"; + + + /** + * Constructor for Messages. + * + * @param file the configuration file + */ + MessagesManager(File file) { + super(file); + load(); + } + + /** + * Retrieve the message from the configuration file. + * + * @param key The key to retrieve + * + * @return The message + */ + String[] retrieve(String key) { + String message = (String) get(key); + if (message != null) { + return formatMessage(message); + } + + // Message is null: log key not being found and send error back as message + String retrievalError = "Error getting message with key '" + key + "'. "; + ConsoleLogger.showError(retrievalError + "Please verify your config file at '" + + getConfigFile().getName() + "'"); + return new String[]{ + retrievalError + "Please contact the admin to verify or update the AuthMe messages file."}; + } + + static String[] formatMessage(String message) { + // TODO: Check that the codes actually exist, i.e. replace &c but not &y + // TODO: Allow '&' to be retained with the code '&&' + String[] lines = message.split("&n"); + for (int i = 0; i < lines.length; ++i) { + // We don't initialize a StringBuilder here because mostly we will only have one entry + lines[i] = lines[i].replace("&", SECTION_SIGN); + } + return lines; + } + +} diff --git a/src/main/java/fr/xephi/authme/permission/AdminPermission.java b/src/main/java/fr/xephi/authme/permission/AdminPermission.java index 846c83227..335875a87 100644 --- a/src/main/java/fr/xephi/authme/permission/AdminPermission.java +++ b/src/main/java/fr/xephi/authme/permission/AdminPermission.java @@ -1,55 +1,125 @@ package fr.xephi.authme.permission; /** - * AuthMe admin permissions. + * AuthMe admin command permissions. */ public enum AdminPermission implements PermissionNode { - REGISTER("authme.admin.register"), + /** + * Administrator command to register a new user. + */ + REGISTER("authme.command.admin.register"), - UNREGISTER("authme.admin.unregister"), + /** + * Administrator command to unregister an existing user. + */ + UNREGISTER("authme.command.admin.unregister"), - FORCE_LOGIN("authme.admin.forcelogin"), + /** + * Administrator command to force-login an existing user. + */ + FORCE_LOGIN("authme.command.admin.forcelogin"), - CHANGE_PASSWORD("authme.admin.changepassword"), + /** + * Administrator command to change the password of a user. + */ + CHANGE_PASSWORD("authme.command.admin.changepassword"), - LAST_LOGIN("authme.admin.lastlogin"), + /** + * Administrator command to see the last login date and time of an user. + */ + LAST_LOGIN("authme.command.admin.lastlogin"), - ACCOUNTS("authme.admin.accounts"), + /** + * Administrator command to see all accounts associated with an user. + */ + ACCOUNTS("authme.command.admin.accounts"), - GET_EMAIL("authme.admin.getemail"), + /** + * Administrator command to get the email address of an user, if set. + */ + GET_EMAIL("authme.command.admin.getemail"), - CHANGE_EMAIL("authme.admin.chgemail"), + /** + * Administrator command to set or change the email adress of an user. + */ + CHANGE_EMAIL("authme.command.admin.changemail"), - GET_IP("authme.admin.getip"), + /** + * Administrator command to get the last known IP of an user. + */ + GET_IP("authme.command.admin.getip"), - SPAWN("authme.admin.spawn"), + /** + * Administrator command to teleport to the AuthMe spawn. + */ + SPAWN("authme.command.admin.spawn"), - SET_SPAWN("authme.admin.setspawn"), + /** + * Administrator command to set the AuthMe spawn. + */ + SET_SPAWN("authme.command.admin.setspawn"), - FIRST_SPAWN("authme.admin.firstspawn"), + /** + * Administrator command to teleport to the first AuthMe spawn. + */ + FIRST_SPAWN("authme.command.admin.firstspawn"), - SET_FIRST_SPAWN("authme.admin.setfirstspawn"), + /** + * Administrator command to set the first AuthMe spawn. + */ + SET_FIRST_SPAWN("authme.command.admin.setfirstspawn"), - PURGE("authme.admin.purge"), + /** + * Administrator command to purge old user data. + */ + PURGE("authme.command.admin.purge"), - PURGE_LAST_POSITION("authme.admin.purgelastpos"), + /** + * Administrator command to purge the last position of an user. + */ + PURGE_LAST_POSITION("authme.command.admin.purgelastpos"), - PURGE_BANNED_PLAYERS("authme.admin.purgebannedplayers"), + /** + * Administrator command to purge all data associated with banned players. + */ + PURGE_BANNED_PLAYERS("authme.command.admin.purgebannedplayers"), - SWITCH_ANTIBOT("authme.admin.switchantibot"), + /** + * Administrator command to toggle the AntiBot protection status. + */ + SWITCH_ANTIBOT("authme.command.admin.switchantibot"), - RELOAD("authme.admin.reload"); + /** + * Administrator command to convert old or other data to AuthMe data. + */ + CONVERTER("authme.command.admin.converter"), + /** + * Administrator command to reload the plugin configuration. + */ + RELOAD("authme.command.admin.reload"); + + /** + * Permission node. + */ private String node; + /** + * Get the permission node. + * @return + */ @Override public String getNode() { return node; } + /** + * Constructor. + * + * @param node Permission node. + */ AdminPermission(String node) { this.node = node; } - } diff --git a/src/main/java/fr/xephi/authme/permission/PlayerPermission.java b/src/main/java/fr/xephi/authme/permission/PlayerPermission.java new file mode 100644 index 000000000..0488a67ad --- /dev/null +++ b/src/main/java/fr/xephi/authme/permission/PlayerPermission.java @@ -0,0 +1,106 @@ +package fr.xephi.authme.permission; + +/** + * AuthMe player permission nodes, for regular players. + */ +public enum PlayerPermission implements PermissionNode { + + /** + * Permission node to bypass AntiBot protection. + */ + BYPASS_ANTIBOT("authme.player.bypassantibot"), + + /** + * Permission node to identify VIP users. + */ + IS_VIP("authme.player.vip"), + + /** + * Command permission to login. + */ + LOGIN("authme.command.player.login"), + + /** + * Command permission to logout. + */ + LOGOUT("authme.command.player.logout"), + + /** + * Command permission to register. + */ + REGISTER("authme.command.player.register"), + + /** + * Command permission to unregister. + */ + UNREGISTER("authme.command.player.unregister"), + + /** + * Command permission to change the password. + */ + CHANGE_PASSWORD("authme.command.player.changepassword"), + + /** + * Command permission to add an email address. + */ + ADD_EMAIL("authme.command.player.email.add"), + + /** + * Command permission to change the email address. + */ + CHANGE_EMAIL("authme.command.player.email.change"), + + /** + * Command permission to recover an account using it's email address. + */ + RECOVER_EMAIL("authme.command.player.email.recover"), + + /** + * Command permission to use captcha. + */ + CAPTCHA("authme.command.player.captcha"), + + /** + * Permission for users a login can be forced to. + */ + CAN_LOGIN_BE_FORCED("authme.player.canbeforced"), + + /** + * Permission for users to bypass force-survival mode. + */ + BYPASS_FORCE_SURVIVAL("authme.command.player.bypassforcesurvival"), + + /** + * Permission for users to allow two accounts. + */ + ALLOW_MULTIPLE_ACCOUNTS("authme.command.player.allow2accounts"), + + /** + * Permission for user to see other accounts. + */ + SEE_OTHER_ACCOUNTS("authme.command.player.seeotheraccounts"); + + /** + * Permission node. + */ + private String node; + + /** + * Get the permission node. + * + * @return Permission node. + */ + @Override + public String getNode() { + return node; + } + + /** + * Constructor. + * + * @param node Permission node. + */ + PlayerPermission(String node) { + this.node = node; + } +} diff --git a/src/main/java/fr/xephi/authme/permission/UserPermission.java b/src/main/java/fr/xephi/authme/permission/UserPermission.java deleted file mode 100644 index 30c3dc877..000000000 --- a/src/main/java/fr/xephi/authme/permission/UserPermission.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.xephi.authme.permission; - -/** - * AuthMe user permission nodes. - */ -public enum UserPermission implements PermissionNode { - - BYPASS_ANTIBOT("authme.bypassantibot"), - - IS_VIP("authme.vip"), - - LOGIN("authme.login"), - - LOGOUT("authme.logout"), - - REGISTER("authme.register"), - - UNREGISTER("authme.unregister"), - - CHANGE_PASSWORD("authme.changepassword"), - - ADD_EMAIL("authme.email.add"), - - CHANGE_EMAIL("authme.email.change"), - - RECOVER_EMAIL("authme.email.recover"), - - CAPTCHA("authme.captcha"), - - CONVERTER("authme.converter"), - - CAN_LOGIN_BE_FORCED("authme.canbeforced"), - - BYPASS_FORCE_SURVIVAL("authme.bypassforcesurvival"), - - ALLOW_MULTIPLE_ACCOUNTS("authme.allow2accounts"), - - SEE_OTHER_ACCOUNTS("authme.seeOtherAccounts"); - - private String node; - - @Override - public String getNode() { - return node; - } - - UserPermission(String node) { - this.node = node; - } - - -} 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 be186598c..5cc1f9ec8 100644 --- a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java +++ b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java @@ -4,9 +4,9 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.permission.UserPermission; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.permission.PlayerPermission; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.entity.Player; @@ -39,7 +39,7 @@ public class AsyncChangeEmail { String playerName = player.getName().toLowerCase(); if (Settings.getmaxRegPerEmail > 0) { - if (!plugin.getPermissionsManager().hasPermission(player, UserPermission.ALLOW_MULTIPLE_ACCOUNTS) + if (!plugin.getPermissionsManager().hasPermission(player, PlayerPermission.ALLOW_MULTIPLE_ACCOUNTS) && plugin.database.getAllAuthsByEmail(newEmail).size() >= Settings.getmaxRegPerEmail) { m.send(player, MessageKey.MAX_REGISTER_EXCEEDED); 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 407554637..df72fdcc4 100644 --- a/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java +++ b/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java @@ -10,9 +10,9 @@ import fr.xephi.authme.events.FirstSpawnTeleportEvent; import fr.xephi.authme.events.ProtectInventoryEvent; import fr.xephi.authme.events.SpawnTeleportEvent; import fr.xephi.authme.listener.AuthMePlayerListener; -import fr.xephi.authme.permission.UserPermission; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.permission.PlayerPermission; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Spawn; import fr.xephi.authme.task.MessageTask; @@ -78,7 +78,7 @@ public class AsynchronousJoin { return; } if (Settings.getMaxJoinPerIp > 0 - && !plugin.getPermissionsManager().hasPermission(player, UserPermission.ALLOW_MULTIPLE_ACCOUNTS) + && !plugin.getPermissionsManager().hasPermission(player, PlayerPermission.ALLOW_MULTIPLE_ACCOUNTS) && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost")) { if (plugin.hasJoinedIp(player.getName(), ip)) { @@ -236,8 +236,11 @@ public class AsynchronousJoin { ? m.retrieve(MessageKey.REGISTER_EMAIL_MESSAGE) : m.retrieve(MessageKey.REGISTER_MESSAGE); } - BukkitTask msgTask = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, msgInterval)); - LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgTask); + if (LimboCache.getInstance().getLimboPlayer(name) != null) + { + BukkitTask msgTask = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, msgInterval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgTask); + } } private boolean needFirstSpawn() { 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 aae9397f3..b3caf159a 100644 --- a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java @@ -8,11 +8,11 @@ import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent; import fr.xephi.authme.listener.AuthMePlayerListener; -import fr.xephi.authme.permission.UserPermission; +import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.RandomString; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.util.Utils; @@ -120,7 +120,7 @@ public class AsynchronousLogin { } return null; } - if (Settings.getMaxLoginPerIp > 0 && !plugin.getPermissionsManager().hasPermission(player, UserPermission.ALLOW_MULTIPLE_ACCOUNTS) && !getIP().equalsIgnoreCase("127.0.0.1") && !getIP().equalsIgnoreCase("localhost")) { + if (Settings.getMaxLoginPerIp > 0 && !plugin.getPermissionsManager().hasPermission(player, PlayerPermission.ALLOW_MULTIPLE_ACCOUNTS) && !getIP().equalsIgnoreCase("127.0.0.1") && !getIP().equalsIgnoreCase("localhost")) { if (plugin.isLoggedIp(name, getIP())) { m.send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); return null; @@ -268,7 +268,7 @@ public class AsynchronousLogin { * uuidaccounts + "."; } } */ for (Player player : Utils.getOnlinePlayers()) { - if (plugin.getPermissionsManager().hasPermission(player, UserPermission.SEE_OTHER_ACCOUNTS)) { + if (plugin.getPermissionsManager().hasPermission(player, PlayerPermission.SEE_OTHER_ACCOUNTS)) { player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts"); player.sendMessage(message.toString()); // player.sendMessage(uuidaccounts.replace("%size%", 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 6714c4dd1..3e719060a 100644 --- a/src/main/java/fr/xephi/authme/process/logout/AsynchronousLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/AsynchronousLogout.java @@ -5,8 +5,8 @@ import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils.GroupType; import org.bukkit.entity.Player; diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java index 811dbcb0c..6b4b9c0ed 100644 --- a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java @@ -4,8 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.events.LogoutEvent; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; 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 22f5b65a0..f9ceddb97 100644 --- a/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java @@ -5,10 +5,10 @@ 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.permission.UserPermission; +import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.security.PasswordSecurity; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.entity.Player; 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 33636af48..dc95e33de 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java @@ -4,8 +4,8 @@ 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.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java index 27f060e14..6434cb592 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java @@ -6,8 +6,8 @@ import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.events.LoginEvent; import fr.xephi.authme.events.RestoreInventoryEvent; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; 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 2268f4235..da5d19f9f 100644 --- a/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java +++ b/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java @@ -7,8 +7,8 @@ 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.security.PasswordSecurity; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.TimeoutTask; diff --git a/src/main/java/fr/xephi/authme/settings/Messages.java b/src/main/java/fr/xephi/authme/settings/Messages.java deleted file mode 100644 index 55ce0b584..000000000 --- a/src/main/java/fr/xephi/authme/settings/Messages.java +++ /dev/null @@ -1,115 +0,0 @@ -package fr.xephi.authme.settings; - -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.util.StringUtils; -import org.bukkit.command.CommandSender; - -import java.io.File; - -/** - * Class for retrieving and sending translatable messages to players. - */ -// TODO ljacqu 20151124: This class is a weird mix between singleton and POJO -// TODO: change it into POJO -public class Messages extends CustomConfiguration { - - /** The section symbol, used in Minecraft for formatting codes. */ - private static final String SECTION_SIGN = "\u00a7"; - private static Messages singleton; - private String language; - - - /** - * Constructor for Messages. - * - * @param file the configuration file - * @param lang the code of the language to use - */ - public Messages(File file, String lang) { - super(file); - load(); - this.language = lang; - } - - public static Messages getInstance() { - if (singleton == null) { - singleton = new Messages(Settings.messageFile, Settings.messagesLanguage); - } - return singleton; - } - - /** - * Send the given message code to the player. - * - * @param sender The entity to send the message to - * @param key The key of the message to send - */ - public void send(CommandSender sender, MessageKey key) { - String[] lines = retrieve(key); - for (String line : lines) { - sender.sendMessage(line); - } - } - - /** - * Retrieve the message from the text file and return it split by new line as an array. - * - * @param key The message key to retrieve - * - * @return The message split by new lines - */ - public String[] retrieve(MessageKey key) { - return retrieve(key.getKey()); - } - - /** - * Retrieve the message from the text file. - * - * @param key The message key to retrieve - * - * @return The message from the file - */ - public String retrieveSingle(MessageKey key) { - return StringUtils.join("\n", retrieve(key.getKey())); - } - - /** - * Retrieve the message from the configuration file. - * - * @param key The key to retrieve - * - * @return The message - */ - private String[] retrieve(String key) { - if (!Settings.messagesLanguage.equalsIgnoreCase(language)) { - reloadMessages(); - } - String message = (String) get(key); - if (message != null) { - return formatMessage(message); - } - - // Message is null: log key not being found and send error back as message - String retrievalError = "Error getting message with key '" + key + "'. "; - ConsoleLogger.showError(retrievalError + "Please verify your config file at '" - + getConfigFile().getName() + "'"); - return new String[]{ - retrievalError + "Please contact the admin to verify or update the AuthMe messages file."}; - } - - private static String[] formatMessage(String message) { - // TODO: Check that the codes actually exist, i.e. replace &c but not &y - // TODO: Allow '&' to be retained with the code '&&' - String[] lines = message.split("&n"); - for (int i = 0; i < lines.length; ++i) { - // We don't initialize a StringBuilder here because mostly we will only have one entry - lines[i] = lines[i].replace("&", SECTION_SIGN); - } - return lines; - } - - public void reloadMessages() { - singleton = new Messages(Settings.messageFile, Settings.messagesLanguage); - } - -} diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index b1bd141b2..f35af4440 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -8,7 +8,11 @@ import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.util.Wrapper; import org.bukkit.configuration.file.YamlConfiguration; +import com.google.common.base.Charsets; +import com.google.common.io.Files; + import java.io.*; +import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; @@ -17,12 +21,13 @@ import java.util.regex.Pattern; /** */ -public final class Settings extends YamlConfiguration { +public final class Settings { public static final File PLUGIN_FOLDER = Wrapper.getInstance().getDataFolder(); public static final File MODULE_FOLDER = new File(PLUGIN_FOLDER, "modules"); public static final File CACHE_FOLDER = new File(PLUGIN_FOLDER, "cache"); public static final File AUTH_FILE = new File(PLUGIN_FOLDER, "auths.db"); + public static final File EMAIL_FILE = new File(PLUGIN_FOLDER, "email.html"); public static final File SETTINGS_FILE = new File(PLUGIN_FOLDER, "config.yml"); public static final File LOG_FILE = new File(PLUGIN_FOLDER, "authme.log"); // This is not an option! @@ -68,7 +73,7 @@ public final class Settings extends YamlConfiguration { enableProtection, enableAntiBot, recallEmail, useWelcomeMessage, broadcastWelcomeMessage, forceRegKick, forceRegLogin, checkVeryGames, delayJoinLeaveMessages, noTeleport, applyBlindEffect, - customAttributes, generateImage, isRemoveSpeedEnabled, isMySQLWebsite; + customAttributes, generateImage, isRemoveSpeedEnabled; public static String helpHeader, getNickRegex, getUnloggedinGroup, getMySQLHost, getMySQLPort, getMySQLUsername, getMySQLPassword, getMySQLDatabase, getMySQLTablename, getMySQLColumnName, getMySQLColumnPassword, @@ -116,7 +121,7 @@ public final class Settings extends YamlConfiguration { if (!exist) { plugin.saveDefaultConfig(); } - instance.load(SETTINGS_FILE); + configFile.load(SETTINGS_FILE); if (exist) { instance.mergeConfig(); } @@ -231,7 +236,7 @@ public final class Settings extends YamlConfiguration { maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5); captchaLength = configFile.getInt("Security.captcha.captchaLength", 5); getMailSubject = configFile.getString("Email.mailSubject", "Your new AuthMe Password"); - getMailText = configFile.getString("Email.mailText", "Dear ,

This is your new AuthMe password for the server

:



Do not forget to change password after login!
/changepassword newPassword"); + getMailText = loadEmailText(); emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false); saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8); getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); @@ -289,20 +294,46 @@ public final class Settings extends YamlConfiguration { forceRegisterCommandsAsConsole = configFile.getStringList("settings.forceRegisterCommandsAsConsole"); customAttributes = configFile.getBoolean("Hooks.customAttributes"); generateImage = configFile.getBoolean("Email.generateImage", false); - isMySQLWebsite = configFile.getBoolean("DataSource.mySQLWebsite", false); // Load the welcome message getWelcomeMessage(); } - /** - * Method setValue. - * - * @param key String - * @param value Object - */ - public static void setValue(String key, Object value) { + private static String loadEmailText() { + if (!EMAIL_FILE.exists()) + saveDefaultEmailText(); + StringBuilder str = new StringBuilder(); + try { + BufferedReader in = new BufferedReader(new FileReader(EMAIL_FILE)); + String s; + while ((s = in.readLine()) != null) + str.append(s); + in.close(); + } catch(IOException e) + { + } + return str.toString(); + } + + private static void saveDefaultEmailText() { + InputStream file = plugin.getResource("email.html"); + StringBuilder str = new StringBuilder(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(file, Charset.forName("utf-8"))); + String s; + while ((s = in.readLine()) != null) + str.append(s); + in.close(); + Files.touch(EMAIL_FILE); + Files.write(str.toString(), EMAIL_FILE, Charsets.UTF_8); + } + catch(Exception e) + { + } + } + + public static void setValue(String key, Object value) { instance.set(key, value); save(); } @@ -373,9 +404,9 @@ public final class Settings extends YamlConfiguration { */ public static boolean save() { try { - instance.save(SETTINGS_FILE); + configFile.save(SETTINGS_FILE); return true; - } catch (Exception ex) { + } catch (IOException ex) { return false; } } @@ -593,7 +624,7 @@ public final class Settings extends YamlConfiguration { set("VeryGames.enableIpCheck", false); changes = true; } - if (getString("settings.restrictions.allowedNicknameCharacters").equals("[a-zA-Z0-9_?]*")) { + if (configFile.getString("settings.restrictions.allowedNicknameCharacters").equals("[a-zA-Z0-9_?]*")) { set("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_]*"); changes = true; } @@ -681,9 +712,11 @@ public final class Settings extends YamlConfiguration { set("DataSource.mySQLRealName", "realname"); changes = true; } - if (!contains("DataSource.mySQLWebsite")) { - set("DataSource.mySQLWebsite", false); - changes = true; + + if (contains("Email.mailText")) + { + set("Email.mailText", null); + ConsoleLogger.showError("Remove Email.mailText from config, we now use the email.html file"); } if (changes) { @@ -692,6 +725,15 @@ public final class Settings extends YamlConfiguration { } } + private static boolean contains(String path) { + return configFile.contains(path); + } + + // public because it's used in AuthMe at one place + public void set(String path, Object value) { + configFile.set(path, value); + } + /** * Saves current configuration (plus defaults) to disk. *

@@ -700,11 +742,13 @@ public final class Settings extends YamlConfiguration { * @return True if saved successfully */ public final boolean saveDefaults() { - options().copyDefaults(true); - options().copyHeader(true); + configFile.options() + .copyDefaults(true) + .copyHeader(true); boolean success = save(); - options().copyDefaults(false); - options().copyHeader(false); + configFile.options() + .copyDefaults(false) + .copyHeader(false); return success; } } diff --git a/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java b/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java index 05d93dfb5..9b4dfac51 100644 --- a/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java +++ b/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java @@ -5,8 +5,8 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.security.PasswordSecurity; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.entity.Player; diff --git a/src/main/java/fr/xephi/authme/task/TimeoutTask.java b/src/main/java/fr/xephi/authme/task/TimeoutTask.java index dc5d06ddf..eedf08755 100644 --- a/src/main/java/fr/xephi/authme/task/TimeoutTask.java +++ b/src/main/java/fr/xephi/authme/task/TimeoutTask.java @@ -2,8 +2,8 @@ package fr.xephi.authme.task; import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index e94dd94ee..3e3c52a06 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -7,7 +7,7 @@ import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.events.AuthMeTeleportEvent; import fr.xephi.authme.permission.PermissionsManager; -import fr.xephi.authme.permission.UserPermission; +import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.settings.Settings; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -202,7 +202,7 @@ public final class Utils { * @param player the player to modify. */ public static void forceGM(Player player) { - if (!plugin.getPermissionsManager().hasPermission(player, UserPermission.BYPASS_FORCE_SURVIVAL)) { + if (!plugin.getPermissionsManager().hasPermission(player, PlayerPermission.BYPASS_FORCE_SURVIVAL)) { player.setGameMode(GameMode.SURVIVAL); } } diff --git a/src/main/java/fr/xephi/authme/util/Wrapper.java b/src/main/java/fr/xephi/authme/util/Wrapper.java index 0666630b9..77f65cff5 100644 --- a/src/main/java/fr/xephi/authme/util/Wrapper.java +++ b/src/main/java/fr/xephi/authme/util/Wrapper.java @@ -2,7 +2,7 @@ package fr.xephi.authme.util; import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.Messages; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.scheduler.BukkitScheduler; diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 5abd17eb8..fd73b7733 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -388,12 +388,14 @@ Protection: # Enable some servers protection ( country based login, antibot ) enableProtection: false # Countries allowed to join the server and register, see http://dev.bukkit.org/bukkit-plugins/authme-reloaded/pages/countries-codes/ for countries' codes + # PLEASE USE QUOTES! countries: - - US - - GB + - 'US' + - 'GB' # Countries blacklisted automatically ( without any needed to enable protection ) + # PLEASE USE QUOTES! countriesBlacklist: - - A1 + - 'A1' # Do we need to enable automatic antibot system? enableAntiBot: false # Max number of player allowed to login in 5 secs before enable AntiBot system automatically diff --git a/src/main/resources/email.html b/src/main/resources/email.html new file mode 100644 index 000000000..12f6cbd5d --- /dev/null +++ b/src/main/resources/email.html @@ -0,0 +1,16 @@ +

+Dear %playername%, +

+ +

+This is your new AuthMe password for the server %servername%: + +%generatedpass% + +%image% + +Do not forget to change password after login! +/changepassword %generatedpass% newPassword' + +See you on %servername%! +

\ No newline at end of file diff --git a/src/main/resources/messages/messages_en.yml b/src/main/resources/messages/messages_en.yml index dd191d24c..fdb361a31 100644 --- a/src/main/resources/messages/messages_en.yml +++ b/src/main/resources/messages/messages_en.yml @@ -1,3 +1,4 @@ +kick_antibot: 'AntiBot protection mode is enabled! You have to wait some minutes before joining the server.' unknown_user: '&cCan''t find the requested user in the database!' unsafe_spawn: '&cYour quit location was unsafe, you have been teleported to the world''s spawnpoint.' not_logged_in: '&cYou''re not logged in!' diff --git a/src/main/resources/messages/messages_ru.yml b/src/main/resources/messages/messages_ru.yml index ddb84cdb5..da68ae19b 100644 --- a/src/main/resources/messages/messages_ru.yml +++ b/src/main/resources/messages/messages_ru.yml @@ -1,50 +1,50 @@ unknown_user: '&fПользователь не найден в Базе Данных' unsafe_spawn: '&eВаше расположение перед выходом было опасным - вы перенесены на спавн' -not_logged_in: '&cВы еще не вошли!' -reg_voluntarily: '&aЧтобы зарегистрироваться введите: &5/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +not_logged_in: '&c&lВы еще не вошли!' +reg_voluntarily: '&aЧтобы зарегистрироваться введите: &e&l/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' usage_log: '&eСинтаксис: &d/l ПАРОЛЬ &eили &d/login ПАРОЛЬ' -wrong_pwd: '&4Неправильный пароль!' +wrong_pwd: '&c&lНеправильный пароль!' unregistered: '&6Вы успешно удалили свой аккаунт!' -reg_disabled: '&4Регистрация отключена' +reg_disabled: '&c&lРегистрация отключена' valid_session: '&aСессия открыта' -login: '&2Вы успешно вошли!' +login: '&a&lВы успешно вошли!' vb_nonActiv: '&6Ваш аккаунт еще не активирован! Проверьте вашу почту!' -user_regged: '&4Такой игрок уже зарегистрирован' -usage_reg: '&4Использование: &5/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' -max_reg: '&4Вы превысили макс количество регистраций на ваш IP' -no_perm: '&4Недостаточно прав' -error: '&4Произошла ошибка. Свяжитесь с администратором' -login_msg: '&4Авторизация: &5/l ПАРОЛЬ' -reg_msg: '&4Регистрация: &5/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' -password_error_nick: '&fВы не можете использовать ваш ник в роли пароля' -password_error_unsafe: '&fВы не можете использовать небезопасный пароль' -reg_email_msg: '&4Регистрация: &5/reg EMAIL ПОВТОР_EMAIL' -usage_unreg: '&4Использование: &5/unregister ПАРОЛЬ' +user_regged: '&c&lТакой игрок уже зарегистрирован' +usage_reg: '&c&lИспользование: &e&l/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +max_reg: '&c&lВы превысили макс количество регистраций на ваш IP' +no_perm: '&c&lНедостаточно прав' +error: '&c&lПроизошла ошибка. Свяжитесь с администратором' +login_msg: '&a&lАвторизация: &e&l/l ПАРОЛЬ' +reg_msg: '&a&lРегистрация: &e&l/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +password_error_nick: '&c&lВы не можете использовать ваш ник в роли пароля' +password_error_unsafe: '&c&lВы не можете использовать небезопасный пароль' +reg_email_msg: '&c&lРегистрация: &e&l/reg EMAIL ПОВТОР_EMAIL' +usage_unreg: '&c&lИспользование: &e&l/unregister ПАРОЛЬ' pwd_changed: '&2Пароль изменен!' -user_unknown: '&4Такой игрок не зарегистрирован' -password_error: '&4Пароль не совпадает' -invalid_session: '&4Сессия некорректна. Дождитесь, пока она закончится' -reg_only: '&4Только для зарегистрированных! Посетите http://сайт_сервера.com/register/ для регистрации' -logged_in: '&4Вы уже авторизированы!' +user_unknown: '&c&lТакой игрок не зарегистрирован' +password_error: '&c&lПароль не совпадает' +invalid_session: '&c&lСессия некорректна. Дождитесь, пока она закончится' +reg_only: '&c&lТолько для зарегистрированных! Посетите http://сайт_сервера.com/register/ для регистрации' +logged_in: '&c&lВы уже авторизированы!' logout: '&2Вы успешно вышли' -same_nick: '&4Такой игрок уже играет на сервере' -registered: '&2Успешная регистрация!' -pass_len: '&4Твой пароль либо слишком длинный, либо слишком короткий' +same_nick: '&c&lТакой игрок уже играет на сервере' +registered: '&a&lУспешная регистрация!' +pass_len: '&c&lТвой пароль либо слишком длинный, либо слишком короткий' reload: '&6Конфигурация и база данных перезагружены' -timeout: '&4Время для авторизации истекло' -usage_changepassword: '&4Использование: &5/changepassword СТАРЫЙ_ПАРОЛЬ НОВЫЙ_ПАРОЛЬ' -name_len: '&4Ваш логин слишком длинный или слишком короткий' -regex: '&4Ваш логин содержит запрещенные символы. Разрешенные символы: REG_EX' -add_email: '&4Добавьте свой email: &5/email add ВАШ_EMAIL ВАШ_EMAIL' -recovery_email: '&4Забыли пароль? Используйте &5/email recovery ВАШ_EMAIL' -usage_captcha: '&4Вы должны ввести код, используйте: &5/captcha ' -wrong_captcha: '&4Неверный код, используйте: &5/captcha THE_CAPTCHA' +timeout: '&c&lВремя для авторизации истекло' +usage_changepassword: '&c&lИспользование: &e&l/changepassword СТАРЫЙ_ПАРОЛЬ НОВЫЙ_ПАРОЛЬ' +name_len: '&c&lВаш ник слишком длинный или слишком короткий' +regex: '&c&lВаш логин содержит запрещенные символы. Разрешенные символы: REG_EX' +add_email: '&c&lДобавьте свой email: &e&l/email add ВАШ_EMAIL ВАШ_EMAIL' +recovery_email: '&c&lЗабыли пароль? Используйте &e&l/email recovery ВАШ_EMAIL' +usage_captcha: '&c&lВы должны ввести код, используйте: &e&l/captcha ' +wrong_captcha: '&c&lНеверный код, используйте: &e&l/captcha THE_CAPTCHA' valid_captcha: '&2Вы успешно ввели код!' kick_forvip: '&6VIP игрок зашел на переполненный сервер!' -kick_fullserver: '&4Сервер переполнен!' -usage_email_add: '&4Использование: &5/email add ВАШ_EMAIL ПОВТОР_EMAIL' -usage_email_change: '&4Использование: &5/email change СТАРЫЙ_EMAIL НОВЫЙ_EMAIL' -usage_email_recovery: '&4Использование: /email recovery EMAIL' +kick_fullserver: '&c&lСервер переполнен!' +usage_email_add: '&c&lИспользование: &e&l/email add ВАШ_EMAIL ПОВТОР_EMAIL' +usage_email_change: '&c&lИспользование: &e&l/email change СТАРЫЙ_EMAIL НОВЫЙ_EMAIL' +usage_email_recovery: '&c&lИспользование: /email recovery EMAIL' new_email_invalid: '[AuthMe] Недействительный новый email!' old_email_invalid: '[AuthMe] Недействительный старый email!' email_invalid: '[AuthMe] Недействительный email' @@ -53,5 +53,5 @@ email_confirm: '[AuthMe] Подтвердите ваш Email!' email_changed: '[AuthMe] Email изменен!' email_send: '[AuthMe] Письмо с инструкциями для восстановления было отправлено на ваш Email!' country_banned: 'Вход с IP-адресов вашей страны воспрещен на этом сервере' -antibot_auto_enabled: '[AuthMe] AntiBot-режим автоматически включен из-за большого количества входов!' -antibot_auto_disabled: '[AuthMe] AntiBot-режим автоматичски отключен после %m мин. Надеюсь атака закончилась' +antibot_auto_enabled: '&a[AuthMe] AntiBot-режим автоматически включен из-за большого количества входов!' +antibot_auto_disabled: '&a[AuthMe] AntiBot-режим автоматичски отключен после %m мин. Надеюсь атака закончилась' 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 7d33a60ef..a81611a5d 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 @@ -4,8 +4,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.CommandParts; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.task.ChangePasswordTask; import fr.xephi.authme.util.WrapperMock; @@ -18,6 +18,7 @@ import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; +import java.util.Arrays; import java.util.Collections; import static java.util.Arrays.asList; @@ -85,7 +86,7 @@ public class ChangePasswordCommandTest { ChangePasswordCommand command = new ChangePasswordCommand(); // when - command.executeCommand(sender, new CommandParts(), new CommandParts("!pass")); + command.executeCommand(sender, new CommandParts(), newParts("old123", "!pass")); // then verify(messagesMock).send(sender, MessageKey.PASSWORD_MATCH_ERROR); @@ -100,7 +101,7 @@ public class ChangePasswordCommandTest { ChangePasswordCommand command = new ChangePasswordCommand(); // when - command.executeCommand(sender, new CommandParts(), new CommandParts("Tester")); + command.executeCommand(sender, new CommandParts(), newParts("old_", "Tester")); // then verify(messagesMock).send(sender, MessageKey.PASSWORD_IS_USERNAME_ERROR); @@ -115,7 +116,7 @@ public class ChangePasswordCommandTest { Settings.passwordMaxLength = 3; // when - command.executeCommand(sender, new CommandParts(), new CommandParts("test")); + command.executeCommand(sender, new CommandParts(), newParts("12", "test")); // then verify(messagesMock).send(sender, MessageKey.INVALID_PASSWORD_LENGTH); @@ -130,7 +131,7 @@ public class ChangePasswordCommandTest { Settings.getPasswordMinLen = 7; // when - command.executeCommand(sender, new CommandParts(), new CommandParts("tester")); + command.executeCommand(sender, new CommandParts(), newParts("oldverylongpassword", "tester")); // then verify(messagesMock).send(sender, MessageKey.INVALID_PASSWORD_LENGTH); @@ -145,7 +146,7 @@ public class ChangePasswordCommandTest { Settings.unsafePasswords = asList("test", "abc123"); // when - command.executeCommand(sender, new CommandParts(), new CommandParts("abc123")); + command.executeCommand(sender, new CommandParts(), newParts("oldpw", "abc123")); // then verify(messagesMock).send(sender, MessageKey.PASSWORD_UNSAFE_ERROR); @@ -157,16 +158,14 @@ public class ChangePasswordCommandTest { // given CommandSender sender = initPlayerWithName("parker", true); ChangePasswordCommand command = new ChangePasswordCommand(); - BukkitScheduler schedulerMock = mock(BukkitScheduler.class); - given(wrapperMock.getServer().getScheduler()).willReturn(schedulerMock); // when - command.executeCommand(sender, new CommandParts(), new CommandParts(asList("abc123", "abc123"))); + command.executeCommand(sender, new CommandParts(), newParts("abc123", "abc123")); // then verify(messagesMock, never()).send(eq(sender), any(MessageKey.class)); ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(ChangePasswordTask.class); - verify(schedulerMock).runTaskAsynchronously(any(AuthMe.class), taskCaptor.capture()); + verify(wrapperMock.getScheduler()).runTaskAsynchronously(any(AuthMe.class), taskCaptor.capture()); ChangePasswordTask task = taskCaptor.getValue(); assertThat((String) ReflectionTestUtils.getFieldValue(ChangePasswordTask.class, task, "newPassword"), equalTo("abc123")); @@ -179,4 +178,8 @@ public class ChangePasswordCommandTest { return player; } + private static CommandParts newParts(String... parts) { + return new CommandParts(Arrays.asList(parts)); + } + } diff --git a/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java index bc6229c10..02bb65a73 100644 --- a/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java @@ -2,8 +2,8 @@ package fr.xephi.authme.command.executable.register; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.process.Management; -import fr.xephi.authme.settings.MessageKey; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.output.Messages; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.WrapperMock; import org.bukkit.command.BlockCommandSender; diff --git a/src/test/java/fr/xephi/authme/command/help/HelpSyntaxHelperTest.java b/src/test/java/fr/xephi/authme/command/help/HelpSyntaxHelperTest.java index 1c3b45146..496dd93fb 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpSyntaxHelperTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpSyntaxHelperTest.java @@ -131,7 +131,7 @@ public class HelpSyntaxHelperTest { } - private static CommandDescription.Builder getDescriptionBuilder() { + private static CommandDescription.CommandBuilder getDescriptionBuilder() { CommandDescription base = CommandDescription.builder() .labels("authme") .description("Base command") diff --git a/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java b/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java new file mode 100644 index 000000000..8975068f6 --- /dev/null +++ b/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java @@ -0,0 +1,77 @@ +package fr.xephi.authme.output; + +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.logging.LogRecord; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Test for {@link ConsoleFilter}. + */ +public class ConsoleFilterTest { + + private final ConsoleFilter filter = new ConsoleFilter(); + + private static final String SENSITIVE_COMMAND = "User issued server command: /login test test"; + private static final String NORMAL_COMMAND = "User issued server command: /motd 2"; + + + @Test + public void shouldReplaceSensitiveRecord() { + // given + LogRecord record = createRecord(SENSITIVE_COMMAND); + + // when + boolean result = filter.isLoggable(record); + + // then + assertThat(result, equalTo(true)); + verify(record).setMessage("User issued an AuthMe command"); + } + + @Test + public void shouldNotFilterRegularCommand() { + // given + LogRecord record = createRecord(NORMAL_COMMAND); + + // when + boolean result = filter.isLoggable(record); + + // then + assertThat(result, equalTo(true)); + verify(record, never()).setMessage("User issued an AuthMe command"); + } + + @Test + public void shouldManageRecordWithNullMessage() { + // given + LogRecord record = createRecord(null); + + // when + boolean result = filter.isLoggable(record); + + // then + assertThat(result, equalTo(true)); + verify(record, never()).setMessage("User issued an AuthMe command"); + } + + + /** + * Creates a mock of {@link LogRecord} and sets it to return the given message. + * + * @param message The message to set. + * + * @return Mock of LogRecord + */ + private static LogRecord createRecord(String message) { + LogRecord record = Mockito.mock(LogRecord.class); + when(record.getMessage()).thenReturn(message); + return record; + } +} diff --git a/src/test/java/fr/xephi/authme/Log4JFilterTest.java b/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java similarity index 98% rename from src/test/java/fr/xephi/authme/Log4JFilterTest.java rename to src/test/java/fr/xephi/authme/output/Log4JFilterTest.java index f8d185d34..fdd338919 100644 --- a/src/test/java/fr/xephi/authme/Log4JFilterTest.java +++ b/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java @@ -1,4 +1,4 @@ -package fr.xephi.authme; +package fr.xephi.authme.output; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @@ -12,8 +12,6 @@ import org.mockito.Mockito; /** * Test for {@link Log4JFilter}. - * @author Gabriele - * @version $Revision: 1.0 $ */ public class Log4JFilterTest { diff --git a/src/test/java/fr/xephi/authme/settings/MessageKeyTest.java b/src/test/java/fr/xephi/authme/output/MessageKeyTest.java similarity index 96% rename from src/test/java/fr/xephi/authme/settings/MessageKeyTest.java rename to src/test/java/fr/xephi/authme/output/MessageKeyTest.java index 2eab88aa8..101306bf9 100644 --- a/src/test/java/fr/xephi/authme/settings/MessageKeyTest.java +++ b/src/test/java/fr/xephi/authme/output/MessageKeyTest.java @@ -1,4 +1,4 @@ -package fr.xephi.authme.settings; +package fr.xephi.authme.output; import fr.xephi.authme.util.StringUtils; import org.junit.Test; diff --git a/src/test/java/fr/xephi/authme/settings/MessagesTest.java b/src/test/java/fr/xephi/authme/output/MessagesIntegrationTest.java similarity index 93% rename from src/test/java/fr/xephi/authme/settings/MessagesTest.java rename to src/test/java/fr/xephi/authme/output/MessagesIntegrationTest.java index b721987ec..aa7367e2b 100644 --- a/src/test/java/fr/xephi/authme/settings/MessagesTest.java +++ b/src/test/java/fr/xephi/authme/output/MessagesIntegrationTest.java @@ -1,5 +1,6 @@ -package fr.xephi.authme.settings; +package fr.xephi.authme.output; +import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.WrapperMock; import org.bukkit.entity.Player; import org.junit.Before; @@ -18,7 +19,7 @@ import static org.mockito.Mockito.verify; /** * Test for {@link Messages}. */ -public class MessagesTest { +public class MessagesIntegrationTest { private static final String YML_TEST_FILE = "messages_test.yml"; private Messages messages; @@ -38,8 +39,9 @@ public class MessagesTest { throw new RuntimeException("File '" + YML_TEST_FILE + "' could not be loaded"); } - File file = new File(url.getFile()); - messages = new Messages(file, "en"); + Settings.messageFile = new File(url.getFile()); + Settings.messagesLanguage = "en"; + messages = Messages.getInstance(); } @Test diff --git a/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java b/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java index 14bf58b54..9a8625ac0 100644 --- a/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java +++ b/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java @@ -13,14 +13,29 @@ import static org.junit.Assert.fail; public class AdminPermissionTest { @Test - public void shouldStartWithAuthMeAdminPrefix() { + public void shouldStartWithAuthMePrefix() { // given - String requiredPrefix = "authme.admin."; + String requiredPrefix = "authme."; // when/then - for (AdminPermission perm : AdminPermission.values()) { - if (!perm.getNode().startsWith(requiredPrefix)) { - fail("The permission '" + perm + "' does not start with the required prefix '" + requiredPrefix + "'"); + for (AdminPermission permission : AdminPermission.values()) { + if (!permission.getNode().startsWith(requiredPrefix)) { + fail("The permission '" + permission + "' does not start with the required prefix '" + + requiredPrefix + "'"); + } + } + } + + @Test + public void shouldContainAdminBranch() { + // given + String requiredBranch = ".admin."; + + // when/then + for (AdminPermission permission : AdminPermission.values()) { + if (!permission.getNode().contains(requiredBranch)) { + fail("The permission '" + permission + "' does not contain with the required branch '" + + requiredBranch + "'"); } } } @@ -31,11 +46,11 @@ public class AdminPermissionTest { Set nodes = new HashSet<>(); // when/then - for (AdminPermission perm : AdminPermission.values()) { - if (nodes.contains(perm.getNode())) { - fail("More than one enum value defines the node '" + perm.getNode() + "'"); + for (AdminPermission permission : AdminPermission.values()) { + if (nodes.contains(permission.getNode())) { + fail("More than one enum value defines the node '" + permission.getNode() + "'"); } - nodes.add(perm.getNode()); + nodes.add(permission.getNode()); } } diff --git a/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java b/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java new file mode 100644 index 000000000..6afc0ac07 --- /dev/null +++ b/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java @@ -0,0 +1,61 @@ +package fr.xephi.authme.permission; + +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.fail; + +/** + * Test for {@link PlayerPermission}. + */ +public class PlayerPermissionTest { + + @Test + public void shouldStartWithAuthMePrefix() { + // given + String requiredPrefix = "authme."; + + // when/then + for (PlayerPermission permission : PlayerPermission.values()) { + if (!permission.getNode().startsWith(requiredPrefix)) { + fail("The permission '" + permission + "' does not start with the required prefix '" + requiredPrefix + + "'"); + } + } + } + + @Test + public void shouldContainPlayerBranch() { + // given + String playerBranch = ".player."; + String adminBranch = ".admin."; + + // when/then + for (PlayerPermission permission : PlayerPermission.values()) { + if (permission.getNode().contains(adminBranch)) { + fail("The permission '" + permission + "' should not use a node with the admin-specific branch '" + + adminBranch + "'"); + + } else if (!permission.getNode().contains(playerBranch)) { + fail("The permission '" + permission + "' should use a node with the player-specific branch '" + + playerBranch + "'"); + } + } + } + + @Test + public void shouldHaveUniqueNodes() { + // given + Set nodes = new HashSet<>(); + + // when/then + for (PlayerPermission permission : PlayerPermission.values()) { + if (nodes.contains(permission.getNode())) { + fail("More than one enum value defines the node '" + permission.getNode() + "'"); + } + nodes.add(permission.getNode()); + } + } +} diff --git a/src/test/java/fr/xephi/authme/permission/UserPermissionTest.java b/src/test/java/fr/xephi/authme/permission/UserPermissionTest.java deleted file mode 100644 index 48d4bbed8..000000000 --- a/src/test/java/fr/xephi/authme/permission/UserPermissionTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.xephi.authme.permission; - -import org.junit.Test; - -import java.util.HashSet; -import java.util.Set; - -import static org.junit.Assert.fail; - -/** - * Test for {@link UserPermission}. - */ -public class UserPermissionTest { - - @Test - public void shouldStartWithRegularAuthMePrefix() { - // given - String requiredPrefix = "authme."; - String adminPrefix = "authme.admin"; - - // when/then - for (UserPermission perm : UserPermission.values()) { - if (!perm.getNode().startsWith(requiredPrefix)) { - fail("The permission '" + perm + "' does not start with the required prefix '" + requiredPrefix + "'"); - } else if (perm.getNode().startsWith(adminPrefix)) { - fail("The permission '" + perm + "' should not use a node with the admin-specific prefix '" - + adminPrefix + "'"); - } - } - } - - @Test - public void shouldHaveUniqueNodes() { - // given - Set nodes = new HashSet<>(); - - // when/then - for (UserPermission perm : UserPermission.values()) { - if (nodes.contains(perm.getNode())) { - fail("More than one enum value defines the node '" + perm.getNode() + "'"); - } - nodes.add(perm.getNode()); - } - } -} diff --git a/src/test/java/fr/xephi/authme/util/UtilsTest.java b/src/test/java/fr/xephi/authme/util/UtilsTest.java index 4c632187f..2b9df6ad6 100644 --- a/src/test/java/fr/xephi/authme/util/UtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/UtilsTest.java @@ -3,7 +3,7 @@ package fr.xephi.authme.util; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.permission.PermissionsManager; -import fr.xephi.authme.permission.UserPermission; +import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.settings.Settings; import org.bukkit.GameMode; import org.bukkit.entity.Player; @@ -54,7 +54,7 @@ public class UtilsTest { public void shouldForceSurvivalGameMode() { // given Player player = mock(Player.class); - given(permissionsManagerMock.hasPermission(player, UserPermission.BYPASS_FORCE_SURVIVAL)).willReturn(false); + given(permissionsManagerMock.hasPermission(player, PlayerPermission.BYPASS_FORCE_SURVIVAL)).willReturn(false); // when Utils.forceGM(player); @@ -68,14 +68,14 @@ public class UtilsTest { public void shouldNotForceGameModeForUserWithBypassPermission() { // given Player player = mock(Player.class); - given(permissionsManagerMock.hasPermission(player, UserPermission.BYPASS_FORCE_SURVIVAL)).willReturn(true); + given(permissionsManagerMock.hasPermission(player, PlayerPermission.BYPASS_FORCE_SURVIVAL)).willReturn(true); // when Utils.forceGM(player); // then verify(authMeMock).getPermissionsManager(); - verify(permissionsManagerMock).hasPermission(player, UserPermission.BYPASS_FORCE_SURVIVAL); + verify(permissionsManagerMock).hasPermission(player, PlayerPermission.BYPASS_FORCE_SURVIVAL); verify(player, never()).setGameMode(any(GameMode.class)); } diff --git a/src/test/java/fr/xephi/authme/util/WrapperMock.java b/src/test/java/fr/xephi/authme/util/WrapperMock.java index f622c00bd..83ed23cd2 100644 --- a/src/test/java/fr/xephi/authme/util/WrapperMock.java +++ b/src/test/java/fr/xephi/authme/util/WrapperMock.java @@ -2,7 +2,7 @@ package fr.xephi.authme.util; import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.output.Messages; import org.bukkit.Server; import org.bukkit.scheduler.BukkitScheduler; import org.mockito.Mockito; diff --git a/team.txt b/team.txt index e1c7e8604..98b60aa52 100644 --- a/team.txt +++ b/team.txt @@ -3,18 +3,16 @@ AuthMe-Team: Active staff: Xephi (Xephi59) - Leader, Main developer DNx5 - Developer -games647 - Developer +ljacqu - Developer TimVisee - Developer +games647 - Developer Gabriele C. (sgdc3) - Project Manager, Contributor -Staff to contact: -CryLegend - Contributor, AuthMeBridge Developer (Needs activation) +AuthMeBridge staff: +CryLegend - Main developer, We need to contact him! -External Contributors: -Gnat008 - Contributor - -Inactive staff: -Maxetto - Ticket Manager, Italian Translator, Basic Developer, Contributor (Inactive) +Retired staff: +Maxetto - Ticket Manager, IT translator darkwarriors (d4rkwarriors) - Original AuthMeReloaded Author (Inactive) Translators: