From 579c51f4a2f3335360f147ffe613ce5c3ea74666 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sat, 21 Nov 2015 20:16:07 +0100 Subject: [PATCH 01/77] Remove the old Vault group management system. (THIS COMMIT BREAKS THE COMPILATION) --- src/main/java/fr/xephi/authme/AuthMe.java | 34 +++---------------- .../executable/authme/ForceLoginCommand.java | 1 + .../executable/authme/GetIpCommand.java | 1 + .../executable/email/AddEmailCommand.java | 1 - .../authme/listener/AuthMeServerListener.java | 6 ---- .../authme/permission/PermissionsManager.java | 6 ---- 6 files changed, 7 insertions(+), 42 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index c253ca5b7..de1a3d398 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -70,9 +70,8 @@ public class AuthMe extends JavaPlugin { /** Defines the current AuthMeReloaded version name. */ private static final String PLUGIN_VERSION_NAME = "5.1-SNAPSHOT"; /** Defines the current AuthMeReloaded version code. */ - private static final int PLUGIN_VERSION_CODE = 100; // Increase this number - // by one when an update - // is released + // Increase this number by one when an update is released + private static final int PLUGIN_VERSION_CODE = 100; private static AuthMe plugin; private static Server server; @@ -96,7 +95,6 @@ public class AuthMe extends JavaPlugin { public boolean delayedAntiBot = true; // Hooks TODO: move into modules - public Permission vaultGroupManagement; // TODO: Remove this instance, and replace every usage with permissions manager! public Essentials ess; public MultiverseCore multiverse; public CombatTagPlus combatTagPlus; @@ -278,9 +276,6 @@ public class AuthMe extends JavaPlugin { mail = new SendMailSSL(this); } - // Find Permissions - checkVault(); - // Check Combat Tag Plus Version checkCombatTagPlus(); @@ -525,21 +520,6 @@ public class AuthMe extends JavaPlugin { }); } - // Check the presence of the Vault plugin and a permissions provider - public void checkVault() { - if (server.getPluginManager().isPluginEnabled("Vault")) { - RegisteredServiceProvider permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); - if (permissionProvider != null) { - vaultGroupManagement = permissionProvider.getProvider(); - ConsoleLogger.info("Vault detected, hooking with the " + vaultGroupManagement.getName() + " group management system..."); - } else { - ConsoleLogger.showError("Vault detected, but I can't find any group management plugin to hook with!"); - } - } else { - vaultGroupManagement = null; - } - } - // Get the Multiverse plugin public void checkMultiverse() { if (Settings.multiverse && server.getPluginManager().isPluginEnabled("Multiverse-Core")) { @@ -706,17 +686,13 @@ public class AuthMe extends JavaPlugin { } ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!"); if (Settings.purgeEssentialsFile && this.ess != null) - dataManager.purgeEssentials(cleared); // name to UUID convertion - // needed with latest versions + dataManager.purgeEssentials(cleared); if (Settings.purgePlayerDat) - dataManager.purgeDat(cleared); // name to UUID convertion needed - // with latest versions of MC + dataManager.purgeDat(cleared); if (Settings.purgeLimitedCreative) dataManager.purgeLimitedCreative(cleared); if (Settings.purgeAntiXray) - dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or - // names... (Actually it purges - // only names!) + dataManager.purgeAntiXray(cleared); if (Settings.purgePermissions) dataManager.purgePermissions(cleared, vaultGroupManagement); } 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 0a9fd9444..8d2179b9e 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 @@ -24,6 +24,7 @@ public class ForceLoginCommand extends ExecutableCommand { // Command logic try { + @SuppressWarnings("deprecation") Player player = Bukkit.getPlayer(playerName); if (player == null || !player.isOnline()) { sender.sendMessage("Player needs to be online!"); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java index 343642c5a..610df993d 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java @@ -22,6 +22,7 @@ public class GetIpCommand extends ExecutableCommand { if(commandArguments.getCount() >= 1) playerName = commandArguments.get(0); + @SuppressWarnings("deprecation") Player player = Bukkit.getPlayer(playerName); if (player == null) { sender.sendMessage("This player is not actually online"); diff --git a/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java index 68f5e54b1..d31261116 100644 --- a/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; -import fr.xephi.authme.settings.Messages; /** */ diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java index 862ac9291..ec17eaaf5 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java @@ -90,10 +90,6 @@ public class AuthMeServerListener implements Listener { plugin.combatTagPlus = null; ConsoleLogger.info("CombatTagPlus has been disabled, unhook!"); } - if (pluginName.equalsIgnoreCase("Vault")) { - plugin.vaultGroupManagement = null; - ConsoleLogger.showError("Vault has been disabled, unhook permissions!"); - } if (pluginName.equalsIgnoreCase("ProtocolLib")) { plugin.inventoryProtector = null; ConsoleLogger.showError("ProtocolLib has been disabled, unhook packet inventory protection!"); @@ -116,8 +112,6 @@ public class AuthMeServerListener implements Listener { plugin.checkMultiverse(); if (pluginName.equalsIgnoreCase("CombatTagPlus")) plugin.checkCombatTagPlus(); - if (pluginName.equalsIgnoreCase("Vault")) - plugin.checkVault(); if (pluginName.equalsIgnoreCase("ProtocolLib")) { plugin.checkProtocolLib(); } diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java index 8640d3e13..9827b0d79 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java @@ -560,7 +560,6 @@ public class PermissionsManager { * @return True if succeed, false otherwise. * False is also returned if this feature isn't supported for the current permissions system. */ - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) public boolean addGroup(Player player, String groupName) { // If no permissions system is used, return false if(!isEnabled()) @@ -623,7 +622,6 @@ public class PermissionsManager { * @return True if succeed, false otherwise. * False is also returned if this feature isn't supported for the current permissions system. */ - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) public boolean addGroups(Player player, List groupNames) { // If no permissions system is used, return false if(!isEnabled()) @@ -648,7 +646,6 @@ public class PermissionsManager { * @return True if succeed, false otherwise. * False is also returned if this feature isn't supported for the current permissions system. */ - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) public boolean removeGroup(Player player, String groupName) { // If no permissions system is used, return false if(!isEnabled()) @@ -711,7 +708,6 @@ public class PermissionsManager { * @return True if succeed, false otherwise. * False is also returned if this feature isn't supported for the current permissions system. */ - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) public boolean removeGroups(Player player, List groupNames) { // If no permissions system is used, return false if(!isEnabled()) @@ -737,7 +733,6 @@ public class PermissionsManager { * @return True if succeed, false otherwise. * False is also returned if this feature isn't supported for the current permissions system. */ - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) public boolean setGroup(Player player, String groupName) { // If no permissions system is used, return false if(!isEnabled()) @@ -808,7 +803,6 @@ public class PermissionsManager { * @return True if succeed, false otherwise. * False is also returned if this feature isn't supported for the current permissions system. */ - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) public boolean setGroups(Player player, List groupNames) { // If no permissions system is used or if there's no group supplied, return false if(!isEnabled() || groupNames.size() <= 0) From 7902cd87bb6a5abe099755104716e7bfcdefb2e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sat, 21 Nov 2015 20:47:56 +0100 Subject: [PATCH 02/77] Added return statement for setGroup method, updated it's JavaDocs --- src/main/java/fr/xephi/authme/util/Utils.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index 278cf41af..457bac0e2 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -121,11 +121,15 @@ public class Utils { } /** - * Method setGroup. - * @param player Player - * @param group GroupType + * Set the group of a player, by it's AuthMe group type. + * + * @param player The player. + * @param group The group type. + * + * @return True if succeed, false otherwise. + * False is also returned if groups aren't supported with the current permissions system. */ - public static void setGroup(Player player, GroupType group) { + public static boolean setGroup(Player player, GroupType group) { if(!Settings.isPermissionCheckEnabled) return; @@ -143,34 +147,33 @@ public class Utils { case UNREGISTERED: // Remove the other group type groups, set the current group permsMan.removeGroups(player, Arrays.asList(Settings.getRegisteredGroup, Settings.getUnloggedinGroup)); - permsMan.addGroup(player, Settings.unRegisteredGroup); - break; + return permsMan.addGroup(player, Settings.unRegisteredGroup); case REGISTERED: // Remove the other group type groups, set the current group permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getUnloggedinGroup)); - permsMan.addGroup(player, Settings.getRegisteredGroup); - break; + return permsMan.addGroup(player, Settings.getRegisteredGroup); case NOTLOGGEDIN: // Remove the other group type groups, set the current group permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getRegisteredGroup)); - permsMan.addGroup(player, Settings.getUnloggedinGroup); - break; + return permsMan.addGroup(player, Settings.getUnloggedinGroup); case LOGGEDIN: // Get the limbo player data LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); if(limbo == null) - break; + return false; // Get the players group String realGroup = limbo.getGroup(); // Remove the other group types groups, set the real group permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getRegisteredGroup, Settings.getUnloggedinGroup)); - permsMan.addGroup(player, realGroup); - break; + return permsMan.addGroup(player, realGroup); + + default: + return false; } } From 89b5444d697f844c1b43224ddad3776cfbcc7e63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sat, 21 Nov 2015 20:50:12 +0100 Subject: [PATCH 03/77] Fixed addNormal method, updated it's JavaDocs --- src/main/java/fr/xephi/authme/util/Utils.java | 41 ++++++++++--------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index 457bac0e2..aa1ba5c53 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -178,27 +178,30 @@ public class Utils { } /** - * Method addNormal. - * @param player Player - * @param group String - - * @return boolean */ + * TODO: This method requires better explanation. + * + * Set the normal group of a player. + * + * @param player The player. + * @param group The normal group. + + * @return True on success, false on failure. + */ public static boolean addNormal(Player player, String group) { - if (!useGroupSystem()) { + if(!Settings.isPermissionCheckEnabled) return false; - } - if (plugin.vaultGroupManagement == null) - return false; - try { - if (plugin.vaultGroupManagement.playerRemoveGroup(player, Settings.getUnloggedinGroup) && plugin.vaultGroupManagement.playerAddGroup(player, group)) { - return true; - } - } catch (UnsupportedOperationException e) { - ConsoleLogger.showError("Your permission system (" + plugin.vaultGroupManagement.getName() + ") do not support Group system with that config... unhook!"); - plugin.vaultGroupManagement = null; - return false; - } - return false; + + // Get the permissions manager, and make sure it's valid + PermissionsManager permsMan = plugin.getPermissionsManager(); + if(permsMan == null) + ConsoleLogger.showError("Failed to access permissions manager instance, shutting down."); + assert permsMan != null; + + // Remove old groups + permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getRegisteredGroup, Settings.getUnloggedinGroup)); + + // Add the normal group, return the result + return permsMan.addGroup(player, group); } // TODO: Move to a Manager From 0a5c0817320af79a050f51ad72a55d0f5e852384 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sat, 21 Nov 2015 20:59:23 +0100 Subject: [PATCH 04/77] Added method to permissions manager to get primary group of player --- .../authme/permission/PermissionsManager.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java index 9827b0d79..9ba1dcf10 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java @@ -493,6 +493,59 @@ public class PermissionsManager { } } + /** + * Get the primary group of a player, if available. + * + * @param player The player. + * + * @return The name of the primary permission group. Or null. + */ + @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) + public String getPrimaryGroup(Player player) { + // If no permissions system is used, return an empty list + if(!isEnabled()) + return null; + + switch(this.permsType) { + case PERMISSIONS_EX: + case PERMISSIONS_BUKKIT: + case B_PERMISSIONS: + case PERMISSIONS: // FIXME: Is this correct for PERMISSIONS? + // Get the groups of the player + List groups = getGroups(player); + + // Make sure there is any group available, or return null + if(groups.size() == 0) + return null; + + // Return the first group + return groups.get(0); + + case ESSENTIALS_GROUP_MANAGER: + // Essentials Group Manager + final AnjoPermissionsHandler handler = groupManagerPerms.getWorldsHolder().getWorldPermissions(player); + if(handler == null) + return null; + return handler.getGroup(player.getName()); + + case Z_PERMISSIONS: + //zPermissions + return zPermissionsService.getPlayerPrimaryGroup(player.getName()); + + case VAULT: + // Vault + return vaultPerms.getPrimaryGroup(player); + + case NONE: + // Not hooked into any permissions system, return null + return null; + + default: + // Something went wrong, return null to prevent problems + return null; + } + } + /** * Check whether the player is in the specified group. * From 18af8f31715cbcd6088802d339db18e7d85851c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sat, 21 Nov 2015 21:02:53 +0100 Subject: [PATCH 05/77] Fixed addLimboPlayer method --- .../xephi/authme/cache/limbo/LimboCache.java | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) 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 7205c7081..c468a90cb 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java @@ -2,6 +2,7 @@ package fr.xephi.authme.cache.limbo; import java.util.concurrent.ConcurrentHashMap; +import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; @@ -13,6 +14,7 @@ import fr.xephi.authme.cache.backup.DataFileCache; import fr.xephi.authme.cache.backup.JsonCache; import fr.xephi.authme.events.ResetInventoryEvent; import fr.xephi.authme.settings.Settings; +import org.bukkit.permissions.Permission; /** */ @@ -34,8 +36,9 @@ public class LimboCache { } /** - * Method addLimboPlayer. - * @param player Player + * Add a limbo player. + * + * @param player Player instance to add. */ public void addLimboPlayer(Player player) { String name = player.getName().toLowerCase(); @@ -45,6 +48,12 @@ public class LimboCache { String playerGroup = ""; boolean flying = false; + // Get the permissions manager, and make sure it's valid + PermissionsManager permsMan = this.plugin.getPermissionsManager(); + if(permsMan == null) + ConsoleLogger.showError("Unable to access permissions manager!"); + assert permsMan != null; + if (playerData.doesCacheExist(player)) { DataFileCache cache = playerData.readCache(player); if (cache != null) { @@ -55,14 +64,10 @@ public class LimboCache { } else { operator = player.isOp(); flying = player.isFlying(); - if (plugin.vaultGroupManagement != null) { - try { - playerGroup = plugin.vaultGroupManagement.getPrimaryGroup(player); - } catch (UnsupportedOperationException e) { - ConsoleLogger.showError("Your permission system (" + plugin.vaultGroupManagement.getName() + ") do not support Group system with that config... unhook!"); - plugin.vaultGroupManagement = null; - } - } + + // Check whether groups are supported + if(permsMan.hasGroupSupport()) + playerGroup = permsMan.getPrimaryGroup(player); } if (Settings.isForceSurvivalModeEnabled) { From e45aa885044409a1f7925c6606d0d3c3fa7fd611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sat, 21 Nov 2015 21:03:50 +0100 Subject: [PATCH 06/77] Fixed result not being returned --- src/main/java/fr/xephi/authme/util/Utils.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index aa1ba5c53..957a948f3 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -130,8 +130,9 @@ public class Utils { * False is also returned if groups aren't supported with the current permissions system. */ public static boolean setGroup(Player player, GroupType group) { + // Check whether the permissions check is enabled if(!Settings.isPermissionCheckEnabled) - return; + return false; // Get the permissions manager, and make sure it's valid PermissionsManager permsMan = plugin.getPermissionsManager(); From ada991904bdc2a52c68639c97c06c47e46737780 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sat, 21 Nov 2015 21:07:32 +0100 Subject: [PATCH 07/77] Improved purgePermissions method --- .../java/fr/xephi/authme/DataManager.java | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/main/java/fr/xephi/authme/DataManager.java b/src/main/java/fr/xephi/authme/DataManager.java index edc96eee7..3d74da41e 100644 --- a/src/main/java/fr/xephi/authme/DataManager.java +++ b/src/main/java/fr/xephi/authme/DataManager.java @@ -7,6 +7,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; @@ -172,13 +173,28 @@ public class DataManager { ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " EssentialsFiles"); } + // TODO: What is this method for? Is it correct? /** - * Method purgePermissions. - * @param cleared List - * @param permission Permission + * @param cleared Cleared players. */ - public synchronized void purgePermissions(List cleared, Permission permission) { + public synchronized void purgePermissions(List cleared) { + // Get the permissions manager, and make sure it's valid + PermissionsManager permsMan = this.plugin.getPermissionsManager(); + if(permsMan == null) + ConsoleLogger.showError("Unable to access permissions manager instance!"); + assert permsMan != null; + int i = 0; + for (String name : cleared) { + try { + permsMan.removeAllGroups(this.getOnlinePlayerLower(name.toLowerCase())); + i++; + } catch(Exception e) { + } + } + ConsoleLogger.info("AutoPurgeDatabase : Removed " + i + " permissions"); + + /*int i = 0; for (String name : cleared) { try { OfflinePlayer p = this.getOfflinePlayer(name); @@ -189,7 +205,7 @@ public class DataManager { } catch (Exception e) { } } - ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " Permissions"); + ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " Permissions");*/ } /** From 1ba18439e9692960ce40fa37e8f0b0be9cfd36f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sat, 21 Nov 2015 21:08:07 +0100 Subject: [PATCH 08/77] Fixed invalid method arguments --- src/main/java/fr/xephi/authme/AuthMe.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index de1a3d398..ba8342510 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -694,7 +694,7 @@ public class AuthMe extends JavaPlugin { if (Settings.purgeAntiXray) dataManager.purgeAntiXray(cleared); if (Settings.purgePermissions) - dataManager.purgePermissions(cleared, vaultGroupManagement); + dataManager.purgePermissions(cleared); } // Return the spawn location of a player From fc3f685de0cf75a78f78b48ce8b220f43724b5d8 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 21 Nov 2015 23:09:04 +0100 Subject: [PATCH 09/77] Create UtilsTest Had to create a getGameServer() method in AuthMe in order to be able to catch this call in tests and replace it with a mock implementation of the actual server. The supertype method getServer() is declared as final, which makes it impossible to mock with Mockito. While there are frameworks that manipulate the bytecode to mock final calls, it is much easier and less risky to simply delegate the server retrieval through another method. --- src/main/java/fr/xephi/authme/AuthMe.java | 11 ++- src/main/java/fr/xephi/authme/util/Utils.java | 73 ++++--------------- .../java/fr/xephi/authme/util/UtilsTest.java | 73 +++++++++++++++++++ 3 files changed, 98 insertions(+), 59 deletions(-) create mode 100644 src/test/java/fr/xephi/authme/util/UtilsTest.java diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index ba8342510..fda2bde0d 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -22,7 +22,6 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; import org.mcstats.Metrics; @@ -933,4 +932,14 @@ public class AuthMe extends JavaPlugin { public Management getManagement() { return management; } + + /** + * Returns the server instance running this plugin. Use this method in favor of + * {@link AuthMe#getServer()} for testability purposes. + * + * @return the server instance + */ + public Server getGameServer() { + return super.getServer(); + } } diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index 957a948f3..aceb6d74c 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -27,7 +27,7 @@ import java.util.zip.GZIPInputStream; /** */ -public class Utils { +public final class Utils { public static AuthMe plugin; @@ -45,11 +45,11 @@ public class Utils { } } - // Check and Download GeoIP data if not exist - /** - * Method checkGeoIP. - - * @return boolean */ + private Utils() { + // Utility class + } + + // Check and Download GeoIP data if it doesn't exist public static boolean checkGeoIP() { if (lookupService != null) { return true; @@ -59,14 +59,15 @@ public class Utils { if (lookupService == null) { try { lookupService = new LookupService(data); - ConsoleLogger.info("[LICENSE] This product uses data from the GeoLite API created by MaxMind, available at http://www.maxmind.com"); + ConsoleLogger.info("[LICENSE] This product uses data from the GeoLite API created by MaxMind, " + + "available at http://www.maxmind.com"); return true; } catch (IOException e) { return false; } } } - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { + plugin.getGameServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { @@ -96,11 +97,6 @@ public class Utils { return false; } - /** - * Method getCountryCode. - * @param ip String - - * @return String */ public static String getCountryCode(String ip) { if (checkGeoIP()) { return lookupService.getCountry(ip).getCode(); @@ -108,11 +104,6 @@ public class Utils { return "--"; } - /** - * Method getCountryName. - * @param ip String - - * @return String */ public static String getCountryName(String ip) { if (checkGeoIP()) { return lookupService.getCountry(ip).getName(); @@ -121,7 +112,7 @@ public class Utils { } /** - * Set the group of a player, by it's AuthMe group type. + * Set the group of a player, by its AuthMe group type. * * @param player The player. * @param group The group type. @@ -206,11 +197,6 @@ public class Utils { } // TODO: Move to a Manager - /** - * Method checkAuth. - * @param player Player - - * @return boolean */ public static boolean checkAuth(Player player) { if (player == null || Utils.isUnrestricted(player)) { return true; @@ -230,20 +216,11 @@ public class Utils { return false; } - /** - * Method isUnrestricted. - * @param player Player - - * @return boolean */ public static boolean isUnrestricted(Player player) { return Settings.isAllowRestrictedIp && !Settings.getUnrestrictedName.isEmpty() && (Settings.getUnrestrictedName.contains(player.getName())); } - /** - * Method useGroupSystem. - - * @return boolean */ private static boolean useGroupSystem() { return Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty(); } @@ -286,12 +263,14 @@ public class Utils { * Used for force player GameMode */ /** - * Method forceGM. - * @param player Player + * Force the game mode of a player. + * + * @param player the player to modify. */ public static void forceGM(Player player) { - if (!plugin.getPermissionsManager().hasPermission(player, "authme.bypassforcesurvival")) + if (!plugin.getPermissionsManager().hasPermission(player, "authme.bypassforcesurvival")) { player.setGameMode(GameMode.SURVIVAL); + } } /** @@ -303,10 +282,6 @@ public class Utils { LOGGEDIN } - /** - * Method purgeDirectory. - * @param file File - */ public static void purgeDirectory(File file) { if (!file.isDirectory()) { return; @@ -325,10 +300,6 @@ public class Utils { } } - /** - * Method getOnlinePlayers. - - * @return Collection */ @SuppressWarnings("unchecked") public static Collection getOnlinePlayers() { if (getOnlinePlayersIsCollection) { @@ -348,22 +319,12 @@ public class Utils { return Collections.emptyList(); } - /** - * Method getPlayer. - * @param name String - - * @return Player */ @SuppressWarnings("deprecation") public static Player getPlayer(String name) { name = name.toLowerCase(); return plugin.getServer().getPlayer(name); } - /** - * Method isNPC. - * @param player Entity - - * @return boolean */ public static boolean isNPC(final Entity player) { try { if (player.hasMetadata("NPC")) { @@ -379,10 +340,6 @@ public class Utils { } } - /** - * Method teleportToSpawn. - * @param player Player - */ public static void teleportToSpawn(Player player) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { Location spawn = plugin.getSpawnLocation(player); diff --git a/src/test/java/fr/xephi/authme/util/UtilsTest.java b/src/test/java/fr/xephi/authme/util/UtilsTest.java new file mode 100644 index 000000000..85aaf4e2a --- /dev/null +++ b/src/test/java/fr/xephi/authme/util/UtilsTest.java @@ -0,0 +1,73 @@ +package fr.xephi.authme.util; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.AuthMeMockUtil; +import fr.xephi.authme.permission.PermissionsManager; +import org.bukkit.GameMode; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; +import org.junit.Before; +import org.junit.Test; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Test for the {@link Utils} class. + */ +public class UtilsTest { + + private AuthMe authMeMock; + private PermissionsManager permissionsManagerMock; + + @Before + public void setUpMocks() { + AuthMeMockUtil.mockAuthMeInstance(); + authMeMock = AuthMe.getInstance(); + + permissionsManagerMock = mock(PermissionsManager.class); + when(authMeMock.getPermissionsManager()).thenReturn(permissionsManagerMock); + + Server serverMock = mock(Server.class); + when(authMeMock.getGameServer()).thenReturn(serverMock); + + BukkitScheduler schedulerMock = mock(BukkitScheduler.class); + when(serverMock.getScheduler()).thenReturn(schedulerMock); + when(schedulerMock.runTaskAsynchronously(any(Plugin.class), any(Runnable.class))) + .thenReturn(mock(BukkitTask.class)); + } + + @Test + public void shouldForceSurvivalGameMode() { + // given + Player player = mock(Player.class); + given(permissionsManagerMock.hasPermission(player, "authme.bypassforcesurvival")).willReturn(false); + + // when + Utils.forceGM(player); + + // then + verify(player).setGameMode(GameMode.SURVIVAL); + } + + @Test + public void shouldNotForceGameModeForUserWithBypassPermission() { + // given + Player player = mock(Player.class); + given(permissionsManagerMock.hasPermission(player, "authme.bypassforcesurvival")).willReturn(true); + + // when + Utils.forceGM(player); + + // then + verify(player, never()).setGameMode(GameMode.SURVIVAL); + } + +} From e456203fc6238f0aee052a13710182de4326fa4d Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sun, 22 Nov 2015 01:30:07 +0100 Subject: [PATCH 10/77] Refactor Utils#getOnlinePlayers and add background info --- .../executable/authme/VersionCommand.java | 12 +++-- src/main/java/fr/xephi/authme/util/Utils.java | 51 ++++++++++++++----- .../java/fr/xephi/authme/util/UtilsTest.java | 50 +++++++++++++++--- 3 files changed, 91 insertions(+), 22 deletions(-) diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java index 5367b8b1a..a09fc1b6b 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java @@ -73,12 +73,16 @@ public class VersionCommand extends ExecutableCommand { * * @param minecraftName The Minecraft player name. * - - * @return True if the player is online, false otherwise. */ + * @return True if the player is online, false otherwise. + */ private boolean isPlayerOnline(String minecraftName) { - for(Player player : Bukkit.getOnlinePlayers()) - if(player.getName().equalsIgnoreCase(minecraftName)) + // Note ljacqu 20151121: Generally you should use Utils#getOnlinePlayers to retrieve the list of online players. + // If it's only used in a for-each loop such as here, it's fine. For other purposes, go through the Utils class. + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getName().equalsIgnoreCase(minecraftName)) { return true; + } + } return false; } } diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index aceb6d74c..7e220e3a4 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -17,6 +17,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.io.*; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLConnection; @@ -26,23 +27,20 @@ import java.util.Collections; import java.util.zip.GZIPInputStream; /** + * Utility class for various operations used in the codebase. */ public final class Utils { public static AuthMe plugin; - private static boolean getOnlinePlayersIsCollection; + private static boolean getOnlinePlayersIsCollection = false; private static Method getOnlinePlayers; private static LookupService lookupService; static { plugin = AuthMe.getInstance(); checkGeoIP(); - try { - Method m = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); - getOnlinePlayersIsCollection = m.getReturnType() == Collection.class; - } catch (Exception ignored) { - } + initializeOnlinePlayersIsCollectionField(); } private Utils() { @@ -259,9 +257,6 @@ public final class Utils { }); } - /* - * Used for force player GameMode - */ /** * Force the game mode of a player. * @@ -300,25 +295,57 @@ public final class Utils { } } + /** + * Safe way to retrieve the list of online players from the server. Depending on the implementation + * of the server, either an array of {@link Player} instances is being returned, or a Collection. + * Always use this wrapper to retrieve online players instead of {@link Bukkit#getOnlinePlayers()} directly. + * + * @return collection of online players + * + * @see SpigotMC forum + * @see StackOverflow + */ @SuppressWarnings("unchecked") public static Collection getOnlinePlayers() { if (getOnlinePlayersIsCollection) { return Bukkit.getOnlinePlayers(); } try { + // The lookup of a method via Reflections is rather expensive, so we keep a reference to it if (getOnlinePlayers == null) { getOnlinePlayers = Bukkit.class.getMethod("getOnlinePlayers"); } Object obj = getOnlinePlayers.invoke(null); - if (obj instanceof Collection) { + if (obj instanceof Collection) { return (Collection) obj; + } else if (obj instanceof Player[]) { + return Arrays.asList((Player[]) obj); + } else { + String type = (obj != null) ? obj.getClass().getName() : "null"; + ConsoleLogger.showError("Unknown list of online players of type " + type); } - return Arrays.asList((Player[]) obj); - } catch (Exception ignored) { + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + ConsoleLogger.showError("Could not retrieve list of online players: [" + + e.getClass().getName() + "] " + e.getMessage()); } return Collections.emptyList(); } + /** + * Method run when the Utils class is loaded to verify whether or not the Bukkit + * implementation returns the online players as a Collection. + * + * @see Utils#getOnlinePlayers() + */ + private static void initializeOnlinePlayersIsCollectionField() { + try { + Method method = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); + getOnlinePlayersIsCollection = method.getReturnType() == Collection.class; + } catch (NoSuchMethodException e) { + ConsoleLogger.showError("Error verifying if getOnlinePlayers is a collection! Method doesn't exist"); + } + } + @SuppressWarnings("deprecation") public static Player getPlayer(String name) { name = name.toLowerCase(); diff --git a/src/test/java/fr/xephi/authme/util/UtilsTest.java b/src/test/java/fr/xephi/authme/util/UtilsTest.java index 85aaf4e2a..d095746b3 100644 --- a/src/test/java/fr/xephi/authme/util/UtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/UtilsTest.java @@ -3,7 +3,6 @@ package fr.xephi.authme.util; import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMeMockUtil; import fr.xephi.authme.permission.PermissionsManager; -import org.bukkit.GameMode; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; @@ -12,11 +11,13 @@ import org.bukkit.scheduler.BukkitTask; import org.junit.Before; import org.junit.Test; -import static org.mockito.BDDMockito.given; +import java.lang.reflect.Field; +import java.util.Collection; + +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** @@ -44,7 +45,8 @@ public class UtilsTest { .thenReturn(mock(BukkitTask.class)); } - @Test + // TODO ljacques 20151122: The tests for Utils.forceGM somehow can't be set up with the mocks correctly + /*@Test public void shouldForceSurvivalGameMode() { // given Player player = mock(Player.class); @@ -67,7 +69,43 @@ public class UtilsTest { Utils.forceGM(player); // then - verify(player, never()).setGameMode(GameMode.SURVIVAL); + verify(authMeMock).getPermissionsManager(); + verify(permissionsManagerMock).hasPermission(player, "authme.bypassforcesurvival"); + verify(player, never()).setGameMode(any(GameMode.class)); + }*/ + + @Test + // Note ljacqu 20151122: This is a heavy test setup with Reflections... If it causes trouble, skip it with @Ignore + public void shouldRetrieveListOfOnlinePlayersFromReflectedMethod() { + // given + setField("getOnlinePlayersIsCollection", false); + try { + setField("getOnlinePlayers", UtilsTest.class.getDeclaredMethod("onlinePlayersImpl")); + } catch (NoSuchMethodException e) { + throw new RuntimeException("Cannot initialize test with custom test method", e); + } + + // when + Collection players = Utils.getOnlinePlayers(); + + // then + assertThat(players, hasSize(2)); + } + + private static void setField(String name, Object value) { + try { + Field field = Utils.class.getDeclaredField(name); + field.setAccessible(true); + field.set(null, value); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException("Could not set field '" + name + "'", e); + } + } + + public static Player[] onlinePlayersImpl() { + return new Player[]{ + mock(Player.class), mock(Player.class) + }; } } From 215fedc585e9e66a2dc6048339bd7ab7168dd4b4 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sun, 22 Nov 2015 02:02:49 +0100 Subject: [PATCH 11/77] Minor refactoring in CustomConfiguration / Messages - CustomConfiguration should be abstract - Reduce visibility of internal method - Fix typo in English messages - Remove or replace unnecessary javadoc --- .../authme/settings/CustomConfiguration.java | 19 +++-------------- .../fr/xephi/authme/settings/Messages.java | 21 ++++--------------- src/main/resources/messages/messages_en.yml | 2 +- 3 files changed, 8 insertions(+), 34 deletions(-) diff --git a/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java b/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java index bb4703591..15e651aa5 100644 --- a/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java +++ b/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java @@ -15,13 +15,13 @@ import fr.xephi.authme.ConsoleLogger; /** */ -public class CustomConfiguration extends YamlConfiguration { +public abstract class CustomConfiguration extends YamlConfiguration { private File configFile; /** * Constructor for CustomConfiguration. - * @param file File + * @param file the config file */ public CustomConfiguration(File file) { this.configFile = file; @@ -41,10 +41,6 @@ public class CustomConfiguration extends YamlConfiguration { } } - /** - * Method reLoad. - - * @return boolean */ public boolean reLoad() { boolean out = true; if (!configFile.exists()) { @@ -63,20 +59,11 @@ public class CustomConfiguration extends YamlConfiguration { } } - /** - * Method getConfigFile. - - * @return File */ public File getConfigFile() { return configFile; } - /** - * Method loadResource. - * @param file File - - * @return boolean */ - public boolean loadResource(File file) { + private boolean loadResource(File file) { if (!file.exists()) { try { if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { diff --git a/src/main/java/fr/xephi/authme/settings/Messages.java b/src/main/java/fr/xephi/authme/settings/Messages.java index 46957da61..15b10c4d5 100644 --- a/src/main/java/fr/xephi/authme/settings/Messages.java +++ b/src/main/java/fr/xephi/authme/settings/Messages.java @@ -15,8 +15,8 @@ public class Messages extends CustomConfiguration { /** * Constructor for Messages. - * @param file File - * @param lang String + * @param file the configuration file + * @param lang the code of the language to use */ public Messages(File file, String lang) { super(file); @@ -25,14 +25,10 @@ public class Messages extends CustomConfiguration { this.lang = lang; } - /** - * Method send. - * @param sender CommandSender - * @param msg String - */ public void send(CommandSender sender, String msg) { - if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) + if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) { singleton.reloadMessages(); + } String loc = (String) singleton.get(msg); if (loc == null) { loc = "Error with Translation files, please contact the admin for verify or update translation"; @@ -43,11 +39,6 @@ public class Messages extends CustomConfiguration { } } - /** - * Method send. - * @param msg String - - * @return String[] */ public String[] send(String msg) { if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) { singleton.reloadMessages(); @@ -71,10 +62,6 @@ public class Messages extends CustomConfiguration { return loc; } - /** - * Method getInstance. - - * @return Messages */ public static Messages getInstance() { if (singleton == null) { singleton = new Messages(Settings.messageFile, Settings.messagesLanguage); diff --git a/src/main/resources/messages/messages_en.yml b/src/main/resources/messages/messages_en.yml index 16218f329..dd191d24c 100644 --- a/src/main/resources/messages/messages_en.yml +++ b/src/main/resources/messages/messages_en.yml @@ -52,7 +52,7 @@ email_added: '&2Email address successfully added to your account!' email_confirm: '&cPlease confirm your email address!' email_changed: '&2Email address changed correctly!' email_send: '&2Recovery email sent correctly! Check your email inbox!' -email_exists: '&cA recovery email was already sent! You can discart it and send a new one using the command below:' +email_exists: '&cA recovery email was already sent! You can discard it and send a new one using the command below:' country_banned: '&4Your country is banned from this server!' antibot_auto_enabled: '&4[AntiBotService] AntiBot enabled due to the huge number of connections!' antibot_auto_disabled: '&2[AntiBotService] AntiBot disabled disabled after %m minutes!' From da662afcf46794b69aeb0c6a66ef7b95ed95cd16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Vis=C3=A9e?= Date: Sun, 22 Nov 2015 21:01:31 +0100 Subject: [PATCH 12/77] Created method to get an exception stack trace as a string --- .../fr/xephi/authme/util/StringUtils.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/main/java/fr/xephi/authme/util/StringUtils.java b/src/main/java/fr/xephi/authme/util/StringUtils.java index f0dd3d9ce..c5d34c578 100644 --- a/src/main/java/fr/xephi/authme/util/StringUtils.java +++ b/src/main/java/fr/xephi/authme/util/StringUtils.java @@ -4,6 +4,9 @@ import net.ricecode.similarity.LevenshteinDistanceStrategy; import net.ricecode.similarity.StringSimilarityService; import net.ricecode.similarity.StringSimilarityServiceImpl; +import java.io.PrintWriter; +import java.io.StringWriter; + /** * Utility class for String operations. */ @@ -84,4 +87,22 @@ public class StringUtils { return sb.toString(); } + /** + * Get a full stack trace of an exception as a string. + * + * @param exception The exception. + * + * @return Stack trace as a string. + */ + public static String getStackTrace(Exception exception) { + // Create a string and print writer to print the stack trace into + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + // Print the stack trace into the print writer + exception.printStackTrace(printWriter); + + // Return the result as a string + return stringWriter.toString(); + } } From 69a09aec17218aa45de29714cb562faa47282bb3 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sun, 22 Nov 2015 17:20:23 +0100 Subject: [PATCH 13/77] cleanup --- src/main/java/fr/xephi/authme/AuthMe.java | 1 - src/main/java/fr/xephi/authme/DataManager.java | 1 - src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java | 1 - .../java/fr/xephi/authme/permission/PermissionsManager.java | 2 +- src/main/java/fr/xephi/authme/util/Utils.java | 4 ---- 5 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index fda2bde0d..f78c1ebdc 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -55,7 +55,6 @@ import fr.xephi.authme.settings.OtherAccounts; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Spawn; import fr.xephi.authme.util.Utils; -import net.milkbowl.vault.permission.Permission; import net.minelink.ctplus.CombatTagPlus; /** diff --git a/src/main/java/fr/xephi/authme/DataManager.java b/src/main/java/fr/xephi/authme/DataManager.java index 3d74da41e..d4688e5c5 100644 --- a/src/main/java/fr/xephi/authme/DataManager.java +++ b/src/main/java/fr/xephi/authme/DataManager.java @@ -14,7 +14,6 @@ import org.bukkit.entity.Player; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.Utils; -import net.milkbowl.vault.permission.Permission; /** */ 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 c468a90cb..59dee4688 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java @@ -14,7 +14,6 @@ import fr.xephi.authme.cache.backup.DataFileCache; import fr.xephi.authme.cache.backup.JsonCache; import fr.xephi.authme.events.ResetInventoryEvent; import fr.xephi.authme.settings.Settings; -import org.bukkit.permissions.Permission; /** */ diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java index 9ba1dcf10..a2af1ba4a 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java @@ -500,7 +500,7 @@ public class PermissionsManager { * * @return The name of the primary permission group. Or null. */ - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) + @SuppressWarnings("deprecation") public String getPrimaryGroup(Player player) { // If no permissions system is used, return an empty list if(!isEnabled()) diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index 7e220e3a4..6623c8dc0 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -219,10 +219,6 @@ public final class Utils { && (Settings.getUnrestrictedName.contains(player.getName())); } - private static boolean useGroupSystem() { - return Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty(); - } - /** * Method packCoords. * @param x double From 9ec2d6d059e7e9fe07bcf8d8ace65d13edc9baff Mon Sep 17 00:00:00 2001 From: AuthMe-Team Date: Mon, 23 Nov 2015 20:20:42 +0100 Subject: [PATCH 14/77] Stuff from the common floobits workspace Author: AuthMe-Team --- .floo | 3 + .flooignore | 123 +++ .gitignore | 2 - pom.xml | 2 +- src/main/java/fr/xephi/authme/AuthMe.java | 802 +++++++++--------- .../java/fr/xephi/authme/ConsoleFilter.java | 7 +- .../java/fr/xephi/authme/ConsoleLogger.java | 70 +- .../java/fr/xephi/authme/DataManager.java | 46 +- .../java/fr/xephi/authme/ImageGenerator.java | 12 +- .../java/fr/xephi/authme/Log4JFilter.java | 118 +-- .../java/fr/xephi/authme/PerformBackup.java | 102 ++- .../java/fr/xephi/authme/SendMailSSL.java | 17 +- src/main/java/fr/xephi/authme/api/API.java | 121 ++- src/main/java/fr/xephi/authme/api/NewAPI.java | 88 +- .../xephi/authme/cache/auth/PlayerAuth.java | 280 +++--- .../xephi/authme/cache/auth/PlayerCache.java | 46 +- .../authme/cache/backup/DataFileCache.java | 20 +- .../xephi/authme/cache/backup/JsonCache.java | 140 ++- .../xephi/authme/cache/limbo/LimboCache.java | 60 +- .../xephi/authme/cache/limbo/LimboPlayer.java | 74 +- .../command/CommandArgumentDescription.java | 18 +- .../authme/command/CommandDescription.java | 594 +++++++------ .../xephi/authme/command/CommandHandler.java | 77 +- .../xephi/authme/command/CommandManager.java | 52 +- .../fr/xephi/authme/command/CommandParts.java | 67 +- .../authme/command/CommandPermissions.java | 98 +-- .../authme/command/ExecutableCommand.java | 3 +- .../authme/command/FoundCommandResult.java | 71 +- .../command/executable/HelpCommand.java | 3 +- .../executable/authme/AccountsCommand.java | 11 +- .../executable/authme/AuthMeCommand.java | 7 +- .../authme/ChangePasswordCommand.java | 9 +- .../executable/authme/FirstSpawnCommand.java | 5 +- .../executable/authme/ForceLoginCommand.java | 9 +- .../executable/authme/GetEmailCommand.java | 10 +- .../executable/authme/GetIpCommand.java | 9 +- .../executable/authme/LastLoginCommand.java | 9 +- .../authme/PurgeBannedPlayersCommand.java | 16 +- .../executable/authme/PurgeCommand.java | 28 +- .../authme/PurgeLastPositionCommand.java | 12 +- .../executable/authme/RegisterCommand.java | 14 +- .../executable/authme/ReloadCommand.java | 7 +- .../executable/authme/ResetNameCommand.java | 16 +- .../executable/authme/SetEmailCommand.java | 8 +- .../authme/SetFirstSpawnCommand.java | 10 +- .../executable/authme/SetSpawnCommand.java | 10 +- .../executable/authme/SpawnCommand.java | 10 +- .../authme/SwitchAntiBotCommand.java | 16 +- .../executable/authme/UnregisterCommand.java | 19 +- .../executable/authme/VersionCommand.java | 31 +- .../executable/captcha/CaptchaCommand.java | 17 +- .../changepassword/ChangePasswordCommand.java | 7 +- .../converter/ConverterCommand.java | 97 +-- .../executable/email/AddEmailCommand.java | 5 +- .../executable/email/ChangeEmailCommand.java | 5 +- .../executable/email/RecoverEmailCommand.java | 11 +- .../executable/login/LoginCommand.java | 5 +- .../executable/logout/LogoutCommand.java | 5 +- .../executable/register/RegisterCommand.java | 7 +- .../unregister/UnregisterCommand.java | 14 +- .../authme/command/help/HelpPrinter.java | 93 +- .../authme/command/help/HelpProvider.java | 55 +- .../authme/command/help/HelpSyntaxHelper.java | 22 +- .../authme/converter/CrazyLoginConverter.java | 22 +- .../fr/xephi/authme/converter/FlatToSql.java | 10 +- .../xephi/authme/converter/FlatToSqlite.java | 36 +- .../authme/converter/ForceFlatToSqlite.java | 5 +- .../authme/converter/RakamakConverter.java | 28 +- .../authme/converter/RoyalAuthConverter.java | 9 +- .../authme/converter/RoyalAuthYamlReader.java | 15 +- .../fr/xephi/authme/converter/SqlToFlat.java | 9 +- .../authme/converter/vAuthConverter.java | 5 +- .../authme/converter/vAuthFileReader.java | 33 +- .../authme/converter/xAuthConverter.java | 5 +- .../xephi/authme/converter/xAuthToFlat.java | 40 +- .../authme/datasource/CacheDataSource.java | 161 ++-- .../xephi/authme/datasource/DataSource.java | 364 ++++---- .../authme/datasource/DatabaseCalls.java | 150 ++-- .../fr/xephi/authme/datasource/FlatFile.java | 157 ++-- .../fr/xephi/authme/datasource/MySQL.java | 189 +++-- .../fr/xephi/authme/datasource/SQLite.java | 175 ++-- .../events/AuthMeAsyncPreLoginEvent.java | 20 +- .../authme/events/AuthMeTeleportEvent.java | 32 +- .../fr/xephi/authme/events/CustomEvent.java | 37 +- .../events/FirstSpawnTeleportEvent.java | 34 +- .../fr/xephi/authme/events/LoginEvent.java | 52 +- .../fr/xephi/authme/events/LogoutEvent.java | 32 +- .../events/PasswordEncryptionEvent.java | 54 +- .../authme/events/ProtectInventoryEvent.java | 29 +- .../authme/events/RegisterTeleportEvent.java | 32 +- .../authme/events/ResetInventoryEvent.java | 8 +- .../authme/events/RestoreInventoryEvent.java | 10 +- .../authme/events/SpawnTeleportEvent.java | 43 +- .../xephi/authme/hooks/BungeeCordMessage.java | 14 +- .../java/fr/xephi/authme/hooks/EssSpawn.java | 15 +- .../authme/listener/AuthMeBlockListener.java | 8 +- .../authme/listener/AuthMeEntityListener.java | 29 +- .../AuthMeInventoryPacketAdapter.java | 25 +- .../authme/listener/AuthMePlayerListener.java | 99 ++- .../listener/AuthMePlayerListener16.java | 7 +- .../listener/AuthMePlayerListener18.java | 7 +- .../authme/listener/AuthMeServerListener.java | 23 +- .../java/fr/xephi/authme/modules/Module.java | 38 +- .../xephi/authme/modules/ModuleManager.java | 37 +- .../authme/permission/PermissionsManager.java | 159 ++-- .../fr/xephi/authme/process/Management.java | 35 +- .../process/email/AsyncChangeEmail.java | 21 +- .../authme/process/join/AsyncronousJoin.java | 36 +- .../process/login/AsyncronousLogin.java | 42 +- .../login/ProcessSyncronousPlayerLogin.java | 33 +- .../process/logout/AsyncronousLogout.java | 12 +- .../logout/ProcessSyncronousPlayerLogout.java | 15 +- .../authme/process/quit/AsyncronousQuit.java | 18 +- .../quit/ProcessSyncronousPlayerQuit.java | 15 +- .../process/register/AsyncRegister.java | 34 +- .../register/ProcessSyncEmailRegister.java | 11 +- .../ProcessSyncronousPasswordRegister.java | 16 +- .../unregister/AsyncronousUnregister.java | 35 +- .../xephi/authme/security/HashAlgorithm.java | 6 +- .../authme/security/PasswordSecurity.java | 53 +- .../xephi/authme/security/RandomString.java | 7 +- .../xephi/authme/security/crypts/BCRYPT.java | 378 ++++----- .../authme/security/crypts/BCRYPT2Y.java | 24 +- .../authme/security/crypts/CRAZYCRYPT1.java | 53 +- .../authme/security/crypts/CryptPBKDF2.java | 28 +- .../security/crypts/CryptPBKDF2Django.java | 29 +- .../authme/security/crypts/DOUBLEMD5.java | 64 +- .../security/crypts/EncryptionMethod.java | 12 +- .../fr/xephi/authme/security/crypts/IPB3.java | 70 +- .../xephi/authme/security/crypts/JOOMLA.java | 66 +- .../fr/xephi/authme/security/crypts/MD5.java | 64 +- .../xephi/authme/security/crypts/MD5VB.java | 66 +- .../fr/xephi/authme/security/crypts/MYBB.java | 70 +- .../xephi/authme/security/crypts/PHPBB.java | 192 +++-- .../authme/security/crypts/PHPFUSION.java | 63 +- .../authme/security/crypts/PLAINTEXT.java | 24 +- .../authme/security/crypts/ROYALAUTH.java | 32 +- .../authme/security/crypts/SALTED2MD5.java | 70 +- .../authme/security/crypts/SALTEDSHA512.java | 70 +- .../fr/xephi/authme/security/crypts/SHA1.java | 64 +- .../xephi/authme/security/crypts/SHA256.java | 66 +- .../xephi/authme/security/crypts/SHA512.java | 64 +- .../fr/xephi/authme/security/crypts/SMF.java | 64 +- .../fr/xephi/authme/security/crypts/WBB3.java | 70 +- .../fr/xephi/authme/security/crypts/WBB4.java | 24 +- .../authme/security/crypts/WHIRLPOOL.java | 154 ++-- .../authme/security/crypts/WORDPRESS.java | 48 +- .../xephi/authme/security/crypts/XAUTH.java | 53 +- .../fr/xephi/authme/security/crypts/XF.java | 41 +- .../authme/security/pbkdf2/BinTools.java | 34 +- .../authme/security/pbkdf2/MacBasedPRF.java | 30 +- .../xephi/authme/security/pbkdf2/PBKDF2.java | 51 +- .../authme/security/pbkdf2/PBKDF2Engine.java | 488 ++++++----- .../security/pbkdf2/PBKDF2Formatter.java | 20 +- .../security/pbkdf2/PBKDF2HexFormatter.java | 14 +- .../security/pbkdf2/PBKDF2Parameters.java | 70 +- .../fr/xephi/authme/security/pbkdf2/PRF.java | 26 +- .../authme/settings/CustomConfiguration.java | 12 +- .../fr/xephi/authme/settings/Messages.java | 20 +- .../xephi/authme/settings/OtherAccounts.java | 38 +- .../fr/xephi/authme/settings/Settings.java | 403 +++++---- .../java/fr/xephi/authme/settings/Spawn.java | 53 +- .../xephi/authme/task/ChangePasswordTask.java | 13 +- .../fr/xephi/authme/task/MessageTask.java | 13 +- .../fr/xephi/authme/task/TimeoutTask.java | 14 +- .../java/fr/xephi/authme/util/GeoLiteAPI.java | 96 +++ .../java/fr/xephi/authme/util/Profiler.java | 50 +- .../fr/xephi/authme/util/StringUtils.java | 33 +- src/main/java/fr/xephi/authme/util/Utils.java | 95 +-- 169 files changed, 5161 insertions(+), 4806 deletions(-) create mode 100644 .floo create mode 100644 .flooignore create mode 100644 src/main/java/fr/xephi/authme/util/GeoLiteAPI.java diff --git a/.floo b/.floo new file mode 100644 index 000000000..b0f2c28e0 --- /dev/null +++ b/.floo @@ -0,0 +1,3 @@ +{ + "url": "https://floobits.com/AuthMe-Team/AuthMeReloaded" +} \ No newline at end of file diff --git a/.flooignore b/.flooignore new file mode 100644 index 000000000..e9c355d00 --- /dev/null +++ b/.flooignore @@ -0,0 +1,123 @@ +### Java ### +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +#*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties + + +### Eclipse ### +*.pydevproject +.metadata +.gradle +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath + +# Eclipse Core +.project + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# PDT-specific +.buildpath + +# sbteclipse plugin +.target + +# TeXlipse plugin +.texlipse + + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties + + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +nbactions.xml +nb-configuration.xml +.nb-gradle/ diff --git a/.gitignore b/.gitignore index a0348ece7..e9c355d00 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,3 @@ -# Created by https://www.gitignore.io - ### Java ### *.class diff --git a/pom.xml b/pom.xml index 1a9a64396..9c19232fd 100644 --- a/pom.xml +++ b/pom.xml @@ -46,7 +46,7 @@ UTF-8 fr.xephi.authme.AuthMe - CustomBuild + 100 [Xephi, sgdc3, DNx5, timvisee, games647, ljacqu] diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index f78c1ebdc..7630b99e2 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -1,18 +1,31 @@ package fr.xephi.authme; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.net.URLConnection; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; - +import com.earth2me.essentials.Essentials; +import com.onarandombox.MultiverseCore.MultiverseCore; +import fr.xephi.authme.api.API; +import fr.xephi.authme.api.NewAPI; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +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.command.CommandHandler; +import fr.xephi.authme.converter.Converter; +import fr.xephi.authme.converter.ForceFlatToSqlite; +import fr.xephi.authme.datasource.*; +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.permission.PermissionsManager; +import fr.xephi.authme.process.Management; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.OtherAccounts; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.Spawn; +import fr.xephi.authme.util.GeoLiteAPI; +import fr.xephi.authme.util.Utils; +import net.minelink.ctplus.CombatTagPlus; import org.apache.logging.log4j.LogManager; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -27,99 +40,148 @@ import org.bukkit.scheduler.BukkitTask; import org.mcstats.Metrics; import org.mcstats.Metrics.Graph; -import com.earth2me.essentials.Essentials; -import com.onarandombox.MultiverseCore.MultiverseCore; - -import fr.xephi.authme.api.API; -import fr.xephi.authme.api.NewAPI; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -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.command.CommandHandler; -import fr.xephi.authme.converter.Converter; -import fr.xephi.authme.converter.ForceFlatToSqlite; -import fr.xephi.authme.datasource.CacheDataSource; -import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.datasource.DatabaseCalls; -import fr.xephi.authme.datasource.FlatFile; -import fr.xephi.authme.datasource.MySQL; -import fr.xephi.authme.datasource.SQLite; -import fr.xephi.authme.hooks.BungeeCordMessage; -import fr.xephi.authme.hooks.EssSpawn; -import fr.xephi.authme.modules.ModuleManager; -import fr.xephi.authme.process.Management; -import fr.xephi.authme.settings.Messages; -import fr.xephi.authme.settings.OtherAccounts; -import fr.xephi.authme.settings.Settings; -import fr.xephi.authme.settings.Spawn; -import fr.xephi.authme.util.Utils; -import net.minelink.ctplus.CombatTagPlus; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; /** * The AuthMe main class. */ public class AuthMe extends JavaPlugin { - /** Defines the name of the plugin. */ - // TODO: Create a getter method for this constant, and make it private - public static final String PLUGIN_NAME = "AuthMeReloaded"; - /** Defines the current AuthMeReloaded version name. */ + /** + * Defines the name of the plugin. + */ + private static final String PLUGIN_NAME = "AuthMeReloaded"; + /** + * Defines the current AuthMeReloaded version name. + */ private static final String PLUGIN_VERSION_NAME = "5.1-SNAPSHOT"; - /** Defines the current AuthMeReloaded version code. */ - // Increase this number by one when an update is released + /** + * Defines the current AuthMeReloaded version code. + */ + // TODO: Increase this number by one when an update is release + // TODO: Increase the count via maven private static final int PLUGIN_VERSION_CODE = 100; private static AuthMe plugin; private static Server server; - private Logger authmeLogger; - - // TODO: Move this to a better place! -- timvisee - private CommandHandler commandHandler = null; - private PermissionsManager permsMan = null; public Management management; public NewAPI api; public SendMailSSL mail; - private Settings settings; - private Messages m; public DataManager dataManager; public DataSource database; - private JsonCache playerBackup; public OtherAccounts otherAccounts; public Location essentialsSpawn; - public boolean antibotMod = false; - public boolean delayedAntiBot = true; - // Hooks TODO: move into modules public Essentials ess; public MultiverseCore multiverse; public CombatTagPlus combatTagPlus; public AuthMeInventoryPacketAdapter inventoryProtector; - - // Module manager - private ModuleManager moduleManager; - - // TODO: Create Manager for fields below + // Random data maps and stuff + // TODO: Create Manager for this public ConcurrentHashMap sessions = new ConcurrentHashMap<>(); public ConcurrentHashMap captcha = new ConcurrentHashMap<>(); public ConcurrentHashMap cap = new ConcurrentHashMap<>(); public ConcurrentHashMap realIp = new ConcurrentHashMap<>(); - - // In case we need to cache PlayerAuths, prevent connection before it's done + // AntiBot Status + // TODO: Create Manager for this + public boolean antiBotMod = false; + public boolean delayedAntiBot = true; + private CommandHandler commandHandler = null; + private PermissionsManager permsMan = null; + private Settings settings; + private Messages messages; + private JsonCache playerBackup; + private ModuleManager moduleManager; + // If cache is enabled, prevent any connection before the players data caching is completed. + // TODO: Move somewhere private boolean canConnect = true; /** - * Method canConnect. - - * @return boolean */ + * Returns the plugin's instance. + * + * @return AuthMe + */ + public static AuthMe getInstance() { + return plugin; + } + + /** + * Get the plugin's name. + * + * @return Plugin name. + */ + public static String getPluginName() { + return PLUGIN_NAME; + } + + /** + * Get the current installed AuthMeReloaded version name. + * + * @return The version name of the currently installed AuthMeReloaded instance. + */ + public static String getVersionName() { + return PLUGIN_VERSION_NAME; + } + + /** + * Get the current installed AuthMeReloaded version code. + * + * @return The version code of the currently installed AuthMeReloaded instance. + */ + public static int getVersionCode() { + return PLUGIN_VERSION_CODE; + } + + /** + * Returns the plugin's Settings. + * + * @return Settings + */ + public Settings getSettings() { + return settings; + } + + /** + * Returns the Messages instance. + * + * @return Messages + */ + + public Messages getMessages() { + return messages; + } + + /** + * Set the Messages instance. + * + * @param m Messages + */ + public void setMessages(Messages m) { + this.messages = m; + } + + /** + * Returns if players are allowed to join the server. + * + * @return boolean + */ public boolean canConnect() { return canConnect; } /** - * Method setCanConnect. + * Define if players are allowed to join the server. + * * @param canConnect boolean */ public void setCanConnect(boolean canConnect) { @@ -127,69 +189,246 @@ public class AuthMe extends JavaPlugin { } /** - * Method getInstance. - - * @return AuthMe */ - public static AuthMe getInstance() { - return plugin; - } - - /** - * Method getSettings. - - * @return Settings */ - public Settings getSettings() { - return settings; - } - - /** - * Method setMessages. - * @param m Messages - */ - public void setMessages(Messages m) { - this.m = m; - } - - /** - * Method getMessages. - - * @return Messages */ - public Messages getMessages() { - return m; - } - - /** - * Method onEnable. + * Method called when the server enables the plugin. + * * @see org.bukkit.plugin.Plugin#onEnable() */ @Override public void onEnable() { - // Set the Instance + // Set various instances server = getServer(); - authmeLogger = Logger.getLogger("AuthMe"); plugin = this; // Set up the permissions manager setupPermissionsManager(); // Set up and initialize the command handler + setupCommandHandler(); + + // Set up the module manager + setupModuleManager(); + + // Load settings and custom configurations, if it fails, stop the server due to security reasons. + if (loadSettings()) { + server.shutdown(); + setEnabled(false); + return; + } + + // Setup otherAccounts file + this.otherAccounts = OtherAccounts.getInstance(); + + // Setup messages + this.messages = Messages.getInstance(); + + // Set up Metrics + setupMetrics(); + + // Set console filter + setupConsoleFilter(); + + // AntiBot delay + setupAntiBotDelay(); + + // Download and load GeoIp.dat file if absent + GeoLiteAPI.isDataAvailable(); + + // Set up the mail API + setupMailApi(); + + // Hooks + // Check Combat Tag Plus Version + checkCombatTagPlus(); + + // Check Multiverse + checkMultiverse(); + + // Check Essentials + checkEssentials(); + + // Check if the protocollib is available. If so we could listen for + // inventory protection + checkProtocolLib(); + // End of Hooks + + // Do a backup on start + new PerformBackup(plugin).doBackup(PerformBackup.BackupCause.START); + + // Connect to the database and setup tables + try { + setupDatabase(); + } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError(e.getMessage()); + ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!"); + stopOrUnload(); + return; + } + + // Setup the inventory backup + playerBackup = new JsonCache(); + + // Set the DataManager + dataManager = new DataManager(this); + + // Set up the new API + setupApi(); + + // Set up the management + management = new Management(this); + + // Set up the Bungeecord hook + setupBungeecordHook(); + + // Reload support hook + reloadSupportHook(); + + // Register event listeners + registerEventListeners(); + + // Purge on start if enabled + autoPurge(); + + // Start Email recall task if needed + recallEmail(); + + // Show settings warnings + showSettingsWarnings(); + + // Sponsor messages + ConsoleLogger.info("AuthMe hooks perfectly with the VeryGames server hosting!"); + ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt."); + ConsoleLogger.info("Do you want a good game server? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!"); + + // Successful message + ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!"); + } + + /** + * Set up the module manager. + */ + private void setupModuleManager() { + // TODO: Clean this up! + // TODO: split the plugin in more modules + // TODO: log number of loaded modules + + // Define the module manager instance + moduleManager = new ModuleManager(this); + + // Load the modules + // int loaded = moduleManager.loadModules(); + } + + /** + * Set up the mail API, if enabled. + */ + private void setupMailApi() { + // Make sure the mail API is enabled + if (Settings.getmailAccount.isEmpty() || Settings.getmailPassword.isEmpty()) { + return; + } + + // Set up the mail API + this.mail = new SendMailSSL(this); + } + + /** + * Show the settings warnings, for various risky settings. + */ + private void showSettingsWarnings() { + // Force single session disabled + if (!Settings.isForceSingleSessionEnabled) { + ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); + } + + // Session timeout disabled + if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) { + ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!"); + } + } + + /** + * Register all event listeners. + */ + private void registerEventListeners() { + // Get the plugin manager instance + PluginManager pluginManager = server.getPluginManager(); + + // Register event listeners + pluginManager.registerEvents(new AuthMePlayerListener(this), this); + pluginManager.registerEvents(new AuthMeBlockListener(this), this); + pluginManager.registerEvents(new AuthMeEntityListener(this), this); + pluginManager.registerEvents(new AuthMeServerListener(this), this); + + // Try to register 1.6 player listeners + try { + Class.forName("org.bukkit.event.player.PlayerEditBookEvent"); + pluginManager.registerEvents(new AuthMePlayerListener16(this), this); + } catch (ClassNotFoundException ignore) { + } + + // Try to register 1.8 player listeners + try { + Class.forName("org.bukkit.event.player.PlayerInteractAtEntityEvent"); + pluginManager.registerEvents(new AuthMePlayerListener18(this), this); + } catch (ClassNotFoundException ignore) { + } + } + + private void reloadSupportHook() { + if (database != null) { + int playersOnline = Utils.getOnlinePlayers().size(); + if (playersOnline < 1) { + database.purgeLogged(); + } else if (Settings.reloadSupport) { + for (PlayerAuth auth : database.getLoggedPlayers()) { + if (auth == null) { + continue; + } + auth.setLastLogin(new Date().getTime()); + database.updateSession(auth); + PlayerCache.getInstance().addPlayer(auth); + } + } + } + } + + /** + * Set up the Bungecoord hook. + */ + private void setupBungeecordHook() { + if (Settings.bungee) { + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); + } + } + + /** + * Set up the API. This sets up the new and the old API. + */ + @SuppressWarnings("deprecation") + private void setupApi() { + // Set up the API + api = new NewAPI(this); + + // Setup the old deprecated API + new API(this); + } + + /** + * Set up the command handler. + */ + private void setupCommandHandler() { this.commandHandler = new CommandHandler(false); this.commandHandler.init(); + } - // TODO: split the plugin in more modules - moduleManager = new ModuleManager(this); - @SuppressWarnings("unused") - int loaded = moduleManager.loadModules(); - - // TODO: remove vault as hard dependency - PluginManager pm = server.getPluginManager(); - - // Setup the Logger - if (authmeLogger == null) - authmeLogger = this.getLogger(); - else authmeLogger.setParent(this.getLogger()); - - // Load settings and custom configurations + /** + * Load the plugin's settings. + * + * @return True on success, false on failure. + */ + private boolean loadSettings() { // TODO: new configuration style (more files) try { settings = new Settings(this); @@ -198,16 +437,48 @@ public class AuthMe extends JavaPlugin { ConsoleLogger.writeStackTrace(e); ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!"); server.shutdown(); - return; + return true; } + return false; + } - // Setup otherAccounts file - otherAccounts = OtherAccounts.getInstance(); + /** + * Set up the antibot delay. + */ + private void setupAntiBotDelay() { + if (Settings.enableAntiBot) { + Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + @Override + public void run() { + delayedAntiBot = false; + } + }, 2400); + } + } - // Setup messages - m = Messages.getInstance(); + /** + * Set up the console filter. + */ + private void setupConsoleFilter() { + if (Settings.removePassword) { + ConsoleFilter filter = new ConsoleFilter(); + ConsoleLogger.getLogger().setFilter(filter); + Bukkit.getLogger().setFilter(filter); + Logger.getLogger("Minecraft").setFilter(filter); + // Set Log4J Filter + try { + Class.forName("org.apache.logging.log4j.core.Filter"); + setLog4JFilter(); + } catch (ClassNotFoundException | NoClassDefFoundError e) { + ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); + } + } + } - // Start the metrics service + /** + * Set up Metrics. + */ + private void setupMetrics() { try { Metrics metrics = new Metrics(this); Graph messagesLanguage = metrics.createGraph("Messages language"); @@ -238,155 +509,14 @@ public class AuthMe extends JavaPlugin { ConsoleLogger.writeStackTrace(e); ConsoleLogger.showError("Can't start Metrics! The plugin will work anyway..."); } - - // Set Console Filter - if (Settings.removePassword) { - ConsoleFilter filter = new ConsoleFilter(); - this.getLogger().setFilter(filter); - Bukkit.getLogger().setFilter(filter); - Logger.getLogger("Minecraft").setFilter(filter); - authmeLogger.setFilter(filter); - // Set Log4J Filter - try { - Class.forName("org.apache.logging.log4j.core.Filter"); - setLog4JFilter(); - } catch (ClassNotFoundException | NoClassDefFoundError e) { - ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); - } - } - - // AntiBot delay - if (Settings.enableAntiBot) { - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { - - @Override - public void run() { - delayedAntiBot = false; - } - }, 2400); - } - - // Download GeoIp.dat file - Utils.checkGeoIP(); - - // Load MailApi if needed - if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty()) { - mail = new SendMailSSL(this); - } - - // Check Combat Tag Plus Version - checkCombatTagPlus(); - - // Check Multiverse - checkMultiverse(); - - // Check Essentials - checkEssentials(); - - // Check if the protocollib is available. If so we could listen for - // inventory protection - checkProtocolLib(); - - // Do backup on start if enabled - if (Settings.isBackupActivated && Settings.isBackupOnStart) { - // Do backup and check return value! - if (new PerformBackup(this).doBackup()) { - ConsoleLogger.info("Backup performed correctly"); - } else { - ConsoleLogger.showError("Error while performing the backup!"); - } - } - - // Connect to the database and setup tables - try { - setupDatabase(); - } catch (Exception e) { - ConsoleLogger.writeStackTrace(e); - ConsoleLogger.showError(e.getMessage()); - ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!"); - stopOrUnload(); - return; - } - - // Setup the inventory backup - playerBackup = new JsonCache(); - - // Set the DataManager - dataManager = new DataManager(this); - - // Setup the new API - api = new NewAPI(this); - // Setup the old deprecated API - new API(this); - - // Setup Management - management = new Management(this); - - // Bungeecord hook - if (Settings.bungee) { - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); - } - - // Reload support hook - if (database != null) { - int playersOnline = Utils.getOnlinePlayers().size(); - if (playersOnline < 1) { - database.purgeLogged(); - } else if (Settings.reloadSupport) { - for (PlayerAuth auth : database.getLoggedPlayers()) { - if (auth == null) - continue; - auth.setLastLogin(new Date().getTime()); - database.updateSession(auth); - PlayerCache.getInstance().addPlayer(auth); - } - } - } - - // Register events - pm.registerEvents(new AuthMePlayerListener(this), this); - // Try to register 1.6 player listeners - try { - Class.forName("org.bukkit.event.player.PlayerEditBookEvent"); - pm.registerEvents(new AuthMePlayerListener16(this), this); - } catch (ClassNotFoundException ignore) { - } - // Try to register 1.8 player listeners - try { - Class.forName("org.bukkit.event.player.PlayerInteractAtEntityEvent"); - pm.registerEvents(new AuthMePlayerListener18(this), this); - } catch (ClassNotFoundException ignore) { - } - pm.registerEvents(new AuthMeBlockListener(this), this); - pm.registerEvents(new AuthMeEntityListener(this), this); - pm.registerEvents(new AuthMeServerListener(this), this); - - // Purge on start if enabled - autoPurge(); - - // Start Email recall task if needed - recallEmail(); - - // Configuration Security Warnings - if (!Settings.isForceSingleSessionEnabled) { - ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); - } - if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) { - ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!"); - } - - // Sponsor messages - ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!"); - ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt."); - ConsoleLogger.info("Do you want a good gameserver? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!"); - - // Successful message - ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!"); } + // Show the exception message and stop/unload the server/plugin as defined + // in the configuration + /** * Method onDisable. + * * @see org.bukkit.plugin.Plugin#onDisable() */ @Override @@ -400,12 +530,7 @@ public class AuthMe extends JavaPlugin { } // Do backup on stop if enabled - if (Settings.isBackupActivated && Settings.isBackupOnStop) { - boolean Backup = new PerformBackup(this).doBackup(); - if (Backup) - ConsoleLogger.info("Backup performed correctly."); - else ConsoleLogger.showError("Error while performing the backup!"); - } + new PerformBackup(plugin).doBackup(PerformBackup.BackupCause.STOP); // Unload modules moduleManager.unloadModules(); @@ -419,6 +544,8 @@ public class AuthMe extends JavaPlugin { ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!"); } + // Initialize and setup the database + // Stop/unload the server/plugin as defined in the configuration public void stopOrUnload() { if (Settings.isStopEnabled) { @@ -429,22 +556,9 @@ public class AuthMe extends JavaPlugin { } } - // Show the exception message and stop/unload the server/plugin as defined - // in the configuration - /** - * Method stopOrUnload. - * @param e Exception - */ - public void stopOrUnload(Exception e) { - ConsoleLogger.showError(e.getMessage()); - stopOrUnload(); - } - - // Initialize and setup the database /** * Method setupDatabase. - - * @throws Exception */ + */ public void setupDatabase() throws Exception { if (database != null) database.close(); @@ -584,49 +698,6 @@ public class AuthMe extends JavaPlugin { } } - /** - * Check if a player/command sender have a permission - * - * @deprecated Deprecated since v5.1. Use the permissions manager instead! See: getPermissionsManager() - * - * @param player - * @param perm - - - * @return boolean */ - public boolean authmePermissible(Player player, String perm) { - // New code: - return getPermissionsManager().hasPermission(player, perm); - - // Legacy code: - /*if (player.hasPermission(perm)) { - return true; - } else if (permission != null) { - return permission.playerHas(player, perm); - } - return false;*/ - } - - /** - * @deprecated Deprecated since v5.1. Use the permissions manager instead! See: getPermissionsManager() - * - * @param sender - * @param perm - - - * @return boolean */ - public boolean authmePermissible(CommandSender sender, String perm) { - // Handle players with the permissions manager - if(sender instanceof Player) { - // Get the player instance - Player player = (Player) sender; - - // Check whether the player has permission, return the result - return getPermissionsManager().hasPermission(player, perm); - } - return false; - } - // Save Player Data public void savePlayer(Player player) { if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) { @@ -754,12 +825,12 @@ public class AuthMe extends JavaPlugin { } public void switchAntiBotMod(boolean mode) { - this.antibotMod = mode; + this.antiBotMod = mode; Settings.switchAntiBotMod(mode); } public boolean getAntiBotModMode() { - return this.antibotMod; + return this.antiBotMod; } private void recallEmail() { @@ -776,7 +847,7 @@ public class AuthMe extends JavaPlugin { if (PlayerCache.getInstance().isAuthenticated(name)) { String email = database.getAuth(name).getEmail(); if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) - m.send(player, "add_email"); + messages.send(player, "add_email"); } } } @@ -784,7 +855,6 @@ public class AuthMe extends JavaPlugin { }, 1, 1200 * Settings.delayRecall); } - public String replaceAllInfos(String message, Player player) { int playersOnline = Utils.getOnlinePlayers().size(); message = message.replace("&", "\u00a7"); @@ -796,11 +866,10 @@ public class AuthMe extends JavaPlugin { message = message.replace("{WORLD}", player.getWorld().getName()); message = message.replace("{SERVER}", server.getServerName()); message = message.replace("{VERSION}", server.getBukkitVersion()); - message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player))); + message = message.replace("{COUNTRY}", GeoLiteAPI.getCountryName(getIP(player))); return message; } - public String getIP(Player player) { String name = player.getName().toLowerCase(); String ip = player.getAddress().getAddress().getHostAddress(); @@ -814,7 +883,6 @@ public class AuthMe extends JavaPlugin { return ip; } - public boolean isLoggedIp(String name, String ip) { int count = 0; for (Player player : Utils.getOnlinePlayers()) { @@ -824,7 +892,6 @@ public class AuthMe extends JavaPlugin { return count >= Settings.getMaxLoginPerIp; } - public boolean hasJoinedIp(String name, String ip) { int count = 0; for (Player player : Utils.getOnlinePlayers()) { @@ -834,7 +901,6 @@ public class AuthMe extends JavaPlugin { return count >= Settings.getMaxJoinPerIp; } - public ModuleManager getModuleManager() { return moduleManager; } @@ -843,7 +909,6 @@ public class AuthMe extends JavaPlugin { * Gets a player's real IP through VeryGames method. * * @param player the player to process - * * @return the real IP of the player */ @Deprecated @@ -864,19 +929,6 @@ public class AuthMe extends JavaPlugin { return realIP; } - - @Deprecated - public String getCountryCode(String ip) { - return Utils.getCountryCode(ip); - } - - - @Deprecated - public String getCountryName(String ip) { - return Utils.getCountryName(ip); - } - - public CommandHandler getCommandHandler() { return this.commandHandler; } @@ -884,20 +936,15 @@ public class AuthMe extends JavaPlugin { /** * Handle Bukkit commands. * - * @param sender - * The command sender (Bukkit). - * @param cmd - * The command (Bukkit). - * @param commandLabel - * The command label (Bukkit). - * @param args - * The command arguments (Bukkit). - * - * @return True if the command was executed, false otherwise. + * @param sender The command sender (Bukkit). + * @param cmd The command (Bukkit). + * @param commandLabel The command label (Bukkit). + * @param args The command arguments (Bukkit). + * @return True if the command was executed, false otherwise. */ @Override public boolean onCommand(CommandSender sender, Command cmd, - String commandLabel, String[] args) { + String commandLabel, String[] args) { // Get the command handler, and make sure it's valid CommandHandler commandHandler = this.getCommandHandler(); if (commandHandler == null) @@ -908,37 +955,20 @@ public class AuthMe extends JavaPlugin { } /** - * Get the current installed AuthMeReloaded version name. - * - * @return The version name of the currently installed AuthMeReloaded - * instance. + * Returns the management instance. */ - public static String getVersionName() { - return PLUGIN_VERSION_NAME; - } - - /** - * Get the current installed AuthMeReloaded version code. - * - * @return The version code of the currently installed AuthMeReloaded - * instance. - */ - public static int getVersionCode() { - return PLUGIN_VERSION_CODE; - } - - /** Returns the management instance. */ public Management getManagement() { return management; } /** - * Returns the server instance running this plugin. Use this method in favor of - * {@link AuthMe#getServer()} for testability purposes. + * Returns the server instance running this plugin. Use this method in favor of {@link + * AuthMe#getServer()} for testability purposes. * * @return the server instance */ public Server getGameServer() { return super.getServer(); } + } diff --git a/src/main/java/fr/xephi/authme/ConsoleFilter.java b/src/main/java/fr/xephi/authme/ConsoleFilter.java index 668ff2066..09da4983a 100644 --- a/src/main/java/fr/xephi/authme/ConsoleFilter.java +++ b/src/main/java/fr/xephi/authme/ConsoleFilter.java @@ -4,6 +4,7 @@ import java.util.logging.Filter; import java.util.logging.LogRecord; /** + * Console filter Class * * @author Xephi59 * @version $Revision: 1.0 $ @@ -15,10 +16,10 @@ public class ConsoleFilter implements Filter { /** * Method isLoggable. + * * @param record LogRecord - - - * @return boolean * @see java.util.logging.Filter#isLoggable(LogRecord) */ + * @return boolean * @see java.util.logging.Filter#isLoggable(LogRecord) + */ @Override public boolean isLoggable(LogRecord record) { try { diff --git a/src/main/java/fr/xephi/authme/ConsoleLogger.java b/src/main/java/fr/xephi/authme/ConsoleLogger.java index 1e58e9138..0bbacbfce 100644 --- a/src/main/java/fr/xephi/authme/ConsoleLogger.java +++ b/src/main/java/fr/xephi/authme/ConsoleLogger.java @@ -1,5 +1,9 @@ package fr.xephi.authme; +import com.google.common.base.Throwables; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.util.StringUtils; + import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; @@ -8,12 +12,8 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Logger; -import com.google.common.base.Throwables; - -import fr.xephi.authme.api.NewAPI; -import fr.xephi.authme.settings.Settings; - /** + * The plugin's static logger. */ public class ConsoleLogger { @@ -21,42 +21,52 @@ public class ConsoleLogger { private static final DateFormat df = new SimpleDateFormat("[MM-dd HH:mm:ss]"); /** - * Method info. + * Returns the plugin's logger. + * + * @return Logger + */ + public static Logger getLogger() { + return log; + } + + /** + * Print an info message. + * * @param message String */ public static void info(String message) { - log.info("[AuthMe] " + message); - if (Settings.useLogging) { - String dateTime; - synchronized (df) { - dateTime = df.format(new Date()); - } - writeLog(dateTime + " " + message); + log.info(message); + if (!Settings.useLogging) { + return; } + writeLog("" + message); } /** - * Method showError. + * Print an error message. + * * @param message String */ public static void showError(String message) { - log.warning("[AuthMe] " + message); - if (Settings.useLogging) { - String dateTime; - synchronized (df) { - dateTime = df.format(new Date()); - } - writeLog(dateTime + " ERROR: " + message); + log.warning(message); + if (!Settings.useLogging) { + return; } + writeLog("ERROR: " + message); } /** - * Method writeLog. + * Write a message into the log file with a TimeStamp. + * * @param message String */ - public static void writeLog(String message) { + private static void writeLog(String message) { + String dateTime; + synchronized (df) { + dateTime = df.format(new Date()); + } try { - Files.write(Settings.LOG_FILE.toPath(), (message + NewAPI.newline).getBytes(), + Files.write(Settings.LOG_FILE.toPath(), (dateTime + ": " + message + StringUtils.newline).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE); } catch (IOException ignored) { @@ -64,16 +74,14 @@ public class ConsoleLogger { } /** - * Method writeStackTrace. + * Write a StackTrace into the log. + * * @param ex Exception */ public static void writeStackTrace(Exception ex) { - if (Settings.useLogging) { - String dateTime; - synchronized (df) { - dateTime = df.format(new Date()); - } - writeLog(dateTime + " " + Throwables.getStackTraceAsString(ex)); + if (!Settings.useLogging) { + return; } + writeLog("" + Throwables.getStackTraceAsString(ex)); } } diff --git a/src/main/java/fr/xephi/authme/DataManager.java b/src/main/java/fr/xephi/authme/DataManager.java index d4688e5c5..58bdca4dc 100644 --- a/src/main/java/fr/xephi/authme/DataManager.java +++ b/src/main/java/fr/xephi/authme/DataManager.java @@ -1,5 +1,12 @@ package fr.xephi.authme; +import fr.xephi.authme.permission.PermissionsManager; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.util.Utils; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + import java.io.File; import java.util.List; import java.util.concurrent.Callable; @@ -7,14 +14,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import fr.xephi.authme.permission.PermissionsManager; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - -import fr.xephi.authme.settings.Settings; -import fr.xephi.authme.util.Utils; - /** */ public class DataManager { @@ -23,6 +22,7 @@ public class DataManager { /** * Constructor for DataManager. + * * @param plugin AuthMe */ public DataManager(AuthMe plugin) { @@ -34,9 +34,10 @@ public class DataManager { /** * Method getOfflinePlayer. + * * @param name String - - * @return OfflinePlayer */ + * @return OfflinePlayer + */ public synchronized OfflinePlayer getOfflinePlayer(final String name) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future result = executor.submit(new Callable() { @@ -65,6 +66,7 @@ public class DataManager { /** * Method purgeAntiXray. + * * @param cleared List */ public synchronized void purgeAntiXray(List cleared) { @@ -88,6 +90,7 @@ public class DataManager { /** * Method purgeLimitedCreative. + * * @param cleared List */ public synchronized void purgeLimitedCreative(List cleared) { @@ -121,6 +124,7 @@ public class DataManager { /** * Method purgeDat. + * * @param cleared List */ public synchronized void purgeDat(List cleared) { @@ -136,7 +140,7 @@ public class DataManager { File playerFile = new File(plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getUniqueId() + ".dat"); playerFile.delete(); i++; - } catch(Exception ignore) { + } catch (Exception ignore) { File playerFile = new File(plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getName() + ".dat"); if (playerFile.exists()) { playerFile.delete(); @@ -151,6 +155,7 @@ public class DataManager { /** * Method purgeEssentials. + * * @param cleared List */ @SuppressWarnings("deprecation") @@ -158,7 +163,7 @@ public class DataManager { int i = 0; for (String name : cleared) { try { - File playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + plugin.getServer().getOfflinePlayer(name).getUniqueId() + ".yml"); + File playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + plugin.getServer().getOfflinePlayer(name).getUniqueId() + ".yml"); playerFile.delete(); i++; } catch (Exception e) { @@ -173,13 +178,14 @@ public class DataManager { } // TODO: What is this method for? Is it correct? + /** * @param cleared Cleared players. */ public synchronized void purgePermissions(List cleared) { // Get the permissions manager, and make sure it's valid PermissionsManager permsMan = this.plugin.getPermissionsManager(); - if(permsMan == null) + if (permsMan == null) ConsoleLogger.showError("Unable to access permissions manager instance!"); assert permsMan != null; @@ -188,7 +194,7 @@ public class DataManager { try { permsMan.removeAllGroups(this.getOnlinePlayerLower(name.toLowerCase())); i++; - } catch(Exception e) { + } catch (Exception e) { } } ConsoleLogger.info("AutoPurgeDatabase : Removed " + i + " permissions"); @@ -209,10 +215,11 @@ public class DataManager { /** * Method isOnline. + * * @param player Player - * @param name String - - * @return boolean */ + * @param name String + * @return boolean + */ public boolean isOnline(Player player, final String name) { if (player.isOnline()) return true; @@ -239,9 +246,10 @@ public class DataManager { /** * Method getOnlinePlayerLower. + * * @param name String - - * @return Player */ + * @return Player + */ public Player getOnlinePlayerLower(String name) { name = name.toLowerCase(); for (Player player : Utils.getOnlinePlayers()) { diff --git a/src/main/java/fr/xephi/authme/ImageGenerator.java b/src/main/java/fr/xephi/authme/ImageGenerator.java index 2b6a187e3..bdcefa44a 100644 --- a/src/main/java/fr/xephi/authme/ImageGenerator.java +++ b/src/main/java/fr/xephi/authme/ImageGenerator.java @@ -1,9 +1,6 @@ package fr.xephi.authme; -import java.awt.Color; -import java.awt.Font; -import java.awt.GradientPaint; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.image.BufferedImage; /** @@ -11,8 +8,10 @@ import java.awt.image.BufferedImage; public class ImageGenerator { private String pass; + /** * Constructor for ImageGenerator. + * * @param pass String */ public ImageGenerator(String pass) { @@ -21,8 +20,9 @@ public class ImageGenerator { /** * Method generateImage. - - * @return BufferedImage */ + * + * @return BufferedImage + */ public BufferedImage generateImage() { BufferedImage image = new BufferedImage(200, 60, BufferedImage.TYPE_BYTE_INDEXED); Graphics2D graphics = image.createGraphics(); diff --git a/src/main/java/fr/xephi/authme/Log4JFilter.java b/src/main/java/fr/xephi/authme/Log4JFilter.java index 917a75369..0db37bb74 100644 --- a/src/main/java/fr/xephi/authme/Log4JFilter.java +++ b/src/main/java/fr/xephi/authme/Log4JFilter.java @@ -1,56 +1,95 @@ package fr.xephi.authme; +import fr.xephi.authme.util.StringUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.message.Message; -import fr.xephi.authme.util.StringUtils; - /** * 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 " }; - /** Constructor. */ + /** + * 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 "}; + + /** + * Constructor. + */ public Log4JFilter() { } + /** + * Validates a Message instance and returns the {@link Result} value + * depending depending on whether the message contains sensitive AuthMe + * data. + * + * @param message the Message object to verify + * @return the Result value + */ + private static Result validateMessage(Message message) { + if (message == null) { + return Result.NEUTRAL; + } + return validateMessage(message.getFormattedMessage()); + } + + /** + * Validates a message and returns the {@link Result} value depending + * depending on whether the message contains sensitive AuthMe data. + * + * @param message the message to verify + * @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; + } + @Override public Result filter(LogEvent record) { - if (record == null) { - return Result.NEUTRAL; - } - return validateMessage(record.getMessage()); + if (record == null) { + return Result.NEUTRAL; + } + return validateMessage(record.getMessage()); } @Override public Result filter(Logger arg0, Level arg1, Marker arg2, String message, - Object... arg4) { - return validateMessage(message); + Object... arg4) { + return validateMessage(message); } @Override public Result filter(Logger arg0, Level arg1, Marker arg2, Object message, - Throwable arg4) { - if (message == null) { - return Result.NEUTRAL; - } - return validateMessage(message.toString()); + Throwable arg4) { + if (message == null) { + return Result.NEUTRAL; + } + return validateMessage(message.toString()); } @Override public Result filter(Logger arg0, Level arg1, Marker arg2, Message message, - Throwable arg4) { - return validateMessage(message); + Throwable arg4) { + return validateMessage(message); } @Override @@ -63,41 +102,4 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter { return Result.NEUTRAL; } - /** - * Validates a Message instance and returns the {@link Result} value - * depending depending on whether the message contains sensitive AuthMe - * data. - * - * @param message the Message object to verify - * - * @return the Result value - */ - private static Result validateMessage(Message message) { - if (message == null) { - return Result.NEUTRAL; - } - return validateMessage(message.getFormattedMessage()); - } - - /** - * Validates a message and returns the {@link Result} value depending - * depending on whether the message contains sensitive AuthMe data. - * - * @param message the message to verify - * - * @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; - } - } diff --git a/src/main/java/fr/xephi/authme/PerformBackup.java b/src/main/java/fr/xephi/authme/PerformBackup.java index 355c16497..92194949f 100644 --- a/src/main/java/fr/xephi/authme/PerformBackup.java +++ b/src/main/java/fr/xephi/authme/PerformBackup.java @@ -1,44 +1,66 @@ package fr.xephi.authme; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.text.SimpleDateFormat; -import java.util.Date; - import fr.xephi.authme.settings.Settings; +import java.io.*; +import java.text.SimpleDateFormat; +import java.util.Date; + /** + * The backup management class * * @author stefano * @version $Revision: 1.0 $ */ public class PerformBackup { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm"); + String dateString = format.format(new Date()); private String dbName = Settings.getMySQLDatabase; private String dbUserName = Settings.getMySQLUsername; private String dbPassword = Settings.getMySQLPassword; private String tblname = Settings.getMySQLTablename; - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm"); - String dateString = format.format(new Date()); private String path = AuthMe.getInstance().getDataFolder() + File.separator + "backups" + File.separator + "backup" + dateString; private AuthMe instance; /** * Constructor for PerformBackup. + * * @param instance AuthMe */ public PerformBackup(AuthMe instance) { this.setInstance(instance); } + /** + * + */ + public void doBackup(BackupCause cause) { + // Check whether a backup should be made at the specified point in time + switch (cause) { + case START: + if (!Settings.isBackupOnStart) + return; + case STOP: + if (!Settings.isBackupOnStop) + return; + case COMMAND: + case OTHER: + } + + // Do backup and check return value! + if (doBackup()) { + ConsoleLogger.info("A backup has been performed successfully"); + } else { + ConsoleLogger.showError("Error while performing a backup!"); + } + } + /** * Method doBackup. - - * @return boolean */ + * + * @return boolean + */ public boolean doBackup() { switch (Settings.getDataSource) { @@ -55,8 +77,9 @@ public class PerformBackup { /** * Method MySqlBackup. - - * @return boolean */ + * + * @return boolean + */ private boolean MySqlBackup() { File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups"); @@ -98,9 +121,10 @@ public class PerformBackup { /** * Method FileBackup. + * * @param backend String - - * @return boolean */ + * @return boolean + */ private boolean FileBackup(String backend) { File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups"); @@ -117,15 +141,12 @@ public class PerformBackup { return false; } - /* - * Check if we are under Windows and correct location of mysqldump.exe - * otherwise return error. - */ /** * Method checkWindows. + * * @param windowsPath String - - * @return boolean */ + * @return boolean + */ private boolean checkWindows(String windowsPath) { String isWin = System.getProperty("os.name").toLowerCase(); if (isWin.indexOf("win") >= 0) { @@ -139,14 +160,17 @@ public class PerformBackup { } /* - * Copyr src bytefile into dst file + * Check if we are under Windows and correct location of mysqldump.exe + * otherwise return error. */ + /** * Method copy. + * * @param src File * @param dst File - - * @throws IOException */ + * @throws IOException + */ void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); @@ -161,8 +185,22 @@ public class PerformBackup { out.close(); } + /* + * Copyr src bytefile into dst file + */ + + /** + * Method getInstance. + * + * @return AuthMe + */ + public AuthMe getInstance() { + return instance; + } + /** * Method setInstance. + * * @param instance AuthMe */ public void setInstance(AuthMe instance) { @@ -170,11 +208,13 @@ public class PerformBackup { } /** - * Method getInstance. - - * @return AuthMe */ - public AuthMe getInstance() { - return instance; + * Possible backup causes. + */ + public enum BackupCause { + START, + STOP, + COMMAND, + OTHER, } } diff --git a/src/main/java/fr/xephi/authme/SendMailSSL.java b/src/main/java/fr/xephi/authme/SendMailSSL.java index f3ed378d9..60f5eaeda 100644 --- a/src/main/java/fr/xephi/authme/SendMailSSL.java +++ b/src/main/java/fr/xephi/authme/SendMailSSL.java @@ -1,19 +1,16 @@ package fr.xephi.authme; -import java.io.File; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.settings.Settings; +import org.apache.commons.mail.HtmlEmail; +import org.bukkit.Bukkit; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.imageio.ImageIO; - -import org.apache.commons.mail.HtmlEmail; -import org.bukkit.Bukkit; - -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.settings.Settings; +import java.io.File; /** - * * @author Xephi59 * @version $Revision: 1.0 $ */ @@ -23,6 +20,7 @@ public class SendMailSSL { /** * Constructor for SendMailSSL. + * * @param plugin AuthMe */ public SendMailSSL(AuthMe plugin) { @@ -31,7 +29,8 @@ public class SendMailSSL { /** * Method main. - * @param auth PlayerAuth + * + * @param auth PlayerAuth * @param newPass String */ public void main(final PlayerAuth auth, final String newPass) { diff --git a/src/main/java/fr/xephi/authme/api/API.java b/src/main/java/fr/xephi/authme/api/API.java index 6119f28eb..595e52027 100644 --- a/src/main/java/fr/xephi/authme/api/API.java +++ b/src/main/java/fr/xephi/authme/api/API.java @@ -1,19 +1,18 @@ package fr.xephi.authme.api; -import java.security.NoSuchAlgorithmException; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; - import fr.xephi.authme.AuthMe; 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.Settings; import fr.xephi.authme.util.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +import java.security.NoSuchAlgorithmException; /** */ @@ -24,6 +23,7 @@ public class API { /** * Constructor for API. + * * @param instance AuthMe */ @Deprecated @@ -34,8 +34,8 @@ public class API { /** * Hook into AuthMe * - - * @return AuthMe instance */ + * @return AuthMe instance + */ @Deprecated public static AuthMe hookAuthMe() { if (instance != null) @@ -49,49 +49,18 @@ public class API { } /** - * Method getPlugin. - - * @return AuthMe */ - @Deprecated - public AuthMe getPlugin() { - return instance; - } - - /** - * * @param player - - * @return true if player is authenticate */ + * @return true if player is authenticate + */ @Deprecated public static boolean isAuthenticated(Player player) { return PlayerCache.getInstance().isAuthenticated(player.getName()); } /** - * * @param player - - * @return true if player is a npc */ - @Deprecated - public boolean isaNPC(Player player) { - return Utils.isNPC(player); - } - - /** - * - * @param player - - * @return true if player is a npc */ - @Deprecated - public boolean isNPC(Player player) { - return Utils.isNPC(player); - } - - /** - * - * @param player - - * @return true if the player is unrestricted */ + * @return true if the player is unrestricted + */ @Deprecated public static boolean isUnrestricted(Player player) { return Utils.isUnrestricted(player); @@ -99,9 +68,10 @@ public class API { /** * Method getLastLocation. + * * @param player Player - - * @return Location */ + * @return Location + */ @Deprecated public static Location getLastLocation(Player player) { try { @@ -121,13 +91,14 @@ public class API { /** * Method setPlayerInventory. - * @param player Player + * + * @param player Player * @param content ItemStack[] - * @param armor ItemStack[] + * @param armor ItemStack[] */ @Deprecated public static void setPlayerInventory(Player player, ItemStack[] content, - ItemStack[] armor) { + ItemStack[] armor) { try { player.getInventory().setContents(content); player.getInventory().setArmorContents(armor); @@ -136,10 +107,9 @@ public class API { } /** - * * @param playerName - - * @return true if player is registered */ + * @return true if player is registered + */ @Deprecated public static boolean isRegistered(String playerName) { String player = playerName.toLowerCase(); @@ -147,14 +117,13 @@ public class API { } /** - - - * @param playerName String + * @param playerName String * @param passwordToCheck String - * @return true if the password is correct , false else */ + * @return true if the password is correct , false else + */ @Deprecated public static boolean checkPassword(String playerName, - String passwordToCheck) { + String passwordToCheck) { if (!isRegistered(playerName)) return false; String player = playerName.toLowerCase(); @@ -169,11 +138,10 @@ public class API { /** * Register a player * - - * @param playerName String - * @param password String - * @return true if the player is register correctly */ + * @param password String + * @return true if the player is register correctly + */ @Deprecated public static boolean registerPlayer(String playerName, String password) { try { @@ -195,7 +163,6 @@ public class API { /** * Force a player to login * - * @param player * player */ @Deprecated @@ -203,4 +170,32 @@ public class API { instance.management.performLogin(player, "dontneed", true); } + /** + * Method getPlugin. + * + * @return AuthMe + */ + @Deprecated + public AuthMe getPlugin() { + return instance; + } + + /** + * @param player + * @return true if player is a npc + */ + @Deprecated + public boolean isaNPC(Player player) { + return Utils.isNPC(player); + } + + /** + * @param player + * @return true if player is a npc + */ + @Deprecated + public boolean isNPC(Player player) { + return Utils.isNPC(player); + } + } diff --git a/src/main/java/fr/xephi/authme/api/NewAPI.java b/src/main/java/fr/xephi/authme/api/NewAPI.java index b1aa27a63..a5bc9a68c 100644 --- a/src/main/java/fr/xephi/authme/api/NewAPI.java +++ b/src/main/java/fr/xephi/authme/api/NewAPI.java @@ -1,30 +1,29 @@ package fr.xephi.authme.api; -import java.security.NoSuchAlgorithmException; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - import fr.xephi.authme.AuthMe; 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.Settings; import fr.xephi.authme.util.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.security.NoSuchAlgorithmException; /** */ public class NewAPI { - public static final String newline = System.getProperty("line.separator"); public static NewAPI singleton; public AuthMe plugin; /** * Constructor for NewAPI. + * * @param plugin AuthMe */ public NewAPI(AuthMe plugin) { @@ -33,6 +32,7 @@ public class NewAPI { /** * Constructor for NewAPI. + * * @param serv Server */ public NewAPI(Server serv) { @@ -42,8 +42,8 @@ public class NewAPI { /** * Hook into AuthMe * - - * @return AuthMe plugin */ + * @return AuthMe plugin + */ public static NewAPI getInstance() { if (singleton != null) return singleton; @@ -58,44 +58,43 @@ public class NewAPI { /** * Method getPlugin. - - * @return AuthMe */ + * + * @return AuthMe + */ public AuthMe getPlugin() { return plugin; } /** - * * @param player - - * @return true if player is authenticate */ + * @return true if player is authenticate + */ public boolean isAuthenticated(Player player) { return PlayerCache.getInstance().isAuthenticated(player.getName()); } /** - * * @param player - - * @return true if player is a npc */ + * @return true if player is a npc + */ public boolean isNPC(Player player) { return Utils.isNPC(player); } /** - * * @param player - - * @return true if the player is unrestricted */ + * @return true if the player is unrestricted + */ public boolean isUnrestricted(Player player) { return Utils.isUnrestricted(player); } /** * Method getLastLocation. + * * @param player Player - - * @return Location */ + * @return Location + */ public Location getLastLocation(Player player) { try { PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); @@ -112,21 +111,19 @@ public class NewAPI { } /** - * * @param playerName - - * @return true if player is registered */ + * @return true if player is registered + */ public boolean isRegistered(String playerName) { String player = playerName.toLowerCase(); return plugin.database.isAuthAvailable(player); } /** - - - * @param playerName String + * @param playerName String * @param passwordToCheck String - * @return true if the password is correct , false else */ + * @return true if the password is correct , false else + */ public boolean checkPassword(String playerName, String passwordToCheck) { if (!isRegistered(playerName)) return false; @@ -142,11 +139,10 @@ public class NewAPI { /** * Register a player * - - * @param playerName String - * @param password String - * @return true if the player is register correctly */ + * @param password String + * @return true if the player is register correctly + */ public boolean registerPlayer(String playerName, String password) { try { String name = playerName.toLowerCase(); @@ -164,7 +160,6 @@ public class NewAPI { /** * Force a player to login * - * @param player * player */ public void forceLogin(Player player) { @@ -174,35 +169,28 @@ public class NewAPI { /** * Force a player to logout * - * @param player * player */ - public void forceLogout(Player player) - { - plugin.management.performLogout(player); + public void forceLogout(Player player) { + plugin.management.performLogout(player); } /** * Force a player to register * - - - * @param player * player + * @param player * player * @param password String */ - public void forceRegister(Player player, String password) - { - plugin.management.performRegister(player, password, null); + public void forceRegister(Player player, String password) { + plugin.management.performRegister(player, password, null); } /** * Force a player to unregister * - * @param player * player */ - public void forceUnregister(Player player) - { - plugin.management.performUnregister(player, "", true); + public void forceUnregister(Player player) { + plugin.management.performUnregister(player, "", true); } } 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 5b2298233..2bfcd4f6d 100644 --- a/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java +++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java @@ -22,10 +22,11 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param ip String + * + * @param nickname String + * @param ip String * @param lastLogin long - * @param realName String + * @param realName String */ public PlayerAuth(String nickname, String ip, long lastLogin, String realName) { this(nickname, "", "", -1, ip, lastLogin, 0, 0, 0, "world", "your@email.com", realName); @@ -33,11 +34,12 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. + * * @param nickname String - * @param x double - * @param y double - * @param z double - * @param world String + * @param x double + * @param y double + * @param z double + * @param world String * @param realName String */ public PlayerAuth(String nickname, double x, double y, double z, String world, String realName) { @@ -46,11 +48,12 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param hash String - * @param ip String + * + * @param nickname String + * @param hash String + * @param ip String * @param lastLogin long - * @param realName String + * @param realName String */ public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String realName) { this(nickname, hash, "", -1, ip, lastLogin, 0, 0, 0, "world", "your@email.com", realName); @@ -58,12 +61,13 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param hash String - * @param ip String + * + * @param nickname String + * @param hash String + * @param ip String * @param lastLogin long - * @param email String - * @param realName String + * @param email String + * @param realName String */ public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String email, String realName) { this(nickname, hash, "", -1, ip, lastLogin, 0, 0, 0, "world", email, realName); @@ -71,12 +75,13 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param hash String - * @param salt String - * @param ip String + * + * @param nickname String + * @param hash String + * @param salt String + * @param ip String * @param lastLogin long - * @param realName String + * @param realName String */ public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, String realName) { this(nickname, hash, salt, -1, ip, lastLogin, 0, 0, 0, "world", "your@email.com", realName); @@ -84,16 +89,17 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param hash String - * @param ip String + * + * @param nickname String + * @param hash String + * @param ip String * @param lastLogin long - * @param x double - * @param y double - * @param z double - * @param world String - * @param email String - * @param realName String + * @param x double + * @param y double + * @param z double + * @param world String + * @param email String + * @param realName String */ public PlayerAuth(String nickname, String hash, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { this(nickname, hash, "", -1, ip, lastLogin, x, y, z, world, email, realName); @@ -101,17 +107,18 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param hash String - * @param salt String - * @param ip String + * + * @param nickname String + * @param hash String + * @param salt String + * @param ip String * @param lastLogin long - * @param x double - * @param y double - * @param z double - * @param world String - * @param email String - * @param realName String + * @param x double + * @param y double + * @param z double + * @param world String + * @param email String + * @param realName String */ public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { this(nickname, hash, salt, -1, ip, lastLogin, x, y, z, world, email, realName); @@ -119,13 +126,14 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param hash String - * @param salt String - * @param groupId int - * @param ip String + * + * @param nickname String + * @param hash String + * @param salt String + * @param groupId int + * @param ip String * @param lastLogin long - * @param realName String + * @param realName String */ public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, String realName) { this(nickname, hash, salt, groupId, ip, lastLogin, 0, 0, 0, "world", "your@email.com", realName); @@ -133,18 +141,19 @@ public class PlayerAuth { /** * Constructor for PlayerAuth. - * @param nickname String - * @param hash String - * @param salt String - * @param groupId int - * @param ip String + * + * @param nickname String + * @param hash String + * @param salt String + * @param groupId int + * @param ip String * @param lastLogin long - * @param x double - * @param y double - * @param z double - * @param world String - * @param email String - * @param realName String + * @param x double + * @param y double + * @param z double + * @param world String + * @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; @@ -163,6 +172,7 @@ public class PlayerAuth { /** * Method set. + * * @param auth PlayerAuth */ public void set(PlayerAuth auth) { @@ -181,6 +191,7 @@ public class PlayerAuth { /** * Method setName. + * * @param nickname String */ public void setName(String nickname) { @@ -189,22 +200,25 @@ public class PlayerAuth { /** * Method getNickname. - - * @return String */ + * + * @return String + */ public String getNickname() { return nickname; } /** * Method getRealName. - - * @return String */ + * + * @return String + */ public String getRealName() { return realName; } /** * Method setRealName. + * * @param realName String */ public void setRealName(String realName) { @@ -213,14 +227,25 @@ public class PlayerAuth { /** * Method getGroupId. - - * @return int */ + * + * @return int + */ public int getGroupId() { return groupId; } + /** + * Method getQuitLocX. + * + * @return double + */ + public double getQuitLocX() { + return x; + } + /** * Method setQuitLocX. + * * @param d double */ public void setQuitLocX(double d) { @@ -228,15 +253,17 @@ public class PlayerAuth { } /** - * Method getQuitLocX. - - * @return double */ - public double getQuitLocX() { - return x; + * Method getQuitLocY. + * + * @return double + */ + public double getQuitLocY() { + return y; } /** * Method setQuitLocY. + * * @param d double */ public void setQuitLocY(double d) { @@ -244,15 +271,17 @@ public class PlayerAuth { } /** - * Method getQuitLocY. - - * @return double */ - public double getQuitLocY() { - return y; + * Method getQuitLocZ. + * + * @return double + */ + public double getQuitLocZ() { + return z; } /** * Method setQuitLocZ. + * * @param d double */ public void setQuitLocZ(double d) { @@ -260,15 +289,17 @@ public class PlayerAuth { } /** - * Method getQuitLocZ. - - * @return double */ - public double getQuitLocZ() { - return z; + * Method getWorld. + * + * @return String + */ + public String getWorld() { + return world; } /** * Method setWorld. + * * @param world String */ public void setWorld(String world) { @@ -276,15 +307,17 @@ public class PlayerAuth { } /** - * Method getWorld. - - * @return String */ - public String getWorld() { - return world; + * Method getIp. + * + * @return String + */ + public String getIp() { + return ip; } /** * Method setIp. + * * @param ip String */ public void setIp(String ip) { @@ -292,15 +325,17 @@ public class PlayerAuth { } /** - * Method getIp. - - * @return String */ - public String getIp() { - return ip; + * Method getLastLogin. + * + * @return long + */ + public long getLastLogin() { + return lastLogin; } /** * Method setLastLogin. + * * @param lastLogin long */ public void setLastLogin(long lastLogin) { @@ -308,15 +343,17 @@ public class PlayerAuth { } /** - * Method getLastLogin. - - * @return long */ - public long getLastLogin() { - return lastLogin; + * Method getEmail. + * + * @return String + */ + public String getEmail() { + return email; } /** * Method setEmail. + * * @param email String */ public void setEmail(String email) { @@ -324,41 +361,28 @@ public class PlayerAuth { } /** - * Method getEmail. - - * @return String */ - public String getEmail() { - return email; + * Method getSalt. + * + * @return String + */ + public String getSalt() { + return this.salt; } /** * Method setSalt. + * * @param salt String */ public void setSalt(String salt) { this.salt = salt; } - /** - * Method getSalt. - - * @return String */ - public String getSalt() { - return this.salt; - } - - /** - * Method setHash. - * @param hash String - */ - public void setHash(String hash) { - this.hash = hash; - } - /** * Method getHash. - - * @return String */ + * + * @return String + */ public String getHash() { if (Settings.getPasswordHash == HashAlgorithm.MD5VB) { if (salt != null && !salt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.MD5VB) { @@ -368,11 +392,21 @@ public class PlayerAuth { return hash; } + /** + * Method setHash. + * + * @param hash String + */ + public void setHash(String hash) { + this.hash = hash; + } + /** * Method equals. + * * @param obj Object - - * @return boolean */ + * @return boolean + */ @Override public boolean equals(Object obj) { if (!(obj instanceof PlayerAuth)) { @@ -384,8 +418,9 @@ public class PlayerAuth { /** * Method hashCode. - - * @return int */ + * + * @return int + */ @Override public int hashCode() { int hashCode = 7; @@ -396,8 +431,9 @@ public class PlayerAuth { /** * Method toString. - - * @return String */ + * + * @return String + */ @Override public String toString() { return ("Player : " + nickname + " | " + realName diff --git a/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java index e72fcd685..53f0a799e 100644 --- a/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java +++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java @@ -13,8 +13,21 @@ public class PlayerCache { cache = new ConcurrentHashMap<>(); } + /** + * Method getInstance. + * + * @return PlayerCache + */ + public static PlayerCache getInstance() { + if (singleton == null) { + singleton = new PlayerCache(); + } + return singleton; + } + /** * Method addPlayer. + * * @param auth PlayerAuth */ public void addPlayer(PlayerAuth auth) { @@ -23,6 +36,7 @@ public class PlayerCache { /** * Method updatePlayer. + * * @param auth PlayerAuth */ public void updatePlayer(PlayerAuth auth) { @@ -32,6 +46,7 @@ public class PlayerCache { /** * Method removePlayer. + * * @param user String */ public void removePlayer(String user) { @@ -40,45 +55,38 @@ public class PlayerCache { /** * Method isAuthenticated. + * * @param user String - - * @return boolean */ + * @return boolean + */ public boolean isAuthenticated(String user) { return cache.containsKey(user.toLowerCase()); } /** * Method getAuth. + * * @param user String - - * @return PlayerAuth */ + * @return PlayerAuth + */ public PlayerAuth getAuth(String user) { return cache.get(user.toLowerCase()); } - /** - * Method getInstance. - - * @return PlayerCache */ - public static PlayerCache getInstance() { - if (singleton == null) { - singleton = new PlayerCache(); - } - return singleton; - } - /** * Method getLogged. - - * @return int */ + * + * @return int + */ public int getLogged() { return cache.size(); } /** * Method getCache. - - * @return ConcurrentHashMap */ + * + * @return ConcurrentHashMap + */ public ConcurrentHashMap getCache() { return this.cache; } diff --git a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java index 01751d789..c40cab961 100644 --- a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java +++ b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java @@ -10,9 +10,10 @@ public class DataFileCache { /** * Constructor for DataFileCache. - * @param group String + * + * @param group String * @param operator boolean - * @param flying boolean + * @param flying boolean */ public DataFileCache(String group, boolean operator, boolean flying) { this.group = group; @@ -22,24 +23,27 @@ public class DataFileCache { /** * Method getGroup. - - * @return String */ + * + * @return String + */ public String getGroup() { return group; } /** * Method getOperator. - - * @return boolean */ + * + * @return boolean + */ public boolean getOperator() { return operator; } /** * Method isFlying. - - * @return boolean */ + * + * @return boolean + */ public boolean isFlying() { return flying; } diff --git a/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java index 70d6614c8..9b0b7f369 100644 --- a/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java +++ b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java @@ -1,27 +1,17 @@ package fr.xephi.authme.cache.backup; +import com.google.common.base.Charsets; +import com.google.common.io.Files; +import com.google.gson.*; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.util.Utils; +import org.bukkit.entity.Player; + import java.io.File; import java.io.IOException; import java.lang.reflect.Type; -import org.bukkit.entity.Player; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.settings.Settings; -import fr.xephi.authme.util.Utils; - /** */ public class JsonCache { @@ -43,7 +33,8 @@ public class JsonCache { /** * Method createCache. - * @param player Player + * + * @param player Player * @param playerData DataFileCache */ public void createCache(Player player, DataFileCache playerData) { @@ -77,9 +68,10 @@ public class JsonCache { /** * Method readCache. + * * @param player Player - - * @return DataFileCache */ + * @return DataFileCache + */ public DataFileCache readCache(Player player) { String path; try { @@ -103,24 +95,41 @@ public class JsonCache { } /** + * Method removeCache. + * + * @param player Player */ - private class PlayerDataSerializer implements JsonSerializer { - /** - * Method serialize. - * @param dataFileCache DataFileCache - * @param type Type - * @param jsonSerializationContext JsonSerializationContext - - * @return JsonElement */ - @Override - public JsonElement serialize(DataFileCache dataFileCache, Type type, JsonSerializationContext jsonSerializationContext) { - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("group", dataFileCache.getGroup()); - jsonObject.addProperty("operator", dataFileCache.getOperator()); - jsonObject.addProperty("flying", dataFileCache.isFlying()); - - return jsonObject; + public void removeCache(Player player) { + String path; + try { + path = player.getUniqueId().toString(); + } catch (Exception | Error e) { + path = player.getName().toLowerCase(); } + File file = new File(cacheDir, path); + if (file.exists()) { + Utils.purgeDirectory(file); + if (!file.delete()) { + ConsoleLogger.showError("Failed to remove" + player.getName() + "cache."); + } + } + } + + /** + * Method doesCacheExist. + * + * @param player Player + * @return boolean + */ + public boolean doesCacheExist(Player player) { + String path; + try { + path = player.getUniqueId().toString(); + } catch (Exception | Error e) { + path = player.getName().toLowerCase(); + } + File file = new File(cacheDir, path + File.separator + "cache.json"); + return file.exists(); } /** @@ -128,13 +137,12 @@ public class JsonCache { private static class PlayerDataDeserializer implements JsonDeserializer { /** * Method deserialize. - * @param jsonElement JsonElement - * @param type Type + * + * @param jsonElement JsonElement + * @param type Type * @param jsonDeserializationContext JsonDeserializationContext - - - - * @return DataFileCache * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ + * @return DataFileCache * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) + */ @Override public DataFileCache deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); @@ -161,39 +169,25 @@ public class JsonCache { } /** - * Method removeCache. - * @param player Player */ - public void removeCache(Player player) { - String path; - try { - path = player.getUniqueId().toString(); - } catch (Exception | Error e) { - path = player.getName().toLowerCase(); - } - File file = new File(cacheDir, path); - if (file.exists()) { - Utils.purgeDirectory(file); - if (!file.delete()) { - ConsoleLogger.showError("Failed to remove" + player.getName() + "cache."); - } - } - } + private class PlayerDataSerializer implements JsonSerializer { + /** + * Method serialize. + * + * @param dataFileCache DataFileCache + * @param type Type + * @param jsonSerializationContext JsonSerializationContext + * @return JsonElement + */ + @Override + public JsonElement serialize(DataFileCache dataFileCache, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("group", dataFileCache.getGroup()); + jsonObject.addProperty("operator", dataFileCache.getOperator()); + jsonObject.addProperty("flying", dataFileCache.isFlying()); - /** - * Method doesCacheExist. - * @param player Player - - * @return boolean */ - public boolean doesCacheExist(Player player) { - String path; - try { - path = player.getUniqueId().toString(); - } catch (Exception | Error e) { - path = player.getName().toLowerCase(); + return jsonObject; } - File file = new File(cacheDir, path + File.separator + "cache.json"); - return file.exists(); } } 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 59dee4688..2fb08b669 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java @@ -1,19 +1,18 @@ package fr.xephi.authme.cache.limbo; -import java.util.concurrent.ConcurrentHashMap; - -import fr.xephi.authme.permission.PermissionsManager; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.entity.Player; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.backup.DataFileCache; import fr.xephi.authme.cache.backup.JsonCache; import fr.xephi.authme.events.ResetInventoryEvent; +import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.settings.Settings; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.concurrent.ConcurrentHashMap; /** */ @@ -21,11 +20,12 @@ public class LimboCache { private volatile static LimboCache singleton; public ConcurrentHashMap cache; - private JsonCache playerData; public AuthMe plugin; + private JsonCache playerData; /** * Constructor for LimboCache. + * * @param plugin AuthMe */ private LimboCache(AuthMe plugin) { @@ -34,6 +34,18 @@ public class LimboCache { this.playerData = new JsonCache(); } + /** + * Method getInstance. + * + * @return LimboCache + */ + public static LimboCache getInstance() { + if (singleton == null) { + singleton = new LimboCache(AuthMe.getInstance()); + } + return singleton; + } + /** * Add a limbo player. * @@ -49,7 +61,7 @@ public class LimboCache { // Get the permissions manager, and make sure it's valid PermissionsManager permsMan = this.plugin.getPermissionsManager(); - if(permsMan == null) + if (permsMan == null) ConsoleLogger.showError("Unable to access permissions manager!"); assert permsMan != null; @@ -65,7 +77,7 @@ public class LimboCache { flying = player.isFlying(); // Check whether groups are supported - if(permsMan.hasGroupSupport()) + if (permsMan.hasGroupSupport()) playerGroup = permsMan.getPrimaryGroup(player); } @@ -91,8 +103,9 @@ public class LimboCache { /** * Method addLimboPlayer. + * * @param player Player - * @param group String + * @param group String */ public void addLimboPlayer(Player player, String group) { cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group)); @@ -100,6 +113,7 @@ public class LimboCache { /** * Method deleteLimboPlayer. + * * @param name String */ public void deleteLimboPlayer(String name) { @@ -108,35 +122,27 @@ public class LimboCache { /** * Method getLimboPlayer. + * * @param name String - - * @return LimboPlayer */ + * @return LimboPlayer + */ public LimboPlayer getLimboPlayer(String name) { return cache.get(name); } /** * Method hasLimboPlayer. + * * @param name String - - * @return boolean */ + * @return boolean + */ public boolean hasLimboPlayer(String name) { return cache.containsKey(name); } - /** - * Method getInstance. - - * @return LimboCache */ - public static LimboCache getInstance() { - if (singleton == null) { - singleton = new LimboCache(AuthMe.getInstance()); - } - return singleton; - } - /** * Method updateLimboPlayer. + * * @param player Player */ public void updateLimboPlayer(Player player) { diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java index d6f7b02b2..64e65dc55 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java @@ -19,15 +19,16 @@ public class LimboPlayer { /** * Constructor for LimboPlayer. - * @param name String - * @param loc Location + * + * @param name String + * @param loc Location * @param gameMode GameMode * @param operator boolean - * @param group String - * @param flying boolean + * @param group String + * @param flying boolean */ public LimboPlayer(String name, Location loc, GameMode gameMode, - boolean operator, String group, boolean flying) { + boolean operator, String group, boolean flying) { this.name = name; this.loc = loc; this.gameMode = gameMode; @@ -38,7 +39,8 @@ public class LimboPlayer { /** * Constructor for LimboPlayer. - * @param name String + * + * @param name String * @param group String */ public LimboPlayer(String name, String group) { @@ -48,46 +50,61 @@ public class LimboPlayer { /** * Method getName. - - * @return String */ + * + * @return String + */ public String getName() { return name; } /** * Method getLoc. - - * @return Location */ + * + * @return Location + */ public Location getLoc() { return loc; } /** * Method getGameMode. - - * @return GameMode */ + * + * @return GameMode + */ public GameMode getGameMode() { return gameMode; } /** * Method getOperator. - - * @return boolean */ + * + * @return boolean + */ public boolean getOperator() { return operator; } /** * Method getGroup. - - * @return String */ + * + * @return String + */ public String getGroup() { return group; } + /** + * Method getTimeoutTaskId. + * + * @return BukkitTask + */ + public BukkitTask getTimeoutTaskId() { + return timeoutTaskId; + } + /** * Method setTimeoutTaskId. + * * @param i BukkitTask */ public void setTimeoutTaskId(BukkitTask i) { @@ -97,15 +114,17 @@ public class LimboPlayer { } /** - * Method getTimeoutTaskId. - - * @return BukkitTask */ - public BukkitTask getTimeoutTaskId() { - return timeoutTaskId; + * Method getMessageTaskId. + * + * @return BukkitTask + */ + public BukkitTask getMessageTaskId() { + return messageTaskId; } /** * Method setMessageTaskId. + * * @param messageTaskId BukkitTask */ public void setMessageTaskId(BukkitTask messageTaskId) { @@ -114,18 +133,11 @@ public class LimboPlayer { this.messageTaskId = messageTaskId; } - /** - * Method getMessageTaskId. - - * @return BukkitTask */ - public BukkitTask getMessageTaskId() { - return messageTaskId; - } - /** * Method isFlying. - - * @return boolean */ + * + * @return boolean + */ public boolean isFlying() { return flying; } diff --git a/src/main/java/fr/xephi/authme/command/CommandArgumentDescription.java b/src/main/java/fr/xephi/authme/command/CommandArgumentDescription.java index 75d6e4aeb..c486a3820 100644 --- a/src/main/java/fr/xephi/authme/command/CommandArgumentDescription.java +++ b/src/main/java/fr/xephi/authme/command/CommandArgumentDescription.java @@ -6,17 +6,23 @@ public class CommandArgumentDescription { // TODO: Allow argument to consist of infinite parts.