From b014f508214fbe0f687178b66285acfaa31dab03 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Thu, 13 Dec 2018 08:17:56 +0100 Subject: [PATCH 01/83] Bump maven-jar-plugin from 3.1.0 to 3.1.1 (#1710) Bumps [maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.1.0 to 3.1.1. - [Release notes](https://github.com/apache/maven-jar-plugin/releases) - [Commits](https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.1.0...maven-jar-plugin-3.1.1) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3bf97db87..3b614b238 100644 --- a/pom.xml +++ b/pom.xml @@ -216,7 +216,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.1.0 + 3.1.1 From 75e1e5ce51cec7b63baa30f1a46675e21132b32e Mon Sep 17 00:00:00 2001 From: ljacqu Date: Mon, 17 Dec 2018 20:42:43 +0100 Subject: [PATCH 02/83] #1707 Make column context thread-safe --- .../xephi/authme/datasource/columnshandler/ColumnContext.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/xephi/authme/datasource/columnshandler/ColumnContext.java b/src/main/java/fr/xephi/authme/datasource/columnshandler/ColumnContext.java index 554266a05..483e31e9c 100644 --- a/src/main/java/fr/xephi/authme/datasource/columnshandler/ColumnContext.java +++ b/src/main/java/fr/xephi/authme/datasource/columnshandler/ColumnContext.java @@ -2,8 +2,8 @@ package fr.xephi.authme.datasource.columnshandler; import fr.xephi.authme.settings.Settings; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * Context for resolving the properties of {@link AuthMeColumns} entries. @@ -11,7 +11,7 @@ import java.util.Map; public class ColumnContext { private final Settings settings; - private final Map, String> columnNames = new HashMap<>(); + private final Map, String> columnNames = new ConcurrentHashMap<>(); private final boolean hasDefaultSupport; /** From 2f7672b489299f8360851a37084de499f2b3eb26 Mon Sep 17 00:00:00 2001 From: games647 Date: Tue, 25 Dec 2018 16:58:03 +0100 Subject: [PATCH 03/83] Hide the inventory for online players on reload (Related #1709) --- .../listener/protocollib/InventoryPacketAdapter.java | 10 +++++++++- .../listener/protocollib/ProtocolLibService.java | 3 ++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java b/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java index d4f5491b5..768c5f59e 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java @@ -27,6 +27,8 @@ import com.comphenix.protocol.reflect.StructureModifier; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerCache; +import fr.xephi.authme.service.BukkitService; + import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -63,8 +65,14 @@ class InventoryPacketAdapter extends PacketAdapter { } } - public void register() { + public void register(BukkitService bukkitService, boolean hideNow) { ProtocolLibrary.getProtocolManager().addPacketListener(this); + + if (hideNow) { + bukkitService.getOnlinePlayers().stream() + .filter(player -> playerCache.isAuthenticated(player.getName())) + .forEach(this::sendBlankInventoryPacket); + } } public void unregister() { diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java index c6acd03ef..bc1654bb4 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java @@ -58,8 +58,9 @@ public class ProtocolLibService implements SettingsDependent { // Set up packet adapters if (protectInvBeforeLogin) { if (inventoryPacketAdapter == null) { + // register the packet listener and start hiding it for all already online players (reload) inventoryPacketAdapter = new InventoryPacketAdapter(plugin, playerCache); - inventoryPacketAdapter.register(); + inventoryPacketAdapter.register(bukkitService, true); } } else if (inventoryPacketAdapter != null) { inventoryPacketAdapter.unregister(); From 696bcc7ba61cc3ee47ab7391f93c10b6238b9020 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristjan=20Kru=C5=A1i=C4=8D?= Date: Tue, 1 Jan 2019 03:50:41 +0100 Subject: [PATCH 04/83] Update the copyright year to 2018 just in time. (#1721) We can't just skip from 2017 to 2019. --- .../xephi/authme/command/executable/authme/VersionCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 d042c9a65..1c0a1225e 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 @@ -36,7 +36,7 @@ public class VersionCommand implements ExecutableCommand { sender.sendMessage(ChatColor.GOLD + "License: " + ChatColor.WHITE + "GNU GPL v3.0" + ChatColor.GRAY + ChatColor.ITALIC + " (See LICENSE file)"); sender.sendMessage(ChatColor.GOLD + "Copyright: " + ChatColor.WHITE - + "Copyright (c) AuthMe-Team 2017. All rights reserved."); + + "Copyright (c) AuthMe-Team 2018. All rights reserved."); } /** From 98efa351835db88791edf1ffe75e6e4e3ebb9c8a Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Tue, 1 Jan 2019 03:52:25 +0100 Subject: [PATCH 05/83] Happy new year! --- .../xephi/authme/command/executable/authme/VersionCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1c0a1225e..65be32961 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 @@ -36,7 +36,7 @@ public class VersionCommand implements ExecutableCommand { sender.sendMessage(ChatColor.GOLD + "License: " + ChatColor.WHITE + "GNU GPL v3.0" + ChatColor.GRAY + ChatColor.ITALIC + " (See LICENSE file)"); sender.sendMessage(ChatColor.GOLD + "Copyright: " + ChatColor.WHITE - + "Copyright (c) AuthMe-Team 2018. All rights reserved."); + + "Copyright (c) AuthMe-Team 2019. All rights reserved."); } /** From 42f22b2d4c1ea05fccf00f54bc2a6691d6ecb284 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Thu, 3 Jan 2019 11:39:38 +0100 Subject: [PATCH 06/83] Bump HikariCP from 3.2.0 to 3.3.0 (#1722) Bumps [HikariCP](https://github.com/brettwooldridge/HikariCP) from 3.2.0 to 3.3.0. - [Release notes](https://github.com/brettwooldridge/HikariCP/releases) - [Changelog](https://github.com/brettwooldridge/HikariCP/blob/dev/CHANGES) - [Commits](https://github.com/brettwooldridge/HikariCP/compare/HikariCP-3.2.0...HikariCP-3.3.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3b614b238..5f6f06e58 100644 --- a/pom.xml +++ b/pom.xml @@ -477,7 +477,7 @@ com.zaxxer HikariCP - 3.2.0 + 3.3.0 true From fdded6be9f620f45ab0e1067ccbce0ef59b20ad1 Mon Sep 17 00:00:00 2001 From: Madis Date: Wed, 9 Jan 2019 03:28:35 +0200 Subject: [PATCH 07/83] Minor fixes for Estonian (#1724) Informal _you_, untranslated word, typo fix --- src/main/resources/messages/messages_et.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/resources/messages/messages_et.yml b/src/main/resources/messages/messages_et.yml index 431f05f1a..a248d0f21 100644 --- a/src/main/resources/messages/messages_et.yml +++ b/src/main/resources/messages/messages_et.yml @@ -8,7 +8,7 @@ registration: register_request: '&3Palun registreeri käsklusega: /register ' command_usage: '&cKasutus: /register ' reg_only: '&4Vaid registreeritud mängijad saavad liituda serveriga! Külasta http://example.com enda kasutaja registreerimiseks!' - kicked_admin_registered: 'Administraator registreeris teie kasutaja, palun logige uuesti sisse.' + kicked_admin_registered: 'Administraator registreeris su kasutaja, palun logi uuesti sisse.' success: '&2Edukalt registreeritud!' disabled: '&cMängusisene registreerimine on välja lülitatud!' name_taken: '&cSee kasutaja on juba registreeritud!' @@ -18,7 +18,7 @@ password: match_error: '&cParoolid ei kattu, palun proovi uuesti!' name_in_password: '&cSa ei saa kasutada oma kasutajanime paroolina, palun vali mõni teine parool.' unsafe_password: '&cSee parool ei ole turvaline, palun vali mõni teine parool.' - forbidden_characters: '&4Teie parool sisaldab keelatud tähemärke. Lubatud tähemärgid: %valid_chars' + forbidden_characters: '&4Su parool sisaldab keelatud tähemärke. Lubatud tähemärgid: %valid_chars' wrong_length: '&cSu parool on liiga pikk või lühike, palun vali mõni teine parool.' # Login @@ -90,7 +90,7 @@ email: request_confirmation: '&cPalun kinnita oma meiliaadress!' changed: '&2Meiliaadress edukalt muudetud!' email_show: '&2Su praegune meiliaadress on: &f%email' - incomplete_settings: 'Error: meili saatmiseks pole kõik vajalikud seaded seadistatud. Teata sellest administraatorile.' + incomplete_settings: 'Viga: meili saatmiseks pole kõik vajalikud seaded seadistatud. Teata sellest administraatorile.' already_used: '&4See meiliaadress on juba kasutuses!' send_failure: 'Meili ei õnnestunud saata. Teata sellest administraatorile.' no_email_for_account: '&2Selle kasutajaga ei ole seotud ühtegi meiliaadressi.' @@ -114,7 +114,7 @@ recovery: # Captcha captcha: - usage_captcha: '&3Sisselogimiseks lahenda captha käsklusega: /captcha %captcha_code' + usage_captcha: '&3Sisselogimiseks lahenda captcha käsklusega: /captcha %captcha_code' wrong_captcha: '&cVale captcha, kasuta käsklust "/captcha %captcha_code"!' valid_captcha: '&2Captcha lahendatud!' captcha_for_registration: 'Registreerimiseks lahenda captcha kasutades käsklust: /captcha %captcha_code' From bdbb7d79fd1786187d283a9984cce4322578da54 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sat, 12 Jan 2019 12:17:08 +0100 Subject: [PATCH 08/83] Specify licensing in about command --- .../xephi/authme/command/executable/authme/VersionCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 65be32961..6b90d3d78 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 @@ -36,7 +36,7 @@ public class VersionCommand implements ExecutableCommand { sender.sendMessage(ChatColor.GOLD + "License: " + ChatColor.WHITE + "GNU GPL v3.0" + ChatColor.GRAY + ChatColor.ITALIC + " (See LICENSE file)"); sender.sendMessage(ChatColor.GOLD + "Copyright: " + ChatColor.WHITE - + "Copyright (c) AuthMe-Team 2019. All rights reserved."); + + "Copyright (c) AuthMe-Team 2019. Released under GPL v3 License."); } /** From a347b4a9bbc7dc58364136328c5b957c14f5a1eb Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sat, 12 Jan 2019 14:03:02 +0100 Subject: [PATCH 09/83] Remove sponsor message --- src/main/java/fr/xephi/authme/AuthMe.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 2f3035d7b..7ee02ef06 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -146,11 +146,6 @@ public class AuthMe extends JavaPlugin { // Set up Metrics OnStartupTasks.sendMetrics(this, settings); - // Sponsor messages - ConsoleLogger.info("Development builds are available on our jenkins, thanks to FastVM.io"); - ConsoleLogger.info("Do you want a good vps for your game server? Look at our sponsor FastVM.io leader " - + "as virtual server provider!"); - // Successful message ConsoleLogger.info("AuthMe " + getPluginVersion() + " build n." + getPluginBuildNumber() + " correctly enabled!"); From 8d32b56852210d2670dcaddf5bd87d5385dd425e Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sat, 12 Jan 2019 14:03:31 +0100 Subject: [PATCH 10/83] Remove sponsor from README --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index 25a325f40..9b10509af 100644 --- a/README.md +++ b/README.md @@ -114,9 +114,6 @@ You can also create your own translation file and, if you want, you can share it ## Credits -##### Sponsor: -[FastVM.io](https://fastvm.io) is leader in VPS hosting solutions. With its own DataCenter offers Anti-DDoS solutions at affordable prices. - ##### Contributors: Team members: developers, translators From 4a57679f6f4b122e346cd8dac0775133348a96a2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Mon, 28 Jan 2019 21:03:19 +0100 Subject: [PATCH 11/83] Bump bcrypt from 0.6.0 to 0.7.0 (#1733) Bumps [bcrypt](https://github.com/patrickfav/bcrypt) from 0.6.0 to 0.7.0. - [Release notes](https://github.com/patrickfav/bcrypt/releases) - [Changelog](https://github.com/patrickfav/bcrypt/blob/master/CHANGELOG) - [Commits](https://github.com/patrickfav/bcrypt/compare/v0.6.0...v0.7.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5f6f06e58..227efe7b3 100644 --- a/pom.xml +++ b/pom.xml @@ -795,7 +795,7 @@ at.favre.lib bcrypt - 0.6.0 + 0.7.0 true From 9e143c421abc6b106e0f20ca6e07021f48bec9d5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Mon, 28 Jan 2019 21:03:34 +0100 Subject: [PATCH 12/83] Bump jacoco-maven-plugin from 0.8.2 to 0.8.3 (#1731) Bumps [jacoco-maven-plugin](https://github.com/jacoco/jacoco) from 0.8.2 to 0.8.3. - [Release notes](https://github.com/jacoco/jacoco/releases) - [Commits](https://github.com/jacoco/jacoco/compare/v0.8.2...v0.8.3) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 227efe7b3..3d36e890f 100644 --- a/pom.xml +++ b/pom.xml @@ -180,7 +180,7 @@ org.jacoco jacoco-maven-plugin - 0.8.2 + 0.8.3 pre-unit-test From bcc6929a18c28c484ebe9d0ef82cdc57525b69c6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Mon, 4 Feb 2019 19:16:48 +0100 Subject: [PATCH 13/83] Bump mockito-core from 2.23.4 to 2.24.0 (#1737) Bumps [mockito-core](https://github.com/mockito/mockito) from 2.23.4 to 2.24.0. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v2.23.4...v2.24.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3d36e890f..68490c66b 100644 --- a/pom.xml +++ b/pom.xml @@ -874,7 +874,7 @@ org.mockito mockito-core test - 2.23.4 + 2.24.0 hamcrest-core From a8fb0528c97e3d7de382c1b0dd0068d1d8a946f3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Mon, 4 Feb 2019 19:16:59 +0100 Subject: [PATCH 14/83] Bump checker-qual from 2.5.8 to 2.6.0 (#1736) Bumps [checker-qual](https://github.com/typetools/checker-framework) from 2.5.8 to 2.6.0. - [Release notes](https://github.com/typetools/checker-framework/releases) - [Changelog](https://github.com/typetools/checker-framework/blob/master/changelog.txt) - [Commits](https://github.com/typetools/checker-framework/compare/checker-framework-2.5.8...checker-framework-2.6.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 68490c66b..a1ec266d3 100644 --- a/pom.xml +++ b/pom.xml @@ -887,7 +887,7 @@ org.checkerframework checker-qual - 2.5.8 + 2.6.0 test From d82b1c7ed3f7e34ac1cefb864181c166b9e0a67c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 8 Feb 2019 08:20:54 +0100 Subject: [PATCH 15/83] Bump HikariCP from 3.3.0 to 3.3.1 (#1749) Bumps [HikariCP](https://github.com/brettwooldridge/HikariCP) from 3.3.0 to 3.3.1. - [Release notes](https://github.com/brettwooldridge/HikariCP/releases) - [Changelog](https://github.com/brettwooldridge/HikariCP/blob/dev/CHANGES) - [Commits](https://github.com/brettwooldridge/HikariCP/compare/HikariCP-3.3.0...HikariCP-3.3.1) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a1ec266d3..e75e417f2 100644 --- a/pom.xml +++ b/pom.xml @@ -477,7 +477,7 @@ com.zaxxer HikariCP - 3.3.0 + 3.3.1 true From f53efaf832b136af185d46af78d976b609002ceb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Wed, 20 Feb 2019 12:36:19 +0100 Subject: [PATCH 16/83] Bump slf4j-simple from 1.7.25 to 1.7.26 (#1759) Bumps [slf4j-simple](https://github.com/qos-ch/slf4j) from 1.7.25 to 1.7.26. - [Release notes](https://github.com/qos-ch/slf4j/releases) - [Commits](https://github.com/qos-ch/slf4j/compare/v_1.7.25...v_1.7.26) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e75e417f2..59871d793 100644 --- a/pom.xml +++ b/pom.xml @@ -490,7 +490,7 @@ org.slf4j slf4j-simple - 1.7.25 + 1.7.26 true From 9c7dfb4daf65e7ccb0119c13dd837df930f00ff1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Wed, 20 Feb 2019 12:37:52 +0100 Subject: [PATCH 17/83] Bump mockito-core from 2.24.0 to 2.24.5 (#1758) Bumps [mockito-core](https://github.com/mockito/mockito) from 2.24.0 to 2.24.5. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v2.24.0...v2.24.5) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 59871d793..b3a0a6ab3 100644 --- a/pom.xml +++ b/pom.xml @@ -874,7 +874,7 @@ org.mockito mockito-core test - 2.24.0 + 2.24.5 hamcrest-core From 81517dc3c7fc08c25f8051ef143387ebe3d0ec4d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Mon, 25 Feb 2019 08:08:37 +0100 Subject: [PATCH 18/83] [Security] Bump h2 from 1.4.197 to 1.4.198 (#1761) Bumps [h2](https://github.com/h2database/h2database) from 1.4.197 to 1.4.198. **This update includes security fixes.** - [Release notes](https://github.com/h2database/h2database/releases) - [Commits](https://github.com/h2database/h2database/compare/version-1.4.197...version-1.4.198) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b3a0a6ab3..ec210eba8 100644 --- a/pom.xml +++ b/pom.xml @@ -901,7 +901,7 @@ com.h2database h2 - 1.4.197 + 1.4.198 test From ffb957ff19fc204614c010d0432e4330c6f14c49 Mon Sep 17 00:00:00 2001 From: lifehome Date: Thu, 28 Feb 2019 19:27:39 +0800 Subject: [PATCH 19/83] Fix a typo (#1763) --- src/main/resources/messages/messages_zhhk.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/messages/messages_zhhk.yml b/src/main/resources/messages/messages_zhhk.yml index b37b54663..722ff7fe3 100644 --- a/src/main/resources/messages/messages_zhhk.yml +++ b/src/main/resources/messages/messages_zhhk.yml @@ -136,7 +136,7 @@ verification: # Two-factor authentication two_factor: - code_created: '&8[&6用戶系統&8] &b你的登入金鑰為&9〔 %c%code&9 〕&b,掃描連結為:%nl%&c %url' + code_created: '&8[&6用戶系統&8] &b你的登入金鑰為&9〔 &c%code&9 〕&b,掃描連結為:%nl%&c %url' confirmation_required: '&8[&6用戶系統&8] &b請使用指令《 &f/2fa confirm <驗證碼>&b 》以確認你的身份。' code_required: '&8[&6用戶系統&8] &b請使用指令《 &f/2fa code <驗證碼>&b 》以驗證你的帳戶。' already_enabled: '&8[&6用戶系統&8] &2嗯...這個帳戶已經啓用了兩步驗證功能,毋須再次啓用。' From c856191659046174a564aeb86481cb2cb9d866c7 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Fri, 1 Mar 2019 20:22:38 +0100 Subject: [PATCH 20/83] Update to ConfigMe 1.1.0 - Squash of PR #1764 --- pom.xml | 2 +- .../xephi/authme/AuthMeInitializationTest.java | 11 +++++++++-- .../settings/SettingsConsistencyTest.java | 4 +++- .../fr/xephi/authme/settings/SettingsTest.java | 18 +++++++++++++++--- 4 files changed, 28 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index ec210eba8..7166f6640 100644 --- a/pom.xml +++ b/pom.xml @@ -560,7 +560,7 @@ ch.jalu configme - 1.0.1 + 1.1.0 true diff --git a/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java b/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java index 887bf6d09..55485de0b 100644 --- a/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java +++ b/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java @@ -1,5 +1,6 @@ package fr.xephi.authme; +import ch.jalu.configme.resource.PropertyReader; import ch.jalu.configme.resource.PropertyResource; import ch.jalu.injector.Injector; import ch.jalu.injector.InjectorBuilder; @@ -34,12 +35,14 @@ import org.mockito.junit.MockitoJUnitRunner; import java.io.File; import java.io.IOException; +import java.util.Collections; import java.util.logging.Logger; import static fr.xephi.authme.settings.properties.AuthMeSettingsRetriever.buildConfigurationData; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -91,8 +94,12 @@ public class AuthMeInitializationTest { @Test public void shouldInitializeAllServices() { // given - Settings settings = - new Settings(dataFolder, mock(PropertyResource.class, RETURNS_DEEP_STUBS), null, buildConfigurationData()); + PropertyReader reader = mock(PropertyReader.class, RETURNS_DEEP_STUBS); + given(reader.getList(anyString())).willReturn(Collections.emptyList()); + PropertyResource resource = mock(PropertyResource.class); + given(resource.createReader()).willReturn(reader); + + Settings settings = new Settings(dataFolder, resource, null, buildConfigurationData()); Injector injector = new InjectorBuilder() .addDefaultHandlers("fr.xephi.authme") diff --git a/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java b/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java index 5a1de0e6e..f589e6c33 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java @@ -120,7 +120,9 @@ public class SettingsConsistencyTest { */ private static Class> getEnumClass(Property property) { if (property instanceof EnumProperty) { - return getFieldValue(EnumProperty.class, (EnumProperty) property, "clazz"); + Class clazz = property.getDefaultValue().getClass(); + // Check if is anonymous class in case enum implements methods, e.g. AllowFlightRestoreType + return clazz.isAnonymousClass() ? clazz.getEnclosingClass() : clazz; } else if (property instanceof EnumSetProperty) { return getFieldValue(EnumSetProperty.class, (EnumSetProperty) property, "enumClass"); } diff --git a/src/test/java/fr/xephi/authme/settings/SettingsTest.java b/src/test/java/fr/xephi/authme/settings/SettingsTest.java index 93934b1ab..73d3cc8d6 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsTest.java @@ -2,6 +2,7 @@ package fr.xephi.authme.settings; import ch.jalu.configme.configurationdata.ConfigurationData; import ch.jalu.configme.configurationdata.ConfigurationDataBuilder; +import ch.jalu.configme.resource.PropertyReader; import ch.jalu.configme.resource.PropertyResource; import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.properties.TestConfiguration; @@ -14,9 +15,12 @@ import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.util.Collections; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -50,7 +54,7 @@ public class SettingsTest { createFile(emailFile); Files.write(emailFile.toPath(), emailMessage.getBytes()); - PropertyResource resource = mock(PropertyResource.class, RETURNS_DEEP_STUBS); + PropertyResource resource = mockPropertyResourceAndReader(); Settings settings = new Settings(testPluginFolder, resource, null, CONFIG_DATA); // when @@ -68,7 +72,7 @@ public class SettingsTest { createFile(emailFile); Files.write(emailFile.toPath(), emailMessage.getBytes()); - PropertyResource resource = mock(PropertyResource.class, RETURNS_DEEP_STUBS); + PropertyResource resource = mockPropertyResourceAndReader(); Settings settings = new Settings(testPluginFolder, resource, null, CONFIG_DATA); // when @@ -86,7 +90,7 @@ public class SettingsTest { createFile(emailFile); Files.write(emailFile.toPath(), emailMessage.getBytes()); - PropertyResource resource = mock(PropertyResource.class, RETURNS_DEEP_STUBS); + PropertyResource resource = mockPropertyResourceAndReader(); Settings settings = new Settings(testPluginFolder, resource, null, CONFIG_DATA); // when @@ -96,6 +100,14 @@ public class SettingsTest { assertThat(result, equalTo(emailMessage)); } + private static PropertyResource mockPropertyResourceAndReader() { + PropertyReader reader = mock(PropertyReader.class, RETURNS_DEEP_STUBS); + given(reader.getList(anyString())).willReturn(Collections.emptyList()); + PropertyResource resource = mock(PropertyResource.class); + given(resource.createReader()).willReturn(reader); + return resource; + } + private static void createFile(File file) { try { file.getParentFile().mkdirs(); From c328f9c75a17fabbf3d089509d73202d4f6923f0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Tue, 5 Mar 2019 08:01:32 +0100 Subject: [PATCH 21/83] Bump maven-javadoc-plugin from 3.0.1 to 3.1.0 (#1770) Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.0.1 to 3.1.0. - [Release notes](https://github.com/apache/maven-javadoc-plugin/releases) - [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.0.1...maven-javadoc-plugin-3.1.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7166f6640..61007e061 100644 --- a/pom.xml +++ b/pom.xml @@ -222,7 +222,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.0.1 + 3.1.0 ${project.finalNameBase} From b60237d455e2cb1ab135be0a49fb428992f4e3d0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Tue, 5 Mar 2019 08:02:21 +0100 Subject: [PATCH 22/83] Bump PBKDF2 from 1.1.2 to 1.1.4 (#1769) Bumps [PBKDF2](https://github.com/m9aertner/PBKDF2) from 1.1.2 to 1.1.4. - [Release notes](https://github.com/m9aertner/PBKDF2/releases) - [Commits](https://github.com/m9aertner/PBKDF2/compare/v1.1.2...v1.1.4) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 61007e061..e00a4b3df 100644 --- a/pom.xml +++ b/pom.xml @@ -498,7 +498,7 @@ de.rtner PBKDF2 - 1.1.2 + 1.1.4 true From b84bc0921ce5b29c258901da92f9283bdd7f406e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Tue, 5 Mar 2019 08:02:35 +0100 Subject: [PATCH 23/83] Bump checker-qual from 2.6.0 to 2.7.0 (#1768) Bumps [checker-qual](https://github.com/typetools/checker-framework) from 2.6.0 to 2.7.0. - [Release notes](https://github.com/typetools/checker-framework/releases) - [Changelog](https://github.com/typetools/checker-framework/blob/master/changelog.txt) - [Commits](https://github.com/typetools/checker-framework/compare/checker-framework-2.6.0...checker-framework-2.7.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e00a4b3df..b9e593d27 100644 --- a/pom.xml +++ b/pom.xml @@ -887,7 +887,7 @@ org.checkerframework checker-qual - 2.6.0 + 2.7.0 test From fffd4b17ee913c83e0c59a239f58555ce065769d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 8 Mar 2019 15:53:37 +0100 Subject: [PATCH 24/83] Bump mockito-core from 2.24.5 to 2.25.0 (#1771) Bumps [mockito-core](https://github.com/mockito/mockito) from 2.24.5 to 2.25.0. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v2.24.5...v2.25.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b9e593d27..0fcc0b211 100644 --- a/pom.xml +++ b/pom.xml @@ -874,7 +874,7 @@ org.mockito mockito-core test - 2.24.5 + 2.25.0 hamcrest-core From e0d30e41124559925e130b8e0eec369066aee477 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Thu, 14 Mar 2019 14:22:09 +0100 Subject: [PATCH 25/83] Bump h2 from 1.4.198 to 1.4.199 (#1775) Bumps [h2](https://github.com/h2database/h2database) from 1.4.198 to 1.4.199. - [Release notes](https://github.com/h2database/h2database/releases) - [Commits](https://github.com/h2database/h2database/compare/version-1.4.198...version-1.4.199) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0fcc0b211..f6817d684 100644 --- a/pom.xml +++ b/pom.xml @@ -901,7 +901,7 @@ com.h2database h2 - 1.4.198 + 1.4.199 test From 188e8f14813c0103c156f4d92967dfb221a5dee0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 15 Mar 2019 20:20:04 +0100 Subject: [PATCH 26/83] Bump sqlite-jdbc from 3.25.2 to 3.27.2 (#1777) Bumps [sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.25.2 to 3.27.2. - [Release notes](https://github.com/xerial/sqlite-jdbc/releases) - [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG) - [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.25.2...3.27.2) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f6817d684..dc8c57bfc 100644 --- a/pom.xml +++ b/pom.xml @@ -895,7 +895,7 @@ org.xerial sqlite-jdbc - 3.25.2 + 3.27.2 test From da7d08862e22105580e88528d3cb102a024169b8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Tue, 19 Mar 2019 23:58:59 +0100 Subject: [PATCH 27/83] Bump mockito-core from 2.25.0 to 2.25.1 (#1778) Bumps [mockito-core](https://github.com/mockito/mockito) from 2.25.0 to 2.25.1. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v2.25.0...v2.25.1) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index dc8c57bfc..512c62078 100644 --- a/pom.xml +++ b/pom.xml @@ -874,7 +874,7 @@ org.mockito mockito-core test - 2.25.0 + 2.25.1 hamcrest-core From b57f6dcbf1c5d520d1b72f57c5497d87d9b072ee Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 5 Apr 2019 08:17:31 +0200 Subject: [PATCH 28/83] Bump checker-qual from 2.7.0 to 2.8.0 (#1785) Bumps [checker-qual](https://github.com/typetools/checker-framework) from 2.7.0 to 2.8.0. - [Release notes](https://github.com/typetools/checker-framework/releases) - [Changelog](https://github.com/typetools/checker-framework/blob/master/changelog.txt) - [Commits](https://github.com/typetools/checker-framework/compare/checker-framework-2.7.0...checker-framework-2.8.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 512c62078..e99f835ef 100644 --- a/pom.xml +++ b/pom.xml @@ -887,7 +887,7 @@ org.checkerframework checker-qual - 2.7.0 + 2.8.0 test From 9c06bd580bbebd24d2557fb4fde3d684ff0e8249 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 5 Apr 2019 08:18:00 +0200 Subject: [PATCH 29/83] Bump mockito-core from 2.25.1 to 2.26.0 (#1784) Bumps [mockito-core](https://github.com/mockito/mockito) from 2.25.1 to 2.26.0. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v2.25.1...v2.26.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e99f835ef..c7cd391b2 100644 --- a/pom.xml +++ b/pom.xml @@ -874,7 +874,7 @@ org.mockito mockito-core test - 2.25.1 + 2.26.0 hamcrest-core From 08c1bb33c7693483597230c14a072796fceb14bf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 5 Apr 2019 22:13:49 +0200 Subject: [PATCH 30/83] Bump sqlite-jdbc from 3.27.2 to 3.27.2.1 (#1780) Bumps [sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.27.2 to 3.27.2.1. - [Release notes](https://github.com/xerial/sqlite-jdbc/releases) - [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG) - [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.27.2...3.27.2.1) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c7cd391b2..b178b8e23 100644 --- a/pom.xml +++ b/pom.xml @@ -895,7 +895,7 @@ org.xerial sqlite-jdbc - 3.27.2 + 3.27.2.1 test From 44cb7875775710d4b6818dd9c5d938ac736dc7c9 Mon Sep 17 00:00:00 2001 From: Alexandre Vanhecke Date: Fri, 5 Apr 2019 21:51:54 +0200 Subject: [PATCH 31/83] Add an option to disable MySQL server certificate check - Fix #1735 --- src/main/java/fr/xephi/authme/datasource/MySQL.java | 7 +++++++ .../xephi/authme/settings/properties/DatabaseSettings.java | 6 ++++++ .../settings/properties/AuthMeSettingsRetrieverTest.java | 2 +- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/xephi/authme/datasource/MySQL.java b/src/main/java/fr/xephi/authme/datasource/MySQL.java index 3bb187ff1..badeea140 100644 --- a/src/main/java/fr/xephi/authme/datasource/MySQL.java +++ b/src/main/java/fr/xephi/authme/datasource/MySQL.java @@ -34,6 +34,7 @@ import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException; public class MySQL extends AbstractSqlDataSource { private boolean useSsl; + private boolean serverCertificateVerification; private String host; private String port; private String username; @@ -103,6 +104,7 @@ public class MySQL extends AbstractSqlDataSource { this.poolSize = settings.getProperty(DatabaseSettings.MYSQL_POOL_SIZE); this.maxLifetime = settings.getProperty(DatabaseSettings.MYSQL_CONNECTION_MAX_LIFETIME); this.useSsl = settings.getProperty(DatabaseSettings.MYSQL_USE_SSL); + this.serverCertificateVerification = settings.getProperty(DatabaseSettings.MYSQL_CHECK_SERVER_CERTIFICATE); } /** @@ -126,6 +128,11 @@ public class MySQL extends AbstractSqlDataSource { // Request mysql over SSL ds.addDataSourceProperty("useSSL", String.valueOf(useSsl)); + // Disabling server certificate verification on need + if (!serverCertificateVerification) { + ds.addDataSourceProperty("verifyServerCertificate", String.valueOf(false)); + } + // Encoding ds.addDataSourceProperty("characterEncoding", "utf8"); ds.addDataSourceProperty("encoding", "UTF-8"); diff --git a/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java b/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java index 40e9933a3..83ed18e7a 100644 --- a/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java +++ b/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java @@ -31,6 +31,12 @@ public final class DatabaseSettings implements SettingsHolder { public static final Property MYSQL_USE_SSL = newProperty("DataSource.mySQLUseSSL", true); + @Comment({"Verification of server's certificate.", + "We would not recommend to set this option to false.", + "Set this option to false at your own risk if and only if you know what you're doing"}) + public static final Property MYSQL_CHECK_SERVER_CERTIFICATE = + newProperty( "DataSource.mySQLCheckServerCertificate", true ); + @Comment("Username to connect to the MySQL database") public static final Property MYSQL_USERNAME = newProperty("DataSource.mySQLUsername", "authme"); diff --git a/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java b/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java index 445b6965a..1860480f5 100644 --- a/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java +++ b/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java @@ -22,7 +22,7 @@ public class AuthMeSettingsRetrieverTest { // an error margin of 10: this prevents us from having to adjust the test every time the config is changed. // If this test fails, replace the first argument in closeTo() with the new number of properties assertThat((double) configurationData.getProperties().size(), - closeTo(171, 10)); + closeTo(182, 10)); } @Test From 7503bd4b9eeb24a3751d8d7dbfd75146f5e1c067 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Mon, 8 Apr 2019 23:48:41 +0200 Subject: [PATCH 32/83] Bump luckperms-api from 4.3 to 4.4 (#1787) Bumps [luckperms-api](https://github.com/lucko/LuckPerms) from 4.3 to 4.4. - [Release notes](https://github.com/lucko/LuckPerms/releases) - [Commits](https://github.com/lucko/LuckPerms/compare/v4.3...v4.4) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b178b8e23..b4f37d04a 100644 --- a/pom.xml +++ b/pom.xml @@ -600,7 +600,7 @@ me.lucko.luckperms luckperms-api - 4.3 + 4.4 provided From 97e34d716deb0efa4575deab9d7d8927a1692673 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Thu, 11 Apr 2019 08:22:36 +0200 Subject: [PATCH 33/83] Bump mockito-core from 2.26.0 to 2.27.0 (#1788) Bumps [mockito-core](https://github.com/mockito/mockito) from 2.26.0 to 2.27.0. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v2.26.0...v2.27.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b4f37d04a..16fc8edcc 100644 --- a/pom.xml +++ b/pom.xml @@ -874,7 +874,7 @@ org.mockito mockito-core test - 2.26.0 + 2.27.0 hamcrest-core From b897f7c25f9225240b7f951678a615b0c2a99a86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sr=C4=91an=20Coki=C4=87?= Date: Sat, 13 Apr 2019 17:30:27 +0200 Subject: [PATCH 34/83] Translation to Serbian (RS) (#1792) * Create messages_rs.yml * Create help_rs.yml --- src/main/resources/messages/help_rs.yml | 45 ++++++ src/main/resources/messages/messages_rs.yml | 154 ++++++++++++++++++++ 2 files changed, 199 insertions(+) create mode 100644 src/main/resources/messages/help_rs.yml create mode 100644 src/main/resources/messages/messages_rs.yml diff --git a/src/main/resources/messages/help_rs.yml b/src/main/resources/messages/help_rs.yml new file mode 100644 index 000000000..144b9d9ad --- /dev/null +++ b/src/main/resources/messages/help_rs.yml @@ -0,0 +1,45 @@ +# Konfiguracija za prevođenje pomoći AuthMe, primer kada kucate /authme help ili /authme help register + +# ------------------------------------------------------- +# Lista of teksta u pomoćnoj sekciji +common: + header: '==========[ AuthMeReloaded POMOĆ ]==========' + optional: 'Opcionalno' + hasPermission: 'Imate dozvola' + noPermission: 'Nemate dozvola' + default: 'Početan' + result: 'Rezultat' + defaultPermissions: + notAllowed: 'Nemate dozvola' + opOnly: 'Samo OP-ovi' + allowed: 'Dozvoljeno svima' + +# ------------------------------------------------------- +# Naslovi pojedinih sekcija pomoći +# Izbrišite deo teksta ako želite da iskjučite to, primer da sakrijte alternative: +# alternatives: '' +section: + command: 'Komanda' + description: 'Kratak opis' + detailedDescription: 'Detaljan opis' + arguments: 'Argumenti' + permissions: 'Dozvole' + alternatives: 'Alternative' + children: 'Komande' + +# ------------------------------------------------------- +# Možete prevesti podatke svih komandi koristeći uzorak ispod. +# Na primer da prevedete /authme reload, napravite sekciju "authme.reload", ili "login" za /login +# Ako komanda ima argumente, možete koristiti arg1 kao što je prikazano ispod za prvi argument, itd +# Prevodi ne moraju biti kompletni; sve sekcije koje nedostaju će biti uklonjene iz početnog tiho +# Važno: Postavite glavne komande kao što su "authme" pre njihovih sledbenika (primer "authme.reload") +commands: + authme.register: + description: 'Registrujte igrača' + detailedDescription: 'Registrujte specifičnog igrača specifičnom lozinkom.' + arg1: + label: 'igrač' + description: 'Ime igrača' + arg2: + label: 'lozinka' + description: 'Lozinka' diff --git a/src/main/resources/messages/messages_rs.yml b/src/main/resources/messages/messages_rs.yml new file mode 100644 index 000000000..9cb79cd37 --- /dev/null +++ b/src/main/resources/messages/messages_rs.yml @@ -0,0 +1,154 @@ +# Lista globalnih tagova: +# %nl% - Nova linija. +# %username% - Zamenjuje ime igrača kome se šalje poruka. +# %displayname% - Zamenjuje nadimak (i boje) igrača kome se šalje poruka. + +# Registracija +registration: + register_request: '&3Molimo Vas, registrujte se na server komandom: /register ' + command_usage: '&cUpotreba: /register ' + reg_only: '&4Samo registrovani igrači mogu ući na server! Molimo Vas posetite http://example.com da biste se registrovali!' + kicked_admin_registered: 'Admin vas je upravo registrovao; molimo Vas uđite ponovo' + success: '&2Uspešno registrovani!' + disabled: '&cRegistracija u igri je isključena!' + name_taken: '&cKorisnik je već registrovan!' + +# Greške lozinki i registracije +password: + match_error: '&cLozinke se nisu složile, proverite ih ponovo!' + name_in_password: '&cNe možete koristiti svoje ime za lozinku, molimo vas da izaberete drugu...' + unsafe_password: '&cIzabrana lozinka nije bezbedna, molimo vas da izaberete drugu...' + forbidden_characters: '&4Vaša lozinka sadrži nedozvoljene karaktere. Dozvoljeni karakteri: %valid_chars' + wrong_length: '&cVaša lozinka je prekratka ili predugačka! Molimo Vas da probate drugu!' + +# Ulogovanje +login: + command_usage: '&cUpotreba: /login ' + wrong_password: '&cPogrešna lozinka!' + success: '&2Uspešno ste se ulogovali!' + login_request: '&cMolimo Vas, ulogujte se komandom: /login ' + timeout_error: '&4Vreme za login isteklo, izbačeni ste sa servera, molimo Vas da pokušate ponovo!' + +# Greške +error: + unregistered_user: '&cKorisnik nije registrovan!' + denied_command: '&cDa biste koristili komande morate se autentifikovati!' + denied_chat: '&cDa biste koristili čet morate se autentifikovati!' + not_logged_in: '&cNiste ulogovani!' + tempban_max_logins: '&cPrivremeno ste banovani zbog previše pogrešnih pokušaja ulogovanja.' + max_registration: '&cDostigli ste maksimalan broj registracija (%reg_count/%max_acc %reg_names) za vaše povezivanje!' + no_permission: '&4Nemate dovoljno dozvola da uradite to!' + unexpected_error: '&4Pojavila se neočekivana greška, molimo Vas kontaktirajte administratora!' + kick_for_vip: '&3VIP igrač je ušao na server dok je bio pun!' + logged_in: '&cVeć ste ulogovani!' + +# AntiBot +antibot: + kick_antibot: 'AntiBot mod zaštite je aktiviran! Morate sačekati par minuta pre povezivanja na server.' + auto_enabled: '&4[AntiBotSlužba] AntiBot je aktiviran zbog prevelikog broja povezivanja!' + auto_disabled: '&2[AntiBotSlužba] AntiBot je isključen posle %m minut(a)!' + +unregister: + success: '&cUspešno odregistrovani!' + command_usage: '&cUpotreba: /unregister ' + +# Ostale poruke +misc: + accounts_owned_self: 'Vi imate %count naloga:' + accounts_owned_other: 'Igrač %name ima %count naloga:' + account_not_activated: '&cVaš nalog još uvek nije aktiviran, molimo Vas proverite svoj email!' + password_changed: '&2Lozinka uspešno promenjena!' + logout: '&2Uspešno ste se odlogovali!' + reload: '&2Konfiguracija i databaza su uspešno osveženi!' + usage_change_password: '&cUpotreba: /changepassword ' + +# Poruke vezane za sesiju +session: + invalid_session: '&cVaš IP je promenjen i vaši podaci o sesiji su istekli!' + valid_session: '&2Ulogovani ste zbog ponovnog povezivanja sesije.' + +# Greške pri povezivanju +on_join_validation: + name_length: '&4Vaše korisničko ime je prekratko ili predugačko!' + characters_in_name: '&4Vaše korisničko ime sadrži nedozvoljene karaktere. Dozvoljeni karakteri: %valid_chars' + country_banned: '&4Vaša država je banovana sa ovog servera!' + not_owner_error: 'Ne posedujete ovaj nalog. Molimo Vas izaberite drugo ime!' + kick_full_server: '&4Server je pun, probajte ponovo kasnije!' + same_nick_online: '&4Isto korisničko ime već igra na serveru!' + invalid_name_case: 'Morate ući sa korisničkim imenom %valid, umesto %invalid.' + same_ip_online: 'Igrač sa istim IP-em je već u igri!' + quick_command: 'Iskoristili ste komandu previše brzo! Molimo Vas, uđite opet na server i sačekajte malo pre korišćenja komandi.' + +# Email +email: + usage_email_add: '&cUpotreba: /email add ' + usage_email_change: '&cUpotreba: /email change ' + new_email_invalid: '&cNevažeći email, pokušajte ponovo!' + old_email_invalid: '&cNevažeći stari email, pokušajte ponovo!' + invalid: '&cNevažeći email, pokušajte ponovo!' + added: '&2Email adresa je uspešno dodata na vaš nalog!' + request_confirmation: '&cMolimo Vas podvrdite svoju email adresu!' + changed: '&2Email adresa uspešno promenjena!' + email_show: '&2Vaša email adresa je: &f%email' + incomplete_settings: 'Greška: nisu postavljena potrebna podešavanja za slanje emaila. Molimo Vas da kontaktirate admina.' + already_used: '&4Email adresa je već u upotrebi' + send_failure: 'Email se nije mogao poslati. Molimo Vas da kontaktirate administratora.' + no_email_for_account: '&2Trenutno nemate email adresu povezanu sa svojim nalogom.' + add_email_request: '&3Molimo Vas dodajte email adresu na vaš nalog komandom: /email add ' + change_password_expired: 'Ne možete više promeniti svoju lozinku koristeći ovu komandu.' + email_cooldown_error: '&cEmail je već poslat. Morate sačekati %time pre nego što možete poslati drugi.' + add_not_allowed: '&cDodavanje emaila nije dozvoljeno' + change_not_allowed: '&cPromena emaila nije dozvoljena' + +# Povratak lozinke putem emaila +recovery: + forgot_password_hint: '&3Zaboravili ste lozinku? Molimo Vas ukucajte komandu: /email recovery ' + command_usage: '&cUpotreba: /email recovery ' + email_sent: '&2Email za povratak je poslat uspešno! Molimo Vas proverite inbox svog emaila!' + code: + code_sent: 'Povratni kod za resetovanje vaše lozinke je poslat na vaš email.' + incorrect: 'Povratni kod nije tačan! Imate još %count pokušaja.' + tries_exceeded: 'Dostigli ste maksimalni broj pokušaja povratka sa kodom. Koristite "/email recovery [email]" da generišite nov.' + correct: 'Povratni kod uspešno unesen!' + change_password: 'Molimo Vas iskoristite komandu /email setpassword da odmah promenite svoju lozinku.' + +# Captcha +captcha: + usage_captcha: '&3Da biste se ulogovali morate rešiti captcha kod, molimo Vas iskoristite komandu: /captcha %captcha_code' + wrong_captcha: '&cPogrešna captcha, molimo Vas kucajte "/captcha %captcha_code" u četu!' + valid_captcha: '&2Captcha kod uspešno unesen!' + captcha_for_registration: 'Da biste se registrovali morate rešiti captcha kod, molimo Vas iskoristite komandu: /captcha %captcha_code' + register_captcha_valid: '&2Ispravna captcha! Sada se možete registrovati koristeći /register' + +# Verifikacioni kod +verification: + code_required: '&3Ova komanda je osetljiva i zahteva verifikaciju emaila! Molimo Vas proverite svoj inbox i pratite instrukcije u emailu.' + command_usage: '&cUpotreba: /verification ' + incorrect_code: '&cNeispravan kod, molimo Vas unesite "/verification " u čet, koristeći kod koji ste dobili u emailu' + success: '&2Vaš identitet je verifikovan! Sada možete koristiti sve komande u trenutnoj sesiji!' + already_verified: '&2Već možete koristiti sve osetljive komande u trenutnoj sesiji!' + code_expired: '&3Vaš kod je istekao! Iskoristite drugu osetljivu komandu da dobijete kod!' + email_needed: '&3Da biste verifikovali svoj identitet morate da povežete svoju email adresu sa svojim nalogom!!' + +two_factor: + code_created: '&2Vaš tajni kod je %code. Možete ga skenirati sa %url' + confirmation_required: 'Molimo Vas potvrdite svoj kod koristeći /2fa confirm ' + code_required: 'Molimo Vas unesite svoj autentifikacioni kod dva-faktora koristeći /2fa code ' + already_enabled: 'Autentifikacioni dupli-faktor je već aktiviran za vaš nalog!' + enable_error_no_code: 'Nijedan 2fa ključ nije generisan za vas ili je istekao. Molimo Vas kucajte /2fa add' + enable_success: 'Uspešno ste aktivirali dvo-faktornu autentifikaciju za vaš nalog' + enable_error_wrong_code: 'Pogrešan kod ili je kod istekao. Molimo Vas kucajte /2fa add' + not_enabled_error: 'Dvo-faktorna autentifikacija nije aktivirana za vaš nalog. Kucajte /2fa add' + removed_success: 'Uspešno ste uklonili dvo-faktornu autentifikaciju sa vašeg naloga' + invalid_code: 'Nevažeći kod!' + +# Vremenske odredbe +time: + second: 'sekund' + seconds: 'sekundi' + minute: 'minut' + minutes: 'minuta' + hour: 'čas' + hours: 'časova' + day: 'dan' + days: 'dana' From 53b844230995b1da367781dc93a227473ed495a8 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sun, 14 Apr 2019 11:10:07 +0200 Subject: [PATCH 35/83] Add Serbian to translation doc, rename from "rs" to "sr", fix percentage bar images --- docs/translations.md | 66 +++++++++---------- .../messages/{help_rs.yml => help_sr.yml} | 0 .../{messages_rs.yml => messages_sr.yml} | 0 .../TranslationPageGenerator.java | 1 + .../docs/translations/translations.tpl.md | 2 +- 5 files changed, 35 insertions(+), 34 deletions(-) rename src/main/resources/messages/{help_rs.yml => help_sr.yml} (100%) rename src/main/resources/messages/{messages_rs.yml => messages_sr.yml} (100%) diff --git a/docs/translations.md b/docs/translations.md index aac58a65f..0f63b6e58 100644 --- a/docs/translations.md +++ b/docs/translations.md @@ -1,5 +1,5 @@ - + # AuthMe Translations The following translations are available in AuthMe. Set `messagesLanguage` to the language code @@ -7,38 +7,38 @@ in your config.yml to use the language, or use another language code to start a Code | Language | Translated |   ---- | -------- | ---------: | ------ -[en](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_en.yml) | English | 100% | bar -[bg](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_bg.yml) | Bulgarian | 76% | bar -[br](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_br.yml) | Brazilian | 80% | bar -[cz](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_cz.yml) | Czech | 80% | bar -[de](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_de.yml) | German | 80% | bar -[eo](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_eo.yml) | Esperanto | 80% | bar -[es](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_es.yml) | Spanish | 100% | bar -[et](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_et.yml) | Estonian | 80% | bar -[eu](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_eu.yml) | Basque | 42% | bar -[fi](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_fi.yml) | Finnish | 45% | bar -[fr](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_fr.yml) | French | 89% | bar -[gl](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_gl.yml) | Galician | 48% | bar -[hu](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_hu.yml) | Hungarian | 87% | bar -[id](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_id.yml) | Indonesian | 47% | bar -[it](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_it.yml) | Italian | 100% | bar -[ko](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_ko.yml) | Korean | 89% | bar -[lt](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_lt.yml) | Lithuanian | 36% | bar -[nl](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_nl.yml) | Dutch | 80% | bar -[pl](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_pl.yml) | Polish | 100% | bar -[pt](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_pt.yml) | Portuguese | 100% | bar -[ro](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_ro.yml) | Romanian | 80% | bar -[ru](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_ru.yml) | Russian | 93% | bar -[sk](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_sk.yml) | Slovakian | 80% | bar -[tr](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_tr.yml) | Turkish | 100% | bar -[uk](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_uk.yml) | Ukrainian | 63% | bar -[vn](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_vn.yml) | Vietnamese | 77% | bar -[zhcn](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhcn.yml) | Chinese (China) | 89% | bar -[zhhk](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhhk.yml) | Chinese (Hong Kong) | 80% | bar -[zhmc](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhmc.yml) | Chinese (Macau) | 65% | bar -[zhtw](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhtw.yml) | Chinese (Taiwan) | 87% | bar - +[en](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_en.yml) | English | 100% | 100 +[bg](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_bg.yml) | Bulgarian | 100% | 100 +[br](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_br.yml) | Brazilian | 97% | 97 +[cz](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_cz.yml) | Czech | 80% | 80 +[de](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_de.yml) | German | 80% | 80 +[eo](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_eo.yml) | Esperanto | 80% | 80 +[es](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_es.yml) | Spanish | 100% | 100 +[et](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_et.yml) | Estonian | 100% | 100 +[eu](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_eu.yml) | Basque | 42% | 42 +[fi](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_fi.yml) | Finnish | 45% | 45 +[fr](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_fr.yml) | French | 100% | 100 +[gl](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_gl.yml) | Galician | 48% | 48 +[hu](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_hu.yml) | Hungarian | 100% | 100 +[id](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_id.yml) | Indonesian | 93% | 93 +[it](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_it.yml) | Italian | 100% | 100 +[ko](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_ko.yml) | Korean | 100% | 100 +[lt](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_lt.yml) | Lithuanian | 36% | 36 +[nl](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_nl.yml) | Dutch | 80% | 80 +[pl](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_pl.yml) | Polish | 100% | 100 +[pt](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_pt.yml) | Portuguese | 100% | 100 +[ro](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_ro.yml) | Romanian | 80% | 80 +[ru](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_ru.yml) | Russian | 100% | 100 +[sk](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_sk.yml) | Slovakian | 80% | 80 +[sr](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_sr.yml) | Serbian | 100% | 100 +[tr](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_tr.yml) | Turkish | 100% | 100 +[uk](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_uk.yml) | Ukrainian | 63% | 63 +[vn](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_vn.yml) | Vietnamese | 77% | 77 +[zhcn](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhcn.yml) | Chinese (China) | 98% | 98 +[zhhk](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhhk.yml) | Chinese (Hong Kong) | 100% | 100 +[zhmc](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhmc.yml) | Chinese (Macau) | 65% | 65 +[zhtw](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhtw.yml) | Chinese (Taiwan) | 87% | 87 --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Thu Aug 02 21:12:10 CEST 2018 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Sun Apr 14 11:09:15 CEST 2019 diff --git a/src/main/resources/messages/help_rs.yml b/src/main/resources/messages/help_sr.yml similarity index 100% rename from src/main/resources/messages/help_rs.yml rename to src/main/resources/messages/help_sr.yml diff --git a/src/main/resources/messages/messages_rs.yml b/src/main/resources/messages/messages_sr.yml similarity index 100% rename from src/main/resources/messages/messages_rs.yml rename to src/main/resources/messages/messages_sr.yml diff --git a/src/test/java/tools/docs/translations/TranslationPageGenerator.java b/src/test/java/tools/docs/translations/TranslationPageGenerator.java index d5e480990..e4087e834 100644 --- a/src/test/java/tools/docs/translations/TranslationPageGenerator.java +++ b/src/test/java/tools/docs/translations/TranslationPageGenerator.java @@ -129,6 +129,7 @@ public class TranslationPageGenerator implements AutoToolTask { .put("ro", "Romanian") .put("ru", "Russian") .put("sk", "Slovakian") + .put("sr", "Serbian") .put("tr", "Turkish") .put("uk", "Ukrainian") .put("vn", "Vietnamese") diff --git a/src/test/java/tools/docs/translations/translations.tpl.md b/src/test/java/tools/docs/translations/translations.tpl.md index 5308b6554..51c5aeadc 100644 --- a/src/test/java/tools/docs/translations/translations.tpl.md +++ b/src/test/java/tools/docs/translations/translations.tpl.md @@ -8,7 +8,7 @@ in your config.yml to use the language, or use another language code to start a Code | Language | Translated |   ---- | -------- | ---------: | ------ [#languages] -[{code}](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_{code}.yml) | {name} | {percentage}% | bar +[{code}](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_{code}.yml) | {name} | {percentage}% | {percentage} [/#languages] {gen_footer} From cdd92ab4ed8daff74456d2343c4cce117e2fbb6a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Wed, 17 Apr 2019 01:50:13 +0200 Subject: [PATCH 36/83] Bump bcrypt from 0.7.0 to 0.8.0 (#1793) Bumps [bcrypt](https://github.com/patrickfav/bcrypt) from 0.7.0 to 0.8.0. - [Release notes](https://github.com/patrickfav/bcrypt/releases) - [Changelog](https://github.com/patrickfav/bcrypt/blob/master/CHANGELOG) - [Commits](https://github.com/patrickfav/bcrypt/compare/v0.7.0...v0.8.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 16fc8edcc..e4c4c812a 100644 --- a/pom.xml +++ b/pom.xml @@ -795,7 +795,7 @@ at.favre.lib bcrypt - 0.7.0 + 0.8.0 true From 7b360a7bb3c95dedc7624be2658d2bb32c1960c6 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Fri, 19 Apr 2019 17:20:55 +0200 Subject: [PATCH 37/83] 5.6.0-beta1 release --- docs/commands.md | 4 +- docs/config.md | 148 +++++++++++++++++++++------------------ docs/hash_algorithms.md | 4 +- docs/permission_nodes.md | 6 +- docs/translations.md | 5 +- pom.xml | 2 +- 6 files changed, 92 insertions(+), 77 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index 163399c0e..60c01dbac 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1,5 +1,5 @@ - + ## AuthMe Commands You can use the following commands to use the features of AuthMe. Mandatory arguments are marked with `< >` @@ -104,4 +104,4 @@ brackets; optional arguments are enclosed in square brackets (`[ ]`). --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Sun Apr 22 11:00:10 CEST 2018 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:04 CEST 2019 diff --git a/docs/config.md b/docs/config.md index 9444bb83e..d68fcd13d 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1,5 +1,5 @@ - + ## AuthMe Configuration The first time you run AuthMe it will create a config.yml file in the plugins/AuthMe folder, @@ -7,66 +7,69 @@ with which you can configure various settings. This following is the initial con the generated config.yml file. ```yml - DataSource: # What type of database do you want to use? - # Valid values: SQLITE, MYSQL - backend: 'SQLITE' + # Valid values: SQLITE, MYSQL, POSTGRESQL + backend: SQLITE # Enable the database caching system, should be disabled on bungeecord environments # or when a website integration is being used. caching: true # Database host address - mySQLHost: '127.0.0.1' + mySQLHost: 127.0.0.1 # Database port mySQLPort: '3306' # Connect to MySQL database over SSL mySQLUseSSL: true + # Verification of server's certificate. + # We would not recommend to set this option to false. + # Set this option to false at your own risk if and only if you know what you're doing + mySQLCheckServerCertificate: true # Username to connect to the MySQL database - mySQLUsername: 'authme' + mySQLUsername: authme # Password to connect to the MySQL database mySQLPassword: '12345' # Database Name, use with converters or as SQLITE database name - mySQLDatabase: 'authme' + mySQLDatabase: authme # Table of the database - mySQLTablename: 'authme' + mySQLTablename: authme # Column of IDs to sort data - mySQLColumnId: 'id' + mySQLColumnId: id # Column for storing or checking players nickname - mySQLColumnName: 'username' + mySQLColumnName: username # Column for storing or checking players RealName - mySQLRealName: 'realname' + mySQLRealName: realname # Column for storing players passwords - mySQLColumnPassword: 'password' + mySQLColumnPassword: password # Column for storing players passwords salts mySQLColumnSalt: '' # Column for storing players emails - mySQLColumnEmail: 'email' + mySQLColumnEmail: email # Column for storing if a player is logged in or not - mySQLColumnLogged: 'isLogged' + mySQLColumnLogged: isLogged # Column for storing if a player has a valid session or not - mySQLColumnHasSession: 'hasSession' + mySQLColumnHasSession: hasSession # Column for storing a player's TOTP key (for two-factor authentication) - mySQLtotpKey: 'totp' + mySQLtotpKey: totp # Column for storing the player's last IP - mySQLColumnIp: 'ip' + mySQLColumnIp: ip # Column for storing players lastlogins - mySQLColumnLastLogin: 'lastlogin' + mySQLColumnLastLogin: lastlogin # Column storing the registration date - mySQLColumnRegisterDate: 'regdate' + mySQLColumnRegisterDate: regdate # Column for storing the IP address at the time of registration - mySQLColumnRegisterIp: 'regip' + mySQLColumnRegisterIp: regip # Column for storing player LastLocation - X - mySQLlastlocX: 'x' + mySQLlastlocX: x # Column for storing player LastLocation - Y - mySQLlastlocY: 'y' + mySQLlastlocY: y # Column for storing player LastLocation - Z - mySQLlastlocZ: 'z' + mySQLlastlocZ: z # Column for storing player LastLocation - World Name - mySQLlastlocWorld: 'world' + mySQLlastlocWorld: world # Column for storing player LastLocation - Yaw - mySQLlastlocYaw: 'yaw' + mySQLlastlocYaw: yaw # Column for storing player LastLocation - Pitch - mySQLlastlocPitch: 'pitch' + mySQLlastlocPitch: pitch # Overrides the size of the DB Connection Pool, default = 10 poolSize: 10 # The maximum lifetime of a connection in the pool, default = 1800 seconds @@ -84,19 +87,19 @@ ExternalBoardOptions: # How much log2 rounds needed in BCrypt (do not change if you do not know what it does) bCryptLog2Round: 10 # phpBB table prefix defined during the phpBB installation process - phpbbTablePrefix: 'phpbb_' + phpbbTablePrefix: phpbb_ # phpBB activated group ID; 2 is the default registered group defined by phpBB phpbbActivatedGroupId: 2 # IP Board table prefix defined during the IP Board installation process - IPBTablePrefix: 'ipb_' + IPBTablePrefix: ipb_ # IP Board default group ID; 3 is the default registered group defined by IP Board IPBActivatedGroupId: 3 # Xenforo table prefix defined during the Xenforo installation process - XFTablePrefix: 'xf_' + XFTablePrefix: xf_ # XenForo default group ID; 2 is the default registered group defined by Xenforo XFActivatedGroupId: 2 # Wordpress prefix defined during WordPress installation - wordpressTablePrefix: 'wp_' + wordpressTablePrefix: wp_ settings: sessions: # Do you want to enable the session feature? @@ -111,13 +114,13 @@ settings: timeout: 10 # Message language, available languages: # https://github.com/AuthMe/AuthMeReloaded/blob/master/docs/translations.md - messagesLanguage: 'en' + messagesLanguage: en # Forces authme to hook into Vault instead of a specific permission handler system. forceVaultHook: false # Log level: INFO, FINE, DEBUG. Use INFO for general messages, # FINE for some additional detailed ones (like password failed), # and DEBUG for debugging - logLevel: 'FINE' + logLevel: FINE # By default we schedule async tasks when talking to the database. If you want # typical communication with the database to happen synchronously, set this to false useAsyncTasks: true @@ -134,14 +137,14 @@ settings: hideChat: false # Allowed commands for unauthenticated players allowCommands: - - '/login' - - '/register' - - '/l' - - '/reg' - - '/email' - - '/captcha' - - '/2fa' - - '/totp' + - /login + - /register + - /l + - /reg + - /email + - /captcha + - /2fa + - /totp # Max number of allowed registrations per IP # The value 0 means an unlimited number of registrations! maxRegPerIp: 1 @@ -163,9 +166,9 @@ settings: # WorldNames where we need to force the spawn location # Case-sensitive! worlds: - - 'world' - - 'world_nether' - - 'world_the_end' + - world + - world_nether + - world_the_end # This option will save the quit location of the players. SaveQuitLocation: false # To activate the restricted user feature you need @@ -207,7 +210,7 @@ settings: # permission: /authme.admin.accounts displayOtherAccounts: true # Spawn priority; values: authme, essentials, cmi, multiverse, default - spawnPriority: 'authme,essentials,cmi,multiverse,default' + spawnPriority: authme,essentials,cmi,multiverse,default # Maximum Login authorized by IP maxLoginPerIp: 0 # Maximum Join authorized by IP @@ -230,6 +233,14 @@ settings: # - 'npcPlayer' # - 'npcPlayer2' UnrestrictedName: [] + # Below you can list all inventories names that AuthMe will ignore + # for registration or login. Configure it at your own risk!! + # This option adds compatibility with some mods. + # It is case-insensitive! Example: + # UnrestrictedInventories: + # - 'myCustomInventory1' + # - 'myCustomInventory2' + UnrestrictedInventories: [] security: # Minimum length of password minPasswordLength: 5 @@ -240,7 +251,7 @@ settings: # PBKDF2DJANGO, WORDPRESS, ROYALAUTH, ARGON2, CUSTOM (for developers only). See full list at # https://github.com/AuthMe/AuthMeReloaded/blob/master/docs/hash_algorithms.md # If you use ARGON2, check that you have the argon2 c library on your system - passwordHash: 'SHA256' + passwordHash: SHA256 # If a password check fails, AuthMe will also try to check with the following hash methods. # Use this setting when you change from one hash method to another. # AuthMe will update the password to the new hash. Example: @@ -259,12 +270,12 @@ settings: # - 'help' unsafePasswords: - '123456' - - 'password' - - 'qwerty' + - password + - qwerty - '12345' - '54321' - '123456789' - - 'help' + - help registration: # Enable registration on the server? enabled: true @@ -278,12 +289,12 @@ settings: # PASSWORD = account is registered with a password supplied by the user; # EMAIL = password is generated and sent to the email provided by the user. # More info at https://github.com/AuthMe/AuthMeReloaded/wiki/Registration - type: 'PASSWORD' + type: PASSWORD # Second argument the /register command should take: NONE = no 2nd argument # CONFIRMATION = must repeat first argument (pass or email) # EMAIL_OPTIONAL = for password register: 2nd argument can be empty or have email address # EMAIL_MANDATORY = for password register: 2nd argument MUST be an email address - secondArg: 'CONFIRMATION' + secondArg: CONFIRMATION # Do we force kick a player after a successful registration? # Do not use with login feature below forceKickAfterRegister: false @@ -339,7 +350,7 @@ GroupOptions: unregisteredPlayerGroup: '' Email: # Email SMTP server host - mailSMTP: 'smtp.gmail.com' + mailSMTP: smtp.gmail.com # Email SMTP server port mailPort: 465 # Only affects port 25: enable TLS/STARTTLS? @@ -355,7 +366,7 @@ Email: # Recovery password length RecoveryPasswordLength: 8 # Mail Subject - mailSubject: 'Your new AuthMe password' + mailSubject: Your new AuthMe password # Like maxRegPerIP but with email maxRegPerEmail: 1 # Recall players to add an email? @@ -364,7 +375,7 @@ Email: delayRecall: 5 # Blacklist these domains for emails emailBlacklisted: - - '10minutemail.com' + - 10minutemail.com # Whitelist ONLY these domains for emails emailWhitelisted: [] # Send the new password drawn in an image? @@ -389,14 +400,16 @@ Protection: enableProtectionRegistered: true # Countries allowed to join the server and register. For country codes, see # https://dev.maxmind.com/geoip/legacy/codes/iso3166/ + # Use "LOCALHOST" for local addresses. # PLEASE USE QUOTES! countries: - - 'US' - - 'GB' + - US + - GB + - LOCALHOST # Countries not allowed to join the server and register # PLEASE USE QUOTES! countriesBlacklist: - - 'A1' + - A1 # Do we need to enable automatic antibot system? enableAntiBot: true # The interval in seconds @@ -421,7 +434,7 @@ Purge: # Do we need to remove the Essentials/userdata/player.yml file during purge process? removeEssentialsFile: false # World in which the players.dat are stored - defaultWorld: 'world' + defaultWorld: world # Remove LimitedCreative/inventories/player.yml, player_creative.yml files during purge? removeLimitedCreativesInventories: false # Do we need to remove the AntiXRayData/PlayerData/player file during purge process? @@ -498,7 +511,7 @@ limbo: # DISABLED: no disk storage, # INDIVIDUAL_FILES: each player data in its own file, # DISTRIBUTED_FILES: distributes players into different files based on their UUID, see below - type: 'INDIVIDUAL_FILES' + type: INDIVIDUAL_FILES # This setting only affects DISTRIBUTED_FILES persistence. The distributed file # persistence attempts to reduce the number of files by distributing players into various # buckets based on their UUID. This setting defines into how many files the players should @@ -508,20 +521,20 @@ limbo: # 6.25 players per file (100 / 16). # Note: if you change this setting all data will be migrated. If you have a lot of data, # change this setting only on server restart, not with /authme reload. - distributionSize: 'SIXTEEN' + distributionSize: SIXTEEN # Whether the player is allowed to fly: RESTORE, ENABLE, DISABLE, NOTHING. # RESTORE sets back the old property from the player. NOTHING will prevent AuthMe # from modifying the 'allow flight' property on the player. - restoreAllowFlight: 'RESTORE' + restoreAllowFlight: RESTORE # Restore fly speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO. # RESTORE: restore the speed the player had; # DEFAULT: always set to default speed; # MAX_RESTORE: take the maximum of the player's current speed and the previous one # RESTORE_NO_ZERO: Like 'restore' but sets speed to default if the player's speed was 0 - restoreFlySpeed: 'RESTORE_NO_ZERO' + restoreFlySpeed: RESTORE_NO_ZERO # Restore walk speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO. # See above for a description of the values. - restoreWalkSpeed: 'RESTORE_NO_ZERO' + restoreWalkSpeed: RESTORE_NO_ZERO BackupSystem: # General configuration for backups: if false, no backups are possible ActivateBackup: false @@ -530,19 +543,19 @@ BackupSystem: # Create backup at every stop of server OnServerStop: true # Windows only: MySQL installation path - MysqlWindowsPath: 'C:\Program Files\MySQL\MySQL Server 5.1\' + MysqlWindowsPath: C:\Program Files\MySQL\MySQL Server 5.1\ # Converter settings: see https://github.com/AuthMe/AuthMeReloaded/wiki/Converters Converter: Rakamak: # Rakamak file name - fileName: 'users.rak' + fileName: users.rak # Rakamak use IP? useIP: false # Rakamak IP file name - ipFileName: 'UsersIp.rak' + ipFileName: UsersIp.rak CrazyLogin: # CrazyLogin database file name - fileName: 'accounts.db' + fileName: accounts.db loginSecurity: # LoginSecurity: convert from SQLite; if false we use MySQL useSqlite: true @@ -555,6 +568,7 @@ Converter: user: '' # LoginSecurity MySQL: password for database user password: '' + ``` To change settings on a running server, save your changes to config.yml and use @@ -562,4 +576,4 @@ To change settings on a running server, save your changes to config.yml and use --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Mon May 21 09:08:25 CEST 2018 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:04 CEST 2019 diff --git a/docs/hash_algorithms.md b/docs/hash_algorithms.md index f22948cee..4272d78a0 100644 --- a/docs/hash_algorithms.md +++ b/docs/hash_algorithms.md @@ -1,5 +1,5 @@ - + ## Hash Algorithms AuthMe supports the following hash algorithms for storing your passwords safely. @@ -80,4 +80,4 @@ or bad. --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Sun Sep 02 20:38:48 CEST 2018 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:06 CEST 2019 diff --git a/docs/permission_nodes.md b/docs/permission_nodes.md index 3f0df2206..2ed9f36c5 100644 --- a/docs/permission_nodes.md +++ b/docs/permission_nodes.md @@ -1,5 +1,5 @@ - + ## AuthMe Permission Nodes The following are the permission nodes that are currently supported by the latest dev builds. @@ -32,8 +32,8 @@ The following are the permission nodes that are currently supported by the lates - **authme.admin.updatemessages** – Permission to use the update messages command. - **authme.allowchatbeforelogin** – Permission to send chat messages before being logged in. - **authme.allowmultipleaccounts** – Permission to be able to register multiple accounts. -- **authme.bypassbungeesend** – Permission node to bypass BungeeCord server teleportation. - **authme.bypassantibot** – Permission node to bypass AntiBot protection. +- **authme.bypassbungeesend** – Permission node to bypass BungeeCord server teleportation. - **authme.bypasscountrycheck** – Permission to bypass the GeoIp country code check. - **authme.bypassforcesurvival** – Permission for users to bypass force-survival mode. - **authme.bypasspurge** – Permission to bypass the purging process. @@ -71,4 +71,4 @@ The following are the permission nodes that are currently supported by the lates --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Mon May 21 08:43:08 CEST 2018 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:06 CEST 2019 diff --git a/docs/translations.md b/docs/translations.md index 0f63b6e58..93f8f92ad 100644 --- a/docs/translations.md +++ b/docs/translations.md @@ -1,5 +1,5 @@ - + # AuthMe Translations The following translations are available in AuthMe. Set `messagesLanguage` to the language code @@ -39,6 +39,7 @@ Code | Language | Translated |   [zhmc](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhmc.yml) | Chinese (Macau) | 65% | 65 [zhtw](https://github.com/AuthMe/AuthMeReloaded/blob/master/src/main/resources/messages/messages_zhtw.yml) | Chinese (Taiwan) | 87% | 87 + --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Sun Apr 14 11:09:15 CEST 2019 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:06 CEST 2019 diff --git a/pom.xml b/pom.xml index e4c4c812a..66f2d4912 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ fr.xephi authme - 5.5.1-SNAPSHOT + 5.6.0-beta1 AuthMeReloaded The first authentication plugin for the Bukkit API! From 85194fa94d116976f92a50e53387b71d69da7e92 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Fri, 19 Apr 2019 17:23:54 +0200 Subject: [PATCH 38/83] Next development cycle --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 66f2d4912..a64911d7b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ fr.xephi authme - 5.6.0-beta1 + 5.6.0-SNAPSHOT AuthMeReloaded The first authentication plugin for the Bukkit API! From 5b97841699a4c888b6a222ff2421987441000b89 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Tue, 23 Apr 2019 17:18:42 +0200 Subject: [PATCH 39/83] Add 1.14 compatibility --- docs/config.md | 6 ++++-- pom.xml | 2 +- .../fr/xephi/authme/listener/PlayerListener.java | 10 +++++----- src/main/java/fr/xephi/authme/mail/EmailService.java | 12 +++++------- .../java/fr/xephi/authme/service/BukkitService.java | 2 -- .../authme/settings/WelcomeMessageConfiguration.java | 3 ++- .../authme/settings/properties/PluginSettings.java | 3 +++ src/main/resources/plugin.yml | 2 +- .../fr/xephi/authme/listener/PlayerListenerTest.java | 1 + .../java/fr/xephi/authme/mail/EmailServiceTest.java | 6 ++---- .../settings/WelcomeMessageConfigurationTest.java | 6 +++--- 11 files changed, 27 insertions(+), 26 deletions(-) diff --git a/docs/config.md b/docs/config.md index d68fcd13d..811481d5e 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1,5 +1,5 @@ - + ## AuthMe Configuration The first time you run AuthMe it will create a config.yml file in the plugins/AuthMe folder, @@ -128,6 +128,8 @@ settings: # but it is incompatible with any permission plugin not included in our compatibility list. # If you have issues with permission checks on player join please disable this option. useAsyncPreLoginEvent: true + # The name of the server, used in some placeholders. + serverName: Your Minecraft Server restrictions: # Can not authenticated players chat? # Keep in mind that this feature also blocks all commands not @@ -576,4 +578,4 @@ To change settings on a running server, save your changes to config.yml and use --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:04 CEST 2019 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Tue Apr 23 17:17:02 CEST 2019 diff --git a/pom.xml b/pom.xml index a64911d7b..3030652b1 100644 --- a/pom.xml +++ b/pom.xml @@ -64,7 +64,7 @@ 3.3.9 - 1.13.2-R0.1-SNAPSHOT + 1.14-pre5-SNAPSHOT AuthMe diff --git a/src/main/java/fr/xephi/authme/listener/PlayerListener.java b/src/main/java/fr/xephi/authme/listener/PlayerListener.java index 9c75ea963..4134581ac 100644 --- a/src/main/java/fr/xephi/authme/listener/PlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/PlayerListener.java @@ -36,7 +36,7 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.*; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; import javax.inject.Inject; import java.util.HashSet; @@ -391,12 +391,12 @@ public class PlayerListener implements Listener { } } - private boolean isInventoryWhitelisted(Inventory inventory) { + private boolean isInventoryWhitelisted(InventoryView inventory) { if (inventory == null) { return false; } Set whitelist = settings.getProperty(RestrictionSettings.UNRESTRICTED_INVENTORIES); - return whitelist.contains(ChatColor.stripColor(inventory.getName())); + return whitelist.contains(ChatColor.stripColor(inventory.getTitle())); } @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @@ -404,7 +404,7 @@ public class PlayerListener implements Listener { final HumanEntity player = event.getPlayer(); if (listenerService.shouldCancelEvent(player) - && !isInventoryWhitelisted(event.getInventory())) { + && !isInventoryWhitelisted(event.getView())) { event.setCancelled(true); /* @@ -418,7 +418,7 @@ public class PlayerListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onPlayerInventoryClick(InventoryClickEvent event) { if (listenerService.shouldCancelEvent(event.getWhoClicked()) - && !isInventoryWhitelisted(event.getClickedInventory())) { + && !isInventoryWhitelisted(event.getView())) { event.setCancelled(true); } } diff --git a/src/main/java/fr/xephi/authme/mail/EmailService.java b/src/main/java/fr/xephi/authme/mail/EmailService.java index c63d7d6f8..29891163e 100644 --- a/src/main/java/fr/xephi/authme/mail/EmailService.java +++ b/src/main/java/fr/xephi/authme/mail/EmailService.java @@ -4,11 +4,11 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.EmailSettings; +import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.FileUtils; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; -import org.bukkit.Server; import javax.activation.DataSource; import javax.activation.FileDataSource; @@ -23,14 +23,12 @@ import java.io.IOException; public class EmailService { private final File dataFolder; - private final String serverName; private final Settings settings; private final SendMailSsl sendMailSsl; @Inject - EmailService(@DataFolder File dataFolder, Server server, Settings settings, SendMailSsl sendMailSsl) { + EmailService(@DataFolder File dataFolder, Settings settings, SendMailSsl sendMailSsl) { this.dataFolder = dataFolder; - this.serverName = server.getServerName(); this.settings = settings; this.sendMailSsl = sendMailSsl; } @@ -146,14 +144,14 @@ public class EmailService { private String replaceTagsForPasswordMail(String mailText, String name, String newPass) { return mailText .replace("", name) - .replace("", serverName) + .replace("", settings.getProperty(PluginSettings.SERVER_NAME)) .replace("", newPass); } private String replaceTagsForVerificationEmail(String mailText, String name, String code, int minutesValid) { return mailText .replace("", name) - .replace("", serverName) + .replace("", settings.getProperty(PluginSettings.SERVER_NAME)) .replace("", code) .replace("", String.valueOf(minutesValid)); } @@ -161,7 +159,7 @@ public class EmailService { private String replaceTagsForRecoveryCodeMail(String mailText, String name, String code, int hoursValid) { return mailText .replace("", name) - .replace("", serverName) + .replace("", settings.getProperty(PluginSettings.SERVER_NAME)) .replace("", code) .replace("", String.valueOf(hoursValid)); } diff --git a/src/main/java/fr/xephi/authme/service/BukkitService.java b/src/main/java/fr/xephi/authme/service/BukkitService.java index 99946718e..302414110 100644 --- a/src/main/java/fr/xephi/authme/service/BukkitService.java +++ b/src/main/java/fr/xephi/authme/service/BukkitService.java @@ -19,7 +19,6 @@ import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; import javax.inject.Inject; -import java.lang.reflect.Method; import java.util.Collection; import java.util.Date; import java.util.Optional; @@ -37,7 +36,6 @@ public class BukkitService implements SettingsDependent { public static final int TICKS_PER_MINUTE = 60 * TICKS_PER_SECOND; private final AuthMe authMe; - private Method getOnlinePlayers; private boolean useAsyncTasks; @Inject diff --git a/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java b/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java index 7a2da188f..0838314a1 100644 --- a/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java +++ b/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java @@ -7,6 +7,7 @@ import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.GeoIpService; +import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.util.PlayerUtils; import fr.xephi.authme.util.lazytags.Tag; @@ -65,7 +66,7 @@ public class WelcomeMessageConfiguration implements Reloadable { createTag("{IP}", PlayerUtils::getPlayerIp), createTag("{LOGINS}", () -> Integer.toString(playerCache.getLogged())), createTag("{WORLD}", pl -> pl.getWorld().getName()), - createTag("{SERVER}", () -> server.getServerName()), + createTag("{SERVER}", () -> service.getProperty(PluginSettings.SERVER_NAME)), createTag("{VERSION}", () -> server.getBukkitVersion()), createTag("{COUNTRY}", pl -> geoIpService.getCountryName(PlayerUtils.getPlayerIp(pl)))); diff --git a/src/main/java/fr/xephi/authme/settings/properties/PluginSettings.java b/src/main/java/fr/xephi/authme/settings/properties/PluginSettings.java index 55202a451..48e48b194 100644 --- a/src/main/java/fr/xephi/authme/settings/properties/PluginSettings.java +++ b/src/main/java/fr/xephi/authme/settings/properties/PluginSettings.java @@ -90,6 +90,9 @@ public final class PluginSettings implements SettingsHolder { public static final Property USE_ASYNC_PRE_LOGIN_EVENT = newProperty("settings.useAsyncPreLoginEvent", true); + @Comment("The name of the server, used in some placeholders.") + public static final Property SERVER_NAME = newProperty("settings.serverName", "Your Minecraft Server"); + private PluginSettings() { } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 027da3dc0..ce8072088 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -4,7 +4,7 @@ website: ${project.url} description: ${project.description} main: ${pluginDescription.main} version: ${pluginDescription.version} -api-version: 1.13 +api-version: 1.14 softdepend: - Vault - LuckPerms diff --git a/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java b/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java index 2f4300024..6d1df49a3 100644 --- a/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java +++ b/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java @@ -786,6 +786,7 @@ public class PlayerListenerTest { // given HumanEntity player = mock(Player.class); InventoryView transaction = mock(InventoryView.class); + given(settings.getProperty(RestrictionSettings.UNRESTRICTED_INVENTORIES)).willReturn(Collections.emptySet()); given(transaction.getPlayer()).willReturn(player); InventoryOpenEvent event = new InventoryOpenEvent(transaction); given(event.getPlayer()).willReturn(player); diff --git a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java index 43cbaa61a..96492daa9 100644 --- a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java +++ b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java @@ -7,10 +7,10 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.EmailSettings; +import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; -import org.bukkit.Server; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -46,8 +46,6 @@ public class EmailServiceTest { @Mock private Settings settings; @Mock - private Server server; - @Mock private SendMailSsl sendMailSsl; @DataFolder private File dataFolder; @@ -63,7 +61,7 @@ public class EmailServiceTest { @BeforeInjecting public void initFields() throws IOException { dataFolder = temporaryFolder.newFolder(); - given(server.getServerName()).willReturn("serverName"); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("mail@example.org"); given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); given(sendMailSsl.hasAllInformation()).willReturn(true); diff --git a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java index 0cf66a973..cf8077c67 100644 --- a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java +++ b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java @@ -9,6 +9,7 @@ import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.GeoIpService; +import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import org.bukkit.Server; import org.bukkit.World; @@ -96,7 +97,7 @@ public class WelcomeMessageConfigurationTest { given(player.getName()).willReturn("Bobby"); TestHelper.mockPlayerIp(player, "123.45.66.77"); given(geoIpService.getCountryName("123.45.66.77")).willReturn("Syldavia"); - given(server.getServerName()).willReturn("CrazyServer"); + given(service.getProperty(PluginSettings.SERVER_NAME)).willReturn("CrazyServer"); // when List result = welcomeMessageConfiguration.getWelcomeMessage(player); @@ -106,8 +107,7 @@ public class WelcomeMessageConfigurationTest { assertThat(result.get(0), equalTo("Hello Bobby, your IP is 123.45.66.77")); assertThat(result.get(1), equalTo("Your country is Syldavia.")); assertThat(result.get(2), equalTo("Welcome to CrazyServer!")); - verify(server, only()).getServerName(); - verifyZeroInteractions(playerCache); + verifyZeroInteractions(server, playerCache); } @Test From 59c69de63dd3f617c727af6e6696b0366873636d Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Wed, 24 Apr 2019 17:22:42 +0200 Subject: [PATCH 40/83] Fix 1.8 - 1.13 compatibility --- src/main/resources/plugin.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index ce8072088..027da3dc0 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -4,7 +4,7 @@ website: ${project.url} description: ${project.description} main: ${pluginDescription.main} version: ${pluginDescription.version} -api-version: 1.14 +api-version: 1.13 softdepend: - Vault - LuckPerms From 7f1894c5be274c29c4f2048e9316f3f45e541548 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 27 Apr 2019 12:46:39 +0200 Subject: [PATCH 41/83] Remove no longer needed method in test class --- .../java/fr/xephi/authme/service/BukkitServiceTest.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java b/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java index 7cf7b86be..504c342f7 100644 --- a/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java @@ -313,12 +313,4 @@ public class BukkitServiceTest { // then assertThat(result, equalTo(ip)); } - - // Note: This method is used through reflections - public static Player[] onlinePlayersImpl() { - return new Player[]{ - mock(Player.class), mock(Player.class) - }; - } - } From 61bb34942f1b64e78c04e7cc5c33812c1fa85e57 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 2 May 2019 08:37:12 +0200 Subject: [PATCH 42/83] Fix dependency exclusion --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3030652b1..3cc0e3940 100644 --- a/pom.xml +++ b/pom.xml @@ -624,7 +624,7 @@ commons-dbcp - AccountsClient + accounts-client com.mojang From a5a27cb239ee95fe53721d8d1720ef17bd5bff1a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Thu, 2 May 2019 08:54:36 +0200 Subject: [PATCH 43/83] Bump checker-qual from 2.8.0 to 2.8.1 (#1802) Bumps [checker-qual](https://github.com/typetools/checker-framework) from 2.8.0 to 2.8.1. - [Release notes](https://github.com/typetools/checker-framework/releases) - [Changelog](https://github.com/typetools/checker-framework/blob/master/changelog.txt) - [Commits](https://github.com/typetools/checker-framework/compare/checker-framework-2.8.0...checker-framework-2.8.1) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3cc0e3940..baca26173 100644 --- a/pom.xml +++ b/pom.xml @@ -887,7 +887,7 @@ org.checkerframework checker-qual - 2.8.0 + 2.8.1 test From d6efc7e95701f576a5bbcb0a1b6fc6e36d85d5ab Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 2 May 2019 08:55:15 +0200 Subject: [PATCH 44/83] Use a maintained zPermissions fork --- pom.xml | 48 ++---------------------------------------------- 1 file changed, 2 insertions(+), 46 deletions(-) diff --git a/pom.xml b/pom.xml index 3cc0e3940..9e06b928c 100644 --- a/pom.xml +++ b/pom.xml @@ -648,56 +648,12 @@ org.tyrannyofheaven.bukkit zPermissions - 1.4-SNAPSHOT + 1.4.3-SNAPSHOT provided - org.bukkit - bukkit - - - com.sk89q - worldguard - - - com.sk89q - worldedit - - - VaultAPI - net.milkbowl.vault - - - uuidprovider - net.kaikk.mc - - - ToHPluginUtils - org.tyrannyofheaven.bukkit - - - Residence - com.bekvon.bukkit - - - Factions - com.massivecraft - - - mcore - com.massivecraft - - - Factoid - me.tabinol.factoid - - - ebean org.avaje - - - persistence-api - javax.persistence + ebean From 19b82fa726bc5e6c9624512ad9994c6ff7509b3c Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 2 May 2019 09:36:18 +0200 Subject: [PATCH 45/83] Update xAuth dependency --- pom.xml | 44 +------------------------------------------- 1 file changed, 1 insertion(+), 43 deletions(-) diff --git a/pom.xml b/pom.xml index 2256c4291..2563f6fe4 100644 --- a/pom.xml +++ b/pom.xml @@ -611,14 +611,6 @@ 1.23.5-SNAPSHOT provided - - org.bukkit - bukkit - - - net.gravitydevelopment.updater - updater - commons-dbcp commons-dbcp @@ -759,42 +751,8 @@ de.luricos.bukkit xAuth - 2.6 + 2.6.1-SNAPSHOT provided - - - org.bukkit - bukkit - - - org.bukkit - craftbukkit - - - updater - net.gravitydevelopment.updater - - - lombok - org.projectlombok - - - EssentialsGroupManager - net.ess3 - - - PermissionsEx - ru.tehkode - - - AccountsClient - com.mojang - - - log4j-core - org.apache.logging.log4j - - From 2aee86fc2b767e167ce8c1977b0bb516ee758d85 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 2 May 2019 09:37:51 +0200 Subject: [PATCH 46/83] Update api to 1.14 release --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2563f6fe4..15475e6ef 100644 --- a/pom.xml +++ b/pom.xml @@ -64,7 +64,7 @@ 3.3.9 - 1.14-pre5-SNAPSHOT + 1.14-R0.1-SNAPSHOT AuthMe From ce4bb43dee62c28746a09ecee259a07cc2c86b13 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 2 May 2019 10:42:24 +0200 Subject: [PATCH 47/83] Remove bPermissions support --- pom.xml | 130 +++++++++++++++--- .../authme/permission/PermissionsManager.java | 3 - .../permission/PermissionsSystemType.java | 5 - .../handlers/BPermissionsHandler.java | 62 --------- .../PermissionsManagerInitializationTest.java | 5 +- .../HelpTranslationVerifier.java | 2 +- .../tools/messages/VerifyMessagesTask.java | 2 +- 7 files changed, 111 insertions(+), 98 deletions(-) delete mode 100644 src/main/java/fr/xephi/authme/permission/handlers/BPermissionsHandler.java diff --git a/pom.xml b/pom.xml index 15475e6ef..0bbe67387 100644 --- a/pom.xml +++ b/pom.xml @@ -382,36 +382,102 @@ spigotmc-repo https://hub.spigotmc.org/nexus/content/repositories/snapshots + + false + + + true + codemc-repo https://repo.codemc.org/repository/maven-public/ + + true + + + true + enderzone-repo - https://ci.ender.zone/plugin/repository/everything + https://ci.ender.zone/plugin/repository/everything/ + + true + + + true + - dmulloy2-repo - http://repo.dmulloy2.net/content/groups/public/ + dmulloy2-repo-releases + http://repo.dmulloy2.net/nexus/repository/releases/ + + true + + + false + + + + dmulloy2-repo-snapshots + http://repo.dmulloy2.net/nexus/repository/snapshots/ + + false + + + true + - onarandombox-repo - http://repo.onarandombox.com/content/groups/public + onarandombox-repo-releases + http://repo.onarandombox.com/content/repositories/multiverse/ + + true + + + false + + + + onarandombox-repo-snapshots + http://repo.onarandombox.com/content/repositories/multiverse-snapshots/ + + false + + + true + - vault-repo + vault-repo-releases http://nexus.hc.to/content/repositories/pub_releases + + true + + + false + + + + vault-repo-snapshots + http://nexus.hc.to/content/repositories/pub_snapshots + + false + + + true + @@ -622,20 +688,6 @@ - - - de.bananaco - bPermissions - 2.12-DEV - provided - - - org.bukkit - bukkit - - - - org.tyrannyofheaven.bukkit @@ -672,7 +724,7 @@ com.onarandombox.multiversecore Multiverse-Core - 2.6.0 + 3.0.0-SNAPSHOT jar provided @@ -735,8 +787,42 @@ net.ess3 EssentialsX - 2.15.0 + 2.16.1 provided + + + io.papermc + paperlib + + + net.ess3 + NMSProvider + + + net.ess3 + UpdatedMetaProvider + + + net.ess3 + 1_8_R1Provider + + + net.ess3 + 1_8_R2Provider + + + net.ess3 + LegacyProvider + + + net.ess3 + ReflectionProvider + + + net.ess3 + FlattenedProvider + + diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java index 59a64f14e..b99b66c5e 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java @@ -4,7 +4,6 @@ import com.google.common.annotations.VisibleForTesting; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.listener.JoiningPlayer; -import fr.xephi.authme.permission.handlers.BPermissionsHandler; import fr.xephi.authme.permission.handlers.LuckPermsHandler; import fr.xephi.authme.permission.handlers.PermissionHandler; import fr.xephi.authme.permission.handlers.PermissionHandlerException; @@ -139,8 +138,6 @@ public class PermissionsManager implements Reloadable { return new ZPermissionsHandler(); case VAULT: return new VaultHandler(server); - case B_PERMISSIONS: - return new BPermissionsHandler(); default: throw new IllegalStateException("Unhandled permission type '" + type + "'"); } diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsSystemType.java b/src/main/java/fr/xephi/authme/permission/PermissionsSystemType.java index 0a87d46cf..00f010362 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsSystemType.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsSystemType.java @@ -15,11 +15,6 @@ public enum PermissionsSystemType { */ PERMISSIONS_EX("PermissionsEx", "PermissionsEx"), - /** - * bPermissions. - */ - B_PERMISSIONS("bPermissions", "bPermissions"), - /** * zPermissions. */ diff --git a/src/main/java/fr/xephi/authme/permission/handlers/BPermissionsHandler.java b/src/main/java/fr/xephi/authme/permission/handlers/BPermissionsHandler.java deleted file mode 100644 index ecf167ac0..000000000 --- a/src/main/java/fr/xephi/authme/permission/handlers/BPermissionsHandler.java +++ /dev/null @@ -1,62 +0,0 @@ -package fr.xephi.authme.permission.handlers; - -import de.bananaco.bpermissions.api.ApiLayer; -import de.bananaco.bpermissions.api.CalculableType; -import fr.xephi.authme.permission.PermissionNode; -import fr.xephi.authme.permission.PermissionsSystemType; -import org.bukkit.OfflinePlayer; - -import java.util.Arrays; -import java.util.List; - -/** - * Handler for bPermissions. - * - * @see bPermissions Bukkit page - * @see bPermissions on Github - */ -public class BPermissionsHandler implements PermissionHandler { - - @Override - public boolean addToGroup(OfflinePlayer player, String group) { - ApiLayer.addGroup(null, CalculableType.USER, player.getName(), group); - return true; - } - - @Override - public boolean hasGroupSupport() { - return true; - } - - @Override - public boolean hasPermissionOffline(String name, PermissionNode node) { - return ApiLayer.hasPermission(null, CalculableType.USER, name, node.getNode()); - } - - @Override - public boolean isInGroup(OfflinePlayer player, String group) { - return ApiLayer.hasGroup(null, CalculableType.USER, player.getName(), group); - } - - @Override - public boolean removeFromGroup(OfflinePlayer player, String group) { - ApiLayer.removeGroup(null, CalculableType.USER, player.getName(), group); - return true; - } - - @Override - public boolean setGroup(OfflinePlayer player, String group) { - ApiLayer.setGroup(null, CalculableType.USER, player.getName(), group); - return true; - } - - @Override - public List getGroups(OfflinePlayer player) { - return Arrays.asList(ApiLayer.getGroups(null, CalculableType.USER, player.getName())); - } - - @Override - public PermissionsSystemType getPermissionSystem() { - return PermissionsSystemType.B_PERMISSIONS; - } -} diff --git a/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java b/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java index 8efaa9540..26b29a83f 100644 --- a/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java +++ b/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java @@ -3,7 +3,6 @@ package fr.xephi.authme.permission; import com.google.common.collect.ImmutableMap; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; -import fr.xephi.authme.permission.handlers.BPermissionsHandler; import fr.xephi.authme.permission.handlers.LuckPermsHandler; import fr.xephi.authme.permission.handlers.PermissionHandler; import fr.xephi.authme.permission.handlers.PermissionsExHandler; @@ -33,7 +32,6 @@ import java.util.Map; import java.util.stream.Collectors; import static com.google.common.collect.Sets.newHashSet; -import static fr.xephi.authme.permission.PermissionsSystemType.B_PERMISSIONS; import static fr.xephi.authme.permission.PermissionsSystemType.LUCK_PERMS; import static fr.xephi.authme.permission.PermissionsSystemType.PERMISSIONS_EX; import static fr.xephi.authme.permission.PermissionsSystemType.VAULT; @@ -147,7 +145,6 @@ public class PermissionsManagerInitializationTest { Map> handlersByPermissionSystemType = ImmutableMap.of( LUCK_PERMS, LuckPermsHandler.class, PERMISSIONS_EX, PermissionsExHandler.class, - B_PERMISSIONS, BPermissionsHandler.class, Z_PERMISSIONS, ZPermissionsHandler.class, VAULT, VaultHandler.class); @@ -175,7 +172,7 @@ public class PermissionsManagerInitializationTest { given(servicesManager.load(ZPermissionsService.class)).willReturn(zPermissionsService); } else if (permissionsSystemType == VAULT) { setUpForVault(); - } else if (permissionsSystemType != B_PERMISSIONS) { + } else { throw new IllegalStateException("Unhandled permission systems type: " + permissionsSystemType); } } diff --git a/src/test/java/tools/helptranslation/HelpTranslationVerifier.java b/src/test/java/tools/helptranslation/HelpTranslationVerifier.java index 9cbf12b5c..f40af5175 100644 --- a/src/test/java/tools/helptranslation/HelpTranslationVerifier.java +++ b/src/test/java/tools/helptranslation/HelpTranslationVerifier.java @@ -1,7 +1,6 @@ package tools.helptranslation; import com.google.common.collect.Sets; -import de.bananaco.bpermissions.imp.YamlConfiguration; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.CommandInitializer; import fr.xephi.authme.command.CommandUtils; @@ -9,6 +8,7 @@ import fr.xephi.authme.command.help.HelpMessage; import fr.xephi.authme.command.help.HelpSection; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.util.ArrayList; diff --git a/src/test/java/tools/messages/VerifyMessagesTask.java b/src/test/java/tools/messages/VerifyMessagesTask.java index d665ce89a..e60fa0fd8 100644 --- a/src/test/java/tools/messages/VerifyMessagesTask.java +++ b/src/test/java/tools/messages/VerifyMessagesTask.java @@ -1,10 +1,10 @@ package tools.messages; import com.google.common.collect.Multimap; -import de.bananaco.bpermissions.imp.YamlConfiguration; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.util.StringUtils; import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; import tools.utils.ToolTask; import tools.utils.ToolsConstants; From 09406f4f92bb96e46961a5cbc90cf797ddfc00a2 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 2 May 2019 21:59:55 +0200 Subject: [PATCH 48/83] Add maven dependency info to Readme --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 9b10509af..4ebbbd305 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,23 @@ You can also create your own translation file and, if you want, you can share it - **Dev resources:** - JavaDocs - Maven Repository + ```xml + + + codemc-repo + https://repo.codemc.org/repository/maven-public/ + + + + + + fr.xephi + authme + 5.6.0-SNAPSHOT + provided + + + ``` - **Statistics:** ![Graph](https://bstats.org/signatures/bukkit/AuthMe.svg) From 7e29efbc4e1acf47d85a967ea3edaca0ef5ca769 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 3 May 2019 09:30:22 +0200 Subject: [PATCH 49/83] Bump maven-compiler-plugin from 3.8.0 to 3.8.1 (#1804) Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.8.0 to 3.8.1. - [Release notes](https://github.com/apache/maven-compiler-plugin/releases) - [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.8.0...maven-compiler-plugin-3.8.1) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0bbe67387..dae9b779e 100644 --- a/pom.xml +++ b/pom.xml @@ -170,7 +170,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + 3.8.1 ${java.version} ${java.version} From 50480989de63340c015774b0e64ab147e62a67ec Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 3 May 2019 09:30:39 +0200 Subject: [PATCH 50/83] Bump maven-compiler-plugin from 3.8.0 to 3.8.1 (#1804) Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.8.0 to 3.8.1. - [Release notes](https://github.com/apache/maven-compiler-plugin/releases) - [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.8.0...maven-compiler-plugin-3.8.1) Signed-off-by: dependabot[bot] From ee63ebc7ac57270c51bbf0bee0f7aa9ae73a5a80 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" Date: Fri, 3 May 2019 09:31:04 +0200 Subject: [PATCH 51/83] Bump maven-surefire-plugin from 2.22.1 to 2.22.2 (#1803) Bumps [maven-surefire-plugin](https://github.com/apache/maven-surefire) from 2.22.1 to 2.22.2. - [Release notes](https://github.com/apache/maven-surefire/releases) - [Commits](https://github.com/apache/maven-surefire/compare/surefire-2.22.1...surefire-2.22.2) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index dae9b779e..6993f7377 100644 --- a/pom.xml +++ b/pom.xml @@ -200,7 +200,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.1 + 2.22.2 From 951c6483110cea816cf47c2147eef8c5edebd190 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Tue, 4 Jun 2019 10:44:47 +0200 Subject: [PATCH 52/83] Update to 1.14.2 --- pom.xml | 2 +- .../DistributedFilesPersistenceHandlerTest.java | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 6993f7377..4cba1daaf 100644 --- a/pom.xml +++ b/pom.xml @@ -64,7 +64,7 @@ 3.3.9 - 1.14-R0.1-SNAPSHOT + 1.14.2-R0.1-SNAPSHOT AuthMe diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index 8357840d1..8c1538ef1 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -153,10 +153,10 @@ public class DistributedFilesPersistenceHandlerTest { public void shouldAddPlayer() { // given Player uuidToAdd1 = mockPlayerWithUuid(UNKNOWN_UUID); - Location location1 = new Location(mockWorldWithName("1world"), 120, 60, -80, 0.42345f, 120.32f); + Location location1 = mockLocation("1world", 120, 60, -80, 0.42345f, 120.32f); LimboPlayer limbo1 = new LimboPlayer(location1, false, Collections.singletonList("group-1"), true, 0.1f, 0.2f); Player uuidToAdd2 = mockPlayerWithUuid(UNKNOWN_UUID2); - Location location2 = new Location(mockWorldWithName("2world"), -40, 20, 33, 4.235f, 8.32299f); + Location location2 = mockLocation("2world", -40, 20, 33, 4.235f, 8.32299f); LimboPlayer limbo2 = new LimboPlayer(location2, true, Collections.emptyList(), false, 0.0f, 0.25f); // when @@ -203,4 +203,11 @@ public class DistributedFilesPersistenceHandlerTest { given(world.getName()).willReturn(name); return world; } + + private static Location mockLocation(String worldName, int x, int y, int z, float yaw,float pitch) { + World world = mockWorldWithName(worldName); + Location location = mock(Location.class); + given(location.getWorld()).willReturn(world); + return location; + } } From 13a36e8f06253b92cbe1fff87b0cdac2bb4288b8 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" Date: Tue, 4 Jun 2019 11:46:38 +0200 Subject: [PATCH 53/83] Bump checker-qual from 2.8.1 to 2.8.2 (#1828) Bumps [checker-qual](https://github.com/typetools/checker-framework) from 2.8.1 to 2.8.2. - [Release notes](https://github.com/typetools/checker-framework/releases) - [Changelog](https://github.com/typetools/checker-framework/blob/master/changelog.txt) - [Commits](https://github.com/typetools/checker-framework/compare/checker-framework-2.8.1...checker-framework-2.8.2) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4cba1daaf..d642a674c 100644 --- a/pom.xml +++ b/pom.xml @@ -887,7 +887,7 @@ org.checkerframework checker-qual - 2.8.1 + 2.8.2 test From b5cfd7612bc71a627e318959b5c7d55814828762 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" Date: Tue, 4 Jun 2019 11:47:42 +0200 Subject: [PATCH 54/83] Bump mockito-core from 2.27.0 to 2.28.2 (#1822) Bumps [mockito-core](https://github.com/mockito/mockito) from 2.27.0 to 2.28.2. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v2.27.0...v2.28.2) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d642a674c..14bd9ce28 100644 --- a/pom.xml +++ b/pom.xml @@ -874,7 +874,7 @@ org.mockito mockito-core test - 2.27.0 + 2.28.2 hamcrest-core From d6e585e8c0c3ec9955263a3f860a37d78aceb87e Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" Date: Tue, 4 Jun 2019 11:48:01 +0200 Subject: [PATCH 55/83] Bump maven-source-plugin from 3.0.1 to 3.1.0 (#1814) Bumps [maven-source-plugin](https://github.com/apache/maven-source-plugin) from 3.0.1 to 3.1.0. - [Release notes](https://github.com/apache/maven-source-plugin/releases) - [Commits](https://github.com/apache/maven-source-plugin/compare/maven-source-plugin-3.0.1...maven-source-plugin-3.1.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 14bd9ce28..441b031dc 100644 --- a/pom.xml +++ b/pom.xml @@ -239,7 +239,7 @@ org.apache.maven.plugins maven-source-plugin - 3.0.1 + 3.1.0 ${project.finalNameBase} From 88828bbee7ff93948f313ca20a7ae3ca6dca1c1a Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" Date: Tue, 4 Jun 2019 11:48:19 +0200 Subject: [PATCH 56/83] Bump maven-jar-plugin from 3.1.1 to 3.1.2 (#1808) Bumps [maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.1.1 to 3.1.2. - [Release notes](https://github.com/apache/maven-jar-plugin/releases) - [Commits](https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.1.1...maven-jar-plugin-3.1.2) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 441b031dc..dadcca1b4 100644 --- a/pom.xml +++ b/pom.xml @@ -216,7 +216,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.1.1 + 3.1.2 From 6e4c4158fb919e64a3867b490b0a2b32a606ed98 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" Date: Tue, 4 Jun 2019 11:48:35 +0200 Subject: [PATCH 57/83] Bump jacoco-maven-plugin from 0.8.3 to 0.8.4 (#1807) Bumps [jacoco-maven-plugin](https://github.com/jacoco/jacoco) from 0.8.3 to 0.8.4. - [Release notes](https://github.com/jacoco/jacoco/releases) - [Commits](https://github.com/jacoco/jacoco/compare/v0.8.3...v0.8.4) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index dadcca1b4..5ca9a1bf8 100644 --- a/pom.xml +++ b/pom.xml @@ -180,7 +180,7 @@ org.jacoco jacoco-maven-plugin - 0.8.3 + 0.8.4 pre-unit-test From 83b38897e605a14f247f6ec4693f9f70ebaee6ed Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" Date: Mon, 10 Jun 2019 22:35:36 +0200 Subject: [PATCH 58/83] Bump Multiverse-Core from 3.0.0-SNAPSHOT to 3.0.0 (#1829) Bumps Multiverse-Core from 3.0.0-SNAPSHOT to 3.0.0. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5ca9a1bf8..60648c2e9 100644 --- a/pom.xml +++ b/pom.xml @@ -724,7 +724,7 @@ com.onarandombox.multiversecore Multiverse-Core - 3.0.0-SNAPSHOT + 3.0.0 jar provided From 55bff96807b7054d23b6b9a72630d62b0be114db Mon Sep 17 00:00:00 2001 From: ljacqu Date: Mon, 17 Jun 2019 21:54:04 +0200 Subject: [PATCH 59/83] #1831 Specify Java version to Javadocs Maven plugin --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 60648c2e9..ee61a8c03 100644 --- a/pom.xml +++ b/pom.xml @@ -225,6 +225,8 @@ 3.1.0 ${project.finalNameBase} + + 8 From e9cd16aaac43bd97a64abd6e395570313438c2be Mon Sep 17 00:00:00 2001 From: ljacqu Date: Mon, 17 Jun 2019 21:58:25 +0200 Subject: [PATCH 60/83] Undo star imports --- src/main/java/fr/xephi/authme/AuthMe.java | 15 +++++++++++-- .../xephi/authme/listener/PlayerListener.java | 21 ++++++++++++++++++- .../authme/listener/PlayerListenerTest.java | 18 +++++++++++++++- 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 7ee02ef06..416e91c95 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -6,8 +6,19 @@ import com.google.common.annotations.VisibleForTesting; import fr.xephi.authme.api.v3.AuthMeApi; import fr.xephi.authme.command.CommandHandler; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.initialization.*; -import fr.xephi.authme.listener.*; +import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.initialization.DataSourceProvider; +import fr.xephi.authme.initialization.OnShutdownPlayerSaver; +import fr.xephi.authme.initialization.OnStartupTasks; +import fr.xephi.authme.initialization.SettingsProvider; +import fr.xephi.authme.initialization.TaskCloser; +import fr.xephi.authme.listener.BlockListener; +import fr.xephi.authme.listener.EntityListener; +import fr.xephi.authme.listener.PlayerListener; +import fr.xephi.authme.listener.PlayerListener111; +import fr.xephi.authme.listener.PlayerListener19; +import fr.xephi.authme.listener.PlayerListener19Spigot; +import fr.xephi.authme.listener.ServerListener; import fr.xephi.authme.security.crypts.Sha256; import fr.xephi.authme.service.BackupService; import fr.xephi.authme.service.BukkitService; diff --git a/src/main/java/fr/xephi/authme/listener/PlayerListener.java b/src/main/java/fr/xephi/authme/listener/PlayerListener.java index 4134581ac..a9afc92d8 100644 --- a/src/main/java/fr/xephi/authme/listener/PlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/PlayerListener.java @@ -35,7 +35,26 @@ import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerEditBookEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.bukkit.event.player.PlayerItemHeldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.inventory.InventoryView; import javax.inject.Inject; diff --git a/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java b/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java index 6d1df49a3..0625f1ff5 100644 --- a/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java +++ b/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java @@ -28,7 +28,23 @@ import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerEditBookEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.inventory.InventoryView; import org.junit.Test; import org.junit.runner.RunWith; From 6903e058d59f3debdfb6b66c69cd2a36cdb6bd37 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Mon, 17 Jun 2019 22:02:10 +0200 Subject: [PATCH 61/83] Undo star imports --- .../persistence/DistributedFilesPersistenceHandlerTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index 8c1538ef1..7c2c84d2a 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -153,10 +153,10 @@ public class DistributedFilesPersistenceHandlerTest { public void shouldAddPlayer() { // given Player uuidToAdd1 = mockPlayerWithUuid(UNKNOWN_UUID); - Location location1 = mockLocation("1world", 120, 60, -80, 0.42345f, 120.32f); + Location location1 = mockLocation("1world"); LimboPlayer limbo1 = new LimboPlayer(location1, false, Collections.singletonList("group-1"), true, 0.1f, 0.2f); Player uuidToAdd2 = mockPlayerWithUuid(UNKNOWN_UUID2); - Location location2 = mockLocation("2world", -40, 20, 33, 4.235f, 8.32299f); + Location location2 = mockLocation("2world"); LimboPlayer limbo2 = new LimboPlayer(location2, true, Collections.emptyList(), false, 0.0f, 0.25f); // when @@ -204,7 +204,7 @@ public class DistributedFilesPersistenceHandlerTest { return world; } - private static Location mockLocation(String worldName, int x, int y, int z, float yaw,float pitch) { + private static Location mockLocation(String worldName) { World world = mockWorldWithName(worldName); Location location = mock(Location.class); given(location.getWorld()).willReturn(world); From d1b6161687f42469b3aef128e682b35777b37bd4 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Mon, 17 Jun 2019 22:47:15 +0200 Subject: [PATCH 62/83] Minor: print stack trace if AuthMe is disabled due to exception, remove unused imports --- src/main/java/fr/xephi/authme/AuthMe.java | 1 + .../limbo/persistence/DistributedFilesPersistenceHandler.java | 1 - .../limbo/persistence/IndividualFilesPersistenceHandler.java | 1 - 3 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 416e91c95..d07b426b8 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -140,6 +140,7 @@ public class AuthMe extends JavaPlugin { YamlParseException yamlParseException = ExceptionUtils.findThrowableInCause(YamlParseException.class, th); if (yamlParseException == null) { ConsoleLogger.logException("Aborting initialization of AuthMe:", th); + th.printStackTrace(); } else { ConsoleLogger.logException("File '" + yamlParseException.getFile() + "' contains invalid YAML. " + "Please run its contents through http://yamllint.com", yamlParseException); diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java index fee322211..ca66afdec 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java @@ -11,7 +11,6 @@ import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; import fr.xephi.authme.util.FileUtils; -import fr.xephi.authme.util.PlayerUtils; import org.bukkit.entity.Player; import javax.inject.Inject; diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java index be9948736..b43b1d3f7 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java @@ -8,7 +8,6 @@ import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.util.FileUtils; -import fr.xephi.authme.util.PlayerUtils; import org.bukkit.entity.Player; import javax.inject.Inject; From ff2f43bdc524f46c8d3a30cc5f032ac6700a0328 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 22 Jun 2019 20:54:01 +0200 Subject: [PATCH 63/83] #1743 Stop mobs from targetting players when not authenticated --- .../xephi/authme/listener/EntityListener.java | 2 +- .../authme/listener/ListenerService.java | 8 ++--- .../authme/listener/EntityListenerTest.java | 33 ++++++++++++++++++- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/main/java/fr/xephi/authme/listener/EntityListener.java b/src/main/java/fr/xephi/authme/listener/EntityListener.java index 7c8281861..b46225c47 100644 --- a/src/main/java/fr/xephi/authme/listener/EntityListener.java +++ b/src/main/java/fr/xephi/authme/listener/EntityListener.java @@ -56,7 +56,7 @@ public class EntityListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onEntityTarget(EntityTargetEvent event) { - if (listenerService.shouldCancelEvent(event)) { + if (listenerService.shouldCancelEvent(event.getTarget())) { event.setTarget(null); event.setCancelled(true); } diff --git a/src/main/java/fr/xephi/authme/listener/ListenerService.java b/src/main/java/fr/xephi/authme/listener/ListenerService.java index 87562c519..d283f3e4e 100644 --- a/src/main/java/fr/xephi/authme/listener/ListenerService.java +++ b/src/main/java/fr/xephi/authme/listener/ListenerService.java @@ -52,11 +52,11 @@ class ListenerService implements SettingsDependent { * @return true if the associated event should be canceled, false otherwise */ public boolean shouldCancelEvent(Entity entity) { - if (entity == null || !(entity instanceof Player)) { - return false; + if (entity instanceof Player) { + Player player = (Player) entity; + return shouldCancelEvent(player); } - Player player = (Player) entity; - return shouldCancelEvent(player); + return false; } /** diff --git a/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java b/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java index f2fd4b0a7..73a29dd71 100644 --- a/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java +++ b/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java @@ -45,7 +45,6 @@ public class EntityListenerTest { @Test public void shouldHandleSimpleEvents() { withServiceMock(listenerService) - .check(listener::onEntityTarget, EntityTargetEvent.class) .check(listener::onFoodLevelChange, FoodLevelChangeEvent.class) .check(listener::onShoot, EntityShootBowEvent.class) .check(listener::onEntityInteract, EntityInteractEvent.class) @@ -216,4 +215,36 @@ public class EntityListenerTest { verify(listenerService).shouldCancelEvent(shooter); assertThat(event.isCancelled(), equalTo(true)); } + + @Test + public void shouldCancelEntityTargetEvent() { + // given + EntityTargetEvent event = mock(EntityTargetEvent.class); + Entity target = mock(Entity.class); + given(event.getTarget()).willReturn(target); + given(listenerService.shouldCancelEvent(target)).willReturn(true); + + // when + listener.onEntityTarget(event); + + // then + verify(listenerService).shouldCancelEvent(target); + verify(event).setCancelled(true); + } + + @Test + public void shouldNotCancelEntityTargetEvent() { + // given + EntityTargetEvent event = mock(EntityTargetEvent.class); + Entity target = mock(Entity.class); + given(event.getTarget()).willReturn(target); + given(listenerService.shouldCancelEvent(target)).willReturn(false); + + // when + listener.onEntityTarget(event); + + // then + verify(listenerService).shouldCancelEvent(target); + verify(event, only()).getTarget(); + } } From 4be130b71be25752dfd505afa3de11d998f1f268 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 22 Jun 2019 22:37:32 +0200 Subject: [PATCH 64/83] Fix #1493 Extract handling of message file paths to a separate class with constants --- .../message/AbstractMessageFileHandler.java | 4 +- .../message/HelpMessagesFileHandler.java | 4 +- .../authme/message/MessagePathHelper.java | 77 +++++++++++++++++++ .../authme/message/MessagesFileHandler.java | 4 +- .../service/HelpTranslationGenerator.java | 3 +- .../help/HelpMessagesConsistencyTest.java | 4 +- .../command/help/HelpMessagesServiceTest.java | 9 ++- ...istributedFilesPersistenceHandlerTest.java | 4 +- .../message/HelpMessageConsistencyTest.java | 9 +-- .../message/MessageFilePlaceholderTest.java | 12 +-- .../authme/message/MessagePathHelperTest.java | 67 ++++++++++++++++ .../message/MessagesFileConsistencyTest.java | 4 +- .../message/MessagesIntegrationTest.java | 11 +-- .../message/YamlTextFileCheckerTest.java | 26 +++---- .../message/updater/MessageUpdaterTest.java | 9 ++- .../translations/TranslationsGatherer.java | 21 ++--- .../messages/AddJavaDocToMessageEnumTask.java | 4 +- .../tools/messages/VerifyMessagesTask.java | 13 ++-- 18 files changed, 210 insertions(+), 75 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/message/MessagePathHelper.java create mode 100644 src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java diff --git a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java index 4dbbe33bf..fc140ef16 100644 --- a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java @@ -14,13 +14,13 @@ import javax.annotation.PostConstruct; import javax.inject.Inject; import java.io.File; +import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; + /** * Handles a YAML message file with a default file fallback. */ public abstract class AbstractMessageFileHandler implements Reloadable { - protected static final String DEFAULT_LANGUAGE = "en"; - @DataFolder @Inject private File dataFolder; diff --git a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java index 378887537..c0d184814 100644 --- a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java @@ -9,6 +9,8 @@ import javax.inject.Inject; import java.io.InputStream; import java.io.InputStreamReader; +import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; + /** * File handler for the help_xx.yml resource. */ @@ -57,6 +59,6 @@ public class HelpMessagesFileHandler extends AbstractMessageFileHandler { @Override protected String createFilePath(String language) { - return "messages/help_" + language + ".yml"; + return MessagePathHelper.createHelpMessageFilePath(language); } } diff --git a/src/main/java/fr/xephi/authme/message/MessagePathHelper.java b/src/main/java/fr/xephi/authme/message/MessagePathHelper.java new file mode 100644 index 000000000..82c829d15 --- /dev/null +++ b/src/main/java/fr/xephi/authme/message/MessagePathHelper.java @@ -0,0 +1,77 @@ +package fr.xephi.authme.message; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Helper for creating and processing paths to message files. + */ +public final class MessagePathHelper { + + /** The default language (used as fallback, assumed to be complete, etc.). */ + public static final String DEFAULT_LANGUAGE = "en"; + /** Local path to the folder containing the message files. */ + public static final String MESSAGES_FOLDER = "messages/"; + /** Local path to the default messages file (messages/messages_en.yml). */ + public static final String DEFAULT_MESSAGES_FILE = createMessageFilePath(DEFAULT_LANGUAGE); + + private static final Pattern MESSAGE_FILE_PATTERN = Pattern.compile("messages_([a-z]+)\\.yml"); + private static final Pattern HELP_MESSAGES_FILE = Pattern.compile("help_[a-z]+\\.yml"); + + private MessagePathHelper() { + } + + /** + * Creates the local path to the messages file for the provided language code. + * + * @param languageCode the language code + * @return local path to the messages file of the given language + */ + public static String createMessageFilePath(String languageCode) { + return "messages/messages_" + languageCode + ".yml"; + } + + /** + * Creates the local path to the help messages file for the provided language code. + * + * @param languageCode the language code + * @return local path to the help messages file of the given language + */ + public static String createHelpMessageFilePath(String languageCode) { + return "messages/help_" + languageCode + ".yml"; + } + + /** + * Returns whether the given file name is a messages file. + * + * @param filename the file name to test + * @return true if it is a messages file, false otherwise + */ + public static boolean isMessagesFile(String filename) { + return MESSAGE_FILE_PATTERN.matcher(filename).matches(); + } + + /** + * Returns the language code the given file name is for if it is a messages file, otherwise null is returned. + * + * @param filename the file name to process + * @return the language code the file name is a messages file for, or null if not applicable + */ + public static String getLanguageIfIsMessagesFile(String filename) { + Matcher matcher = MESSAGE_FILE_PATTERN.matcher(filename); + if (matcher.matches()) { + return matcher.group(1); + } + return null; + } + + /** + * Returns whether the given file name is a help messages file. + * + * @param filename the file name to test + * @return true if it is a help messages file, false otherwise + */ + public static boolean isHelpFile(String filename) { + return HELP_MESSAGES_FILE.matcher(filename).matches(); + } +} diff --git a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java index 7ca19249e..a047ee145 100644 --- a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java @@ -5,6 +5,8 @@ import fr.xephi.authme.message.updater.MessageUpdater; import javax.inject.Inject; +import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; + /** * File handler for the messages_xx.yml resource. */ @@ -38,6 +40,6 @@ public class MessagesFileHandler extends AbstractMessageFileHandler { @Override protected String createFilePath(String language) { - return "messages/messages_" + language + ".yml"; + return MessagePathHelper.createMessageFilePath(language); } } diff --git a/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java b/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java index 21407b4f0..e1c8c5ba7 100644 --- a/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java +++ b/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java @@ -8,6 +8,7 @@ import fr.xephi.authme.command.help.HelpMessage; import fr.xephi.authme.command.help.HelpMessagesService; import fr.xephi.authme.command.help.HelpSection; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.permission.DefaultPermission; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -49,7 +50,7 @@ public class HelpTranslationGenerator { */ public File updateHelpFile() throws IOException { String languageCode = settings.getProperty(PluginSettings.MESSAGES_LANGUAGE); - File helpFile = new File(dataFolder, "messages/help_" + languageCode + ".yml"); + File helpFile = new File(dataFolder, MessagePathHelper.createHelpMessageFilePath(languageCode)); Map helpEntries = generateHelpMessageEntries(); String helpEntriesYaml = exportToYaml(helpEntries); diff --git a/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java b/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java index 1c4f7542f..019e6c863 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java @@ -5,6 +5,7 @@ import ch.jalu.configme.resource.YamlFileReader; import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.CommandInitializer; +import fr.xephi.authme.message.MessagePathHelper; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; @@ -25,7 +26,8 @@ import static org.junit.Assert.assertThat; */ public class HelpMessagesConsistencyTest { - private static final File DEFAULT_MESSAGES_FILE = TestHelper.getJarFile("/messages/help_en.yml"); + private static final File DEFAULT_MESSAGES_FILE = + TestHelper.getJarFile("/" + MessagePathHelper.createHelpMessageFilePath(MessagePathHelper.DEFAULT_LANGUAGE)); @Test public void shouldHaveIdenticalTexts() { diff --git a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java index c7202a92f..514724a97 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java @@ -7,6 +7,7 @@ import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.TestCommandsUtil; import fr.xephi.authme.message.AbstractMessageFileHandler; import fr.xephi.authme.message.HelpMessagesFileHandler; +import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.permission.DefaultPermission; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -32,7 +33,7 @@ import static org.mockito.Mockito.mock; */ public class HelpMessagesServiceTest { - private static final String TEST_FILE = "/fr/xephi/authme/command/help/help_test.yml"; + private static final String TEST_FILE = TestHelper.PROJECT_ROOT + "command/help/help_test.yml"; private static final Collection COMMANDS = TestCommandsUtil.generateCommands(); private HelpMessagesService helpMessagesService; @@ -42,10 +43,10 @@ public class HelpMessagesServiceTest { private File dataFolder; @Before - public void initializeHandler() throws IOException, InstantiationException, IllegalAccessException { + public void initializeHandler() throws IOException { dataFolder = temporaryFolder.newFolder(); new File(dataFolder, "messages").mkdirs(); - File messagesFile = new File(dataFolder, "messages/help_test.yml"); + File messagesFile = new File(dataFolder, MessagePathHelper.createHelpMessageFilePath("test")); Files.copy(TestHelper.getJarFile(TEST_FILE), messagesFile); HelpMessagesFileHandler helpMessagesFileHandler = createMessagesFileHandler(); @@ -146,7 +147,7 @@ public class HelpMessagesServiceTest { assertThat(description, equalTo(command.getDescription())); } - private HelpMessagesFileHandler createMessagesFileHandler() throws IllegalAccessException, InstantiationException { + private HelpMessagesFileHandler createMessagesFileHandler() { Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index 7c2c84d2a..fd41134a1 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -26,6 +26,8 @@ import java.io.IOException; import java.util.Collections; import java.util.UUID; +import static fr.xephi.authme.TestHelper.PROJECT_ROOT; +import static fr.xephi.authme.TestHelper.TEST_RESOURCES_FOLDER; import static fr.xephi.authme.data.limbo.LimboPlayerMatchers.hasLocation; import static fr.xephi.authme.data.limbo.LimboPlayerMatchers.isLimbo; import static java.util.UUID.fromString; @@ -96,7 +98,7 @@ public class DistributedFilesPersistenceHandlerTest { playerDataFolder = new File(dataFolder, "playerdata"); playerDataFolder.mkdir(); - File limboFilesFolder = new File("src/test/resources/fr/xephi/authme/data/limbo"); + File limboFilesFolder = new File(TEST_RESOURCES_FOLDER + PROJECT_ROOT + "data/limbo"); for (File file : limboFilesFolder.listFiles()) { File from = new File(playerDataFolder, file.getName()); Files.copy(file, from); diff --git a/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java b/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java index 83db38d2f..b6fcba7cc 100644 --- a/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java @@ -13,9 +13,9 @@ import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.List; -import java.util.regex.Pattern; import java.util.stream.Collectors; +import static fr.xephi.authme.message.MessagePathHelper.MESSAGES_FOLDER; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.emptyString; import static org.hamcrest.Matchers.not; @@ -28,20 +28,17 @@ import static org.junit.Assert.assertThat; */ public class HelpMessageConsistencyTest { - private static final String MESSAGES_FOLDER = "/messages"; - private static final Pattern HELP_MESSAGES_FILE = Pattern.compile("help_[a-z]+\\.yml"); - private List helpFiles; @Before public void findHelpMessagesFiles() { - File folder = TestHelper.getJarFile(MESSAGES_FOLDER); + File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); File[] files = folder.listFiles(); if (files == null || files.length == 0) { throw new IllegalStateException("Could not get files from '" + MESSAGES_FOLDER + "'"); } helpFiles = Arrays.stream(files) - .filter(file -> HELP_MESSAGES_FILE.matcher(file.getName()).matches()) + .filter(file -> MessagePathHelper.isHelpFile(file.getName())) .collect(Collectors.toList()); } diff --git a/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java b/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java index f7b8596d0..0966902ba 100644 --- a/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java +++ b/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java @@ -14,9 +14,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.regex.Pattern; import java.util.stream.Collectors; +import static fr.xephi.authme.message.MessagePathHelper.MESSAGES_FOLDER; import static org.junit.Assert.fail; import static tools.utils.FileIoUtils.listFilesOrThrow; @@ -27,12 +27,6 @@ import static tools.utils.FileIoUtils.listFilesOrThrow; @RunWith(Parameterized.class) public class MessageFilePlaceholderTest { - /** Path in the resources folder where the message files are located. */ - private static final String MESSAGES_FOLDER = "/messages/"; - - /** Pattern for detecting messages files. */ - private static final Pattern IS_MESSAGES_FILE = Pattern.compile("messages_.*?\\.yml"); - /** Defines exclusions: a (key, tag) pair in this map will not be checked in the test. */ private static final Multimap EXCLUSIONS = ImmutableMultimap.builder() .put(MessageKey.INCORRECT_RECOVERY_CODE, "%count") @@ -80,10 +74,10 @@ public class MessageFilePlaceholderTest { @Parameterized.Parameters(name = "{1}") public static List buildParams() { - File folder = TestHelper.getJarFile(MESSAGES_FOLDER); + File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); List messageFiles = Arrays.stream(listFilesOrThrow(folder)) - .filter(file -> IS_MESSAGES_FILE.matcher(file.getName()).matches()) + .filter(file -> MessagePathHelper.isMessagesFile(file.getName())) .map(file -> new Object[]{file, file.getName()}) .collect(Collectors.toList()); if (messageFiles.isEmpty()) { diff --git a/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java b/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java new file mode 100644 index 000000000..7e12aa4f5 --- /dev/null +++ b/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java @@ -0,0 +1,67 @@ +package fr.xephi.authme.message; + +import fr.xephi.authme.settings.properties.PluginSettings; +import org.junit.Test; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +/** + * Test for {@link MessagePathHelper}. + */ +public class MessagePathHelperTest { + + @Test + public void shouldHaveLanguageInSyncWithConfigurations() { + // given / when / then + assertThat(MessagePathHelper.DEFAULT_LANGUAGE, equalTo(PluginSettings.MESSAGES_LANGUAGE.getDefaultValue())); + assertThat(MessagePathHelper.DEFAULT_MESSAGES_FILE, equalTo(MessagePathHelper.createMessageFilePath(MessagePathHelper.DEFAULT_LANGUAGE))); + } + + @Test + public void shouldBuildTextFilePaths() { + // given / when / then + assertThat(MessagePathHelper.createMessageFilePath("qq"), equalTo(MessagePathHelper.MESSAGES_FOLDER + "messages_qq.yml")); + assertThat(MessagePathHelper.createHelpMessageFilePath("qq"), equalTo(MessagePathHelper.MESSAGES_FOLDER + "help_qq.yml")); + } + + @Test + public void shouldRecognizeIfIsMessagesFile() { + // given / when / then + assertThat(MessagePathHelper.isMessagesFile("messages_nl.yml"), equalTo(true)); + assertThat(MessagePathHelper.isMessagesFile("messages_testtest.yml"), equalTo(true)); + + assertThat(MessagePathHelper.isMessagesFile("messages/messages_fr.yml"), equalTo(false)); + assertThat(MessagePathHelper.isMessagesFile("Messages_fr.yml"), equalTo(false)); + assertThat(MessagePathHelper.isMessagesFile("otherfile.txt"), equalTo(false)); + assertThat(MessagePathHelper.isMessagesFile("messages_de.txt"), equalTo(false)); + assertThat(MessagePathHelper.isMessagesFile(""), equalTo(false)); + } + + @Test + public void shouldReturnLanguageForMessagesFile() { + // given / when / then + assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("messages_nl.yml"), equalTo("nl")); + assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("messages_testtest.yml"), equalTo("testtest")); + + assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("messages/messages_fr.yml"), nullValue()); + assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("Messages_fr.yml"), nullValue()); + assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("otherfile.txt"), nullValue()); + assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("messages_de.txt"), nullValue()); + assertThat(MessagePathHelper.getLanguageIfIsMessagesFile(""), nullValue()); + } + + @Test + public void shouldRecognizeIfIsHelpFile() { + // given / when / then + assertThat(MessagePathHelper.isHelpFile("help_nl.yml"), equalTo(true)); + assertThat(MessagePathHelper.isHelpFile("help_testtest.yml"), equalTo(true)); + + assertThat(MessagePathHelper.isHelpFile("messages/help_fr.yml"), equalTo(false)); + assertThat(MessagePathHelper.isHelpFile("Help_fr.yml"), equalTo(false)); + assertThat(MessagePathHelper.isHelpFile("otherfile.txt"), equalTo(false)); + assertThat(MessagePathHelper.isHelpFile("help_de.txt"), equalTo(false)); + assertThat(MessagePathHelper.isHelpFile(""), equalTo(false)); + } +} diff --git a/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java b/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java index c1362dd61..1679e9ac3 100644 --- a/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java @@ -19,11 +19,11 @@ import static org.junit.Assert.fail; */ public class MessagesFileConsistencyTest { - private static final String MESSAGES_FILE = "/messages/messages_en.yml"; + private static final String MESSAGES_FILE = MessagePathHelper.DEFAULT_MESSAGES_FILE; @Test public void shouldHaveAllMessages() { - File file = TestHelper.getJarFile(MESSAGES_FILE); + File file = TestHelper.getJarFile("/" + MESSAGES_FILE); PropertyReader reader = new YamlFileReader(file); List errors = new ArrayList<>(); for (MessageKey messageKey : MessageKey.values()) { diff --git a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java index d8a2bd00b..d57e29fec 100644 --- a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java @@ -44,7 +44,8 @@ import static org.mockito.hamcrest.MockitoHamcrest.argThat; */ public class MessagesIntegrationTest { - private static final String YML_TEST_FILE = TestHelper.PROJECT_ROOT + "message/messages_test.yml"; + private static final String TEST_MESSAGES_LOCAL_PATH = "message/messages_test.yml"; + private static final String YML_TEST_FILE = TestHelper.PROJECT_ROOT + TEST_MESSAGES_LOCAL_PATH; private Messages messages; private MessagesFileHandler messagesFileHandler; @@ -68,8 +69,8 @@ public class MessagesIntegrationTest { @Before public void setUpMessages() throws IOException { dataFolder = temporaryFolder.newFolder(); - File testFile = new File(dataFolder, "messages/messages_test.yml"); - new File(dataFolder, "messages").mkdirs(); + File testFile = new File(dataFolder, MessagePathHelper.createMessageFilePath("test")); + new File(dataFolder, MessagePathHelper.MESSAGES_FOLDER).mkdirs(); FileUtils.create(testFile); Files.copy(TestHelper.getJarFile(YML_TEST_FILE), testFile); @@ -276,8 +277,8 @@ public class MessagesIntegrationTest { public void shouldFormatDurationObjects() throws IOException { // given // Use the JAR's messages_en.yml file for this, so copy to the file we're using and reload the file handler - File testFile = new File(dataFolder, "messages/messages_test.yml"); - Files.copy(TestHelper.getJarFile("/messages/messages_en.yml"), testFile); + File testFile = new File(dataFolder, MessagePathHelper.createMessageFilePath("test")); + Files.copy(TestHelper.getJarFile("/" + MessagePathHelper.DEFAULT_MESSAGES_FILE), testFile); messagesFileHandler.reload(); Map expectedTexts = ImmutableMap.builder() diff --git a/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java b/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java index 2b1820fb6..98a87e757 100644 --- a/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java +++ b/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java @@ -11,10 +11,10 @@ import org.junit.Test; import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.regex.Pattern; +import java.util.function.Predicate; +import static fr.xephi.authme.message.MessagePathHelper.MESSAGES_FOLDER; import static org.junit.Assert.fail; import static tools.utils.FileIoUtils.listFilesOrThrow; @@ -23,52 +23,50 @@ import static tools.utils.FileIoUtils.listFilesOrThrow; */ public class YamlTextFileCheckerTest { - /** Path in the resources folder where the message files are located. */ - private static final String MESSAGES_FOLDER = "/messages/"; /** Contains all files of the MESSAGES_FOLDER. */ - private static List messageFiles; + private static File[] messageFiles; @BeforeClass public static void loadMessagesFiles() { - File folder = TestHelper.getJarFile(MESSAGES_FOLDER); - messageFiles = Arrays.asList(listFilesOrThrow(folder)); + File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); + messageFiles = listFilesOrThrow(folder); } @Test public void testAllMessagesYmlFiles() { checkFiles( - Pattern.compile("messages_\\w+\\.yml"), + MessagePathHelper::isMessagesFile, MessageKey.LOGIN_MESSAGE.getKey()); } @Test public void testAllHelpYmlFiles() { checkFiles( - Pattern.compile("help_\\w+\\.yml"), + MessagePathHelper::isHelpFile, HelpSection.ALTERNATIVES.getKey()); } /** * Checks all files in the messages folder that match the given pattern. * - * @param pattern the pattern the file name needs to match + * @param isRelevantFilePredicate predicate determining which files should be tested * @param mandatoryKey key present in all matched files */ - private void checkFiles(Pattern pattern, String mandatoryKey) { + private void checkFiles(Predicate isRelevantFilePredicate, String mandatoryKey) { List errors = new ArrayList<>(); boolean hasMatch = false; for (File file : messageFiles) { - if (pattern.matcher(file.getName()).matches()) { + if (isRelevantFilePredicate.test(file.getName())) { checkFile(file, mandatoryKey, errors); hasMatch = true; } } if (!errors.isEmpty()) { - fail("Errors while checking files matching '" + pattern + "':\n-" + String.join("\n-", errors)); + fail("Errors while checking files\n-" + String.join("\n-", errors)); } else if (!hasMatch) { - fail("Could not find any files satisfying pattern '" + pattern + "'"); + fail("Could not find any files matching criteria"); } } diff --git a/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java b/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java index cb4d03158..eac3b67e3 100644 --- a/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java +++ b/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_MESSAGES_FILE; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @@ -40,7 +41,7 @@ public class MessageUpdaterTest { @Test public void shouldNotUpdateDefaultFile() throws IOException { // given - String messagesFilePath = "messages/messages_en.yml"; + String messagesFilePath = DEFAULT_MESSAGES_FILE; File messagesFile = temporaryFolder.newFile(); Files.copy(TestHelper.getJarFile("/" + messagesFilePath), messagesFile); long modifiedDate = messagesFile.lastModified(); @@ -60,7 +61,7 @@ public class MessageUpdaterTest { Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/messages_test.yml"), messagesFile); // when - boolean wasChanged = messageUpdater.migrateAndSave(messagesFile, "does-not-exist", "messages/messages_en.yml"); + boolean wasChanged = messageUpdater.migrateAndSave(messagesFile, "does-not-exist", DEFAULT_MESSAGES_FILE); // then assertThat(wasChanged, equalTo(true)); @@ -80,7 +81,7 @@ public class MessageUpdaterTest { Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/messages_en_old.yml"), messagesFile); // when - boolean wasChanged = messageUpdater.migrateAndSave(messagesFile, "messages/messages_en.yml", "messages/messages_en.yml"); + boolean wasChanged = messageUpdater.migrateAndSave(messagesFile, DEFAULT_MESSAGES_FILE, DEFAULT_MESSAGES_FILE); // then assertThat(wasChanged, equalTo(true)); @@ -106,7 +107,7 @@ public class MessageUpdaterTest { Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/messages_test2.yml"), messagesFile); // when - boolean wasChanged = messageUpdater.migrateAndSave(messagesFile, "messages/messages_en.yml", "messages/messages_en.yml"); + boolean wasChanged = messageUpdater.migrateAndSave(messagesFile, DEFAULT_MESSAGES_FILE, DEFAULT_MESSAGES_FILE); // then assertThat(wasChanged, equalTo(true)); diff --git a/src/test/java/tools/docs/translations/TranslationsGatherer.java b/src/test/java/tools/docs/translations/TranslationsGatherer.java index 3e2119ff2..9a08bd50d 100644 --- a/src/test/java/tools/docs/translations/TranslationsGatherer.java +++ b/src/test/java/tools/docs/translations/TranslationsGatherer.java @@ -2,14 +2,14 @@ package tools.docs.translations; import ch.jalu.configme.resource.PropertyReader; import ch.jalu.configme.resource.YamlFileReader; +import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.message.MessageKey; import tools.utils.ToolsConstants; import java.io.File; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import static tools.utils.FileIoUtils.listFilesOrThrow; @@ -18,14 +18,13 @@ import static tools.utils.FileIoUtils.listFilesOrThrow; */ public class TranslationsGatherer { - private static final Pattern MESSAGES_PATTERN = Pattern.compile("messages_([a-z]{2,4})\\.yml"); - private static final String MESSAGES_FOLDER = ToolsConstants.MAIN_RESOURCES_ROOT + "messages/"; + private static final String MESSAGES_FOLDER = ToolsConstants.MAIN_RESOURCES_ROOT + MessagePathHelper.MESSAGES_FOLDER; private List translationInfo = new ArrayList<>(); public TranslationsGatherer() { gatherTranslations(); - translationInfo.sort((e1, e2) -> getSortCode(e1).compareTo(getSortCode(e2))); + translationInfo.sort(Comparator.comparing(TranslationsGatherer::getSortCode)); } public List getTranslationInfo() { @@ -35,7 +34,7 @@ public class TranslationsGatherer { private void gatherTranslations() { File[] files = listFilesOrThrow(new File(MESSAGES_FOLDER)); for (File file : files) { - String code = getLanguageCode(file.getName()); + String code = MessagePathHelper.getLanguageIfIsMessagesFile(file.getName()); if (code != null) { processMessagesFile(code, file); } @@ -53,14 +52,6 @@ public class TranslationsGatherer { translationInfo.add(new TranslationInfo(code, (double) availableMessages / MessageKey.values().length)); } - private String getLanguageCode(String messagesFile) { - Matcher matcher = MESSAGES_PATTERN.matcher(messagesFile); - if (matcher.find()) { - return matcher.group(1); - } - return null; - } - /** * Returns the language code from the translation info for sorting purposes. * Returns "a" for "en" language code to sort English on top. @@ -69,7 +60,7 @@ public class TranslationsGatherer { * @return the language code for sorting */ private static String getSortCode(TranslationInfo info) { - return "en".equals(info.code) ? "a" : info.code; + return MessagePathHelper.DEFAULT_LANGUAGE.equals(info.code) ? "a" : info.code; } public static final class TranslationInfo { diff --git a/src/test/java/tools/messages/AddJavaDocToMessageEnumTask.java b/src/test/java/tools/messages/AddJavaDocToMessageEnumTask.java index 44306dc81..383a3e965 100644 --- a/src/test/java/tools/messages/AddJavaDocToMessageEnumTask.java +++ b/src/test/java/tools/messages/AddJavaDocToMessageEnumTask.java @@ -1,5 +1,6 @@ package tools.messages; +import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.message.MessageKey; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; @@ -15,7 +16,8 @@ import java.util.List; */ public class AddJavaDocToMessageEnumTask implements AutoToolTask { - private static final String MESSAGES_FILE = ToolsConstants.MAIN_RESOURCES_ROOT + "messages/messages_en.yml"; + private static final String MESSAGES_FILE = + ToolsConstants.MAIN_RESOURCES_ROOT + MessagePathHelper.DEFAULT_MESSAGES_FILE; private FileConfiguration configuration; diff --git a/src/test/java/tools/messages/VerifyMessagesTask.java b/src/test/java/tools/messages/VerifyMessagesTask.java index e60fa0fd8..c08108cde 100644 --- a/src/test/java/tools/messages/VerifyMessagesTask.java +++ b/src/test/java/tools/messages/VerifyMessagesTask.java @@ -1,6 +1,7 @@ package tools.messages; import com.google.common.collect.Multimap; +import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.util.StringUtils; import org.bukkit.configuration.file.FileConfiguration; @@ -15,8 +16,8 @@ import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; -import java.util.regex.Pattern; +import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_MESSAGES_FILE; import static tools.utils.FileIoUtils.listFilesOrThrow; /** @@ -25,11 +26,7 @@ import static tools.utils.FileIoUtils.listFilesOrThrow; public final class VerifyMessagesTask implements ToolTask { /** The folder containing the message files. */ - private static final String MESSAGES_FOLDER = ToolsConstants.MAIN_RESOURCES_ROOT + "messages/"; - /** Pattern of the message file names. */ - private static final Pattern MESSAGE_FILE_PATTERN = Pattern.compile("messages_[a-z]{2,7}\\.yml"); - /** File to get default messages from (assumes that it is complete). */ - private static final String DEFAULT_MESSAGES_FILE = MESSAGES_FOLDER + "messages_en.yml"; + private static final String MESSAGES_FOLDER = ToolsConstants.MAIN_RESOURCES_ROOT + MessagePathHelper.MESSAGES_FOLDER; @Override public String getTaskName() { @@ -50,7 +47,7 @@ public final class VerifyMessagesTask implements ToolTask { if (StringUtils.isEmpty(inputFile)) { messageFiles = getMessagesFiles(); } else { - File customFile = new File(MESSAGES_FOLDER, "messages_" + inputFile + ".yml"); + File customFile = new File(ToolsConstants.MAIN_RESOURCES_ROOT, MessagePathHelper.createMessageFilePath(inputFile)); messageFiles = Collections.singletonList(customFile); } @@ -118,7 +115,7 @@ public final class VerifyMessagesTask implements ToolTask { File[] files = listFilesOrThrow(new File(MESSAGES_FOLDER)); List messageFiles = new ArrayList<>(); for (File file : files) { - if (MESSAGE_FILE_PATTERN.matcher(file.getName()).matches()) { + if (MessagePathHelper.isMessagesFile(file.getName())) { messageFiles.add(file); } } From 81cf14fbc16aaecf7ac72dfea9a8acbff21f4f6d Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 22 Jun 2019 23:30:56 +0200 Subject: [PATCH 65/83] #1752 #1830 Do not hide inventory if player is not registered --- .../protocollib/InventoryPacketAdapter.java | 23 +++++++++++-------- .../protocollib/ProtocolLibService.java | 10 +++++--- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java b/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java index 768c5f59e..88e7f5fb5 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java @@ -27,6 +27,7 @@ import com.comphenix.protocol.reflect.StructureModifier; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerCache; +import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.service.BukkitService; import org.bukkit.Material; @@ -48,10 +49,12 @@ class InventoryPacketAdapter extends PacketAdapter { private static final int HOTBAR_SIZE = 9; private final PlayerCache playerCache; + private final DataSource dataSource; - InventoryPacketAdapter(AuthMe plugin, PlayerCache playerCache) { + InventoryPacketAdapter(AuthMe plugin, PlayerCache playerCache, DataSource dataSource) { super(plugin, PacketType.Play.Server.SET_SLOT, PacketType.Play.Server.WINDOW_ITEMS); this.playerCache = playerCache; + this.dataSource = dataSource; } @Override @@ -59,20 +62,22 @@ class InventoryPacketAdapter extends PacketAdapter { Player player = packetEvent.getPlayer(); PacketContainer packet = packetEvent.getPacket(); - byte windowId = packet.getIntegers().read(0).byteValue(); - if (windowId == PLAYER_INVENTORY && !playerCache.isAuthenticated(player.getName())) { + int windowId = packet.getIntegers().read(0); + if (windowId == PLAYER_INVENTORY && shouldHideInventory(player.getName())) { packetEvent.setCancelled(true); } } - public void register(BukkitService bukkitService, boolean hideNow) { + public void register(BukkitService bukkitService) { ProtocolLibrary.getProtocolManager().addPacketListener(this); - if (hideNow) { - bukkitService.getOnlinePlayers().stream() - .filter(player -> playerCache.isAuthenticated(player.getName())) - .forEach(this::sendBlankInventoryPacket); - } + bukkitService.getOnlinePlayers().stream() + .filter(player -> shouldHideInventory(player.getName())) + .forEach(this::sendBlankInventoryPacket); + } + + private boolean shouldHideInventory(String playerName) { + return !playerCache.isAuthenticated(playerName) && dataSource.isAuthAvailable(playerName); } public void unregister() { diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java index bc1654bb4..0804c1966 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java @@ -4,6 +4,7 @@ import ch.jalu.injector.annotations.NoFieldScan; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerCache; +import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.SettingsDependent; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; @@ -28,12 +29,15 @@ public class ProtocolLibService implements SettingsDependent { private AuthMe plugin; private BukkitService bukkitService; private PlayerCache playerCache; + private DataSource dataSource; @Inject - ProtocolLibService(AuthMe plugin, Settings settings, BukkitService bukkitService, PlayerCache playerCache) { + ProtocolLibService(AuthMe plugin, Settings settings, BukkitService bukkitService, PlayerCache playerCache, + DataSource dataSource) { this.plugin = plugin; this.bukkitService = bukkitService; this.playerCache = playerCache; + this.dataSource = dataSource; reload(settings); } @@ -59,8 +63,8 @@ public class ProtocolLibService implements SettingsDependent { if (protectInvBeforeLogin) { if (inventoryPacketAdapter == null) { // register the packet listener and start hiding it for all already online players (reload) - inventoryPacketAdapter = new InventoryPacketAdapter(plugin, playerCache); - inventoryPacketAdapter.register(bukkitService, true); + inventoryPacketAdapter = new InventoryPacketAdapter(plugin, playerCache, dataSource); + inventoryPacketAdapter.register(bukkitService); } } else if (inventoryPacketAdapter != null) { inventoryPacketAdapter.unregister(); From fc06558687f49033b2381f5e83f1565f22479360 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 22 Jun 2019 23:50:06 +0200 Subject: [PATCH 66/83] Minor: change bukkit service to return a plain collection of Player - List is read-only and can be easily "upcast" to Collection - Remove awkward hack that was needed for mocking the method previously (issues with generics) --- .../executable/authme/VersionCommand.java | 6 +++--- .../xephi/authme/listener/OnJoinVerifier.java | 4 ++-- .../fr/xephi/authme/service/BukkitService.java | 5 +++-- .../authme/listener/OnJoinVerifierTest.java | 5 ++--- .../process/login/AsynchronousLoginTest.java | 3 +-- .../authme/service/AntiBotServiceTest.java | 3 +-- .../service/BukkitServiceTestHelper.java | 18 ------------------ .../WelcomeMessageConfigurationTest.java | 5 +---- 8 files changed, 13 insertions(+), 36 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 6b90d3d78..03a1c5a37 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 @@ -23,7 +23,7 @@ public class VersionCommand implements ExecutableCommand { sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.WHITE + AuthMe.getPluginName() + " v" + AuthMe.getPluginVersion() + ChatColor.GRAY + " (build: " + AuthMe.getPluginBuildNumber() + ")"); sender.sendMessage(ChatColor.GOLD + "Developers:"); - Collection onlinePlayers = bukkitService.getOnlinePlayers(); + Collection onlinePlayers = bukkitService.getOnlinePlayers(); printDeveloper(sender, "Alexandre Vanhecke", "xephi59", "Original Author", onlinePlayers); printDeveloper(sender, "Lucas J.", "ljacqu", "Main Developer", onlinePlayers); printDeveloper(sender, "Gnat008", "gnat008", "Developer", onlinePlayers); @@ -49,7 +49,7 @@ public class VersionCommand implements ExecutableCommand { * @param onlinePlayers The list of online players */ private static void printDeveloper(CommandSender sender, String name, String minecraftName, String function, - Collection onlinePlayers) { + Collection onlinePlayers) { // Print the name StringBuilder msg = new StringBuilder(); msg.append(" ") @@ -77,7 +77,7 @@ public class VersionCommand implements ExecutableCommand { * * @return True if the player is online, false otherwise */ - private static boolean isPlayerOnline(String minecraftName, Collection onlinePlayers) { + private static boolean isPlayerOnline(String minecraftName, Collection onlinePlayers) { for (Player player : onlinePlayers) { if (player.getName().equalsIgnoreCase(minecraftName)) { return true; diff --git a/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java b/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java index c1c30cf94..390d7ca09 100644 --- a/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java +++ b/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java @@ -128,7 +128,7 @@ public class OnJoinVerifier implements Reloadable { } // Server is full and player is VIP; attempt to kick a non-VIP player to make room - Collection onlinePlayers = bukkitService.getOnlinePlayers(); + Collection onlinePlayers = bukkitService.getOnlinePlayers(); if (onlinePlayers.size() < server.getMaxPlayers()) { event.allow(); return false; @@ -207,7 +207,7 @@ public class OnJoinVerifier implements Reloadable { * * @return the player to kick, or null if none applicable */ - private Player generateKickPlayer(Collection onlinePlayers) { + private Player generateKickPlayer(Collection onlinePlayers) { for (Player player : onlinePlayers) { if (!permissionsManager.hasPermission(player, PlayerStatePermission.IS_VIP)) { return player; diff --git a/src/main/java/fr/xephi/authme/service/BukkitService.java b/src/main/java/fr/xephi/authme/service/BukkitService.java index 302414110..a6af581ab 100644 --- a/src/main/java/fr/xephi/authme/service/BukkitService.java +++ b/src/main/java/fr/xephi/authme/service/BukkitService.java @@ -233,8 +233,9 @@ public class BukkitService implements SettingsDependent { * * @return collection of online players */ - public Collection getOnlinePlayers() { - return Bukkit.getOnlinePlayers(); + @SuppressWarnings("unchecked") + public Collection getOnlinePlayers() { + return (Collection) Bukkit.getOnlinePlayers(); } /** diff --git a/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java b/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java index 114d42101..d8fd9d6bb 100644 --- a/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java +++ b/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java @@ -33,7 +33,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import static fr.xephi.authme.service.BukkitServiceTestHelper.returnGivenOnlinePlayers; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; @@ -123,7 +122,7 @@ public class OnJoinVerifierTest { List onlinePlayers = Arrays.asList(mock(Player.class), mock(Player.class)); given(permissionsManager.hasPermission(onlinePlayers.get(0), PlayerStatePermission.IS_VIP)).willReturn(true); given(permissionsManager.hasPermission(onlinePlayers.get(1), PlayerStatePermission.IS_VIP)).willReturn(false); - returnGivenOnlinePlayers(bukkitService, onlinePlayers); + given(bukkitService.getOnlinePlayers()).willReturn(onlinePlayers); given(server.getMaxPlayers()).willReturn(onlinePlayers.size()); given(messages.retrieveSingle(player, MessageKey.KICK_FOR_VIP)).willReturn("kick for vip"); @@ -147,7 +146,7 @@ public class OnJoinVerifierTest { given(permissionsManager.hasPermission(player, PlayerStatePermission.IS_VIP)).willReturn(true); List onlinePlayers = Collections.singletonList(mock(Player.class)); given(permissionsManager.hasPermission(onlinePlayers.get(0), PlayerStatePermission.IS_VIP)).willReturn(true); - returnGivenOnlinePlayers(bukkitService, onlinePlayers); + given(bukkitService.getOnlinePlayers()).willReturn(onlinePlayers); given(server.getMaxPlayers()).willReturn(onlinePlayers.size()); given(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER)).willReturn("kick full server"); diff --git a/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java b/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java index 2c02e581f..33ef76f09 100644 --- a/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java +++ b/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java @@ -27,7 +27,6 @@ import org.mockito.stubbing.Answer; import java.util.Arrays; import java.util.List; -import static fr.xephi.authme.service.BukkitServiceTestHelper.returnGivenOnlinePlayers; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -266,7 +265,7 @@ public class AsynchronousLoginTest { TestHelper.mockPlayerIp(playerF, "3.3.3.3"); List onlinePlayers = Arrays.asList(playerA, playerB, playerC, playerD, playerE, playerF); - returnGivenOnlinePlayers(bukkitService, onlinePlayers); + given(bukkitService.getOnlinePlayers()).willReturn(onlinePlayers); } } diff --git a/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java b/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java index f992e2554..f3f1f3f80 100644 --- a/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java @@ -19,7 +19,6 @@ import org.mockito.Mock; import java.util.Arrays; import java.util.List; -import static fr.xephi.authme.service.BukkitServiceTestHelper.returnGivenOnlinePlayers; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @@ -158,7 +157,7 @@ public class AntiBotServiceTest { public void shouldInformPlayersOnActivation() { // given - listening antibot List players = Arrays.asList(mock(Player.class), mock(Player.class)); - returnGivenOnlinePlayers(bukkitService, players); + given(bukkitService.getOnlinePlayers()).willReturn(players); given(permissionsManager.hasPermission(players.get(0), AdminPermission.ANTIBOT_MESSAGES)).willReturn(false); given(permissionsManager.hasPermission(players.get(1), AdminPermission.ANTIBOT_MESSAGES)).willReturn(true); diff --git a/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java b/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java index 7d57869dd..9807e4f5b 100644 --- a/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java +++ b/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java @@ -1,12 +1,7 @@ package fr.xephi.authme.service; -import org.bukkit.entity.Player; - -import java.util.Collection; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doAnswer; /** @@ -86,17 +81,4 @@ public final class BukkitServiceTestHelper { return null; }).when(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), anyLong()); } - - /** - * Sets a BukkitService mock to return the given players when its method - * {@link BukkitService#getOnlinePlayers()} is invoked. - * - * @param bukkitService the mock to set behavior on - * @param players the players to return - */ - @SuppressWarnings("unchecked") - public static void returnGivenOnlinePlayers(BukkitService bukkitService, Collection players) { - // The compiler gets lost in generics because Collection is returned from getOnlinePlayers() - given(bukkitService.getOnlinePlayers()).willReturn((Collection) players); - } } diff --git a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java index cf8077c67..7550ed694 100644 --- a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java +++ b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java @@ -26,15 +26,12 @@ import java.nio.file.Files; import java.util.Arrays; import java.util.List; -import static fr.xephi.authme.service.BukkitServiceTestHelper.returnGivenOnlinePlayers; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.only; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -115,7 +112,7 @@ public class WelcomeMessageConfigurationTest { // given String welcomeMessage = "{ONLINE}/{MAXPLAYERS} online\n{LOGINS} logged in\nYour world is {WORLD}\nServer: {VERSION}"; setWelcomeMessageAndReload(welcomeMessage); - returnGivenOnlinePlayers(bukkitService, Arrays.asList(mock(Player.class), mock(Player.class))); + given(bukkitService.getOnlinePlayers()).willReturn(Arrays.asList(mock(Player.class), mock(Player.class))); given(server.getMaxPlayers()).willReturn(20); given(playerCache.getLogged()).willReturn(1); given(server.getBukkitVersion()).willReturn("Bukkit-456.77.8"); From 65ed08409b131f5f4a76abb6b3f89642658fc0c9 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Sun, 23 Jun 2019 23:32:54 +0200 Subject: [PATCH 67/83] Bump postgresql from 42.2.5 to 42.2.6 (#1841) Bumps [postgresql](https://github.com/pgjdbc/pgjdbc) from 42.2.5 to 42.2.6. - [Release notes](https://github.com/pgjdbc/pgjdbc/releases) - [Changelog](https://github.com/pgjdbc/pgjdbc/blob/master/CHANGELOG.md) - [Commits](https://github.com/pgjdbc/pgjdbc/compare/REL42.2.5...REL42.2.6) Signed-off-by: dependabot-preview[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ee61a8c03..89f2224df 100644 --- a/pom.xml +++ b/pom.xml @@ -853,7 +853,7 @@ org.postgresql postgresql - 42.2.5 + 42.2.6 From ae1b0c4cacff09246a4815a9670937116a6c0add Mon Sep 17 00:00:00 2001 From: Pronin Egor <42776347+MrZillaGold@users.noreply.github.com> Date: Tue, 25 Jun 2019 04:08:38 +1000 Subject: [PATCH 68/83] Update messages_ru.yml (#1843) --- src/main/resources/messages/messages_ru.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/messages/messages_ru.yml b/src/main/resources/messages/messages_ru.yml index 6b0bb7a3e..3252894d4 100644 --- a/src/main/resources/messages/messages_ru.yml +++ b/src/main/resources/messages/messages_ru.yml @@ -93,7 +93,7 @@ recovery: command_usage: '&cИспользование: /email recovery <эл. почта>' email_sent: '&2Письмо с инструкциями для восстановления было отправлено на вашу электронную почту!' code: - code_sent: 'Код восстановления для сброса пароля был отправлен на электронную почт.' + code_sent: 'Код восстановления для сброса пароля был отправлен на электронную почту.' incorrect: 'Неверный код восстановления! Попыток осталось: %count.' tries_exceeded: 'Вы слишком много раз неверно ввели код восстановления. Используйте «/email recovery [эл. почта]», чтобы получить новый код.' correct: 'Код восстановления введён верно!' From b834a7837672a2afa8c8bacaa555d543b3197b9a Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2019 12:37:54 +0200 Subject: [PATCH 69/83] Bump sqlite-jdbc from 3.27.2.1 to 3.28.0 (#1845) Bumps [sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.27.2.1 to 3.28.0. - [Release notes](https://github.com/xerial/sqlite-jdbc/releases) - [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG) - [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.27.2.1...3.28.0) Signed-off-by: dependabot-preview[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 89f2224df..00b8afc18 100644 --- a/pom.xml +++ b/pom.xml @@ -897,7 +897,7 @@ org.xerial sqlite-jdbc - 3.27.2.1 + 3.28.0 test From e2c2e8beadc0286153ab7ac4ac35a0e695dbbac3 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Sat, 6 Jul 2019 18:26:04 +0200 Subject: [PATCH 70/83] Bump checker-qual from 2.8.2 to 2.9.0 (#1849) Bumps [checker-qual](https://github.com/typetools/checker-framework) from 2.8.2 to 2.9.0. - [Release notes](https://github.com/typetools/checker-framework/releases) - [Changelog](https://github.com/typetools/checker-framework/blob/master/changelog.txt) - [Commits](https://github.com/typetools/checker-framework/compare/checker-framework-2.8.2...checker-framework-2.9.0) Signed-off-by: dependabot-preview[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 00b8afc18..6e84a08da 100644 --- a/pom.xml +++ b/pom.xml @@ -889,7 +889,7 @@ org.checkerframework checker-qual - 2.8.2 + 2.9.0 test From 210a4f61cba30b316cd35f5a3eaf6c62f9233992 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sat, 6 Jul 2019 18:26:43 +0200 Subject: [PATCH 71/83] #1219 Make 2FA tokens one-use only (#1848) - Make TotpAuthenticator keep track of the used codes and reject any known ones --- .../security/totp/GenerateTotpService.java | 2 +- .../security/totp/TotpAuthenticator.java | 29 ++++++++++++++--- .../totp/GenerateTotpServiceTest.java | 6 ++-- .../security/totp/TotpAuthenticatorTest.java | 32 ++++++++++++++++--- 4 files changed, 56 insertions(+), 13 deletions(-) diff --git a/src/main/java/fr/xephi/authme/security/totp/GenerateTotpService.java b/src/main/java/fr/xephi/authme/security/totp/GenerateTotpService.java index 14a6a6bbb..3d00f78a0 100644 --- a/src/main/java/fr/xephi/authme/security/totp/GenerateTotpService.java +++ b/src/main/java/fr/xephi/authme/security/totp/GenerateTotpService.java @@ -59,7 +59,7 @@ public class GenerateTotpService implements HasCleanup { */ public boolean isTotpCodeCorrectForGeneratedTotpKey(Player player, String totpCode) { TotpGenerationResult totpDetails = totpKeys.get(player.getName().toLowerCase()); - return totpDetails != null && totpAuthenticator.checkCode(totpDetails.getTotpKey(), totpCode); + return totpDetails != null && totpAuthenticator.checkCode(player.getName(), totpDetails.getTotpKey(), totpCode); } @Override diff --git a/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java b/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java index 4905a521e..ad74ffc62 100644 --- a/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java +++ b/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java @@ -1,23 +1,31 @@ package fr.xephi.authme.security.totp; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; import com.google.common.primitives.Ints; import com.warrenstrange.googleauth.GoogleAuthenticator; import com.warrenstrange.googleauth.GoogleAuthenticatorKey; import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator; import com.warrenstrange.googleauth.IGoogleAuthenticator; import fr.xephi.authme.data.auth.PlayerAuth; +import fr.xephi.authme.initialization.HasCleanup; import fr.xephi.authme.service.BukkitService; import org.bukkit.entity.Player; import javax.inject.Inject; +import static fr.xephi.authme.util.Utils.MILLIS_PER_MINUTE; + /** * Provides TOTP functions (wrapping a third-party TOTP implementation). */ -public class TotpAuthenticator { +public class TotpAuthenticator implements HasCleanup { + + private static final int CODE_RETENTION_MINUTES = 5; private final IGoogleAuthenticator authenticator; private final BukkitService bukkitService; + private final Table usedCodes = HashBasedTable.create(); @Inject TotpAuthenticator(BukkitService bukkitService) { @@ -33,19 +41,26 @@ public class TotpAuthenticator { } public boolean checkCode(PlayerAuth auth, String totpCode) { - return checkCode(auth.getTotpKey(), totpCode); + return checkCode(auth.getNickname(), auth.getTotpKey(), totpCode); } /** * Returns whether the given input code matches for the provided TOTP key. * + * @param playerName the player name * @param totpKey the key to check with * @param inputCode the input code to verify * @return true if code is valid, false otherwise */ - public boolean checkCode(String totpKey, String inputCode) { + public boolean checkCode(String playerName, String totpKey, String inputCode) { + String nameLower = playerName.toLowerCase(); Integer totpCode = Ints.tryParse(inputCode); - return totpCode != null && authenticator.authorize(totpKey, totpCode); + if (totpCode != null && !usedCodes.contains(nameLower, totpCode) + && authenticator.authorize(totpKey, totpCode)) { + usedCodes.put(nameLower, totpCode, System.currentTimeMillis()); + return true; + } + return false; } public TotpGenerationResult generateTotpKey(Player player) { @@ -55,6 +70,12 @@ public class TotpAuthenticator { return new TotpGenerationResult(credentials.getKey(), qrCodeUrl); } + @Override + public void performCleanup() { + long threshold = System.currentTimeMillis() - CODE_RETENTION_MINUTES * MILLIS_PER_MINUTE; + usedCodes.values().removeIf(value -> value < threshold); + } + public static final class TotpGenerationResult { private final String totpKey; private final String authenticatorQrCodeUrl; diff --git a/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java b/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java index 1a22d26e7..3778cc100 100644 --- a/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java +++ b/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java @@ -70,7 +70,7 @@ public class GenerateTotpServiceTest { given(totpAuthenticator.generateTotpKey(player)).willReturn(givenGenerationResult); generateTotpService.generateTotpKey(player); String validCode = "928374"; - given(totpAuthenticator.checkCode(generatedKey, validCode)).willReturn(true); + given(totpAuthenticator.checkCode("Aria", generatedKey, validCode)).willReturn(true); // when boolean invalidCodeResult = generateTotpService.isTotpCodeCorrectForGeneratedTotpKey(player, "000000"); @@ -81,8 +81,8 @@ public class GenerateTotpServiceTest { assertThat(invalidCodeResult, equalTo(false)); assertThat(validCodeResult, equalTo(true)); assertThat(unknownPlayerResult, equalTo(false)); - verify(totpAuthenticator).checkCode(generatedKey, "000000"); - verify(totpAuthenticator).checkCode(generatedKey, validCode); + verify(totpAuthenticator).checkCode("Aria", generatedKey, "000000"); + verify(totpAuthenticator).checkCode("Aria", generatedKey, validCode); } @Test diff --git a/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java b/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java index 3afc81817..ed3bf2c7e 100644 --- a/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java +++ b/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java @@ -1,9 +1,12 @@ package fr.xephi.authme.security.totp; +import com.google.common.collect.Table; import com.warrenstrange.googleauth.IGoogleAuthenticator; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.security.totp.TotpAuthenticator.TotpGenerationResult; import fr.xephi.authme.service.BukkitService; +import fr.xephi.authme.util.Utils; import org.bukkit.entity.Player; import org.junit.Before; import org.junit.Test; @@ -63,24 +66,26 @@ public class TotpAuthenticatorTest { } @Test - public void shouldCheckCode() { + public void shouldCheckCodeAndDeclareItValidOnlyOnce() { // given String secret = "the_secret"; int code = 21398; given(googleAuthenticator.authorize(secret, code)).willReturn(true); // when - boolean result = totpAuthenticator.checkCode(secret, Integer.toString(code)); + boolean result1 = totpAuthenticator.checkCode("pl", secret, Integer.toString(code)); + boolean result2 = totpAuthenticator.checkCode("pl", secret, Integer.toString(code)); // then - assertThat(result, equalTo(true)); + assertThat(result1, equalTo(true)); + assertThat(result2, equalTo(false)); verify(googleAuthenticator).authorize(secret, code); } @Test public void shouldHandleInvalidNumberInput() { // given / when - boolean result = totpAuthenticator.checkCode("Some_Secret", "123ZZ"); + boolean result = totpAuthenticator.checkCode("foo", "Some_Secret", "123ZZ"); // then assertThat(result, equalTo(false)); @@ -96,7 +101,7 @@ public class TotpAuthenticatorTest { .totpKey(totpKey) .build(); String inputCode = "408435"; - given(totpAuthenticator.checkCode(totpKey, inputCode)).willReturn(true); + given(totpAuthenticator.checkCode("Maya", totpKey, inputCode)).willReturn(true); // when boolean result = totpAuthenticator.checkCode(auth, inputCode); @@ -106,6 +111,23 @@ public class TotpAuthenticatorTest { verify(googleAuthenticator).authorize(totpKey, 408435); } + @Test + public void shouldRemoveOldEntries() { + // given + Table usedCodes = ReflectionTestUtils.getFieldValue( + TotpAuthenticator.class, totpAuthenticator, "usedCodes"); + usedCodes.put("bobby", 414213, System.currentTimeMillis()); + usedCodes.put("charlie", 732050, System.currentTimeMillis() - 6 * Utils.MILLIS_PER_MINUTE); + usedCodes.put("bobby", 236067, System.currentTimeMillis() - 9 * Utils.MILLIS_PER_MINUTE); + + // when + totpAuthenticator.performCleanup(); + + // then + assertThat(usedCodes.size(), equalTo(1)); + assertThat(usedCodes.contains("bobby", 414213), equalTo(true)); + } + private final class TotpAuthenticatorTestImpl extends TotpAuthenticator { TotpAuthenticatorTestImpl(BukkitService bukkitService) { From 61af2a0554c11335ddaa99347fd0683d9df79ff7 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Fri, 2 Aug 2019 15:23:46 +0200 Subject: [PATCH 72/83] Update depenencies - As reported by dependabot: closes #1859, closes #1860, closes #1867, closes #1871, closes #1873 --- pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 6e84a08da..be13db624 100644 --- a/pom.xml +++ b/pom.xml @@ -222,7 +222,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.1.0 + 3.1.1 ${project.finalNameBase} @@ -364,7 +364,7 @@ org.apache.maven.plugins maven-site-plugin - 3.7.1 + 3.8.2 @@ -726,7 +726,7 @@ com.onarandombox.multiversecore Multiverse-Core - 3.0.0 + 4.0.1 jar provided @@ -876,7 +876,7 @@ org.mockito mockito-core test - 2.28.2 + 3.0.0 hamcrest-core @@ -889,7 +889,7 @@ org.checkerframework checker-qual - 2.9.0 + 2.10.0 test From c00109074a8aaacc9f6417205bca41be4df63dde Mon Sep 17 00:00:00 2001 From: ljacqu Date: Fri, 2 Aug 2019 15:29:06 +0200 Subject: [PATCH 73/83] Minor: create dummy string of specific length with better method --- .../tools/docs/hashmethods/EncryptionMethodInfoGatherer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java b/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java index 0362e26ca..29b03c947 100644 --- a/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java +++ b/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java @@ -2,6 +2,7 @@ package tools.docs.hashmethods; import ch.jalu.injector.Injector; import ch.jalu.injector.InjectorBuilder; +import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.TestHelper; @@ -15,7 +16,6 @@ import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.settings.Settings; import java.lang.annotation.Annotation; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; @@ -171,7 +171,7 @@ public class EncryptionMethodInfoGatherer { @Override public String computeHash(String password) { // Argon2 produces hashes of 96 characters -> return dummy value with this length - return String.join("", Collections.nCopies(96, ".")); + return Strings.repeat(".", 96); } } } From f0d3d085c6ebd565456b66399ae8239af6b39922 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Fri, 2 Aug 2019 15:38:13 +0200 Subject: [PATCH 74/83] #1574 Use server name in 2FA QR code link instead of IP --- .../authme/security/totp/TotpAuthenticator.java | 11 ++++++----- .../security/totp/TotpAuthenticatorTest.java | 17 ++++++++++------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java b/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java index ad74ffc62..e26b136f4 100644 --- a/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java +++ b/src/main/java/fr/xephi/authme/security/totp/TotpAuthenticator.java @@ -9,7 +9,8 @@ import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator; import com.warrenstrange.googleauth.IGoogleAuthenticator; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.initialization.HasCleanup; -import fr.xephi.authme.service.BukkitService; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.PluginSettings; import org.bukkit.entity.Player; import javax.inject.Inject; @@ -24,13 +25,13 @@ public class TotpAuthenticator implements HasCleanup { private static final int CODE_RETENTION_MINUTES = 5; private final IGoogleAuthenticator authenticator; - private final BukkitService bukkitService; + private final Settings settings; private final Table usedCodes = HashBasedTable.create(); @Inject - TotpAuthenticator(BukkitService bukkitService) { + TotpAuthenticator(Settings settings) { this.authenticator = createGoogleAuthenticator(); - this.bukkitService = bukkitService; + this.settings = settings; } /** @@ -66,7 +67,7 @@ public class TotpAuthenticator implements HasCleanup { public TotpGenerationResult generateTotpKey(Player player) { GoogleAuthenticatorKey credentials = authenticator.createCredentials(); String qrCodeUrl = GoogleAuthenticatorQRGenerator.getOtpAuthURL( - bukkitService.getIp(), player.getName(), credentials); + settings.getProperty(PluginSettings.SERVER_NAME), player.getName(), credentials); return new TotpGenerationResult(credentials.getKey(), qrCodeUrl); } diff --git a/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java b/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java index ed3bf2c7e..52f8b9906 100644 --- a/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java +++ b/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java @@ -5,7 +5,8 @@ import com.warrenstrange.googleauth.IGoogleAuthenticator; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.security.totp.TotpAuthenticator.TotpGenerationResult; -import fr.xephi.authme.service.BukkitService; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.util.Utils; import org.bukkit.entity.Player; import org.junit.Before; @@ -15,6 +16,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; @@ -33,25 +35,25 @@ public class TotpAuthenticatorTest { private TotpAuthenticator totpAuthenticator; @Mock - private BukkitService bukkitService; + private Settings settings; @Mock private IGoogleAuthenticator googleAuthenticator; @Before public void initializeTotpAuthenticator() { - totpAuthenticator = new TotpAuthenticatorTestImpl(bukkitService); + totpAuthenticator = new TotpAuthenticatorTestImpl(settings); } @Test public void shouldGenerateTotpKey() { // given // Use the GoogleAuthenticator instance the TotpAuthenticator normally creates to test its parameters - totpAuthenticator = new TotpAuthenticator(bukkitService); + totpAuthenticator = new TotpAuthenticator(settings); Player player = mock(Player.class); given(player.getName()).willReturn("Bobby"); - given(bukkitService.getIp()).willReturn("127.48.44.4"); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("MCtopia"); // when TotpGenerationResult key1 = totpAuthenticator.generateTotpKey(player); @@ -61,6 +63,7 @@ public class TotpAuthenticatorTest { assertThat(key1.getTotpKey(), stringWithLength(16)); assertThat(key2.getTotpKey(), stringWithLength(16)); assertThat(key1.getAuthenticatorQrCodeUrl(), startsWith("https://chart.googleapis.com/chart?chs=200x200")); + assertThat(key1.getAuthenticatorQrCodeUrl(), containsString("MCtopia")); assertThat(key2.getAuthenticatorQrCodeUrl(), startsWith("https://chart.googleapis.com/chart?chs=200x200")); assertThat(key1.getTotpKey(), not(equalTo(key2.getTotpKey()))); } @@ -130,8 +133,8 @@ public class TotpAuthenticatorTest { private final class TotpAuthenticatorTestImpl extends TotpAuthenticator { - TotpAuthenticatorTestImpl(BukkitService bukkitService) { - super(bukkitService); + TotpAuthenticatorTestImpl(Settings settings) { + super(settings); } @Override From 7bede2528f773b6f7260e31744a0542014d5abe6 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Mon, 5 Aug 2019 19:31:59 +0200 Subject: [PATCH 75/83] #1523 Create admin commands to handle players' 2FA data (#1876) * #1523 Create admin commands to handle players' 2FA data - Create admin command to view if a player has enabled 2FA - Create admin command to disable 2FA for a specified player --- docs/commands.md | 8 +- docs/permission_nodes.md | 6 +- .../authme/command/CommandInitializer.java | 24 ++++ .../authme/TotpDisableAdminCommand.java | 58 +++++++++ .../authme/TotpViewStatusCommand.java | 38 ++++++ .../authme/permission/AdminPermission.java | 10 ++ src/main/resources/plugin.yml | 11 +- .../authme/TotpDisableAdminCommandTest.java | 120 ++++++++++++++++++ .../authme/TotpViewStatusCommandTest.java | 92 ++++++++++++++ 9 files changed, 362 insertions(+), 5 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java create mode 100644 src/main/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommand.java create mode 100644 src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java create mode 100644 src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java diff --git a/docs/commands.md b/docs/commands.md index 60c01dbac..ef8f28a8a 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1,5 +1,5 @@ - + ## AuthMe Commands You can use the following commands to use the features of AuthMe. Mandatory arguments are marked with `< >` @@ -24,6 +24,10 @@ brackets; optional arguments are enclosed in square brackets (`[ ]`).
Requires `authme.admin.changemail` - **/authme getip** <player>: Get the IP address of the specified online player.
Requires `authme.admin.getip` +- **/authme totp** <player>: Returns whether the specified player has enabled two-factor authentication +
Requires `authme.admin.totpviewstatus` +- **/authme disabletotp** <player>: Disable two-factor authentication for a player +
Requires `authme.admin.totpdisable` - **/authme spawn**: Teleport to the spawn.
Requires `authme.admin.spawn` - **/authme setspawn**: Change the player's spawn to your current position. @@ -104,4 +108,4 @@ brackets; optional arguments are enclosed in square brackets (`[ ]`). --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:04 CEST 2019 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Aug 02 16:25:51 CEST 2019 diff --git a/docs/permission_nodes.md b/docs/permission_nodes.md index 2ed9f36c5..c53953b55 100644 --- a/docs/permission_nodes.md +++ b/docs/permission_nodes.md @@ -1,5 +1,5 @@ - + ## AuthMe Permission Nodes The following are the permission nodes that are currently supported by the latest dev builds. @@ -28,6 +28,8 @@ The following are the permission nodes that are currently supported by the lates - **authme.admin.setspawn** – Administrator command to set the AuthMe spawn. - **authme.admin.spawn** – Administrator command to teleport to the AuthMe spawn. - **authme.admin.switchantibot** – Administrator command to toggle the AntiBot protection status. +- **authme.admin.totpdisable** – Administrator command to disable the two-factor auth of a user. +- **authme.admin.totpviewstatus** – Administrator command to see whether a player has enabled two-factor authentication. - **authme.admin.unregister** – Administrator command to unregister an existing user. - **authme.admin.updatemessages** – Permission to use the update messages command. - **authme.allowchatbeforelogin** – Permission to send chat messages before being logged in. @@ -71,4 +73,4 @@ The following are the permission nodes that are currently supported by the lates --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Apr 19 17:16:06 CEST 2019 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Fri Aug 02 16:25:54 CEST 2019 diff --git a/src/main/java/fr/xephi/authme/command/CommandInitializer.java b/src/main/java/fr/xephi/authme/command/CommandInitializer.java index ba48e0112..fcc3ce611 100644 --- a/src/main/java/fr/xephi/authme/command/CommandInitializer.java +++ b/src/main/java/fr/xephi/authme/command/CommandInitializer.java @@ -24,6 +24,8 @@ import fr.xephi.authme.command.executable.authme.SetFirstSpawnCommand; import fr.xephi.authme.command.executable.authme.SetSpawnCommand; import fr.xephi.authme.command.executable.authme.SpawnCommand; import fr.xephi.authme.command.executable.authme.SwitchAntiBotCommand; +import fr.xephi.authme.command.executable.authme.TotpDisableAdminCommand; +import fr.xephi.authme.command.executable.authme.TotpViewStatusCommand; import fr.xephi.authme.command.executable.authme.UnregisterAdminCommand; import fr.xephi.authme.command.executable.authme.UpdateHelpMessagesCommand; import fr.xephi.authme.command.executable.authme.VersionCommand; @@ -290,6 +292,28 @@ public class CommandInitializer { .executableCommand(GetIpCommand.class) .register(); + // Register totp command + CommandDescription.builder() + .parent(authmeBase) + .labels("totp", "2fa") + .description("See if a player has enabled TOTP") + .detailedDescription("Returns whether the specified player has enabled two-factor authentication.") + .withArgument("player", "Player name", MANDATORY) + .permission(AdminPermission.VIEW_TOTP_STATUS) + .executableCommand(TotpViewStatusCommand.class) + .register(); + + // Register disable totp command + CommandDescription.builder() + .parent(authmeBase) + .labels("disabletotp", "disable2fa", "deletetotp", "delete2fa") + .description("Delete TOTP token of a player") + .detailedDescription("Disable two-factor authentication for a player.") + .withArgument("player", "Player name", MANDATORY) + .permission(AdminPermission.DISABLE_TOTP) + .executableCommand(TotpDisableAdminCommand.class) + .register(); + // Register the spawn command CommandDescription.builder() .parent(authmeBase) diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java new file mode 100644 index 000000000..5c9b30f42 --- /dev/null +++ b/src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java @@ -0,0 +1,58 @@ +package fr.xephi.authme.command.executable.authme; + +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.command.ExecutableCommand; +import fr.xephi.authme.data.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.message.MessageKey; +import fr.xephi.authme.message.Messages; +import fr.xephi.authme.service.BukkitService; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import javax.inject.Inject; +import java.util.List; + +/** + * Command to disable two-factor authentication for a user. + */ +public class TotpDisableAdminCommand implements ExecutableCommand { + + @Inject + private DataSource dataSource; + + @Inject + private Messages messages; + + @Inject + private BukkitService bukkitService; + + @Override + public void executeCommand(CommandSender sender, List arguments) { + String player = arguments.get(0); + + PlayerAuth auth = dataSource.getAuth(player); + if (auth == null) { + messages.send(sender, MessageKey.UNKNOWN_USER); + } else if (auth.getTotpKey() == null) { + sender.sendMessage(ChatColor.RED + "Player '" + player + "' does not have two-factor auth enabled"); + } else { + removeTotpKey(sender, player); + } + } + + private void removeTotpKey(CommandSender sender, String player) { + if (dataSource.removeTotpKey(player)) { + sender.sendMessage("Disabled two-factor authentication successfully for '" + player + "'"); + ConsoleLogger.info(sender.getName() + " disable two-factor authentication for '" + player + "'"); + + Player onlinePlayer = bukkitService.getPlayerExact(player); + if (onlinePlayer != null) { + messages.send(onlinePlayer, MessageKey.TWO_FACTOR_REMOVED_SUCCESS); + } + } else { + messages.send(sender, MessageKey.ERROR); + } + } +} diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommand.java new file mode 100644 index 000000000..d9b2c92c9 --- /dev/null +++ b/src/main/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommand.java @@ -0,0 +1,38 @@ +package fr.xephi.authme.command.executable.authme; + +import fr.xephi.authme.command.ExecutableCommand; +import fr.xephi.authme.data.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.message.MessageKey; +import fr.xephi.authme.message.Messages; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import javax.inject.Inject; +import java.util.List; + +/** + * Command to see whether a user has enabled two-factor authentication. + */ +public class TotpViewStatusCommand implements ExecutableCommand { + + @Inject + private DataSource dataSource; + + @Inject + private Messages messages; + + @Override + public void executeCommand(CommandSender sender, List arguments) { + String player = arguments.get(0); + + PlayerAuth auth = dataSource.getAuth(player); + if (auth == null) { + messages.send(sender, MessageKey.UNKNOWN_USER); + } else if (auth.getTotpKey() == null) { + sender.sendMessage(ChatColor.RED + "Player '" + player + "' does NOT have two-factor auth enabled"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Player '" + player + "' has enabled two-factor authentication"); + } + } +} diff --git a/src/main/java/fr/xephi/authme/permission/AdminPermission.java b/src/main/java/fr/xephi/authme/permission/AdminPermission.java index 7664e1436..20e27f2fc 100644 --- a/src/main/java/fr/xephi/authme/permission/AdminPermission.java +++ b/src/main/java/fr/xephi/authme/permission/AdminPermission.java @@ -45,6 +45,16 @@ public enum AdminPermission implements PermissionNode { */ CHANGE_EMAIL("authme.admin.changemail"), + /** + * Administrator command to see whether a player has enabled two-factor authentication. + */ + VIEW_TOTP_STATUS("authme.admin.totpviewstatus"), + + /** + * Administrator command to disable the two-factor auth of a user. + */ + DISABLE_TOTP("authme.admin.totpdisable"), + /** * Administrator command to get the last known IP of a user. */ diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 027da3dc0..aa267deac 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -18,7 +18,7 @@ softdepend: commands: authme: description: AuthMe op commands - usage: /authme register|unregister|forcelogin|password|lastlogin|accounts|email|setemail|getip|spawn|setspawn|firstspawn|setfirstspawn|purge|purgeplayer|backup|resetpos|purgebannedplayers|switchantibot|reload|version|converter|messages|recent|debug + usage: /authme register|unregister|forcelogin|password|lastlogin|accounts|email|setemail|getip|totp|disabletotp|spawn|setspawn|firstspawn|setfirstspawn|purge|purgeplayer|backup|resetpos|purgebannedplayers|switchantibot|reload|version|converter|messages|recent|debug email: description: Add email or recover password usage: /email show|add|change|recover|code|setpassword @@ -85,6 +85,8 @@ permissions: authme.admin.setspawn: true authme.admin.spawn: true authme.admin.switchantibot: true + authme.admin.totpdisable: true + authme.admin.totpviewstatus: true authme.admin.unregister: true authme.admin.updatemessages: true authme.admin.accounts: @@ -156,6 +158,13 @@ permissions: authme.admin.switchantibot: description: Administrator command to toggle the AntiBot protection status. default: op + authme.admin.totpdisable: + description: Administrator command to disable the two-factor auth of a user. + default: op + authme.admin.totpviewstatus: + description: Administrator command to see whether a player has enabled two-factor + authentication. + default: op authme.admin.unregister: description: Administrator command to unregister an existing user. default: op diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java new file mode 100644 index 000000000..e6728d894 --- /dev/null +++ b/src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java @@ -0,0 +1,120 @@ +package fr.xephi.authme.command.executable.authme; + +import fr.xephi.authme.TestHelper; +import fr.xephi.authme.data.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.message.MessageKey; +import fr.xephi.authme.message.Messages; +import fr.xephi.authme.service.BukkitService; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Collections; + +import static org.hamcrest.Matchers.containsString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; +import static org.mockito.Mockito.verify; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + +/** + * Test for {@link TotpDisableAdminCommand}. + */ +@RunWith(MockitoJUnitRunner.class) +public class TotpDisableAdminCommandTest { + + @InjectMocks + private TotpDisableAdminCommand command; + + @Mock + private DataSource dataSource; + + @Mock + private Messages messages; + + @Mock + private BukkitService bukkitService; + + @BeforeClass + public static void initLogger() { + TestHelper.setupLogger(); + } + + @Test + public void shouldHandleUnknownUser() { + // given + CommandSender sender = mock(CommandSender.class); + given(dataSource.getAuth("user")).willReturn(null); + + // when + command.executeCommand(sender, Collections.singletonList("user")); + + // then + verify(messages).send(sender, MessageKey.UNKNOWN_USER); + verify(dataSource, only()).getAuth("user"); + } + + @Test + public void shouldHandleUserWithNoTotpEnabled() { + // given + CommandSender sender = mock(CommandSender.class); + PlayerAuth auth = PlayerAuth.builder() + .name("billy") + .totpKey(null) + .build(); + given(dataSource.getAuth("Billy")).willReturn(auth); + + // when + command.executeCommand(sender, Collections.singletonList("Billy")); + + // then + verify(sender).sendMessage(argThat(containsString("'Billy' does not have two-factor auth enabled"))); + verify(dataSource, only()).getAuth("Billy"); + } + + @Test + public void shouldRemoveTotpFromUser() { + // given + CommandSender sender = mock(CommandSender.class); + PlayerAuth auth = PlayerAuth.builder() + .name("Bobby") + .totpKey("56484998") + .build(); + given(dataSource.getAuth("Bobby")).willReturn(auth); + given(dataSource.removeTotpKey("Bobby")).willReturn(true); + Player player = mock(Player.class); + given(bukkitService.getPlayerExact("Bobby")).willReturn(player); + + // when + command.executeCommand(sender, Collections.singletonList("Bobby")); + + // then + verify(sender).sendMessage(argThat(containsString("Disabled two-factor authentication successfully"))); + verify(messages).send(player, MessageKey.TWO_FACTOR_REMOVED_SUCCESS); + } + + @Test + public void shouldHandleErrorWhileRemovingTotp() { + // given + CommandSender sender = mock(CommandSender.class); + PlayerAuth auth = PlayerAuth.builder() + .name("Bobby") + .totpKey("321654") + .build(); + given(dataSource.getAuth("Bobby")).willReturn(auth); + given(dataSource.removeTotpKey("Bobby")).willReturn(false); + + // when + command.executeCommand(sender, Collections.singletonList("Bobby")); + + // then + verify(messages).send(sender, MessageKey.ERROR); + } +} diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java new file mode 100644 index 000000000..ba6560306 --- /dev/null +++ b/src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java @@ -0,0 +1,92 @@ +package fr.xephi.authme.command.executable.authme; + +import fr.xephi.authme.TestHelper; +import fr.xephi.authme.data.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.message.MessageKey; +import fr.xephi.authme.message.Messages; +import org.bukkit.command.CommandSender; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Collections; + +import static org.hamcrest.Matchers.containsString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; +import static org.mockito.Mockito.verify; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + +/** + * Test for {@link TotpViewStatusCommand}. + */ +@RunWith(MockitoJUnitRunner.class) +public class TotpViewStatusCommandTest { + + @InjectMocks + private TotpViewStatusCommand command; + + @Mock + private DataSource dataSource; + + @Mock + private Messages messages; + + @BeforeClass + public static void initLogger() { + TestHelper.setupLogger(); + } + + @Test + public void shouldHandleUnknownUser() { + // given + CommandSender sender = mock(CommandSender.class); + given(dataSource.getAuth("user")).willReturn(null); + + // when + command.executeCommand(sender, Collections.singletonList("user")); + + // then + verify(messages).send(sender, MessageKey.UNKNOWN_USER); + verify(dataSource, only()).getAuth("user"); + } + + @Test + public void shouldInformForUserWithoutTotp() { + // given + CommandSender sender = mock(CommandSender.class); + PlayerAuth auth = PlayerAuth.builder() + .name("billy") + .totpKey(null) + .build(); + given(dataSource.getAuth("Billy")).willReturn(auth); + + // when + command.executeCommand(sender, Collections.singletonList("Billy")); + + // then + verify(sender).sendMessage(argThat(containsString("'Billy' does NOT have two-factor auth enabled"))); + } + + @Test + public void shouldInformForUserWithTotpEnabled() { + // given + CommandSender sender = mock(CommandSender.class); + PlayerAuth auth = PlayerAuth.builder() + .name("billy") + .totpKey("92841575") + .build(); + given(dataSource.getAuth("Billy")).willReturn(auth); + + // when + command.executeCommand(sender, Collections.singletonList("Billy")); + + // then + verify(sender).sendMessage(argThat(containsString("'Billy' has enabled two-factor authentication"))); + } +} From ae68667f5e98493db0abea91ca56ef3468e48b18 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Tue, 6 Aug 2019 01:12:01 +0200 Subject: [PATCH 76/83] Add Maven profile to skip Javadoc generation for local builds (#1878) * #1877 Add Maven profile to skip Javadoc generation for local builds * Make it nicer --- pom.xml | 26 ++++++++++++++++++- .../java/tools/bathelpers/analyze_project.bat | 6 ----- .../java/tools/bathelpers/quick_build.bat | 2 +- .../java/tools/shhelpers/analyze_project.sh | 11 -------- src/test/java/tools/shhelpers/quick_build.sh | 2 +- 5 files changed, 27 insertions(+), 20 deletions(-) delete mode 100644 src/test/java/tools/bathelpers/analyze_project.bat delete mode 100644 src/test/java/tools/shhelpers/analyze_project.sh diff --git a/pom.xml b/pom.xml index be13db624..b378bf874 100644 --- a/pom.xml +++ b/pom.xml @@ -105,6 +105,21 @@ true + + + skipJavadocGeneration + + + + org.apache.maven.plugins + maven-javadoc-plugin + + true + + + + + @@ -131,6 +146,16 @@ + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + + + @@ -222,7 +247,6 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.1.1 ${project.finalNameBase} diff --git a/src/test/java/tools/bathelpers/analyze_project.bat b/src/test/java/tools/bathelpers/analyze_project.bat deleted file mode 100644 index ec494c75c..000000000 --- a/src/test/java/tools/bathelpers/analyze_project.bat +++ /dev/null @@ -1,6 +0,0 @@ -: Analyze the project with Sonar (requires you install SonarQube) -if "%jarfile%" == "" ( - call setvars.bat -) - -mvn clean verify sonar:sonar -f "%pomfile%" \ No newline at end of file diff --git a/src/test/java/tools/bathelpers/quick_build.bat b/src/test/java/tools/bathelpers/quick_build.bat index 543b53b04..a3624fcd7 100644 --- a/src/test/java/tools/bathelpers/quick_build.bat +++ b/src/test/java/tools/bathelpers/quick_build.bat @@ -3,4 +3,4 @@ if "%jarfile%" == "" ( call setvars.bat ) -mvn install -o -f "%pomfile%" -Dmaven.test.skip +mvn install -o -f "%pomfile%" -Dmaven.test.skip -PskipJavadocGeneration diff --git a/src/test/java/tools/shhelpers/analyze_project.sh b/src/test/java/tools/shhelpers/analyze_project.sh deleted file mode 100644 index ef817fca6..000000000 --- a/src/test/java/tools/shhelpers/analyze_project.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh -# -# Usage: ./analyze_project.sh -# - -if [ -z $jarfile ]; - then - ./setvars.sh -fi - -mvn clean verify sonar:sonar -f $pomfile diff --git a/src/test/java/tools/shhelpers/quick_build.sh b/src/test/java/tools/shhelpers/quick_build.sh index 3ec108a23..b882bde68 100644 --- a/src/test/java/tools/shhelpers/quick_build.sh +++ b/src/test/java/tools/shhelpers/quick_build.sh @@ -8,4 +8,4 @@ if [ -z $jarfile ]; ./setvars.sh fi -mvn install -f $pomfile -Dmaven.test.skip +mvn install -f $pomfile -Dmaven.test.skip -PskipJavadocGeneration From 254d4d75a28c68b267f022f310c52986556329d9 Mon Sep 17 00:00:00 2001 From: Alexandre Vanhecke Date: Tue, 6 Aug 2019 15:13:13 +0200 Subject: [PATCH 77/83] Add optional column for players uuids (#1840) --- .../fr/xephi/authme/data/auth/PlayerAuth.java | 20 +++++++++++++- .../datasource/AbstractSqlDataSource.java | 3 ++- .../fr/xephi/authme/datasource/Columns.java | 2 ++ .../fr/xephi/authme/datasource/MySQL.java | 10 +++++++ .../datasource/PostgreSqlDataSource.java | 5 ++++ .../fr/xephi/authme/datasource/SQLite.java | 5 ++++ .../columnshandler/AuthMeColumns.java | 8 +++++- .../converter/LoginSecurityConverter.java | 4 +++ .../executors/PlayerAuthBuilderHelper.java | 1 + .../settings/properties/DatabaseSettings.java | 4 +++ .../java/fr/xephi/authme/util/UuidUtils.java | 27 +++++++++++++++++++ 11 files changed, 86 insertions(+), 3 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/util/UuidUtils.java diff --git a/src/main/java/fr/xephi/authme/data/auth/PlayerAuth.java b/src/main/java/fr/xephi/authme/data/auth/PlayerAuth.java index 32bdc01b0..4aebd88db 100644 --- a/src/main/java/fr/xephi/authme/data/auth/PlayerAuth.java +++ b/src/main/java/fr/xephi/authme/data/auth/PlayerAuth.java @@ -5,6 +5,7 @@ import org.bukkit.Location; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import static com.google.common.base.Preconditions.checkNotNull; @@ -40,6 +41,7 @@ public class PlayerAuth { private String world; private float yaw; private float pitch; + private UUID uuid; /** * Hidden constructor. @@ -169,6 +171,14 @@ public class PlayerAuth { this.totpKey = totpKey; } + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + @Override public boolean equals(Object obj) { if (!(obj instanceof PlayerAuth)) { @@ -193,7 +203,8 @@ public class PlayerAuth { + " ! LastLogin : " + lastLogin + " ! LastPosition : " + x + "," + y + "," + z + "," + world + " ! Email : " + email - + " ! Password : {" + password.getHash() + ", " + password.getSalt() + "}"; + + " ! Password : {" + password.getHash() + ", " + password.getSalt() + "}" + + " ! UUID : " + uuid; } public static Builder builder() { @@ -218,6 +229,7 @@ public class PlayerAuth { private String world; private float yaw; private float pitch; + private UUID uuid; /** * Creates a PlayerAuth object. @@ -243,6 +255,7 @@ public class PlayerAuth { auth.world = Optional.ofNullable(world).orElse("world"); auth.yaw = yaw; auth.pitch = pitch; + auth.uuid = uuid; return auth; } @@ -349,5 +362,10 @@ public class PlayerAuth { this.registrationDate = date; return this; } + + public Builder uuid(UUID uuid) { + this.uuid = uuid; + return this; + } } } diff --git a/src/main/java/fr/xephi/authme/datasource/AbstractSqlDataSource.java b/src/main/java/fr/xephi/authme/datasource/AbstractSqlDataSource.java index 0c40c479d..067851684 100644 --- a/src/main/java/fr/xephi/authme/datasource/AbstractSqlDataSource.java +++ b/src/main/java/fr/xephi/authme/datasource/AbstractSqlDataSource.java @@ -53,7 +53,8 @@ public abstract class AbstractSqlDataSource implements DataSource { public boolean saveAuth(PlayerAuth auth) { return columnsHandler.insert(auth, AuthMeColumns.NAME, AuthMeColumns.NICK_NAME, AuthMeColumns.PASSWORD, AuthMeColumns.SALT, - AuthMeColumns.EMAIL, AuthMeColumns.REGISTRATION_DATE, AuthMeColumns.REGISTRATION_IP); + AuthMeColumns.EMAIL, AuthMeColumns.REGISTRATION_DATE, AuthMeColumns.REGISTRATION_IP, + AuthMeColumns.UUID); } @Override diff --git a/src/main/java/fr/xephi/authme/datasource/Columns.java b/src/main/java/fr/xephi/authme/datasource/Columns.java index 0d372a239..a604d0a4d 100644 --- a/src/main/java/fr/xephi/authme/datasource/Columns.java +++ b/src/main/java/fr/xephi/authme/datasource/Columns.java @@ -30,6 +30,7 @@ public final class Columns { public final String HAS_SESSION; public final String REGISTRATION_DATE; public final String REGISTRATION_IP; + public final String PLAYER_UUID; public Columns(Settings settings) { NAME = settings.getProperty(DatabaseSettings.MYSQL_COL_NAME); @@ -52,6 +53,7 @@ public final class Columns { HAS_SESSION = settings.getProperty(DatabaseSettings.MYSQL_COL_HASSESSION); REGISTRATION_DATE = settings.getProperty(DatabaseSettings.MYSQL_COL_REGISTER_DATE); REGISTRATION_IP = settings.getProperty(DatabaseSettings.MYSQL_COL_REGISTER_IP); + PLAYER_UUID = settings.getProperty(DatabaseSettings.MYSQL_COL_PLAYER_UUID); } } diff --git a/src/main/java/fr/xephi/authme/datasource/MySQL.java b/src/main/java/fr/xephi/authme/datasource/MySQL.java index badeea140..570a23ce8 100644 --- a/src/main/java/fr/xephi/authme/datasource/MySQL.java +++ b/src/main/java/fr/xephi/authme/datasource/MySQL.java @@ -11,6 +11,7 @@ import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.HooksSettings; +import fr.xephi.authme.util.UuidUtils; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -23,6 +24,7 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.UUID; import static fr.xephi.authme.datasource.SqlDataSourceUtils.getNullableLong; import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException; @@ -264,6 +266,11 @@ public class MySQL extends AbstractSqlDataSource { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);"); } + + if (!col.PLAYER_UUID.isEmpty() && isColumnMissing(md, col.PLAYER_UUID)) { + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)"); + } } ConsoleLogger.info("MySQL setup finished"); } @@ -454,6 +461,8 @@ public class MySQL extends AbstractSqlDataSource { private PlayerAuth buildAuthFromResultSet(ResultSet row) throws SQLException { String salt = col.SALT.isEmpty() ? null : row.getString(col.SALT); int group = col.GROUP.isEmpty() ? -1 : row.getInt(col.GROUP); + UUID uuid = col.PLAYER_UUID.isEmpty() + ? null : UuidUtils.parseUuidSafely(row.getString(col.PLAYER_UUID)); return PlayerAuth.builder() .name(row.getString(col.NAME)) .realName(row.getString(col.REAL_NAME)) @@ -471,6 +480,7 @@ public class MySQL extends AbstractSqlDataSource { .locZ(row.getDouble(col.LASTLOC_Z)) .locYaw(row.getFloat(col.LASTLOC_YAW)) .locPitch(row.getFloat(col.LASTLOC_PITCH)) + .uuid(uuid) .build(); } } diff --git a/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java b/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java index eaf869b8a..62c26b648 100644 --- a/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java +++ b/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java @@ -241,6 +241,11 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);"); } + + if (!col.PLAYER_UUID.isEmpty() && isColumnMissing(md, col.PLAYER_UUID)) { + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)"); + } } ConsoleLogger.info("PostgreSQL setup finished"); } diff --git a/src/main/java/fr/xephi/authme/datasource/SQLite.java b/src/main/java/fr/xephi/authme/datasource/SQLite.java index fe7260ec6..b1b796e42 100644 --- a/src/main/java/fr/xephi/authme/datasource/SQLite.java +++ b/src/main/java/fr/xephi/authme/datasource/SQLite.java @@ -182,6 +182,11 @@ public class SQLite extends AbstractSqlDataSource { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);"); } + + if (!col.PLAYER_UUID.isEmpty() && isColumnMissing(md, col.PLAYER_UUID)) { + st.executeUpdate("ALTER TABLE " + tableName + + " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)"); + } } ConsoleLogger.info("SQLite Setup finished"); } diff --git a/src/main/java/fr/xephi/authme/datasource/columnshandler/AuthMeColumns.java b/src/main/java/fr/xephi/authme/datasource/columnshandler/AuthMeColumns.java index 5c235095f..7c4d2e6a7 100644 --- a/src/main/java/fr/xephi/authme/datasource/columnshandler/AuthMeColumns.java +++ b/src/main/java/fr/xephi/authme/datasource/columnshandler/AuthMeColumns.java @@ -3,6 +3,8 @@ package fr.xephi.authme.datasource.columnshandler; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.settings.properties.DatabaseSettings; +import java.util.UUID; + import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.DEFAULT_FOR_NULL; import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.OPTIONAL; import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.createDouble; @@ -46,6 +48,11 @@ public final class AuthMeColumns { public static final PlayerAuthColumn REGISTRATION_DATE = createLong( DatabaseSettings.MYSQL_COL_REGISTER_DATE, PlayerAuth::getRegistrationDate); + public static final PlayerAuthColumn UUID = createString( + DatabaseSettings.MYSQL_COL_PLAYER_UUID, + auth -> ( auth.getUuid() == null ? null : auth.getUuid().toString()), + OPTIONAL); + // -------- // Location columns // -------- @@ -76,7 +83,6 @@ public final class AuthMeColumns { public static final DataSourceColumn HAS_SESSION = createInteger( DatabaseSettings.MYSQL_COL_HASSESSION); - private AuthMeColumns() { } } diff --git a/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java index 4fd5fb34c..d13f373cf 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java @@ -7,6 +7,7 @@ import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ConverterSettings; +import fr.xephi.authme.util.UuidUtils; import org.bukkit.command.CommandSender; import javax.inject.Inject; @@ -21,6 +22,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; +import java.util.UUID; import static fr.xephi.authme.util.Utils.logAndSendMessage; @@ -119,6 +121,7 @@ public class LoginSecurityConverter implements Converter { .map(Timestamp::getTime).orElse(null); long regDate = Optional.ofNullable(resultSet.getDate("registration_date")) .map(Date::getTime).orElse(System.currentTimeMillis()); + UUID uuid = UuidUtils.parseUuidSafely(resultSet.getString("unique_user_id")); return PlayerAuth.builder() .name(name) .realName(name) @@ -132,6 +135,7 @@ public class LoginSecurityConverter implements Converter { .locWorld(resultSet.getString("world")) .locYaw(resultSet.getFloat("yaw")) .locPitch(resultSet.getFloat("pitch")) + .uuid(uuid) .build(); } diff --git a/src/main/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelper.java b/src/main/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelper.java index d8c6a5fcc..a9717fdce 100644 --- a/src/main/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelper.java +++ b/src/main/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelper.java @@ -29,6 +29,7 @@ final class PlayerAuthBuilderHelper { .email(email) .registrationIp(PlayerUtils.getPlayerIp(player)) .registrationDate(System.currentTimeMillis()) + .uuid(player.getUniqueId()) .build(); } } diff --git a/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java b/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java index 83ed18e7a..358d612f4 100644 --- a/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java +++ b/src/main/java/fr/xephi/authme/settings/properties/DatabaseSettings.java @@ -129,6 +129,10 @@ public final class DatabaseSettings implements SettingsHolder { public static final Property MYSQL_COL_LASTLOC_PITCH = newProperty("DataSource.mySQLlastlocPitch", "pitch"); + @Comment("Column for storing players uuids (optional)") + public static final Property MYSQL_COL_PLAYER_UUID = + newProperty( "DataSource.mySQLPlayerUUID", "" ); + @Comment("Column for storing players groups") public static final Property MYSQL_COL_GROUP = newProperty("ExternalBoardOptions.mySQLColumnGroup", ""); diff --git a/src/main/java/fr/xephi/authme/util/UuidUtils.java b/src/main/java/fr/xephi/authme/util/UuidUtils.java new file mode 100644 index 000000000..4a2306af6 --- /dev/null +++ b/src/main/java/fr/xephi/authme/util/UuidUtils.java @@ -0,0 +1,27 @@ +package fr.xephi.authme.util; + +import java.util.UUID; + +/** + * Utility class for various operations on UUID. + */ +public final class UuidUtils { + + // Utility class + private UuidUtils() { + } + + /** + * Returns whether the given string as an UUID or null + * + * @param string the uuid to parse + * @return parsed UUID if succeed or null + */ + public static UUID parseUuidSafely(String string) { + try { + return UUID.fromString(string); + } catch (IllegalArgumentException | NullPointerException ex) { + return null; + } + } +} From c34f00f75923f3176e968cf7c37f9d505abdc222 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Tue, 6 Aug 2019 15:15:16 +0200 Subject: [PATCH 78/83] #1874 Introduce individual ConsoleLogger instance per class (#1875) * #1874 Introduce individual ConsoleLogger instance per class - Create ConsoleLoggerFactory from which a separate logger can be created for each class - Allows to support individual log level settings in the future * Fix CodeStyle issue * Replace full class name with import * Update usages after merge from master --- src/main/java/fr/xephi/authme/AuthMe.java | 32 ++-- .../java/fr/xephi/authme/ConsoleLogger.java | 140 +++++++++++------- .../executable/authme/ConverterCommand.java | 5 +- .../authme/RegisterAdminCommand.java | 5 +- .../executable/authme/ReloadCommand.java | 7 +- .../authme/TotpDisableAdminCommand.java | 5 +- .../authme/UpdateHelpMessagesCommand.java | 5 +- .../authme/debug/DebugSectionUtils.java | 8 +- .../authme/debug/MySqlDefaultChanger.java | 13 +- .../authme/debug/TestEmailSender.java | 5 +- .../email/EmailSetPasswordCommand.java | 5 +- .../executable/email/RecoverEmailCommand.java | 5 +- .../executable/register/RegisterCommand.java | 5 +- .../executable/totp/ConfirmTotpCommand.java | 5 +- .../executable/totp/RemoveTotpCommand.java | 5 +- .../executable/totp/TotpCodeCommand.java | 9 +- .../verification/VerificationCommand.java | 5 +- .../authme/data/limbo/AuthGroupHandler.java | 7 +- .../xephi/authme/data/limbo/LimboService.java | 13 +- .../authme/data/limbo/LimboServiceHelper.java | 10 +- .../data/limbo/WalkFlySpeedRestoreType.java | 23 +-- .../DistributedFilesPersistenceHandler.java | 14 +- .../IndividualFilesPersistenceHandler.java | 9 +- .../limbo/persistence/LimboPersistence.java | 11 +- .../authme/datasource/CacheDataSource.java | 5 +- .../fr/xephi/authme/datasource/MySQL.java | 22 +-- .../authme/datasource/MySqlMigrater.java | 13 +- .../datasource/PostgreSqlDataSource.java | 23 +-- .../fr/xephi/authme/datasource/SQLite.java | 12 +- .../authme/datasource/SqLiteMigrater.java | 10 +- .../authme/datasource/SqlDataSourceUtils.java | 7 +- .../AbstractDataSourceConverter.java | 19 +-- .../converter/CrazyLoginConverter.java | 9 +- .../converter/LoginSecurityConverter.java | 8 +- .../converter/RakamakConverter.java | 4 +- .../converter/RoyalAuthConverter.java | 6 +- .../datasource/converter/VAuthConverter.java | 4 +- .../initialization/DataSourceProvider.java | 15 +- .../authme/initialization/OnStartupTasks.java | 10 +- .../xephi/authme/listener/EntityListener.java | 8 +- .../xephi/authme/listener/OnJoinVerifier.java | 5 +- .../xephi/authme/listener/PlayerListener.java | 5 +- .../xephi/authme/listener/ServerListener.java | 14 +- .../protocollib/InventoryPacketAdapter.java | 5 +- .../protocollib/ProtocolLibService.java | 15 +- .../protocollib/TabCompletePacketAdapter.java | 4 +- .../fr/xephi/authme/mail/EmailService.java | 15 +- .../fr/xephi/authme/mail/SendMailSsl.java | 7 +- .../message/AbstractMessageFileHandler.java | 6 +- .../message/HelpMessagesFileHandler.java | 5 +- .../fr/xephi/authme/message/Messages.java | 8 +- .../authme/message/MessagesFileHandler.java | 5 +- .../message/updater/JarMessageSource.java | 8 +- .../message/updater/MessageUpdater.java | 9 +- .../authme/output/ConsoleLoggerFactory.java | 51 +++++++ .../authme/permission/PermissionsManager.java | 22 +-- .../permission/handlers/LuckPermsHandler.java | 12 +- .../changepassword/AsyncChangePassword.java | 13 +- .../authme/process/email/AsyncAddEmail.java | 7 +- .../process/email/AsyncChangeEmail.java | 5 +- .../authme/process/join/AsynchronousJoin.java | 5 +- .../process/login/AsynchronousLogin.java | 13 +- .../logout/ProcessSyncPlayerLogout.java | 5 +- .../register/ProcessSyncEmailRegister.java | 5 +- .../register/ProcessSyncPasswordRegister.java | 5 +- .../unregister/AsynchronousUnregister.java | 9 +- .../xephi/authme/security/crypts/Argon2.java | 5 +- .../xephi/authme/security/crypts/Pbkdf2.java | 4 +- .../authme/security/crypts/Pbkdf2Django.java | 4 +- .../authme/security/crypts/TwoFactor.java | 5 +- .../fr/xephi/authme/security/crypts/Wbb4.java | 4 +- .../xephi/authme/service/BackupService.java | 19 ++- .../fr/xephi/authme/service/GeoIpService.java | 18 ++- .../authme/service/MigrationService.java | 11 +- .../service/PasswordRecoveryService.java | 5 +- .../authme/service/PluginHookService.java | 6 +- .../xephi/authme/service/SessionService.java | 4 +- .../authme/service/TeleportationService.java | 15 +- .../authme/service/ValidationService.java | 7 +- .../service/bungeecord/BungeeReceiver.java | 14 +- .../service/bungeecord/BungeeSender.java | 4 +- .../fr/xephi/authme/settings/Settings.java | 6 +- .../settings/SettingsMigrationService.java | 22 +-- .../xephi/authme/settings/SettingsWarner.java | 13 +- .../fr/xephi/authme/settings/SpawnLoader.java | 13 +- .../settings/WelcomeMessageConfiguration.java | 7 +- .../authme/task/purge/PurgeExecutor.java | 19 ++- .../xephi/authme/task/purge/PurgeService.java | 7 +- .../fr/xephi/authme/task/purge/PurgeTask.java | 8 +- .../java/fr/xephi/authme/util/FileUtils.java | 13 +- src/main/java/fr/xephi/authme/util/Utils.java | 11 +- .../fr/xephi/authme/ConsoleLoggerTest.java | 87 ++++++++--- src/test/java/fr/xephi/authme/TestHelper.java | 4 +- .../executable/authme/ReloadCommandTest.java | 3 +- .../data/limbo/LimboServiceHelperTest.java | 7 + .../message/MessagesIntegrationTest.java | 10 +- .../output/ConsoleLoggerFactoryTest.java | 94 ++++++++++++ .../EncryptionMethodInfoGatherer.java | 2 +- 98 files changed, 853 insertions(+), 387 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/output/ConsoleLoggerFactory.java create mode 100644 src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index d07b426b8..9d1e9dfb4 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -12,6 +12,7 @@ import fr.xephi.authme.initialization.OnShutdownPlayerSaver; import fr.xephi.authme.initialization.OnStartupTasks; import fr.xephi.authme.initialization.SettingsProvider; import fr.xephi.authme.initialization.TaskCloser; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.listener.BlockListener; import fr.xephi.authme.listener.EntityListener; import fr.xephi.authme.listener.PlayerListener; @@ -56,7 +57,7 @@ public class AuthMe extends JavaPlugin { private static final String LOG_FILENAME = "authme.log"; private static final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE; - // Default version and build number values + // Version and build number values private static String pluginVersion = "N/D"; private static String pluginBuildNumber = "Unknown"; @@ -67,6 +68,7 @@ public class AuthMe extends JavaPlugin { private BukkitService bukkitService; private Injector injector; private BackupService backupService; + private ConsoleLogger logger; /** * Constructor. @@ -78,8 +80,7 @@ public class AuthMe extends JavaPlugin { * Constructor for unit testing. */ @VisibleForTesting - @SuppressWarnings("deprecation") // the super constructor is deprecated to mark it for unit testing only - protected AuthMe(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { + AuthMe(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { super(loader, description, dataFolder, file); } @@ -120,14 +121,14 @@ public class AuthMe extends JavaPlugin { // Check server version if (!isClassLoaded("org.bukkit.event.player.PlayerInteractAtEntityEvent")) { - ConsoleLogger.warning("You are running an unsupported server version! AuthMe requires MC 1.8.X or later!"); + getLogger().warning("You are running an unsupported server version! AuthMe requires MC 1.8.X or later!"); stopOrUnload(); return; } // Prevent running AuthMeBridge due to major exploit issues if (getServer().getPluginManager().isPluginEnabled("AuthMeBridge")) { - ConsoleLogger.warning("Detected AuthMeBridge, support for it has been dropped as it was " + getLogger().warning("Detected AuthMeBridge, support for it has been dropped as it was " + "causing exploit issues, please use AuthMeBungee instead! Aborting!"); stopOrUnload(); return; @@ -139,10 +140,10 @@ public class AuthMe extends JavaPlugin { } catch (Throwable th) { YamlParseException yamlParseException = ExceptionUtils.findThrowableInCause(YamlParseException.class, th); if (yamlParseException == null) { - ConsoleLogger.logException("Aborting initialization of AuthMe:", th); + logger.logException("Aborting initialization of AuthMe:", th); th.printStackTrace(); } else { - ConsoleLogger.logException("File '" + yamlParseException.getFile() + "' contains invalid YAML. " + logger.logException("File '" + yamlParseException.getFile() + "' contains invalid YAML. " + "Please run its contents through http://yamllint.com", yamlParseException); } stopOrUnload(); @@ -159,8 +160,7 @@ public class AuthMe extends JavaPlugin { OnStartupTasks.sendMetrics(this, settings); // Successful message - ConsoleLogger.info("AuthMe " + getPluginVersion() + " build n." + getPluginBuildNumber() - + " correctly enabled!"); + logger.info("AuthMe " + getPluginVersion() + " build n." + getPluginBuildNumber() + " successfully enabled!"); // Purge on start if enabled PurgeService purgeService = injector.getSingleton(PurgeService.class); @@ -192,8 +192,7 @@ public class AuthMe extends JavaPlugin { */ private void initialize() { // Set the Logger instance and log file path - ConsoleLogger.setLogger(getLogger()); - ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME)); + ConsoleLogger.initialize(getLogger(), new File(getDataFolder(), LOG_FILENAME)); // Check java version if (!SystemUtils.isJavaVersionAtLeast(1.8f)) { @@ -217,8 +216,9 @@ public class AuthMe extends JavaPlugin { // Get settings and set up logger settings = injector.getSingleton(Settings.class); - ConsoleLogger.setLoggingOptions(settings); - OnStartupTasks.setupConsoleFilter(settings, getLogger()); + ConsoleLoggerFactory.reloadSettings(settings); + logger = ConsoleLoggerFactory.get(AuthMe.class); + OnStartupTasks.setupConsoleFilter(getLogger()); // Set all service fields on the AuthMe class instantiateServices(injector); @@ -294,7 +294,7 @@ public class AuthMe extends JavaPlugin { */ public void stopOrUnload() { if (settings == null || settings.getProperty(SecuritySettings.STOP_SERVER_ON_PROBLEM)) { - ConsoleLogger.warning("THE SERVER IS GOING TO SHUT DOWN AS DEFINED IN THE CONFIGURATION!"); + getLogger().warning("THE SERVER IS GOING TO SHUT DOWN AS DEFINED IN THE CONFIGURATION!"); setEnabled(false); getServer().shutdown(); } else { @@ -321,8 +321,8 @@ public class AuthMe extends JavaPlugin { new TaskCloser(this, database).run(); // Disabled correctly - ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!"); - ConsoleLogger.close(); + logger.info("AuthMe " + this.getDescription().getVersion() + " disabled!"); + ConsoleLogger.closeFileWriter(); } /** diff --git a/src/main/java/fr/xephi/authme/ConsoleLogger.java b/src/main/java/fr/xephi/authme/ConsoleLogger.java index 3e8d59a4a..caa20ee43 100644 --- a/src/main/java/fr/xephi/authme/ConsoleLogger.java +++ b/src/main/java/fr/xephi/authme/ConsoleLogger.java @@ -1,15 +1,19 @@ package fr.xephi.authme; import com.google.common.base.Throwables; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.ExceptionUtils; +import java.io.Closeable; import java.io.File; -import java.io.FileWriter; +import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; @@ -20,64 +24,73 @@ import java.util.logging.Logger; import java.util.stream.Collectors; /** - * The plugin's static logger. + * AuthMe logger. */ public final class ConsoleLogger { private static final String NEW_LINE = System.getProperty("line.separator"); private static final DateFormat DATE_FORMAT = new SimpleDateFormat("[MM-dd HH:mm:ss]"); - private static Logger logger; - private static LogLevel logLevel = LogLevel.INFO; - private static boolean useLogging = false; - private static File logFile; - private static FileWriter fileWriter; - private ConsoleLogger() { + // Outside references + private static File logFile; + private static Logger logger; + + // Shared state + private static OutputStreamWriter fileWriter; + + // Individual state + private final String name; + private LogLevel logLevel = LogLevel.INFO; + + /** + * Constructor. + * + * @param name the name of this logger (the fully qualified class name using it) + */ + public ConsoleLogger(String name) { + this.name = name; } // -------- // Configurations // -------- - /** - * Set the logger to use. - * - * @param logger The logger - */ - public static void setLogger(Logger logger) { + public static void initialize(Logger logger, File logFile) { ConsoleLogger.logger = logger; - } - - /** - * Set the file to log to if enabled. - * - * @param logFile The log file - */ - public static void setLogFile(File logFile) { ConsoleLogger.logFile = logFile; } /** - * Load the required settings. + * Sets logging settings which are shared by all logger instances. * - * @param settings The settings instance + * @param settings the settings to read from */ - public static void setLoggingOptions(Settings settings) { - ConsoleLogger.logLevel = settings.getProperty(PluginSettings.LOG_LEVEL); - ConsoleLogger.useLogging = settings.getProperty(SecuritySettings.USE_LOGGING); + public static void initializeSharedSettings(Settings settings) { + boolean useLogging = settings.getProperty(SecuritySettings.USE_LOGGING); if (useLogging) { - if (fileWriter == null) { - try { - fileWriter = new FileWriter(logFile, true); - } catch (IOException e) { - ConsoleLogger.logException("Failed to create the log file:", e); - } - } + initializeFileWriter(); } else { - close(); + closeFileWriter(); } } + /** + * Sets logging settings which are individual to all loggers. + * + * @param settings the settings to read from + */ + public void initializeSettings(Settings settings) { + this.logLevel = settings.getProperty(PluginSettings.LOG_LEVEL); + } + + public LogLevel getLogLevel() { + return logLevel; + } + + public String getName() { + return name; + } + // -------- // Logging methods @@ -88,7 +101,7 @@ public final class ConsoleLogger { * * @param message The message to log */ - public static void warning(String message) { + public void warning(String message) { logger.warning(message); writeLog("[WARN] " + message); } @@ -100,7 +113,7 @@ public final class ConsoleLogger { * @param message The message to accompany the exception * @param th The Throwable to log */ - public static void logException(String message, Throwable th) { + public void logException(String message, Throwable th) { warning(message + " " + ExceptionUtils.formatException(th)); writeLog(Throwables.getStackTraceAsString(th)); } @@ -110,7 +123,7 @@ public final class ConsoleLogger { * * @param message The message to log */ - public static void info(String message) { + public void info(String message) { logger.info(message); writeLog("[INFO] " + message); } @@ -123,7 +136,7 @@ public final class ConsoleLogger { * * @param message The message to log */ - public static void fine(String message) { + public void fine(String message) { if (logLevel.includes(LogLevel.FINE)) { logger.info(message); writeLog("[FINE] " + message); @@ -142,7 +155,7 @@ public final class ConsoleLogger { * * @param message The message to log */ - public static void debug(String message) { + public void debug(String message) { if (logLevel.includes(LogLevel.DEBUG)) { String debugMessage = "[DEBUG] " + message; logger.info(debugMessage); @@ -155,7 +168,7 @@ public final class ConsoleLogger { * * @param msgSupplier the message supplier */ - public static void debug(Supplier msgSupplier) { + public void debug(Supplier msgSupplier) { if (logLevel.includes(LogLevel.DEBUG)) { String debugMessage = "[DEBUG] " + msgSupplier.get(); logger.info(debugMessage); @@ -169,7 +182,7 @@ public final class ConsoleLogger { * @param message the message * @param param1 parameter to replace in the message */ - public static void debug(String message, Object param1) { + public void debug(String message, Object param1) { if (logLevel.includes(LogLevel.DEBUG)) { String debugMessage = "[DEBUG] " + message; logger.log(Level.INFO, debugMessage, param1); @@ -185,7 +198,7 @@ public final class ConsoleLogger { * @param param2 second param to replace in message */ // Avoids array creation if DEBUG level is disabled - public static void debug(String message, Object param1, Object param2) { + public void debug(String message, Object param1, Object param2) { if (logLevel.includes(LogLevel.DEBUG)) { debug(message, new Object[]{param1, param2}); } @@ -197,7 +210,7 @@ public final class ConsoleLogger { * @param message the message * @param params the params to replace in the message */ - public static void debug(String message, Object... params) { + public void debug(String message, Object... params) { if (logLevel.includes(LogLevel.DEBUG)) { String debugMessage = "[DEBUG] " + message; logger.log(Level.INFO, debugMessage, params); @@ -206,21 +219,21 @@ public final class ConsoleLogger { } } - // -------- // Helpers // -------- /** - * Close all file handles. + * Closes the file writer. */ - public static void close() { + public static void closeFileWriter() { if (fileWriter != null) { try { fileWriter.flush(); - fileWriter.close(); - fileWriter = null; } catch (IOException ignored) { + } finally { + closeSilently(fileWriter); + fileWriter = null; } } } @@ -231,7 +244,7 @@ public final class ConsoleLogger { * @param message The message to write to the log */ private static void writeLog(String message) { - if (useLogging) { + if (fileWriter != null) { String dateTime; synchronized (DATE_FORMAT) { dateTime = DATE_FORMAT.format(new Date()); @@ -246,4 +259,31 @@ public final class ConsoleLogger { } } } + + private static void closeSilently(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException ignored) { + } + } + } + + /** + * Populates the {@link #fileWriter} field if it is null, handling any exceptions that might + * arise during its creation. + */ + private static void initializeFileWriter() { + if (fileWriter == null) { + FileOutputStream fos = null; + try { + fos = new FileOutputStream(logFile, true); + fileWriter = new OutputStreamWriter(fos, StandardCharsets.UTF_8); + } catch (Exception e) { + closeSilently(fos); + ConsoleLoggerFactory.get(ConsoleLogger.class) + .logException("Failed to create the log file:", e); + } + } + } } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java index 2973ba2d0..b95eda17d 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java @@ -14,6 +14,7 @@ import fr.xephi.authme.datasource.converter.RoyalAuthConverter; import fr.xephi.authme.datasource.converter.SqliteToSql; import fr.xephi.authme.datasource.converter.VAuthConverter; import fr.xephi.authme.datasource.converter.XAuthConverter; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; @@ -31,6 +32,8 @@ public class ConverterCommand implements ExecutableCommand { @VisibleForTesting static final Map> CONVERTERS = getConverters(); + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ConverterCommand.class); + @Inject private CommonService commonService; @@ -59,7 +62,7 @@ public class ConverterCommand implements ExecutableCommand { converter.execute(sender); } catch (Exception e) { commonService.send(sender, MessageKey.ERROR); - ConsoleLogger.logException("Error during conversion:", e); + logger.logException("Error during conversion:", e); } } }); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommand.java index e05089da8..ada52966a 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommand.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.crypts.HashedPassword; @@ -22,6 +23,8 @@ import java.util.List; */ public class RegisterAdminCommand implements ExecutableCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(RegisterAdminCommand.class); + @Inject private PasswordSecurity passwordSecurity; @@ -70,7 +73,7 @@ public class RegisterAdminCommand implements ExecutableCommand { } commonService.send(sender, MessageKey.REGISTER_SUCCESS); - ConsoleLogger.info(sender.getName() + " registered " + playerName); + logger.info(sender.getName() + " registered " + playerName); final Player player = bukkitService.getPlayerExact(playerName); if (player != null) { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(() -> diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java index 164b59132..84de195c5 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java @@ -7,6 +7,7 @@ import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.SettingsDependent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.settings.Settings; @@ -23,6 +24,8 @@ import java.util.List; */ public class ReloadCommand implements ExecutableCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ReloadCommand.class); + @Inject private AuthMe plugin; @@ -48,7 +51,7 @@ public class ReloadCommand implements ExecutableCommand { public void executeCommand(CommandSender sender, List arguments) { try { settings.reload(); - ConsoleLogger.setLoggingOptions(settings); + ConsoleLoggerFactory.reloadSettings(settings); settingsWarner.logWarningsForMisconfigurations(); // We do not change database type for consistency issues, but we'll output a note in the logs @@ -59,7 +62,7 @@ public class ReloadCommand implements ExecutableCommand { commonService.send(sender, MessageKey.CONFIG_RELOAD_SUCCESS); } catch (Exception e) { sender.sendMessage("Error occurred during reload of AuthMe: aborting"); - ConsoleLogger.logException("Aborting! Encountered exception during reload of AuthMe:", e); + logger.logException("Aborting! Encountered exception during reload of AuthMe:", e); plugin.stopOrUnload(); } } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java index 5c9b30f42..4789e0439 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommand.java @@ -6,6 +6,7 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; @@ -19,6 +20,8 @@ import java.util.List; */ public class TotpDisableAdminCommand implements ExecutableCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(TotpDisableAdminCommand.class); + @Inject private DataSource dataSource; @@ -45,7 +48,7 @@ public class TotpDisableAdminCommand implements ExecutableCommand { private void removeTotpKey(CommandSender sender, String player) { if (dataSource.removeTotpKey(player)) { sender.sendMessage("Disabled two-factor authentication successfully for '" + player + "'"); - ConsoleLogger.info(sender.getName() + " disable two-factor authentication for '" + player + "'"); + logger.info(sender.getName() + " disable two-factor authentication for '" + player + "'"); Player onlinePlayer = bukkitService.getPlayerExact(player); if (onlinePlayer != null) { diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommand.java index d790962a5..7f61afd0f 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommand.java @@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.help.HelpMessagesService; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.HelpTranslationGenerator; import org.bukkit.command.CommandSender; @@ -17,6 +18,8 @@ import java.util.List; */ public class UpdateHelpMessagesCommand implements ExecutableCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(UpdateHelpMessagesCommand.class); + @Inject private HelpTranslationGenerator helpTranslationGenerator; @Inject @@ -30,7 +33,7 @@ public class UpdateHelpMessagesCommand implements ExecutableCommand { helpMessagesService.reloadMessagesFile(); } catch (IOException e) { sender.sendMessage("Could not update help file: " + e.getMessage()); - ConsoleLogger.logException("Could not update help file:", e); + logger.logException("Could not update help file:", e); } } } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtils.java b/src/main/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtils.java index 14b07ac9d..fa4200a0a 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtils.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtils.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.CacheDataSource; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.Location; import java.lang.reflect.Field; @@ -19,6 +20,7 @@ import java.util.function.Function; */ final class DebugSectionUtils { + private static ConsoleLogger logger = ConsoleLoggerFactory.get(DebugSectionUtils.class); private static Field limboEntriesField; private DebugSectionUtils() { @@ -72,7 +74,7 @@ final class DebugSectionUtils { field.setAccessible(true); limboEntriesField = field; } catch (Exception e) { - ConsoleLogger.logException("Could not retrieve LimboService entries field:", e); + logger.logException("Could not retrieve LimboService entries field:", e); } } return limboEntriesField; @@ -95,7 +97,7 @@ final class DebugSectionUtils { try { return function.apply((Map) limboEntriesField.get(limboService)); } catch (Exception e) { - ConsoleLogger.logException("Could not retrieve LimboService values:", e); + logger.logException("Could not retrieve LimboService values:", e); } } return null; @@ -119,7 +121,7 @@ final class DebugSectionUtils { source.setAccessible(true); return (DataSource) source.get(dataSource); } catch (NoSuchFieldException | IllegalAccessException e) { - ConsoleLogger.logException("Could not get source of CacheDataSource:", e); + logger.logException("Could not get source of CacheDataSource:", e); return null; } } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChanger.java b/src/main/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChanger.java index 4f201fa5c..d4eb1d3c1 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChanger.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChanger.java @@ -5,6 +5,7 @@ import com.google.common.annotations.VisibleForTesting; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.MySQL; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.DebugSectionPermissions; import fr.xephi.authme.permission.PermissionNode; import fr.xephi.authme.settings.Settings; @@ -43,6 +44,8 @@ class MySqlDefaultChanger implements DebugSection { private static final String NOT_NULL_SUFFIX = ChatColor.DARK_AQUA + "@" + ChatColor.RESET; private static final String DEFAULT_VALUE_SUFFIX = ChatColor.GOLD + "#" + ChatColor.RESET; + private ConsoleLogger logger = ConsoleLoggerFactory.get(MySqlDefaultChanger.class); + @Inject private Settings settings; @@ -98,7 +101,7 @@ class MySqlDefaultChanger implements DebugSection { throw new IllegalStateException("Unknown operation '" + operation + "'"); } } catch (SQLException | IllegalStateException e) { - ConsoleLogger.logException("Failed to perform MySQL default altering operation:", e); + logger.logException("Failed to perform MySQL default altering operation:", e); } } } @@ -134,7 +137,7 @@ class MySqlDefaultChanger implements DebugSection { } // Log success message - ConsoleLogger.info("Changed MySQL column '" + columnName + "' to be NOT NULL, as initiated by '" + logger.info("Changed MySQL column '" + columnName + "' to be NOT NULL, as initiated by '" + sender.getName() + "'"); } @@ -168,7 +171,7 @@ class MySqlDefaultChanger implements DebugSection { + "') to be NULL, modifying " + updatedRows + " entries"); // Log success message - ConsoleLogger.info("Changed MySQL column '" + columnName + "' to allow NULL, as initiated by '" + logger.info("Changed MySQL column '" + columnName + "' to allow NULL, as initiated by '" + sender.getName() + "'"); } @@ -191,7 +194,7 @@ class MySqlDefaultChanger implements DebugSection { + " (" + columnName + "): " + isNullText + ", " + defaultText); } } catch (SQLException e) { - ConsoleLogger.logException("Failed while showing column details:", e); + logger.logException("Failed while showing column details:", e); sender.sendMessage("Failed while showing column details. See log for info"); } @@ -228,7 +231,7 @@ class MySqlDefaultChanger implements DebugSection { } return String.join(ChatColor.RESET + ", ", formattedColumns); } catch (SQLException e) { - ConsoleLogger.logException("Failed to construct column list:", e); + logger.logException("Failed to construct column list:", e); return ChatColor.RED + "An error occurred! Please see the console for details."; } } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/debug/TestEmailSender.java b/src/main/java/fr/xephi/authme/command/executable/authme/debug/TestEmailSender.java index 02bd4a213..f393db72f 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/debug/TestEmailSender.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/debug/TestEmailSender.java @@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.authme.debug; import ch.jalu.datasourcecolumns.data.DataSourceValue; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.mail.SendMailSsl; import fr.xephi.authme.permission.DebugSectionPermissions; import fr.xephi.authme.permission.PermissionNode; @@ -22,6 +23,8 @@ import java.util.List; */ class TestEmailSender implements DebugSection { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(TestEmailSender.class); + @Inject private DataSource dataSource; @@ -110,7 +113,7 @@ class TestEmailSender implements DebugSection { try { htmlEmail = sendMailSsl.initializeMail(email); } catch (EmailException e) { - ConsoleLogger.logException("Failed to create email for sample email:", e); + logger.logException("Failed to create email for sample email:", e); return false; } diff --git a/src/main/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommand.java index 376e8db29..734fc064b 100644 --- a/src/main/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommand.java @@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.email; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.crypts.HashedPassword; @@ -20,6 +21,8 @@ import java.util.List; */ public class EmailSetPasswordCommand extends PlayerCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailSetPasswordCommand.class); + @Inject private DataSource dataSource; @@ -46,7 +49,7 @@ public class EmailSetPasswordCommand extends PlayerCommand { HashedPassword hashedPassword = passwordSecurity.computeHash(password, name); dataSource.updatePassword(name, hashedPassword); recoveryService.removeFromSuccessfulRecovery(player); - ConsoleLogger.info("Player '" + name + "' has changed their password from recovery"); + logger.info("Player '" + name + "' has changed their password from recovery"); commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS); } else { commonService.send(player, result.getMessageKey(), result.getArgs()); diff --git a/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java index 0a3a96945..5fa7e27fb 100644 --- a/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java @@ -5,6 +5,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.BukkitService; @@ -22,6 +23,8 @@ import java.util.List; */ public class RecoverEmailCommand extends PlayerCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(RecoverEmailCommand.class); + @Inject private CommonService commonService; @@ -49,7 +52,7 @@ public class RecoverEmailCommand extends PlayerCommand { final String playerName = player.getName(); if (!emailService.hasAllInformation()) { - ConsoleLogger.warning("Mail API is not set"); + logger.warning("Mail API is not set"); commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS); return; } diff --git a/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java index a67076487..922e1104e 100644 --- a/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java @@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.register; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.data.captcha.RegistrationCaptchaManager; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.Management; @@ -34,6 +35,8 @@ import static fr.xephi.authme.settings.properties.RegistrationSettings.REGISTER_ */ public class RegisterCommand extends PlayerCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(RegisterCommand.class); + @Inject private Management management; @@ -155,7 +158,7 @@ public class RegisterCommand extends PlayerCommand { private void handleEmailRegistration(Player player, List arguments) { if (!emailService.hasAllInformation()) { commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS); - ConsoleLogger.warning("Cannot register player '" + player.getName() + "': no email or password is set " + logger.warning("Cannot register player '" + player.getName() + "': no email or password is set " + "to send emails from. Please adjust your config at " + EmailSettings.MAIL_ACCOUNT.getPath()); return; } diff --git a/src/main/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommand.java b/src/main/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommand.java index 1ab8192be..a4cd7857f 100644 --- a/src/main/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommand.java @@ -5,6 +5,7 @@ import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.security.totp.GenerateTotpService; @@ -19,6 +20,8 @@ import java.util.List; */ public class ConfirmTotpCommand extends PlayerCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ConfirmTotpCommand.class); + @Inject private GenerateTotpService generateTotpService; @@ -63,7 +66,7 @@ public class ConfirmTotpCommand extends PlayerCommand { messages.send(player, MessageKey.TWO_FACTOR_ENABLE_SUCCESS); auth.setTotpKey(totpDetails.getTotpKey()); playerCache.updatePlayer(auth); - ConsoleLogger.info("Player '" + player.getName() + "' has successfully added a TOTP key to their account"); + logger.info("Player '" + player.getName() + "' has successfully added a TOTP key to their account"); } else { messages.send(player, MessageKey.ERROR); } diff --git a/src/main/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommand.java b/src/main/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommand.java index ebcf554c2..bc3cdd3d8 100644 --- a/src/main/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommand.java @@ -5,6 +5,7 @@ import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.security.totp.TotpAuthenticator; @@ -18,6 +19,8 @@ import java.util.List; */ public class RemoveTotpCommand extends PlayerCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(RemoveTotpCommand.class); + @Inject private DataSource dataSource; @@ -51,7 +54,7 @@ public class RemoveTotpCommand extends PlayerCommand { auth.setTotpKey(null); playerCache.updatePlayer(auth); messages.send(player, MessageKey.TWO_FACTOR_REMOVED_SUCCESS); - ConsoleLogger.info("Player '" + player.getName() + "' removed their TOTP key"); + logger.info("Player '" + player.getName() + "' removed their TOTP key"); } else { messages.send(player, MessageKey.ERROR); } diff --git a/src/main/java/fr/xephi/authme/command/executable/totp/TotpCodeCommand.java b/src/main/java/fr/xephi/authme/command/executable/totp/TotpCodeCommand.java index 398759028..1ac483746 100644 --- a/src/main/java/fr/xephi/authme/command/executable/totp/TotpCodeCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/totp/TotpCodeCommand.java @@ -8,6 +8,7 @@ import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.LimboPlayerState; import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.process.login.AsynchronousLogin; @@ -22,6 +23,8 @@ import java.util.List; */ public class TotpCodeCommand extends PlayerCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(TotpCodeCommand.class); + @Inject private LimboService limboService; @@ -57,7 +60,7 @@ public class TotpCodeCommand extends PlayerCommand { if (limbo != null && limbo.getState() == LimboPlayerState.TOTP_REQUIRED) { processCode(player, auth, arguments.get(0)); } else { - ConsoleLogger.debug(() -> "Aborting TOTP check for player '" + player.getName() + logger.debug(() -> "Aborting TOTP check for player '" + player.getName() + "'. Invalid limbo state: " + (limbo == null ? "no limbo" : limbo.getState())); messages.send(player, MessageKey.LOGIN_MESSAGE); } @@ -66,10 +69,10 @@ public class TotpCodeCommand extends PlayerCommand { private void processCode(Player player, PlayerAuth auth, String inputCode) { boolean isCodeValid = totpAuthenticator.checkCode(auth, inputCode); if (isCodeValid) { - ConsoleLogger.debug("Successfully checked TOTP code for `{0}`", player.getName()); + logger.debug("Successfully checked TOTP code for `{0}`", player.getName()); asynchronousLogin.performLogin(player, auth); } else { - ConsoleLogger.debug("Input TOTP code was invalid for player `{0}`", player.getName()); + logger.debug("Input TOTP code was invalid for player `{0}`", player.getName()); messages.send(player, MessageKey.TWO_FACTOR_INVALID_CODE); } } diff --git a/src/main/java/fr/xephi/authme/command/executable/verification/VerificationCommand.java b/src/main/java/fr/xephi/authme/command/executable/verification/VerificationCommand.java index 6aeeda282..ac8ddb868 100644 --- a/src/main/java/fr/xephi/authme/command/executable/verification/VerificationCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/verification/VerificationCommand.java @@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.verification; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.data.VerificationCodeManager; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import org.bukkit.entity.Player; @@ -15,6 +16,8 @@ import java.util.List; */ public class VerificationCommand extends PlayerCommand { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(VerificationCommand.class); + @Inject private CommonService commonService; @@ -26,7 +29,7 @@ public class VerificationCommand extends PlayerCommand { final String playerName = player.getName(); if (!codeManager.canSendMail()) { - ConsoleLogger.warning("Mail API is not set"); + logger.warning("Mail API is not set"); commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS); return; } diff --git a/src/main/java/fr/xephi/authme/data/limbo/AuthGroupHandler.java b/src/main/java/fr/xephi/authme/data/limbo/AuthGroupHandler.java index 0e8b77a27..366db7c94 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/AuthGroupHandler.java +++ b/src/main/java/fr/xephi/authme/data/limbo/AuthGroupHandler.java @@ -2,6 +2,7 @@ package fr.xephi.authme.data.limbo; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -26,6 +27,8 @@ import java.util.Collections; */ class AuthGroupHandler implements Reloadable { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AuthGroupHandler.class); + @Inject private PermissionsManager permissionsManager; @@ -78,7 +81,7 @@ class AuthGroupHandler implements Reloadable { throw new IllegalStateException("Encountered unhandled auth group type '" + groupType + "'"); } - ConsoleLogger.debug(() -> player.getName() + " changed to " + logger.debug(() -> player.getName() + " changed to " + groupType + ": has groups " + permissionsManager.getGroups(player)); } @@ -95,7 +98,7 @@ class AuthGroupHandler implements Reloadable { // Make sure group support is available if (!permissionsManager.hasGroupSupport()) { - ConsoleLogger.warning("The current permissions system doesn't have group support, unable to set group!"); + logger.warning("The current permissions system doesn't have group support, unable to set group!"); return false; } return true; diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboService.java b/src/main/java/fr/xephi/authme/data/limbo/LimboService.java index fae9d44ed..937ed912d 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboService.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboService.java @@ -2,6 +2,7 @@ package fr.xephi.authme.data.limbo; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.persistence.LimboPersistence; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; @@ -22,6 +23,8 @@ import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_WALK_SPE */ public class LimboService { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(LimboService.class); + private final Map entries = new ConcurrentHashMap<>(); @Inject @@ -56,13 +59,13 @@ public class LimboService { LimboPlayer limboFromDisk = persistence.getLimboPlayer(player); if (limboFromDisk != null) { - ConsoleLogger.debug("LimboPlayer for `{0}` already exists on disk", name); + logger.debug("LimboPlayer for `{0}` already exists on disk", name); } LimboPlayer existingLimbo = entries.remove(name); if (existingLimbo != null) { existingLimbo.clearTasks(); - ConsoleLogger.debug("LimboPlayer for `{0}` already present in memory", name); + logger.debug("LimboPlayer for `{0}` already present in memory", name); } Location location = spawnLoader.getPlayerLocationOrSpawn(player); @@ -112,14 +115,14 @@ public class LimboService { LimboPlayer limbo = entries.remove(lowerName); if (limbo == null) { - ConsoleLogger.debug("No LimboPlayer found for `{0}` - cannot restore", lowerName); + logger.debug("No LimboPlayer found for `{0}` - cannot restore", lowerName); } else { player.setOp(limbo.isOperator()); settings.getProperty(RESTORE_ALLOW_FLIGHT).restoreAllowFlight(player, limbo); settings.getProperty(RESTORE_FLY_SPEED).restoreFlySpeed(player, limbo); settings.getProperty(RESTORE_WALK_SPEED).restoreWalkSpeed(player, limbo); limbo.clearTasks(); - ConsoleLogger.debug("Restored LimboPlayer stats for `{0}`", lowerName); + logger.debug("Restored LimboPlayer stats for `{0}`", lowerName); persistence.removeLimboPlayer(player); } authGroupHandler.setGroup(player, limbo, AuthGroupType.LOGGED_IN); @@ -177,7 +180,7 @@ public class LimboService { private Optional getLimboOrLogError(Player player, String context) { LimboPlayer limbo = entries.get(player.getName().toLowerCase()); if (limbo == null) { - ConsoleLogger.debug("No LimboPlayer found for `{0}`. Action: {1}", player.getName(), context); + logger.debug("No LimboPlayer found for `{0}`. Action: {1}", player.getName(), context); } return Optional.ofNullable(limbo); } diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java b/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java index 4d63a2d98..d51afbef7 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java @@ -1,6 +1,7 @@ package fr.xephi.authme.data.limbo; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; @@ -19,6 +20,8 @@ import static fr.xephi.authme.util.Utils.isCollectionEmpty; */ class LimboServiceHelper { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(LimboServiceHelper.class); + @Inject private PermissionsManager permissionsManager; @@ -41,7 +44,7 @@ class LimboServiceHelper { float flySpeed = player.getFlySpeed(); Collection playerGroups = permissionsManager.hasGroupSupport() ? permissionsManager.getGroups(player) : Collections.emptyList(); - ConsoleLogger.debug("Player `{0}` has groups `{1}`", player.getName(), String.join(", ", playerGroups)); + logger.debug("Player `{0}` has groups `{1}`", player.getName(), String.join(", ", playerGroups)); return new LimboPlayer(location, isOperator, playerGroups, flyEnabled, walkSpeed, flySpeed); } @@ -98,9 +101,8 @@ class LimboServiceHelper { return first == null ? second : first; } - private static Collection getLimboGroups(Collection oldLimboGroups, - Collection newLimboGroups) { - ConsoleLogger.debug("Limbo merge: new and old groups are `{0}` and `{1}`", newLimboGroups, oldLimboGroups); + private Collection getLimboGroups(Collection oldLimboGroups, Collection newLimboGroups) { + logger.debug("Limbo merge: new and old groups are `{0}` and `{1}`", newLimboGroups, oldLimboGroups); return isCollectionEmpty(oldLimboGroups) ? newLimboGroups : oldLimboGroups; } } diff --git a/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java b/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java index 4f17d14e4..f4a249017 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java +++ b/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java @@ -1,6 +1,7 @@ package fr.xephi.authme.data.limbo; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.entity.Player; /** @@ -15,14 +16,14 @@ public enum WalkFlySpeedRestoreType { RESTORE { @Override public void restoreFlySpeed(Player player, LimboPlayer limbo) { - ConsoleLogger.debug("Restoring fly speed for LimboPlayer " + player.getName() + " to " + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " + limbo.getFlySpeed() + " (RESTORE mode)"); player.setFlySpeed(limbo.getFlySpeed()); } @Override public void restoreWalkSpeed(Player player, LimboPlayer limbo) { - ConsoleLogger.debug("Restoring walk speed for LimboPlayer " + player.getName() + " to " + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " + limbo.getWalkSpeed() + " (RESTORE mode)"); player.setWalkSpeed(limbo.getWalkSpeed()); } @@ -36,11 +37,11 @@ public enum WalkFlySpeedRestoreType { public void restoreFlySpeed(Player player, LimboPlayer limbo) { float limboFlySpeed = limbo.getFlySpeed(); if (limboFlySpeed > 0.01f) { - ConsoleLogger.debug("Restoring fly speed for LimboPlayer " + player.getName() + " to " + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " + limboFlySpeed + " (RESTORE_NO_ZERO mode)"); player.setFlySpeed(limboFlySpeed); } else { - ConsoleLogger.debug("Restoring fly speed for LimboPlayer " + player.getName() + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to DEFAULT, it was 0! (RESTORE_NO_ZERO mode)"); player.setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); } @@ -50,11 +51,11 @@ public enum WalkFlySpeedRestoreType { public void restoreWalkSpeed(Player player, LimboPlayer limbo) { float limboWalkSpeed = limbo.getWalkSpeed(); if (limboWalkSpeed > 0.01f) { - ConsoleLogger.debug("Restoring walk speed for LimboPlayer " + player.getName() + " to " + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " + limboWalkSpeed + " (RESTORE_NO_ZERO mode)"); player.setWalkSpeed(limboWalkSpeed); } else { - ConsoleLogger.debug("Restoring walk speed for LimboPlayer " + player.getName() + "" + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + "" + " to DEFAULT, it was 0! (RESTORE_NO_ZERO mode)"); player.setWalkSpeed(LimboPlayer.DEFAULT_WALK_SPEED); } @@ -68,7 +69,7 @@ public enum WalkFlySpeedRestoreType { @Override public void restoreFlySpeed(Player player, LimboPlayer limbo) { float newSpeed = Math.max(player.getFlySpeed(), limbo.getFlySpeed()); - ConsoleLogger.debug("Restoring fly speed for LimboPlayer " + player.getName() + " to " + newSpeed + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " + newSpeed + " (Current: " + player.getFlySpeed() + ", Limbo: " + limbo.getFlySpeed() + ") (MAX_RESTORE mode)"); player.setFlySpeed(newSpeed); } @@ -76,7 +77,7 @@ public enum WalkFlySpeedRestoreType { @Override public void restoreWalkSpeed(Player player, LimboPlayer limbo) { float newSpeed = Math.max(player.getWalkSpeed(), limbo.getWalkSpeed()); - ConsoleLogger.debug("Restoring walk speed for LimboPlayer " + player.getName() + " to " + newSpeed + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " + newSpeed + " (Current: " + player.getWalkSpeed() + ", Limbo: " + limbo.getWalkSpeed() + ") (MAX_RESTORE mode)"); player.setWalkSpeed(newSpeed); } @@ -88,19 +89,21 @@ public enum WalkFlySpeedRestoreType { DEFAULT { @Override public void restoreFlySpeed(Player player, LimboPlayer limbo) { - ConsoleLogger.debug("Restoring fly speed for LimboPlayer " + player.getName() + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to DEFAULT (DEFAULT mode)"); player.setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); } @Override public void restoreWalkSpeed(Player player, LimboPlayer limbo) { - ConsoleLogger.debug("Restoring walk speed for LimboPlayer " + player.getName() + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to DEFAULT (DEFAULT mode)"); player.setWalkSpeed(LimboPlayer.DEFAULT_WALK_SPEED); } }; + private static final ConsoleLogger logger = ConsoleLoggerFactory.get(WalkFlySpeedRestoreType.class); + /** * Restores the fly speed from Limbo to Player according to the restoration type. * diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java index ca66afdec..9708ce884 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandler.java @@ -7,6 +7,7 @@ import com.google.gson.GsonBuilder; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; @@ -33,6 +34,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler { private static final Type LIMBO_MAP_TYPE = new TypeToken>(){}.getType(); + private final ConsoleLogger logger = ConsoleLoggerFactory.get(DistributedFilesPersistenceHandler.class); private final File cacheFolder; private final Gson gson; private final SegmentNameBuilder segmentNameBuilder; @@ -103,7 +105,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler { try (FileWriter fw = new FileWriter(file)) { gson.toJson(entries, fw); } catch (Exception e) { - ConsoleLogger.logException("Could not write to '" + file + "':", e); + logger.logException("Could not write to '" + file + "':", e); } } @@ -115,7 +117,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler { try { return gson.fromJson(Files.asCharSource(file, StandardCharsets.UTF_8).read(), LIMBO_MAP_TYPE); } catch (Exception e) { - ConsoleLogger.logException("Failed reading '" + file + "':", e); + logger.logException("Failed reading '" + file + "':", e); } return null; } @@ -164,7 +166,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler { private void saveToNewSegments(Map limbosFromOldSegments) { Map> limboBySegment = groupBySegment(limbosFromOldSegments); - ConsoleLogger.info("Saving " + limbosFromOldSegments.size() + " LimboPlayers from old segments into " + logger.info("Saving " + limbosFromOldSegments.size() + " LimboPlayers from old segments into " + limboBySegment.size() + " current segments"); for (Map.Entry> entry : limboBySegment.entrySet()) { File file = getSegmentFile(entry.getKey()); @@ -203,7 +205,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler { .filter(f -> isLimboJsonFile(f) && f.length() < 3) .peek(FileUtils::delete) .count(); - ConsoleLogger.debug("Limbo: Deleted {0} empty segment files", deletedFiles); + logger.debug("Limbo: Deleted {0} empty segment files", deletedFiles); } /** @@ -215,10 +217,10 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler { return name.startsWith("seg") && name.endsWith("-limbo.json"); } - private static File[] listFiles(File folder) { + private File[] listFiles(File folder) { File[] files = folder.listFiles(); if (files == null) { - ConsoleLogger.warning("Could not get files of '" + folder + "'"); + logger.warning("Could not get files of '" + folder + "'"); return new File[0]; } return files; diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java index b43b1d3f7..9772ec064 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandler.java @@ -6,6 +6,7 @@ import com.google.gson.GsonBuilder; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.util.FileUtils; import org.bukkit.entity.Player; @@ -20,6 +21,8 @@ import java.nio.charset.StandardCharsets; */ class IndividualFilesPersistenceHandler implements LimboPersistenceHandler { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(IndividualFilesPersistenceHandler.class); + private final Gson gson; private final File cacheDir; @@ -27,7 +30,7 @@ class IndividualFilesPersistenceHandler implements LimboPersistenceHandler { IndividualFilesPersistenceHandler(@DataFolder File dataFolder, BukkitService bukkitService) { cacheDir = new File(dataFolder, "playerdata"); if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) { - ConsoleLogger.warning("Failed to create playerdata directory '" + cacheDir + "'"); + logger.warning("Failed to create playerdata directory '" + cacheDir + "'"); } gson = new GsonBuilder() .registerTypeAdapter(LimboPlayer.class, new LimboPlayerSerializer()) @@ -48,7 +51,7 @@ class IndividualFilesPersistenceHandler implements LimboPersistenceHandler { String str = Files.asCharSource(file, StandardCharsets.UTF_8).read(); return gson.fromJson(str, LimboPlayer.class); } catch (IOException e) { - ConsoleLogger.logException("Could not read player data on disk for '" + player.getName() + "'", e); + logger.logException("Could not read player data on disk for '" + player.getName() + "'", e); return null; } } @@ -62,7 +65,7 @@ class IndividualFilesPersistenceHandler implements LimboPersistenceHandler { Files.touch(file); Files.write(gson.toJson(limboPlayer), file, StandardCharsets.UTF_8); } catch (IOException e) { - ConsoleLogger.logException("Failed to write " + player.getName() + " data:", e); + logger.logException("Failed to write " + player.getName() + " data:", e); } } diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPersistence.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPersistence.java index 391878dad..844c9cdf5 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPersistence.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPersistence.java @@ -4,6 +4,7 @@ import ch.jalu.injector.factory.Factory; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.initialization.SettingsDependent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; import org.bukkit.entity.Player; @@ -15,6 +16,8 @@ import javax.inject.Inject; */ public class LimboPersistence implements SettingsDependent { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(LimboPersistence.class); + private final Factory handlerFactory; private LimboPersistenceHandler handler; @@ -35,7 +38,7 @@ public class LimboPersistence implements SettingsDependent { try { return handler.getLimboPlayer(player); } catch (Exception e) { - ConsoleLogger.logException("Could not get LimboPlayer for '" + player.getName() + "'", e); + logger.logException("Could not get LimboPlayer for '" + player.getName() + "'", e); } return null; } @@ -50,7 +53,7 @@ public class LimboPersistence implements SettingsDependent { try { handler.saveLimboPlayer(player, limbo); } catch (Exception e) { - ConsoleLogger.logException("Could not save LimboPlayer for '" + player.getName() + "'", e); + logger.logException("Could not save LimboPlayer for '" + player.getName() + "'", e); } } @@ -63,7 +66,7 @@ public class LimboPersistence implements SettingsDependent { try { handler.removeLimboPlayer(player); } catch (Exception e) { - ConsoleLogger.logException("Could not remove LimboPlayer for '" + player.getName() + "'", e); + logger.logException("Could not remove LimboPlayer for '" + player.getName() + "'", e); } } @@ -72,7 +75,7 @@ public class LimboPersistence implements SettingsDependent { LimboPersistenceType persistenceType = settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE); // If we're changing from an existing handler, output a quick hint that nothing is converted. if (handler != null && handler.getType() != persistenceType) { - ConsoleLogger.info("Limbo persistence type has changed! Note that the data is not converted."); + logger.info("Limbo persistence type has changed! Note that the data is not converted."); } handler = handlerFactory.newInstance(persistenceType.getImplementationClass()); } diff --git a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java index ec57cd57f..e1418dcaf 100644 --- a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java +++ b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java @@ -12,6 +12,7 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.util.Utils; @@ -25,6 +26,8 @@ import java.util.stream.Collectors; public class CacheDataSource implements DataSource { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(CacheDataSource.class); + private final DataSource source; private final PlayerCache playerCache; private final LoadingCache> cachedAuths; @@ -164,7 +167,7 @@ public class CacheDataSource implements DataSource { try { executorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { - ConsoleLogger.logException("Could not close executor service:", e); + logger.logException("Could not close executor service:", e); } cachedAuths.invalidateAll(); source.closeConnection(); diff --git a/src/main/java/fr/xephi/authme/datasource/MySQL.java b/src/main/java/fr/xephi/authme/datasource/MySQL.java index 570a23ce8..768af7320 100644 --- a/src/main/java/fr/xephi/authme/datasource/MySQL.java +++ b/src/main/java/fr/xephi/authme/datasource/MySQL.java @@ -8,6 +8,7 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtension; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.HooksSettings; @@ -34,6 +35,7 @@ import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException; */ @SuppressWarnings({"checkstyle:AbbreviationAsWordInName"}) // Justification: Class name cannot be changed anymore public class MySQL extends AbstractSqlDataSource { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(MySQL.class); private boolean useSsl; private boolean serverCertificateVerification; @@ -58,14 +60,14 @@ public class MySQL extends AbstractSqlDataSource { this.setConnectionArguments(); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { - ConsoleLogger.warning("Invalid database arguments! Please check your configuration!"); - ConsoleLogger.warning("If this error persists, please report it to the developer!"); + logger.warning("Invalid database arguments! Please check your configuration!"); + logger.warning("If this error persists, please report it to the developer!"); } if (e instanceof PoolInitializationException) { - ConsoleLogger.warning("Can't initialize database connection! Please check your configuration!"); - ConsoleLogger.warning("If this error persists, please report it to the developer!"); + logger.warning("Can't initialize database connection! Please check your configuration!"); + logger.warning("If this error persists, please report it to the developer!"); } - ConsoleLogger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!"); + logger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!"); throw e; } @@ -74,8 +76,8 @@ public class MySQL extends AbstractSqlDataSource { checkTablesAndColumns(); } catch (SQLException e) { closeConnection(); - ConsoleLogger.logException("Can't initialize the MySQL database:", e); - ConsoleLogger.warning("Please check your database settings in the config.yml file!"); + logger.logException("Can't initialize the MySQL database:", e); + logger.warning("Please check your database settings in the config.yml file!"); throw e; } } @@ -149,7 +151,7 @@ public class MySQL extends AbstractSqlDataSource { ds.addDataSourceProperty("prepStmtCacheSize", "275"); ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!"); + logger.info("Connection arguments loaded, Hikari ConnectionPool ready!"); } @Override @@ -158,7 +160,7 @@ public class MySQL extends AbstractSqlDataSource { ds.close(); } setConnectionArguments(); - ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!"); + logger.info("Hikari ConnectionPool arguments reloaded!"); } private Connection getConnection() throws SQLException { @@ -272,7 +274,7 @@ public class MySQL extends AbstractSqlDataSource { + " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)"); } } - ConsoleLogger.info("MySQL setup finished"); + logger.info("MySQL setup finished"); } private boolean isColumnMissing(DatabaseMetaData metaData, String columnName) throws SQLException { diff --git a/src/main/java/fr/xephi/authme/datasource/MySqlMigrater.java b/src/main/java/fr/xephi/authme/datasource/MySqlMigrater.java index 79331be56..fec564d5a 100644 --- a/src/main/java/fr/xephi/authme/datasource/MySqlMigrater.java +++ b/src/main/java/fr/xephi/authme/datasource/MySqlMigrater.java @@ -1,6 +1,7 @@ package fr.xephi.authme.datasource; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -12,6 +13,8 @@ import java.sql.Types; * Performs migrations on the MySQL data source if necessary. */ final class MySqlMigrater { + + private static ConsoleLogger logger = ConsoleLoggerFactory.get(MySqlMigrater.class); private MySqlMigrater() { } @@ -35,7 +38,7 @@ final class MySqlMigrater { String sql = String.format("ALTER TABLE %s MODIFY %s VARCHAR(40) CHARACTER SET ascii COLLATE ascii_bin", tableName, col.LAST_IP); st.execute(sql); - ConsoleLogger.info("Changed last login column to allow NULL values. Please verify the registration feature " + logger.info("Changed last login column to allow NULL values. Please verify the registration feature " + "if you are hooking into a forum."); } } @@ -53,7 +56,7 @@ final class MySqlMigrater { final int columnType; try (ResultSet rs = metaData.getColumns(null, null, tableName, col.LAST_LOGIN)) { if (!rs.next()) { - ConsoleLogger.warning("Could not get LAST_LOGIN meta data. This should never happen!"); + logger.warning("Could not get LAST_LOGIN meta data. This should never happen!"); return; } columnType = rs.getInt("DATA_TYPE"); @@ -75,7 +78,7 @@ final class MySqlMigrater { */ private static void migrateLastLoginColumnFromInt(Statement st, String tableName, Columns col) throws SQLException { // Change from int to bigint - ConsoleLogger.info("Migrating lastlogin column from int to bigint"); + logger.info("Migrating lastlogin column from int to bigint"); String sql = String.format("ALTER TABLE %s MODIFY %s BIGINT;", tableName, col.LAST_LOGIN); st.execute(sql); @@ -86,7 +89,7 @@ final class MySqlMigrater { tableName, col.LAST_LOGIN, col.LAST_LOGIN, col.LAST_LOGIN, rangeStart, col.LAST_LOGIN, rangeEnd); int changedRows = st.executeUpdate(sql); - ConsoleLogger.warning("You may have entries with invalid timestamps. Please check your data " + logger.warning("You may have entries with invalid timestamps. Please check your data " + "before purging. " + changedRows + " rows were migrated from seconds to milliseconds."); } @@ -107,7 +110,7 @@ final class MySqlMigrater { long currentTimestamp = System.currentTimeMillis(); int updatedRows = st.executeUpdate(String.format("UPDATE %s SET %s = %d;", tableName, col.REGISTRATION_DATE, currentTimestamp)); - ConsoleLogger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, " + logger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, " + currentTimestamp + ", to all " + updatedRows + " rows"); } } diff --git a/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java b/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java index 62c26b648..566166d60 100644 --- a/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java +++ b/src/main/java/fr/xephi/authme/datasource/PostgreSqlDataSource.java @@ -8,6 +8,7 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtension; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.HooksSettings; @@ -32,6 +33,8 @@ import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException; */ public class PostgreSqlDataSource extends AbstractSqlDataSource { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PostgreSqlDataSource.class); + private String host; private String port; private String username; @@ -53,14 +56,14 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource { this.setConnectionArguments(); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { - ConsoleLogger.warning("Invalid database arguments! Please check your configuration!"); - ConsoleLogger.warning("If this error persists, please report it to the developer!"); + logger.warning("Invalid database arguments! Please check your configuration!"); + logger.warning("If this error persists, please report it to the developer!"); } if (e instanceof PoolInitializationException) { - ConsoleLogger.warning("Can't initialize database connection! Please check your configuration!"); - ConsoleLogger.warning("If this error persists, please report it to the developer!"); + logger.warning("Can't initialize database connection! Please check your configuration!"); + logger.warning("If this error persists, please report it to the developer!"); } - ConsoleLogger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!"); + logger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!"); throw e; } @@ -69,8 +72,8 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource { checkTablesAndColumns(); } catch (SQLException e) { closeConnection(); - ConsoleLogger.logException("Can't initialize the PostgreSQL database:", e); - ConsoleLogger.warning("Please check your database settings in the config.yml file!"); + logger.logException("Can't initialize the PostgreSQL database:", e); + logger.warning("Please check your database settings in the config.yml file!"); throw e; } } @@ -129,7 +132,7 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource { ds.addDataSourceProperty("cachePrepStmts", "true"); ds.addDataSourceProperty("preparedStatementCacheQueries", "275"); - ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!"); + logger.info("Connection arguments loaded, Hikari ConnectionPool ready!"); } @Override @@ -138,7 +141,7 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource { ds.close(); } setConnectionArguments(); - ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!"); + logger.info("Hikari ConnectionPool arguments reloaded!"); } private Connection getConnection() throws SQLException { @@ -247,7 +250,7 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource { + " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)"); } } - ConsoleLogger.info("PostgreSQL setup finished"); + logger.info("PostgreSQL setup finished"); } private boolean isColumnMissing(DatabaseMetaData metaData, String columnName) throws SQLException { diff --git a/src/main/java/fr/xephi/authme/datasource/SQLite.java b/src/main/java/fr/xephi/authme/datasource/SQLite.java index b1b796e42..29b6a87c1 100644 --- a/src/main/java/fr/xephi/authme/datasource/SQLite.java +++ b/src/main/java/fr/xephi/authme/datasource/SQLite.java @@ -4,6 +4,7 @@ import com.google.common.annotations.VisibleForTesting; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; @@ -30,6 +31,7 @@ import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException; @SuppressWarnings({"checkstyle:AbbreviationAsWordInName"}) // Justification: Class name cannot be changed anymore public class SQLite extends AbstractSqlDataSource { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(SQLite.class); private final Settings settings; private final File dataFolder; private final String database; @@ -57,7 +59,7 @@ public class SQLite extends AbstractSqlDataSource { this.setup(); this.migrateIfNeeded(); } catch (Exception ex) { - ConsoleLogger.logException("Error during SQLite initialization:", ex); + logger.logException("Error during SQLite initialization:", ex); throw ex; } } @@ -85,7 +87,7 @@ public class SQLite extends AbstractSqlDataSource { throw new IllegalStateException("Failed to load SQLite JDBC class", e); } - ConsoleLogger.debug("SQLite driver loaded"); + logger.debug("SQLite driver loaded"); this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db"); this.columnsHandler = AuthMeColumnsHandler.createForSqlite(con, settings); } @@ -188,7 +190,7 @@ public class SQLite extends AbstractSqlDataSource { + " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)"); } } - ConsoleLogger.info("SQLite Setup finished"); + logger.info("SQLite Setup finished"); } /** @@ -219,7 +221,7 @@ public class SQLite extends AbstractSqlDataSource { this.setup(); this.migrateIfNeeded(); } catch (SQLException ex) { - ConsoleLogger.logException("Error while reloading SQLite:", ex); + logger.logException("Error while reloading SQLite:", ex); } } @@ -398,7 +400,7 @@ public class SQLite extends AbstractSqlDataSource { long currentTimestamp = System.currentTimeMillis(); int updatedRows = st.executeUpdate(String.format("UPDATE %s SET %s = %d;", tableName, col.REGISTRATION_DATE, currentTimestamp)); - ConsoleLogger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, " + logger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, " + currentTimestamp + ", to all " + updatedRows + " rows"); } diff --git a/src/main/java/fr/xephi/authme/datasource/SqLiteMigrater.java b/src/main/java/fr/xephi/authme/datasource/SqLiteMigrater.java index aab79f187..b4a2a577b 100644 --- a/src/main/java/fr/xephi/authme/datasource/SqLiteMigrater.java +++ b/src/main/java/fr/xephi/authme/datasource/SqLiteMigrater.java @@ -2,6 +2,7 @@ package fr.xephi.authme.datasource; import com.google.common.io.Files; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.util.FileUtils; @@ -19,6 +20,7 @@ import java.sql.Statement; */ class SqLiteMigrater { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(SqLiteMigrater.class); private final File dataFolder; private final String databaseName; private final String tableName; @@ -53,13 +55,13 @@ class SqLiteMigrater { * @param sqLite the instance to migrate */ void performMigration(SQLite sqLite) throws SQLException { - ConsoleLogger.warning("YOUR SQLITE DATABASE NEEDS MIGRATING! DO NOT TURN OFF YOUR SERVER"); + logger.warning("YOUR SQLITE DATABASE NEEDS MIGRATING! DO NOT TURN OFF YOUR SERVER"); String backupName = createBackup(); - ConsoleLogger.info("Made a backup of your database at 'backups/" + backupName + "'"); + logger.info("Made a backup of your database at 'backups/" + backupName + "'"); recreateDatabaseWithNewDefinitions(sqLite); - ConsoleLogger.info("SQLite database migrated successfully"); + logger.info("SQLite database migrated successfully"); } private String createBackup() { @@ -104,7 +106,7 @@ class SqLiteMigrater { + " CASE WHEN $email = 'your@email.com' THEN NULL ELSE $email END, $isLogged" + " FROM " + tempTable + ";"; int insertedEntries = st.executeUpdate(replaceColumnVariables(copySql)); - ConsoleLogger.info("Copied over " + insertedEntries + " from the old table to the new one"); + logger.info("Copied over " + insertedEntries + " from the old table to the new one"); st.execute("DROP TABLE " + tempTable + ";"); } diff --git a/src/main/java/fr/xephi/authme/datasource/SqlDataSourceUtils.java b/src/main/java/fr/xephi/authme/datasource/SqlDataSourceUtils.java index da5a6ca28..b115b276b 100644 --- a/src/main/java/fr/xephi/authme/datasource/SqlDataSourceUtils.java +++ b/src/main/java/fr/xephi/authme/datasource/SqlDataSourceUtils.java @@ -1,6 +1,7 @@ package fr.xephi.authme.datasource; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -11,6 +12,8 @@ import java.sql.SQLException; */ public final class SqlDataSourceUtils { + private static final ConsoleLogger logger = ConsoleLoggerFactory.get(SqlDataSourceUtils.class); + private SqlDataSourceUtils() { } @@ -20,7 +23,7 @@ public final class SqlDataSourceUtils { * @param e the exception to log */ public static void logSqlException(SQLException e) { - ConsoleLogger.logException("Error during SQL operation:", e); + logger.logException("Error during SQL operation:", e); } /** @@ -58,7 +61,7 @@ public final class SqlDataSourceUtils { if (nullableCode == DatabaseMetaData.columnNoNulls) { return true; } else if (nullableCode == DatabaseMetaData.columnNullableUnknown) { - ConsoleLogger.warning("Unknown nullable status for column '" + columnName + "'"); + logger.warning("Unknown nullable status for column '" + columnName + "'"); } } return false; diff --git a/src/main/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverter.java index 3ae721906..fdced2fa4 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverter.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSourceType; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.command.CommandSender; import java.util.ArrayList; @@ -18,8 +19,10 @@ import static fr.xephi.authme.util.Utils.logAndSendMessage; */ public abstract class AbstractDataSourceConverter implements Converter { - private DataSource destination; - private DataSourceType destinationType; + private final ConsoleLogger logger = ConsoleLoggerFactory.get(MySqlToSqlite.class); + + private final DataSource destination; + private final DataSourceType destinationType; /** * Constructor. @@ -51,7 +54,7 @@ public abstract class AbstractDataSourceConverter implemen source = getSource(); } catch (Exception e) { logAndSendMessage(sender, "The data source to convert from could not be initialized"); - ConsoleLogger.logException("Could not initialize source:", e); + logger.logException("Could not initialize source:", e); return; } @@ -60,7 +63,6 @@ public abstract class AbstractDataSourceConverter implemen if (destination.isAuthAvailable(auth.getNickname())) { skippedPlayers.add(auth.getNickname()); } else { - adaptPlayerAuth(auth); destination.saveAuth(auth); destination.updateSession(auth); destination.updateQuitLoc(auth); @@ -75,15 +77,6 @@ public abstract class AbstractDataSourceConverter implemen + " to " + destinationType); } - /** - * Adapts the PlayerAuth from the source before it is saved in the destination. - * - * @param auth the auth from the source - */ - protected void adaptPlayerAuth(PlayerAuth auth) { - // noop - } - /** * @return the data source to convert from * @throws Exception during initialization of source diff --git a/src/main/java/fr/xephi/authme/datasource/converter/CrazyLoginConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/CrazyLoginConverter.java index 13266a891..b1c9613e2 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/CrazyLoginConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/CrazyLoginConverter.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ConverterSettings; import org.bukkit.command.CommandSender; @@ -19,6 +20,8 @@ import java.io.IOException; */ public class CrazyLoginConverter implements Converter { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(CrazyLoginConverter.class); + private final DataSource database; private final Settings settings; private final File dataFolder; @@ -46,10 +49,10 @@ public class CrazyLoginConverter implements Converter { migrateAccount(line); } } - ConsoleLogger.info("CrazyLogin database has been imported correctly"); + logger.info("CrazyLogin database has been imported correctly"); } catch (IOException ex) { - ConsoleLogger.warning("Can't open the crazylogin database file! Does it exist?"); - ConsoleLogger.logException("Encountered", ex); + logger.warning("Can't open the crazylogin database file! Does it exist?"); + logger.logException("Encountered", ex); } } diff --git a/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java index d13f373cf..5f74ec1e8 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/LoginSecurityConverter.java @@ -5,6 +5,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ConverterSettings; import fr.xephi.authme.util.UuidUtils; @@ -31,6 +32,7 @@ import static fr.xephi.authme.util.Utils.logAndSendMessage; */ public class LoginSecurityConverter implements Converter { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(LoginSecurityConverter.class); private final File dataFolder; private final DataSource dataSource; @@ -60,7 +62,7 @@ public class LoginSecurityConverter implements Converter { } } catch (SQLException e) { sender.sendMessage("Failed to convert from SQLite. Please see the log for more info"); - ConsoleLogger.logException("Could not fetch or migrate data:", e); + logger.logException("Could not fetch or migrate data:", e); } } @@ -189,7 +191,7 @@ public class LoginSecurityConverter implements Converter { return DriverManager.getConnection( "jdbc:sqlite:" + path, "trump", "donald"); } catch (SQLException e) { - ConsoleLogger.logException("Could not connect to SQLite database", e); + logger.logException("Could not connect to SQLite database", e); return null; } } @@ -199,7 +201,7 @@ public class LoginSecurityConverter implements Converter { return DriverManager.getConnection( "jdbc:mysql://" + mySqlHost + "/" + mySqlDatabase, mySqlUser, mySqlPassword); } catch (SQLException e) { - ConsoleLogger.logException("Could not connect to SQLite database", e); + logger.logException("Could not connect to SQLite database", e); return null; } } diff --git a/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java index 2c9e16b80..b69fe688d 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.settings.Settings; @@ -25,6 +26,7 @@ import java.util.Map.Entry; */ public class RakamakConverter implements Converter { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(RakamakConverter.class); private final DataSource database; private final Settings settings; private final File pluginFolder; @@ -88,7 +90,7 @@ public class RakamakConverter implements Converter { } Utils.logAndSendMessage(sender, "Rakamak database has been imported successfully"); } catch (IOException ex) { - ConsoleLogger.logException("Can't open the rakamak database file! Does it exist?", ex); + logger.logException("Can't open the rakamak database file! Does it exist?", ex); } } } diff --git a/src/main/java/fr/xephi/authme/datasource/converter/RoyalAuthConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/RoyalAuthConverter.java index d921ade82..7c45aebfa 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/RoyalAuthConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/RoyalAuthConverter.java @@ -4,6 +4,7 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; @@ -18,6 +19,9 @@ public class RoyalAuthConverter implements Converter { private static final String LAST_LOGIN_PATH = "timestamps.quit"; private static final String PASSWORD_PATH = "login.password"; + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(RoyalAuthConverter.class); + private final AuthMe plugin; private final DataSource dataSource; @@ -48,7 +52,7 @@ public class RoyalAuthConverter implements Converter { dataSource.saveAuth(auth); dataSource.updateSession(auth); } catch (Exception e) { - ConsoleLogger.logException("Error while trying to import " + player.getName() + " RoyalAuth data", e); + logger.logException("Error while trying to import " + player.getName() + " RoyalAuth data", e); } } } diff --git a/src/main/java/fr/xephi/authme/datasource/converter/VAuthConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/VAuthConverter.java index c21be1375..e9c706077 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/VAuthConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/VAuthConverter.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; @@ -18,6 +19,7 @@ import static fr.xephi.authme.util.FileUtils.makePath; public class VAuthConverter implements Converter { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(VAuthConverter.class); private final DataSource dataSource; private final File vAuthPasswordsFile; @@ -58,7 +60,7 @@ public class VAuthConverter implements Converter { dataSource.saveAuth(auth); } } catch (IOException e) { - ConsoleLogger.logException("Error while trying to import some vAuth data", e); + logger.logException("Error while trying to import some vAuth data", e); } } diff --git a/src/main/java/fr/xephi/authme/initialization/DataSourceProvider.java b/src/main/java/fr/xephi/authme/initialization/DataSourceProvider.java index 94e8898ed..857a795a9 100644 --- a/src/main/java/fr/xephi/authme/initialization/DataSourceProvider.java +++ b/src/main/java/fr/xephi/authme/initialization/DataSourceProvider.java @@ -9,6 +9,7 @@ import fr.xephi.authme.datasource.MySQL; import fr.xephi.authme.datasource.PostgreSqlDataSource; import fr.xephi.authme.datasource.SQLite; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; @@ -16,7 +17,6 @@ import fr.xephi.authme.settings.properties.DatabaseSettings; import javax.inject.Inject; import javax.inject.Provider; import java.io.File; -import java.io.IOException; import java.sql.SQLException; /** @@ -26,6 +26,8 @@ public class DataSourceProvider implements Provider { private static final int SQLITE_MAX_SIZE = 4000; + private final ConsoleLogger logger = ConsoleLoggerFactory.get(DataSourceProvider.class); + @Inject @DataFolder private File dataFolder; @@ -46,7 +48,7 @@ public class DataSourceProvider implements Provider { try { return createDataSource(); } catch (Exception e) { - ConsoleLogger.logException("Could not create data source:", e); + logger.logException("Could not create data source:", e); throw new IllegalStateException("Error during initialization of data source", e); } } @@ -54,11 +56,10 @@ public class DataSourceProvider implements Provider { /** * Sets up the data source. * - * @return the constructed datasource - * @throws SQLException when initialization of a SQL datasource failed - * @throws IOException if flat file cannot be read + * @return the constructed data source + * @throws SQLException when initialization of a SQL data source failed */ - private DataSource createDataSource() throws SQLException, IOException { + private DataSource createDataSource() throws SQLException { DataSourceType dataSourceType = settings.getProperty(DatabaseSettings.BACKEND); DataSource dataSource; switch (dataSourceType) { @@ -88,7 +89,7 @@ public class DataSourceProvider implements Provider { bukkitService.runTaskAsynchronously(() -> { int accounts = dataSource.getAccountsRegistered(); if (accounts >= SQLITE_MAX_SIZE) { - ConsoleLogger.warning("YOU'RE USING THE SQLITE DATABASE WITH " + logger.warning("YOU'RE USING THE SQLITE DATABASE WITH " + accounts + "+ ACCOUNTS; FOR BETTER PERFORMANCE, PLEASE UPGRADE TO MYSQL!!"); } }); diff --git a/src/main/java/fr/xephi/authme/initialization/OnStartupTasks.java b/src/main/java/fr/xephi/authme/initialization/OnStartupTasks.java index 498e5c266..1645ae651 100644 --- a/src/main/java/fr/xephi/authme/initialization/OnStartupTasks.java +++ b/src/main/java/fr/xephi/authme/initialization/OnStartupTasks.java @@ -3,6 +3,7 @@ package fr.xephi.authme.initialization; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.output.ConsoleFilter; @@ -28,6 +29,8 @@ import static fr.xephi.authme.settings.properties.EmailSettings.RECALL_PLAYERS; */ public class OnStartupTasks { + private static ConsoleLogger consoleLogger = ConsoleLoggerFactory.get(OnStartupTasks.class); + @Inject private DataSource dataSource; @Inject @@ -58,17 +61,16 @@ public class OnStartupTasks { /** * Sets up the console filter if enabled. * - * @param settings the settings - * @param logger the plugin logger + * @param logger the plugin logger */ - public static void setupConsoleFilter(Settings settings, Logger logger) { + public static void setupConsoleFilter(Logger logger) { // Try to set the log4j filter try { Class.forName("org.apache.logging.log4j.core.filter.AbstractFilter"); setLog4JFilter(); } catch (ClassNotFoundException | NoClassDefFoundError e) { // log4j is not available - ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); + consoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); ConsoleFilter filter = new ConsoleFilter(); logger.setFilter(filter); Bukkit.getLogger().setFilter(filter); diff --git a/src/main/java/fr/xephi/authme/listener/EntityListener.java b/src/main/java/fr/xephi/authme/listener/EntityListener.java index b46225c47..609edaae3 100644 --- a/src/main/java/fr/xephi/authme/listener/EntityListener.java +++ b/src/main/java/fr/xephi/authme/listener/EntityListener.java @@ -1,6 +1,7 @@ package fr.xephi.authme.listener; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; @@ -22,18 +23,21 @@ import java.lang.reflect.Method; public class EntityListener implements Listener { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(EntityListener.class); private final ListenerService listenerService; + private Method getShooter; private boolean shooterIsLivingEntity; @Inject EntityListener(ListenerService listenerService) { this.listenerService = listenerService; + try { getShooter = Projectile.class.getDeclaredMethod("getShooter"); shooterIsLivingEntity = getShooter.getReturnType() == LivingEntity.class; } catch (NoSuchMethodException | SecurityException e) { - ConsoleLogger.logException("Cannot load getShooter() method on Projectile class", e); + logger.logException("Cannot load getShooter() method on Projectile class", e); } } @@ -107,7 +111,7 @@ public class EntityListener implements Listener { } shooterRaw = getShooter.invoke(projectile); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - ConsoleLogger.logException("Error getting shooter", e); + logger.logException("Error getting shooter", e); } } else { shooterRaw = projectile.getShooter(); diff --git a/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java b/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java index 390d7ca09..aea422ded 100644 --- a/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java +++ b/src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionsManager; @@ -30,6 +31,8 @@ import java.util.regex.Pattern; * Service for performing various verifications when a player joins. */ public class OnJoinVerifier implements Reloadable { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(OnJoinVerifier.class); @Inject private Settings settings; @@ -139,7 +142,7 @@ public class OnJoinVerifier implements Reloadable { event.allow(); return false; } else { - ConsoleLogger.info("VIP player " + player.getName() + " tried to join, but the server was full"); + logger.info("VIP player " + player.getName() + " tried to join, but the server was full"); event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER)); return true; } diff --git a/src/main/java/fr/xephi/authme/listener/PlayerListener.java b/src/main/java/fr/xephi/authme/listener/PlayerListener.java index a9afc92d8..bd165b7a0 100644 --- a/src/main/java/fr/xephi/authme/listener/PlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/PlayerListener.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.QuickCommandsProtectionManager; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionsManager; @@ -69,6 +70,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.ALLOW_UNAU */ public class PlayerListener implements Listener { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PlayerListener.class); + @Inject private Settings settings; @Inject @@ -289,7 +292,7 @@ public class PlayerListener implements Listener { try { permissionsManager.loadUserData(event.getUniqueId()); } catch (PermissionLoadUserException e) { - ConsoleLogger.logException("Unable to load the permission data of user " + name, e); + logger.logException("Unable to load the permission data of user " + name, e); } // getAddress() sometimes returning null if not yet resolved diff --git a/src/main/java/fr/xephi/authme/listener/ServerListener.java b/src/main/java/fr/xephi/authme/listener/ServerListener.java index 8bebf3613..60b04dbb9 100644 --- a/src/main/java/fr/xephi/authme/listener/ServerListener.java +++ b/src/main/java/fr/xephi/authme/listener/ServerListener.java @@ -1,6 +1,7 @@ package fr.xephi.authme.listener; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.listener.protocollib.ProtocolLibService; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.service.PluginHookService; @@ -14,8 +15,11 @@ import org.bukkit.event.server.PluginEnableEvent; import javax.inject.Inject; /** + * Listener for server events. */ public class ServerListener implements Listener { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ServerListener.class); @Inject private PluginHookService pluginHookService; @@ -40,20 +44,20 @@ public class ServerListener implements Listener { if ("Essentials".equalsIgnoreCase(pluginName)) { pluginHookService.unhookEssentials(); - ConsoleLogger.info("Essentials has been disabled: unhooking"); + logger.info("Essentials has been disabled: unhooking"); } else if ("CMI".equalsIgnoreCase(pluginName)) { pluginHookService.unhookCmi(); spawnLoader.unloadCmiSpawn(); - ConsoleLogger.info("CMI has been disabled: unhooking"); + logger.info("CMI has been disabled: unhooking"); } else if ("Multiverse-Core".equalsIgnoreCase(pluginName)) { pluginHookService.unhookMultiverse(); - ConsoleLogger.info("Multiverse-Core has been disabled: unhooking"); + logger.info("Multiverse-Core has been disabled: unhooking"); } else if ("EssentialsSpawn".equalsIgnoreCase(pluginName)) { spawnLoader.unloadEssentialsSpawn(); - ConsoleLogger.info("EssentialsSpawn has been disabled: unhooking"); + logger.info("EssentialsSpawn has been disabled: unhooking"); } else if ("ProtocolLib".equalsIgnoreCase(pluginName)) { protocolLibService.disable(); - ConsoleLogger.warning("ProtocolLib has been disabled, unhooking packet adapters!"); + logger.warning("ProtocolLib has been disabled, unhooking packet adapters!"); } } diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java b/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java index 88e7f5fb5..5ebaadb46 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/InventoryPacketAdapter.java @@ -28,8 +28,8 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; - import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -48,6 +48,7 @@ class InventoryPacketAdapter extends PacketAdapter { private static final int MAIN_SIZE = 27; private static final int HOTBAR_SIZE = 9; + private final ConsoleLogger logger = ConsoleLoggerFactory.get(InventoryPacketAdapter.class); private final PlayerCache playerCache; private final DataSource dataSource; @@ -106,7 +107,7 @@ class InventoryPacketAdapter extends PacketAdapter { try { protocolManager.sendServerPacket(player, inventoryPacket, false); } catch (InvocationTargetException invocationExc) { - ConsoleLogger.logException("Error during sending blank inventory", invocationExc); + logger.logException("Error during sending blank inventory", invocationExc); } } } diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java index 0804c1966..024077570 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java @@ -6,6 +6,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.SettingsDependent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.RestrictionSettings; @@ -16,6 +17,8 @@ import javax.inject.Inject; @NoFieldScan public class ProtocolLibService implements SettingsDependent { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProtocolLibService.class); + /* Packet Adapters */ private InventoryPacketAdapter inventoryPacketAdapter; private TabCompletePacketAdapter tabCompletePacketAdapter; @@ -26,10 +29,10 @@ public class ProtocolLibService implements SettingsDependent { /* Service */ private boolean isEnabled; - private AuthMe plugin; - private BukkitService bukkitService; - private PlayerCache playerCache; - private DataSource dataSource; + private final AuthMe plugin; + private final BukkitService bukkitService; + private final PlayerCache playerCache; + private final DataSource dataSource; @Inject ProtocolLibService(AuthMe plugin, Settings settings, BukkitService bukkitService, PlayerCache playerCache, @@ -48,11 +51,11 @@ public class ProtocolLibService implements SettingsDependent { // Check if ProtocolLib is enabled on the server. if (!plugin.getServer().getPluginManager().isPluginEnabled("ProtocolLib")) { if (protectInvBeforeLogin) { - ConsoleLogger.warning("WARNING! The protectInventory feature requires ProtocolLib! Disabling it..."); + logger.warning("WARNING! The protectInventory feature requires ProtocolLib! Disabling it..."); } if (denyTabCompleteBeforeLogin) { - ConsoleLogger.warning("WARNING! The denyTabComplete feature requires ProtocolLib! Disabling it..."); + logger.warning("WARNING! The denyTabComplete feature requires ProtocolLib! Disabling it..."); } this.isEnabled = false; diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/TabCompletePacketAdapter.java b/src/main/java/fr/xephi/authme/listener/protocollib/TabCompletePacketAdapter.java index 4d3a24a81..3f0bb3161 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/TabCompletePacketAdapter.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/TabCompletePacketAdapter.java @@ -9,9 +9,11 @@ import com.comphenix.protocol.reflect.FieldAccessException; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerCache; +import fr.xephi.authme.output.ConsoleLoggerFactory; class TabCompletePacketAdapter extends PacketAdapter { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(TabCompletePacketAdapter.class); private final PlayerCache playerCache; TabCompletePacketAdapter(AuthMe plugin, PlayerCache playerCache) { @@ -27,7 +29,7 @@ class TabCompletePacketAdapter extends PacketAdapter { event.setCancelled(true); } } catch (FieldAccessException e) { - ConsoleLogger.logException("Couldn't access field:", e); + logger.logException("Couldn't access field:", e); } } } diff --git a/src/main/java/fr/xephi/authme/mail/EmailService.java b/src/main/java/fr/xephi/authme/mail/EmailService.java index 29891163e..6aef04337 100644 --- a/src/main/java/fr/xephi/authme/mail/EmailService.java +++ b/src/main/java/fr/xephi/authme/mail/EmailService.java @@ -2,6 +2,7 @@ package fr.xephi.authme.mail; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -22,6 +23,8 @@ import java.io.IOException; */ public class EmailService { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailService.class); + private final File dataFolder; private final Settings settings; private final SendMailSsl sendMailSsl; @@ -48,7 +51,7 @@ public class EmailService { */ public boolean sendPasswordMail(String name, String mailAddress, String newPass) { if (!hasAllInformation()) { - ConsoleLogger.warning("Cannot perform email registration: not all email settings are complete"); + logger.warning("Cannot perform email registration: not all email settings are complete"); return false; } @@ -56,7 +59,7 @@ public class EmailService { try { email = sendMailSsl.initializeMail(mailAddress); } catch (EmailException e) { - ConsoleLogger.logException("Failed to create email with the given settings:", e); + logger.logException("Failed to create email with the given settings:", e); return false; } @@ -68,7 +71,7 @@ public class EmailService { file = generatePasswordImage(name, newPass); mailText = embedImageIntoEmailContent(file, email, mailText); } catch (IOException | EmailException e) { - ConsoleLogger.logException( + logger.logException( "Unable to send new password as image for email " + mailAddress + ":", e); } } @@ -88,7 +91,7 @@ public class EmailService { */ public boolean sendVerificationMail(String name, String mailAddress, String code) { if (!hasAllInformation()) { - ConsoleLogger.warning("Cannot send verification email: not all email settings are complete"); + logger.warning("Cannot send verification email: not all email settings are complete"); return false; } @@ -96,7 +99,7 @@ public class EmailService { try { email = sendMailSsl.initializeMail(mailAddress); } catch (EmailException e) { - ConsoleLogger.logException("Failed to create verification email with the given settings:", e); + logger.logException("Failed to create verification email with the given settings:", e); return false; } @@ -118,7 +121,7 @@ public class EmailService { try { htmlEmail = sendMailSsl.initializeMail(email); } catch (EmailException e) { - ConsoleLogger.logException("Failed to create email for recovery code:", e); + logger.logException("Failed to create email for recovery code:", e); return false; } diff --git a/src/main/java/fr/xephi/authme/mail/SendMailSsl.java b/src/main/java/fr/xephi/authme/mail/SendMailSsl.java index 6dff833ff..8c7e1bfff 100644 --- a/src/main/java/fr/xephi/authme/mail/SendMailSsl.java +++ b/src/main/java/fr/xephi/authme/mail/SendMailSsl.java @@ -1,6 +1,7 @@ package fr.xephi.authme.mail; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.EmailSettings; @@ -26,6 +27,8 @@ import static fr.xephi.authme.settings.properties.EmailSettings.MAIL_PASSWORD; */ public class SendMailSsl { + private ConsoleLogger logger = ConsoleLoggerFactory.get(SendMailSsl.class); + @Inject private Settings settings; @@ -96,14 +99,14 @@ public class SendMailSsl { email.setHtmlMsg(content); email.setTextMsg(content); } catch (EmailException e) { - ConsoleLogger.logException("Your email.html config contains an error and cannot be sent:", e); + logger.logException("Your email.html config contains an error and cannot be sent:", e); return false; } try { email.send(); return true; } catch (EmailException e) { - ConsoleLogger.logException("Failed to send a mail to " + email.getToAddresses() + ":", e); + logger.logException("Failed to send a mail to " + email.getToAddresses() + ":", e); return false; } } diff --git a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java index fc140ef16..5e6fc2210 100644 --- a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java @@ -4,6 +4,7 @@ import com.google.common.annotations.VisibleForTesting; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.util.FileUtils; @@ -21,6 +22,8 @@ import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; */ public abstract class AbstractMessageFileHandler implements Reloadable { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AbstractMessageFileHandler.class); + @DataFolder @Inject private File dataFolder; @@ -116,8 +119,7 @@ public abstract class AbstractMessageFileHandler implements Reloadable { if (FileUtils.copyFileFromResource(file, defaultFile)) { return file; } else { - ConsoleLogger.warning("Wanted to copy default messages file '" + defaultFile - + "' from JAR but it didn't exist"); + logger.warning("Wanted to copy default messages file '" + defaultFile + "' from JAR but it didn't exist"); return null; } } diff --git a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java index c0d184814..89dc52245 100644 --- a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java @@ -1,6 +1,7 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.util.FileUtils; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; @@ -16,6 +17,8 @@ import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; */ public class HelpMessagesFileHandler extends AbstractMessageFileHandler { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(HelpMessagesFileHandler.class); + private FileConfiguration defaultConfiguration; @Inject // Trigger injection in the superclass @@ -33,7 +36,7 @@ public class HelpMessagesFileHandler extends AbstractMessageFileHandler { String message = getMessageIfExists(key); if (message == null) { - ConsoleLogger.warning("Error getting message with key '" + key + "'. " + logger.warning("Error getting message with key '" + key + "'. " + "Please update your config file '" + getFilename() + "' or run /authme messages help"); return getDefault(key); } diff --git a/src/main/java/fr/xephi/authme/message/Messages.java b/src/main/java/fr/xephi/authme/message/Messages.java index be887276f..2305de332 100644 --- a/src/main/java/fr/xephi/authme/message/Messages.java +++ b/src/main/java/fr/xephi/authme/message/Messages.java @@ -2,6 +2,8 @@ package fr.xephi.authme.message; import com.google.common.collect.ImmutableMap; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.util.expiring.Duration; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; @@ -37,6 +39,8 @@ public class Messages { .put(TimeUnit.HOURS, MessageKey.HOURS) .put(TimeUnit.DAYS, MessageKey.DAYS).build(); + private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailService.class); + private MessagesFileHandler messagesFileHandler; /* @@ -162,7 +166,7 @@ public class Messages { message = message.replace(tags[i], replacements[i]); } } else { - ConsoleLogger.warning("Invalid number of replacements for message key '" + key + "'"); + logger.warning("Invalid number of replacements for message key '" + key + "'"); } return message; } @@ -185,7 +189,7 @@ public class Messages { message = message.replace(tags[i], replacements[i]); } } else { - ConsoleLogger.warning("Invalid number of replacements for message key '" + key + "'"); + logger.warning("Invalid number of replacements for message key '" + key + "'"); } return message; } diff --git a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java index a047ee145..18b776464 100644 --- a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java @@ -1,6 +1,7 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.updater.MessageUpdater; import javax.inject.Inject; @@ -12,6 +13,8 @@ import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; */ public class MessagesFileHandler extends AbstractMessageFileHandler { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(MessagesFileHandler.class); + @Inject private MessageUpdater messageUpdater; @@ -31,7 +34,7 @@ public class MessagesFileHandler extends AbstractMessageFileHandler { getUserLanguageFile(), createFilePath(language), createFilePath(DEFAULT_LANGUAGE)); if (hasChange) { if (isFromReload) { - ConsoleLogger.warning("Migration after reload attempt"); + logger.warning("Migration after reload attempt"); } else { reloadInternal(true); } diff --git a/src/main/java/fr/xephi/authme/message/updater/JarMessageSource.java b/src/main/java/fr/xephi/authme/message/updater/JarMessageSource.java index f1996f236..73075f4e8 100644 --- a/src/main/java/fr/xephi/authme/message/updater/JarMessageSource.java +++ b/src/main/java/fr/xephi/authme/message/updater/JarMessageSource.java @@ -3,6 +3,7 @@ package fr.xephi.authme.message.updater; import ch.jalu.configme.properties.Property; import ch.jalu.configme.resource.PropertyReader; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.util.FileUtils; import java.io.IOException; @@ -14,6 +15,7 @@ import java.io.InputStream; */ public class JarMessageSource { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(JarMessageSource.class); private final PropertyReader localJarMessages; private final PropertyReader defaultJarMessages; @@ -42,15 +44,15 @@ public class JarMessageSource { return reader == null ? null : reader.getString(path); } - private static MessageMigraterPropertyReader loadJarFile(String jarPath) { + private MessageMigraterPropertyReader loadJarFile(String jarPath) { try (InputStream stream = FileUtils.getResourceFromJar(jarPath)) { if (stream == null) { - ConsoleLogger.debug("Could not load '" + jarPath + "' from JAR"); + logger.debug("Could not load '" + jarPath + "' from JAR"); return null; } return MessageMigraterPropertyReader.loadFromStream(stream); } catch (IOException e) { - ConsoleLogger.logException("Exception while handling JAR path '" + jarPath + "'", e); + logger.logException("Exception while handling JAR path '" + jarPath + "'", e); } return null; } diff --git a/src/main/java/fr/xephi/authme/message/updater/MessageUpdater.java b/src/main/java/fr/xephi/authme/message/updater/MessageUpdater.java index 895764f2b..a4f9767f8 100644 --- a/src/main/java/fr/xephi/authme/message/updater/MessageUpdater.java +++ b/src/main/java/fr/xephi/authme/message/updater/MessageUpdater.java @@ -9,6 +9,7 @@ import ch.jalu.configme.resource.PropertyResource; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.util.FileUtils; @@ -29,6 +30,8 @@ import static java.util.Collections.singletonList; */ public class MessageUpdater { + private ConsoleLogger logger = ConsoleLoggerFactory.get(MessageUpdater.class); + /** * Applies any necessary migrations to the user's messages file and saves it if it has been modified. * @@ -68,7 +71,7 @@ public class MessageUpdater { backupMessagesFile(userFile); userResource.exportProperties(configurationData); - ConsoleLogger.debug("Successfully saved {0}", userFile); + logger.debug("Successfully saved {0}", userFile); return true; } return false; @@ -91,7 +94,7 @@ public class MessageUpdater { private boolean migrateOldKeys(PropertyReader propertyReader, MessageKeyConfigurationData configurationData) { boolean hasChange = OldMessageKeysMigrater.migrateOldPaths(propertyReader, configurationData); if (hasChange) { - ConsoleLogger.info("Old keys have been moved to the new ones in your messages_xx.yml file"); + logger.info("Old keys have been moved to the new ones in your messages_xx.yml file"); } return hasChange; } @@ -106,7 +109,7 @@ public class MessageUpdater { } } if (!addedKeys.isEmpty()) { - ConsoleLogger.info( + logger.info( "Added " + addedKeys.size() + " missing keys to your messages_xx.yml file: " + addedKeys); return true; } diff --git a/src/main/java/fr/xephi/authme/output/ConsoleLoggerFactory.java b/src/main/java/fr/xephi/authme/output/ConsoleLoggerFactory.java new file mode 100644 index 000000000..5fee9273a --- /dev/null +++ b/src/main/java/fr/xephi/authme/output/ConsoleLoggerFactory.java @@ -0,0 +1,51 @@ +package fr.xephi.authme.output; + +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.Settings; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Creates and keeps track of {@link ConsoleLogger} instances. + */ +public final class ConsoleLoggerFactory { + + private static final Map consoleLoggers = new ConcurrentHashMap<>(); + private static Settings settings; + + private ConsoleLoggerFactory() { + } + + /** + * Creates or returns the already existing logger associated with the given class. + * + * @param owningClass the class whose logger should be retrieved + * @return logger for the given class + */ + public static ConsoleLogger get(Class owningClass) { + String name = owningClass.getCanonicalName(); + return consoleLoggers.computeIfAbsent(name, ConsoleLoggerFactory::createLogger); + } + + /** + * Sets up all loggers according to the properties returned by the settings instance. + * + * @param settings the settings instance + */ + public static void reloadSettings(Settings settings) { + ConsoleLoggerFactory.settings = settings; + ConsoleLogger.initializeSharedSettings(settings); + + consoleLoggers.values() + .forEach(logger -> logger.initializeSettings(settings)); + } + + private static ConsoleLogger createLogger(String name) { + ConsoleLogger logger = new ConsoleLogger(name); + if (settings != null) { + logger.initializeSettings(settings); + } + return logger; + } +} diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java index b99b66c5e..e016b2b08 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java @@ -3,6 +3,7 @@ package fr.xephi.authme.permission; import com.google.common.annotations.VisibleForTesting; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.listener.JoiningPlayer; import fr.xephi.authme.permission.handlers.LuckPermsHandler; import fr.xephi.authme.permission.handlers.PermissionHandler; @@ -40,6 +41,7 @@ import java.util.UUID; */ public class PermissionsManager implements Reloadable { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PermissionsManager.class); private final Server server; private final PluginManager pluginManager; private final Settings settings; @@ -78,11 +80,11 @@ public class PermissionsManager implements Reloadable { if (handler != null) { // Show a success message and return this.handler = handler; - ConsoleLogger.info("Hooked into " + PermissionsSystemType.VAULT.getDisplayName() + "!"); + logger.info("Hooked into " + PermissionsSystemType.VAULT.getDisplayName() + "!"); return; } } catch (PermissionHandlerException e) { - ConsoleLogger.logException("Failed to create Vault hook (forced):", e); + logger.logException("Failed to create Vault hook (forced):", e); } } else { // Loop through all the available permissions system types @@ -92,18 +94,18 @@ public class PermissionsManager implements Reloadable { if (handler != null) { // Show a success message and return this.handler = handler; - ConsoleLogger.info("Hooked into " + type.getDisplayName() + "!"); + logger.info("Hooked into " + type.getDisplayName() + "!"); return; } } catch (Exception ex) { // An error occurred, show a warning message - ConsoleLogger.logException("Error while hooking into " + type.getDisplayName(), ex); + logger.logException("Error while hooking into " + type.getDisplayName(), ex); } } } // No recognized permissions system found, show a message and return - ConsoleLogger.info("No supported permissions system found! Permissions are disabled!"); + logger.info("No supported permissions system found! Permissions are disabled!"); } /** @@ -125,7 +127,7 @@ public class PermissionsManager implements Reloadable { // Make sure the plugin is enabled before hooking if (!plugin.isEnabled()) { - ConsoleLogger.info("Not hooking into " + type.getDisplayName() + " because it's disabled!"); + logger.info("Not hooking into " + type.getDisplayName() + " because it's disabled!"); return null; } @@ -151,7 +153,7 @@ public class PermissionsManager implements Reloadable { this.handler = null; // Print a status message to the console - ConsoleLogger.info("Unhooked from Permissions!"); + logger.info("Unhooked from Permissions!"); } /** @@ -174,7 +176,7 @@ public class PermissionsManager implements Reloadable { public void onPluginEnable(String pluginName) { // Check if any known permissions system is enabling if (PermissionsSystemType.isPermissionSystem(pluginName)) { - ConsoleLogger.info(pluginName + " plugin enabled, dynamically updating permissions hooks!"); + logger.info(pluginName + " plugin enabled, dynamically updating permissions hooks!"); setup(); } } @@ -187,7 +189,7 @@ public class PermissionsManager implements Reloadable { public void onPluginDisable(String pluginName) { // Check if any known permission system is being disabled if (PermissionsSystemType.isPermissionSystem(pluginName)) { - ConsoleLogger.info(pluginName + " plugin disabled, updating hooks!"); + logger.info(pluginName + " plugin disabled, updating hooks!"); setup(); } } @@ -454,7 +456,7 @@ public class PermissionsManager implements Reloadable { try { loadUserData(offlinePlayer.getUniqueId()); } catch (PermissionLoadUserException e) { - ConsoleLogger.logException("Unable to load the permission data of user " + offlinePlayer.getName(), e); + logger.logException("Unable to load the permission data of user " + offlinePlayer.getName(), e); return false; } return true; diff --git a/src/main/java/fr/xephi/authme/permission/handlers/LuckPermsHandler.java b/src/main/java/fr/xephi/authme/permission/handlers/LuckPermsHandler.java index 5cc3ae0f5..cc11a12c3 100644 --- a/src/main/java/fr/xephi/authme/permission/handlers/LuckPermsHandler.java +++ b/src/main/java/fr/xephi/authme/permission/handlers/LuckPermsHandler.java @@ -1,6 +1,7 @@ package fr.xephi.authme.permission.handlers; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionNode; import fr.xephi.authme.permission.PermissionsSystemType; import me.lucko.luckperms.LuckPerms; @@ -31,6 +32,7 @@ import java.util.stream.Collectors; */ public class LuckPermsHandler implements PermissionHandler { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(LuckPermsHandler.class); private LuckPermsApi luckPermsApi; public LuckPermsHandler() throws PermissionHandlerException { @@ -79,7 +81,7 @@ public class LuckPermsHandler implements PermissionHandler { public boolean hasPermissionOffline(String name, PermissionNode node) { User user = luckPermsApi.getUser(name); if (user == null) { - ConsoleLogger.warning("LuckPermsHandler: tried to check permission for offline user " + logger.warning("LuckPermsHandler: tried to check permission for offline user " + name + " but it isn't loaded!"); return false; } @@ -96,7 +98,7 @@ public class LuckPermsHandler implements PermissionHandler { public boolean isInGroup(OfflinePlayer player, String group) { User user = luckPermsApi.getUser(player.getName()); if (user == null) { - ConsoleLogger.warning("LuckPermsHandler: tried to check group for offline user " + logger.warning("LuckPermsHandler: tried to check group for offline user " + player.getName() + " but it isn't loaded!"); return false; } @@ -112,7 +114,7 @@ public class LuckPermsHandler implements PermissionHandler { public boolean removeFromGroup(OfflinePlayer player, String group) { User user = luckPermsApi.getUser(player.getName()); if (user == null) { - ConsoleLogger.warning("LuckPermsHandler: tried to remove group for offline user " + logger.warning("LuckPermsHandler: tried to remove group for offline user " + player.getName() + " but it isn't loaded!"); return false; } @@ -133,7 +135,7 @@ public class LuckPermsHandler implements PermissionHandler { public boolean setGroup(OfflinePlayer player, String group) { User user = luckPermsApi.getUser(player.getName()); if (user == null) { - ConsoleLogger.warning("LuckPermsHandler: tried to set group for offline user " + logger.warning("LuckPermsHandler: tried to set group for offline user " + player.getName() + " but it isn't loaded!"); return false; } @@ -157,7 +159,7 @@ public class LuckPermsHandler implements PermissionHandler { public List getGroups(OfflinePlayer player) { User user = luckPermsApi.getUser(player.getName()); if (user == null) { - ConsoleLogger.warning("LuckPermsHandler: tried to get groups for offline user " + logger.warning("LuckPermsHandler: tried to get groups for offline user " + player.getName() + " but it isn't loaded!"); return Collections.emptyList(); } diff --git a/src/main/java/fr/xephi/authme/process/changepassword/AsyncChangePassword.java b/src/main/java/fr/xephi/authme/process/changepassword/AsyncChangePassword.java index 1caaa5c68..11495c54c 100644 --- a/src/main/java/fr/xephi/authme/process/changepassword/AsyncChangePassword.java +++ b/src/main/java/fr/xephi/authme/process/changepassword/AsyncChangePassword.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.security.PasswordSecurity; @@ -17,6 +18,8 @@ import org.bukkit.entity.Player; import javax.inject.Inject; public class AsyncChangePassword implements AsynchronousProcess { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsyncChangePassword.class); @Inject private DataSource dataSource; @@ -58,7 +61,7 @@ public class AsyncChangePassword implements AsynchronousProcess { playerCache.updatePlayer(auth); commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS); - ConsoleLogger.info(player.getName() + " changed his password"); + logger.info(player.getName() + " changed his password"); } else { commonService.send(player, MessageKey.WRONG_PASSWORD); } @@ -75,7 +78,7 @@ public class AsyncChangePassword implements AsynchronousProcess { final String lowerCaseName = playerName.toLowerCase(); if (!(playerCache.isAuthenticated(lowerCaseName) || dataSource.isAuthAvailable(lowerCaseName))) { if (sender == null) { - ConsoleLogger.warning("Tried to change password for user " + lowerCaseName + " but it doesn't exist!"); + logger.warning("Tried to change password for user " + lowerCaseName + " but it doesn't exist!"); } else { commonService.send(sender, MessageKey.UNKNOWN_USER); } @@ -87,15 +90,15 @@ public class AsyncChangePassword implements AsynchronousProcess { bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_PASSWORD, lowerCaseName); if (sender != null) { commonService.send(sender, MessageKey.PASSWORD_CHANGED_SUCCESS); - ConsoleLogger.info(sender.getName() + " changed password of " + lowerCaseName); + logger.info(sender.getName() + " changed password of " + lowerCaseName); } else { - ConsoleLogger.info("Changed password of " + lowerCaseName); + logger.info("Changed password of " + lowerCaseName); } } else { if (sender != null) { commonService.send(sender, MessageKey.ERROR); } - ConsoleLogger.warning("An error occurred while changing password for user " + lowerCaseName + "!"); + logger.warning("An error occurred while changing password for user " + lowerCaseName + "!"); } } } diff --git a/src/main/java/fr/xephi/authme/process/email/AsyncAddEmail.java b/src/main/java/fr/xephi/authme/process/email/AsyncAddEmail.java index 1896bfd3b..16ad41811 100644 --- a/src/main/java/fr/xephi/authme/process/email/AsyncAddEmail.java +++ b/src/main/java/fr/xephi/authme/process/email/AsyncAddEmail.java @@ -5,6 +5,7 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.EmailChangedEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.service.BukkitService; @@ -22,6 +23,8 @@ import javax.inject.Inject; */ public class AsyncAddEmail implements AsynchronousProcess { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsyncAddEmail.class); + @Inject private CommonService service; @@ -65,7 +68,7 @@ public class AsyncAddEmail implements AsynchronousProcess { EmailChangedEvent event = bukkitService.createAndCallEvent(isAsync -> new EmailChangedEvent(player, null, email, isAsync)); if (event.isCancelled()) { - ConsoleLogger.info("Could not add email to player '" + player + "' – event was cancelled"); + logger.info("Could not add email to player '" + player + "' – event was cancelled"); service.send(player, MessageKey.EMAIL_ADD_NOT_ALLOWED); return; } @@ -75,7 +78,7 @@ public class AsyncAddEmail implements AsynchronousProcess { bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_EMAIL, playerName); service.send(player, MessageKey.EMAIL_ADDED_SUCCESS); } else { - ConsoleLogger.warning("Could not save email for player '" + player + "'"); + logger.warning("Could not save email for player '" + player + "'"); service.send(player, MessageKey.ERROR); } } diff --git a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java index df141c6cd..4e00d4869 100644 --- a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java +++ b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java @@ -5,6 +5,7 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.EmailChangedEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.service.BukkitService; @@ -20,6 +21,8 @@ import javax.inject.Inject; * Async task for changing the email. */ public class AsyncChangeEmail implements AsynchronousProcess { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsyncChangeEmail.class); @Inject private CommonService service; @@ -83,7 +86,7 @@ public class AsyncChangeEmail implements AsynchronousProcess { EmailChangedEvent event = bukkitService.createAndCallEvent(isAsync -> new EmailChangedEvent(player, oldEmail, newEmail, isAsync)); if (event.isCancelled()) { - ConsoleLogger.info("Could not change email for player '" + player + "' – event was cancelled"); + logger.info("Could not change email for player '" + player + "' – event was cancelled"); service.send(player, MessageKey.EMAIL_CHANGE_NOT_ALLOWED); return; } diff --git a/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java b/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java index 9924eef8e..7544e4c29 100644 --- a/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java +++ b/src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.ProtectInventoryEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.process.AsynchronousProcess; @@ -35,6 +36,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.PROTECT_IN * Asynchronous process for when a player joins. */ public class AsynchronousJoin implements AsynchronousProcess { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsynchronousJoin.class); @Inject private Server server; @@ -112,7 +115,7 @@ public class AsynchronousJoin implements AsynchronousProcess { isAsync -> new ProtectInventoryEvent(player, isAsync)); if (ev.isCancelled()) { player.updateInventory(); - ConsoleLogger.fine("ProtectInventoryEvent has been cancelled for " + player.getName() + "..."); + logger.fine("ProtectInventoryEvent has been cancelled for " + player.getName() + "..."); } } diff --git a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java index 2441ea283..56d5236de 100644 --- a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java @@ -12,6 +12,7 @@ import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent; import fr.xephi.authme.events.FailedLoginEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.permission.AdminPermission; @@ -44,6 +45,8 @@ import java.util.List; * Asynchronous task for a player login. */ public class AsynchronousLogin implements AsynchronousProcess { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsynchronousLogin.class); @Inject private DataSource dataSource; @@ -199,7 +202,7 @@ public class AsynchronousLogin implements AsynchronousProcess { * @param ip the ip address of the player */ private void handleWrongPassword(Player player, PlayerAuth auth, String ip) { - ConsoleLogger.fine(player.getName() + " used the wrong password"); + logger.fine(player.getName() + " used the wrong password"); bukkitService.createAndCallEvent(isAsync -> new FailedLoginEvent(player, isAsync)); if (tempbanManager.shouldTempban(ip)) { @@ -256,7 +259,7 @@ public class AsynchronousLogin implements AsynchronousProcess { service.send(player, MessageKey.ADD_EMAIL_MESSAGE); } - ConsoleLogger.fine(player.getName() + " logged in!"); + logger.fine(player.getName() + " logged in!"); // makes player loggedin playerCache.updatePlayer(auth); @@ -270,7 +273,7 @@ public class AsynchronousLogin implements AsynchronousProcess { // processed in other order. syncProcessManager.processSyncPlayerLogin(player, isFirstLogin, auths); } else { - ConsoleLogger.warning("Player '" + player.getName() + "' wasn't online during login process, aborted..."); + logger.warning("Player '" + player.getName() + "' wasn't online during login process, aborted..."); } } @@ -297,8 +300,8 @@ public class AsynchronousLogin implements AsynchronousProcess { String message = ChatColor.GRAY + String.join(", ", formattedNames) + "."; - ConsoleLogger.fine("The user " + player.getName() + " has " + auths.size() + " accounts:"); - ConsoleLogger.fine(message); + logger.fine("The user " + player.getName() + " has " + auths.size() + " accounts:"); + logger.fine(message); for (Player onlinePlayer : bukkitService.getOnlinePlayers()) { if (onlinePlayer.getName().equalsIgnoreCase(player.getName()) diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java index cecf023c5..46fd7fefc 100644 --- a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java @@ -3,6 +3,7 @@ package fr.xephi.authme.process.logout; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.events.LogoutEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.listener.protocollib.ProtocolLibService; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.SynchronousProcess; @@ -23,6 +24,8 @@ import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND; public class ProcessSyncPlayerLogout implements SynchronousProcess { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProcessSyncPlayerLogout.class); + @Inject private CommonService service; @@ -61,7 +64,7 @@ public class ProcessSyncPlayerLogout implements SynchronousProcess { bukkitService.callEvent(new LogoutEvent(player)); service.send(player, MessageKey.LOGOUT_SUCCESS); - ConsoleLogger.info(player.getName() + " logged out"); + logger.info(player.getName() + " logged out"); } private void applyLogoutEffect(Player player) { diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java index e740a0ded..486910b2d 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java @@ -3,6 +3,7 @@ package fr.xephi.authme.process.register; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.events.RegisterEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.SynchronousProcess; import fr.xephi.authme.service.BukkitService; @@ -16,6 +17,8 @@ import javax.inject.Inject; * Performs synchronous tasks after a successful {@link RegistrationType#EMAIL email registration}. */ public class ProcessSyncEmailRegister implements SynchronousProcess { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProcessSyncEmailRegister.class); @Inject private BukkitService bukkitService; @@ -40,7 +43,7 @@ public class ProcessSyncEmailRegister implements SynchronousProcess { player.saveData(); bukkitService.callEvent(new RegisterEvent(player)); - ConsoleLogger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player)); + logger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player)); } } diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java index dc8aa136f..5cf971edc 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java @@ -3,6 +3,7 @@ package fr.xephi.authme.process.register; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.events.RegisterEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.SynchronousProcess; import fr.xephi.authme.service.BukkitService; @@ -21,6 +22,8 @@ import javax.inject.Inject; */ public class ProcessSyncPasswordRegister implements SynchronousProcess { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProcessSyncPasswordRegister.class); + @Inject private BungeeSender bungeeSender; @@ -66,7 +69,7 @@ public class ProcessSyncPasswordRegister implements SynchronousProcess { player.saveData(); bukkitService.callEvent(new RegisterEvent(player)); - ConsoleLogger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player)); + logger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player)); // Kick Player after Registration is enabled, kick the player if (service.getProperty(RegistrationSettings.FORCE_KICK_AFTER_REGISTER)) { diff --git a/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java b/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java index 7291be685..808b1cdbd 100644 --- a/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java +++ b/src/main/java/fr/xephi/authme/process/unregister/AsynchronousUnregister.java @@ -7,6 +7,7 @@ import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.UnregisterByAdminEvent; import fr.xephi.authme.events.UnregisterByPlayerEvent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.security.PasswordSecurity; @@ -28,6 +29,8 @@ import javax.inject.Inject; import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND; public class AsynchronousUnregister implements AsynchronousProcess { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsynchronousUnregister.class); @Inject private DataSource dataSource; @@ -72,7 +75,7 @@ public class AsynchronousUnregister implements AsynchronousProcess { if (passwordSecurity.comparePassword(password, cachedAuth.getPassword(), name)) { if (dataSource.removeAuth(name)) { performPostUnregisterActions(name, player); - ConsoleLogger.info(name + " unregistered himself"); + logger.info(name + " unregistered himself"); bukkitService.createAndCallEvent(isAsync -> new UnregisterByPlayerEvent(player, isAsync)); } else { service.send(player, MessageKey.ERROR); @@ -97,9 +100,9 @@ public class AsynchronousUnregister implements AsynchronousProcess { bukkitService.createAndCallEvent(isAsync -> new UnregisterByAdminEvent(player, name, isAsync, initiator)); if (initiator == null) { - ConsoleLogger.info(name + " was unregistered"); + logger.info(name + " was unregistered"); } else { - ConsoleLogger.info(name + " was unregistered by " + initiator.getName()); + logger.info(name + " was unregistered by " + initiator.getName()); service.send(initiator, MessageKey.UNREGISTERED_SUCCESS); } } else if (initiator != null) { diff --git a/src/main/java/fr/xephi/authme/security/crypts/Argon2.java b/src/main/java/fr/xephi/authme/security/crypts/Argon2.java index 27b89027c..e002886ba 100644 --- a/src/main/java/fr/xephi/authme/security/crypts/Argon2.java +++ b/src/main/java/fr/xephi/authme/security/crypts/Argon2.java @@ -3,6 +3,7 @@ package fr.xephi.authme.security.crypts; import de.mkammerer.argon2.Argon2Constants; import de.mkammerer.argon2.Argon2Factory; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.crypts.description.HasSalt; import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.SaltType; @@ -14,6 +15,8 @@ import fr.xephi.authme.security.crypts.description.Usage; // and isn't exposed to the outside, so we treat it as an unsalted implementation public class Argon2 extends UnsaltedMethod { + private static ConsoleLogger logger = ConsoleLoggerFactory.get(Argon2.class); + private de.mkammerer.argon2.Argon2 argon2; public Argon2() { @@ -30,7 +33,7 @@ public class Argon2 extends UnsaltedMethod { System.loadLibrary("argon2"); return true; } catch (UnsatisfiedLinkError e) { - ConsoleLogger.logException( + logger.logException( "Cannot find argon2 library: https://github.com/AuthMe/AuthMeReloaded/wiki/Argon2-as-Password-Hash", e); } return false; diff --git a/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2.java b/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2.java index d9695abc5..c79647ab7 100644 --- a/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2.java +++ b/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2.java @@ -5,6 +5,7 @@ import de.rtner.misc.BinTools; import de.rtner.security.auth.spi.PBKDF2Engine; import de.rtner.security.auth.spi.PBKDF2Parameters; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.Usage; import fr.xephi.authme.settings.Settings; @@ -16,6 +17,7 @@ import javax.inject.Inject; public class Pbkdf2 extends HexSaltedMethod { private static final int DEFAULT_ROUNDS = 10_000; + private final ConsoleLogger logger = ConsoleLoggerFactory.get(Pbkdf2.class); private int numberOfRounds; @Inject @@ -41,7 +43,7 @@ public class Pbkdf2 extends HexSaltedMethod { } Integer iterations = Ints.tryParse(line[1]); if (iterations == null) { - ConsoleLogger.warning("Cannot read number of rounds for Pbkdf2: '" + line[1] + "'"); + logger.warning("Cannot read number of rounds for Pbkdf2: '" + line[1] + "'"); return false; } diff --git a/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2Django.java b/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2Django.java index e32930db1..a0877cd4b 100644 --- a/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2Django.java +++ b/src/main/java/fr/xephi/authme/security/crypts/Pbkdf2Django.java @@ -4,6 +4,7 @@ import com.google.common.primitives.Ints; import de.rtner.security.auth.spi.PBKDF2Engine; import de.rtner.security.auth.spi.PBKDF2Parameters; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.crypts.description.AsciiRestricted; import java.util.Base64; @@ -12,6 +13,7 @@ import java.util.Base64; public class Pbkdf2Django extends HexSaltedMethod { private static final int DEFAULT_ITERATIONS = 24000; + private final ConsoleLogger logger = ConsoleLoggerFactory.get(Pbkdf2Django.class); @Override public String computeHash(String password, String salt, String name) { @@ -30,7 +32,7 @@ public class Pbkdf2Django extends HexSaltedMethod { } Integer iterations = Ints.tryParse(line[1]); if (iterations == null) { - ConsoleLogger.warning("Cannot read number of rounds for Pbkdf2Django: '" + line[1] + "'"); + logger.warning("Cannot read number of rounds for Pbkdf2Django: '" + line[1] + "'"); return false; } diff --git a/src/main/java/fr/xephi/authme/security/crypts/TwoFactor.java b/src/main/java/fr/xephi/authme/security/crypts/TwoFactor.java index 1e1f36a15..67b22c780 100644 --- a/src/main/java/fr/xephi/authme/security/crypts/TwoFactor.java +++ b/src/main/java/fr/xephi/authme/security/crypts/TwoFactor.java @@ -5,6 +5,7 @@ import com.google.common.io.BaseEncoding; import com.google.common.net.UrlEscapers; import com.google.common.primitives.Ints; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.crypts.description.HasSalt; import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.SaltType; @@ -34,6 +35,8 @@ public class TwoFactor extends UnsaltedMethod { private static final int TIME_PRECISION = 3; private static final String CRYPTO_ALGO = "HmacSHA1"; + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(TwoFactor.class); /** * Creates a link to a QR barcode with the provided secret. @@ -71,7 +74,7 @@ public class TwoFactor extends UnsaltedMethod { try { return checkPassword(hashedPassword.getHash(), password); } catch (Exception e) { - ConsoleLogger.logException("Failed to verify two auth code:", e); + logger.logException("Failed to verify two auth code:", e); return false; } } diff --git a/src/main/java/fr/xephi/authme/security/crypts/Wbb4.java b/src/main/java/fr/xephi/authme/security/crypts/Wbb4.java index 9eeec4426..a55a2d48b 100644 --- a/src/main/java/fr/xephi/authme/security/crypts/Wbb4.java +++ b/src/main/java/fr/xephi/authme/security/crypts/Wbb4.java @@ -3,6 +3,7 @@ package fr.xephi.authme.security.crypts; import at.favre.lib.crypto.bcrypt.BCrypt; import at.favre.lib.crypto.bcrypt.IllegalBCryptFormatException; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.crypts.description.HasSalt; import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.SaltType; @@ -19,6 +20,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; @HasSalt(value = SaltType.TEXT, length = SALT_LENGTH_ENCODED) public class Wbb4 implements EncryptionMethod { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(Wbb4.class); private BCryptHasher bCryptHasher = new BCryptHasher(BCrypt.Version.VERSION_2A, 8); private SecureRandom random = new SecureRandom(); @@ -44,7 +46,7 @@ public class Wbb4 implements EncryptionMethod { String computedHash = hashInternal(password, salt); return isEqual(hashedPassword.getHash(), computedHash); } catch (IllegalBCryptFormatException | IllegalArgumentException e) { - ConsoleLogger.logException("Invalid WBB4 hash:", e); + logger.logException("Invalid WBB4 hash:", e); } return false; } diff --git a/src/main/java/fr/xephi/authme/service/BackupService.java b/src/main/java/fr/xephi/authme/service/BackupService.java index 6d60226e7..2e72a7b0c 100644 --- a/src/main/java/fr/xephi/authme/service/BackupService.java +++ b/src/main/java/fr/xephi/authme/service/BackupService.java @@ -3,6 +3,8 @@ package fr.xephi.authme.service; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSourceType; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.BackupSettings; import fr.xephi.authme.settings.properties.DatabaseSettings; @@ -25,10 +27,13 @@ import static fr.xephi.authme.util.Utils.logAndSendWarning; */ public class BackupService { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailService.class); + private final File dataFolder; private final File backupFolder; private final Settings settings; + /** * Constructor. * @@ -89,7 +94,7 @@ public class BackupService { String dbName = settings.getProperty(DatabaseSettings.MYSQL_DATABASE); return performFileBackup(dbName + ".db"); default: - ConsoleLogger.warning("Unknown data source type '" + dataSourceType + "' for backup"); + logger.warning("Unknown data source type '" + dataSourceType + "' for backup"); } return false; @@ -114,13 +119,13 @@ public class BackupService { Process runtimeProcess = Runtime.getRuntime().exec(backupCommand); int processComplete = runtimeProcess.waitFor(); if (processComplete == 0) { - ConsoleLogger.info("Backup created successfully. (Using Windows = " + isUsingWindows + ")"); + logger.info("Backup created successfully. (Using Windows = " + isUsingWindows + ")"); return true; } else { - ConsoleLogger.warning("Could not create the backup! (Using Windows = " + isUsingWindows + ")"); + logger.warning("Could not create the backup! (Using Windows = " + isUsingWindows + ")"); } } catch (IOException | InterruptedException e) { - ConsoleLogger.logException("Error during backup (using Windows = " + isUsingWindows + "):", e); + logger.logException("Error during backup (using Windows = " + isUsingWindows + "):", e); } return false; } @@ -133,7 +138,7 @@ public class BackupService { copy(new File(dataFolder, filename), backupFile); return true; } catch (IOException ex) { - ConsoleLogger.logException("Encountered an error during file backup:", ex); + logger.logException("Encountered an error during file backup:", ex); } return false; } @@ -145,13 +150,13 @@ public class BackupService { * @param windowsPath The path to check * @return True if the path is correct, false if it is incorrect or the OS is not Windows */ - private static boolean useWindowsCommand(String windowsPath) { + private boolean useWindowsCommand(String windowsPath) { String isWin = System.getProperty("os.name").toLowerCase(); if (isWin.contains("win")) { if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) { return true; } else { - ConsoleLogger.warning("Mysql Windows Path is incorrect. Please check it"); + logger.warning("Mysql Windows Path is incorrect. Please check it"); return false; } } diff --git a/src/main/java/fr/xephi/authme/service/GeoIpService.java b/src/main/java/fr/xephi/authme/service/GeoIpService.java index 804b82a15..ef4f003f2 100644 --- a/src/main/java/fr/xephi/authme/service/GeoIpService.java +++ b/src/main/java/fr/xephi/authme/service/GeoIpService.java @@ -15,6 +15,7 @@ import com.maxmind.db.model.Country; import com.maxmind.db.model.CountryResponse; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.InternetProtocolUtils; @@ -61,6 +62,7 @@ public class GeoIpService { // but every HTTP implementation have to support RFC 1023 private static final String TIME_RFC_1023 = "EEE, dd-MMM-yy HH:mm:ss zzz"; + private final ConsoleLogger logger = ConsoleLoggerFactory.get(GeoIpService.class); private final Path dataFile; private final BukkitService bukkitService; @@ -109,10 +111,10 @@ public class GeoIpService { // don't fire the update task - we are up to date return true; } else { - ConsoleLogger.debug("GEO IP database is older than " + UPDATE_INTERVAL_DAYS + " Days"); + logger.debug("GEO IP database is older than " + UPDATE_INTERVAL_DAYS + " Days"); } } catch (IOException ioEx) { - ConsoleLogger.logException("Failed to load GeoLiteAPI database", ioEx); + logger.logException("Failed to load GeoLiteAPI database", ioEx); return false; } } @@ -130,7 +132,7 @@ public class GeoIpService { * Tries to update the database by downloading a new version from the website. */ private void updateDatabase() { - ConsoleLogger.info("Downloading GEO IP database, because the old database is older than " + logger.info("Downloading GEO IP database, because the old database is older than " + UPDATE_INTERVAL_DAYS + " days or doesn't exist"); Path tempFile = null; @@ -138,7 +140,7 @@ public class GeoIpService { // download database to temporarily location tempFile = Files.createTempFile(ARCHIVE_FILE, null); if (!downloadDatabaseArchive(tempFile)) { - ConsoleLogger.info("There is no newer GEO IP database uploaded to MaxMind. Using the old one for now."); + logger.info("There is no newer GEO IP database uploaded to MaxMind. Using the old one for now."); startReading(); return; } @@ -151,10 +153,10 @@ public class GeoIpService { extractDatabase(tempFile, dataFile); //only set this value to false on success otherwise errors could lead to endless download triggers - ConsoleLogger.info("Successfully downloaded new GEO IP database to " + dataFile); + logger.info("Successfully downloaded new GEO IP database to " + dataFile); startReading(); } catch (IOException ioEx) { - ConsoleLogger.logException("Could not download GeoLiteAPI database", ioEx); + logger.logException("Could not download GeoLiteAPI database", ioEx); } finally { // clean up if (tempFile != null) { @@ -165,7 +167,7 @@ public class GeoIpService { private void startReading() throws IOException { databaseReader = new Reader(dataFile.toFile(), FileMode.MEMORY, new CHMCache()); - ConsoleLogger.info(LICENSE); + logger.info(LICENSE); // clear downloading flag, because we now have working reader instance downloading = false; @@ -315,7 +317,7 @@ public class GeoIpService { // Ignore invalid ip addresses // Legacy GEO IP Database returned a unknown country object with Country-Code: '--' and Country-Name: 'N/A' } catch (IOException ioEx) { - ConsoleLogger.logException("Cannot lookup country for " + ip + " at GEO IP database", ioEx); + logger.logException("Cannot lookup country for " + ip + " at GEO IP database", ioEx); } return Optional.empty(); diff --git a/src/main/java/fr/xephi/authme/service/MigrationService.java b/src/main/java/fr/xephi/authme/service/MigrationService.java index 338ef51a1..de8d88a78 100644 --- a/src/main/java/fr/xephi/authme/service/MigrationService.java +++ b/src/main/java/fr/xephi/authme/service/MigrationService.java @@ -3,6 +3,7 @@ package fr.xephi.authme.service; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.Sha256; @@ -15,6 +16,8 @@ import java.util.List; * Migrations to perform during the initialization of AuthMe. */ public final class MigrationService { + + private static ConsoleLogger logger = ConsoleLoggerFactory.get(MigrationService.class); private MigrationService() { } @@ -29,14 +32,14 @@ public final class MigrationService { public static void changePlainTextToSha256(Settings settings, DataSource dataSource, Sha256 authmeSha256) { if (HashAlgorithm.PLAINTEXT == settings.getProperty(SecuritySettings.PASSWORD_HASH)) { - ConsoleLogger.warning("Your HashAlgorithm has been detected as plaintext and is now deprecated;" + logger.warning("Your HashAlgorithm has been detected as plaintext and is now deprecated;" + " it will be changed and hashed now to the AuthMe default hashing method"); - ConsoleLogger.warning("Don't stop your server; wait for the conversion to have been completed!"); + logger.warning("Don't stop your server; wait for the conversion to have been completed!"); List allAuths = dataSource.getAllAuths(); for (PlayerAuth auth : allAuths) { String hash = auth.getPassword().getHash(); if (hash.startsWith("$SHA$")) { - ConsoleLogger.warning("Skipping conversion for " + auth.getNickname() + "; detected SHA hash"); + logger.warning("Skipping conversion for " + auth.getNickname() + "; detected SHA hash"); } else { HashedPassword hashedPassword = authmeSha256.computeHash(hash, auth.getNickname()); auth.setPassword(hashedPassword); @@ -45,7 +48,7 @@ public final class MigrationService { } settings.setProperty(SecuritySettings.PASSWORD_HASH, HashAlgorithm.SHA256); settings.save(); - ConsoleLogger.info("Migrated " + allAuths.size() + " accounts from plaintext to SHA256"); + logger.info("Migrated " + allAuths.size() + " accounts from plaintext to SHA256"); } } } diff --git a/src/main/java/fr/xephi/authme/service/PasswordRecoveryService.java b/src/main/java/fr/xephi/authme/service/PasswordRecoveryService.java index 200aa11c7..20a78d7f4 100644 --- a/src/main/java/fr/xephi/authme/service/PasswordRecoveryService.java +++ b/src/main/java/fr/xephi/authme/service/PasswordRecoveryService.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.HasCleanup; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; @@ -27,6 +28,8 @@ import static fr.xephi.authme.settings.properties.EmailSettings.RECOVERY_PASSWOR * Manager for password recovery. */ public class PasswordRecoveryService implements Reloadable, HasCleanup { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PasswordRecoveryService.class); @Inject private CommonService commonService; @@ -95,7 +98,7 @@ public class PasswordRecoveryService implements Reloadable, HasCleanup { String thePass = RandomStringUtils.generate(commonService.getProperty(RECOVERY_PASSWORD_LENGTH)); HashedPassword hashNew = passwordSecurity.computeHash(thePass, name); - ConsoleLogger.info("Generating new password for '" + name + "'"); + logger.info("Generating new password for '" + name + "'"); dataSource.updatePassword(name, hashNew); boolean couldSendMail = emailService.sendPasswordMail(name, email, thePass); diff --git a/src/main/java/fr/xephi/authme/service/PluginHookService.java b/src/main/java/fr/xephi/authme/service/PluginHookService.java index ab344fac3..3615aa736 100644 --- a/src/main/java/fr/xephi/authme/service/PluginHookService.java +++ b/src/main/java/fr/xephi/authme/service/PluginHookService.java @@ -5,6 +5,7 @@ import com.earth2me.essentials.Essentials; import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MVWorldManager; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; @@ -20,6 +21,7 @@ import java.io.File; @NoFieldScan public class PluginHookService { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PluginHookService.class); private final PluginManager pluginManager; private Essentials essentials; private Plugin cmi; @@ -182,11 +184,11 @@ public class PluginHookService { // Helpers // ------ - private static T getPlugin(PluginManager pluginManager, String name, Class clazz) + private T getPlugin(PluginManager pluginManager, String name, Class clazz) throws Exception, NoClassDefFoundError { if (pluginManager.isPluginEnabled(name)) { T plugin = clazz.cast(pluginManager.getPlugin(name)); - ConsoleLogger.info("Hooked successfully into " + name); + logger.info("Hooked successfully into " + name); return plugin; } return null; diff --git a/src/main/java/fr/xephi/authme/service/SessionService.java b/src/main/java/fr/xephi/authme/service/SessionService.java index f821a64b3..31715a7b0 100644 --- a/src/main/java/fr/xephi/authme/service/SessionService.java +++ b/src/main/java/fr/xephi/authme/service/SessionService.java @@ -5,6 +5,7 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.RestoreSessionEvent; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.util.PlayerUtils; @@ -19,6 +20,7 @@ import static fr.xephi.authme.util.Utils.MILLIS_PER_MINUTE; */ public class SessionService implements Reloadable { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(SessionService.class); private final CommonService service; private final BukkitService bukkitService; private final DataSource database; @@ -68,7 +70,7 @@ public class SessionService implements Reloadable { */ private SessionState fetchSessionStatus(PlayerAuth auth, Player player) { if (auth == null) { - ConsoleLogger.warning("No PlayerAuth in database for '" + player.getName() + "' during session check"); + logger.warning("No PlayerAuth in database for '" + player.getName() + "' during session check"); return SessionState.NOT_VALID; } else if (auth.getLastLogin() == null) { return SessionState.NOT_VALID; diff --git a/src/main/java/fr/xephi/authme/service/TeleportationService.java b/src/main/java/fr/xephi/authme/service/TeleportationService.java index 1588c4404..f0eb7f851 100644 --- a/src/main/java/fr/xephi/authme/service/TeleportationService.java +++ b/src/main/java/fr/xephi/authme/service/TeleportationService.java @@ -10,6 +10,7 @@ import fr.xephi.authme.events.AuthMeTeleportEvent; import fr.xephi.authme.events.FirstSpawnTeleportEvent; import fr.xephi.authme.events.SpawnTeleportEvent; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.properties.RestrictionSettings; @@ -28,6 +29,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.TELEPORT_U * Handles teleportation (placement of player to spawn). */ public class TeleportationService implements Reloadable { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(TeleportationService.class); @Inject private Settings settings; @@ -64,7 +67,7 @@ public class TeleportationService implements Reloadable { public void teleportOnJoin(final Player player) { if (!settings.getProperty(RestrictionSettings.NO_TELEPORT) && settings.getProperty(TELEPORT_UNAUTHED_TO_SPAWN)) { - ConsoleLogger.debug("Teleport on join for player `{0}`", player.getName()); + logger.debug("Teleport on join for player `{0}`", player.getName()); teleportToSpawn(player, playerCache.isAuthenticated(player.getName())); } } @@ -88,7 +91,7 @@ public class TeleportationService implements Reloadable { return null; } - ConsoleLogger.debug("Returning custom location for >1.9 join event for player `{0}`", player.getName()); + logger.debug("Returning custom location for >1.9 join event for player `{0}`", player.getName()); return location; } return null; @@ -110,7 +113,7 @@ public class TeleportationService implements Reloadable { } if (!player.hasPlayedBefore() || !dataSource.isAuthAvailable(player.getName())) { - ConsoleLogger.debug("Attempting to teleport player `{0}` to first spawn", player.getName()); + logger.debug("Attempting to teleport player `{0}` to first spawn", player.getName()); performTeleportation(player, new FirstSpawnTeleportEvent(player, firstSpawn)); } } @@ -134,15 +137,15 @@ public class TeleportationService implements Reloadable { // The world in LimboPlayer is from where the player comes, before any teleportation by AuthMe if (mustForceSpawnAfterLogin(worldName)) { - ConsoleLogger.debug("Teleporting `{0}` to spawn because of 'force-spawn after login'", player.getName()); + logger.debug("Teleporting `{0}` to spawn because of 'force-spawn after login'", player.getName()); teleportToSpawn(player, true); } else if (settings.getProperty(TELEPORT_UNAUTHED_TO_SPAWN)) { if (settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION) && auth.getQuitLocY() != 0) { Location location = buildLocationFromAuth(player, auth); - ConsoleLogger.debug("Teleporting `{0}` after login, based on the player auth", player.getName()); + logger.debug("Teleporting `{0}` after login, based on the player auth", player.getName()); teleportBackFromSpawn(player, location); } else if (limbo != null && limbo.getLocation() != null) { - ConsoleLogger.debug("Teleporting `{0}` after login, based on the limbo player", player.getName()); + logger.debug("Teleporting `{0}` after login, based on the limbo player", player.getName()); teleportBackFromSpawn(player, limbo.getLocation()); } } diff --git a/src/main/java/fr/xephi/authme/service/ValidationService.java b/src/main/java/fr/xephi/authme/service/ValidationService.java index 2583cdf77..183a3b4a6 100644 --- a/src/main/java/fr/xephi/authme/service/ValidationService.java +++ b/src/main/java/fr/xephi/authme/service/ValidationService.java @@ -6,6 +6,7 @@ import com.google.common.collect.Multimap; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; @@ -33,6 +34,8 @@ import static fr.xephi.authme.util.StringUtils.isInsideString; * Validation service. */ public class ValidationService implements Reloadable { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(ValidationService.class); @Inject private Settings settings; @@ -125,7 +128,7 @@ public class ValidationService implements Reloadable { String countryCode = geoIpService.getCountryCode(hostAddress); boolean isCountryAllowed = validateWhitelistAndBlacklist(countryCode, ProtectionSettings.COUNTRIES_WHITELIST, ProtectionSettings.COUNTRIES_BLACKLIST); - ConsoleLogger.debug("Country code `{0}` for `{1}` is allowed: {2}", countryCode, hostAddress, isCountryAllowed); + logger.debug("Country code `{0}` for `{1}` is allowed: {2}", countryCode, hostAddress, isCountryAllowed); return isCountryAllowed; } @@ -211,7 +214,7 @@ public class ValidationService implements Reloadable { String[] data = restriction.split(";"); restrictions.put(data[0].toLowerCase(), data[1]); } else { - ConsoleLogger.warning("Restricted user rule must have a ';' separating name from restriction," + logger.warning("Restricted user rule must have a ';' separating name from restriction," + " but found: '" + restriction + "'"); } } diff --git a/src/main/java/fr/xephi/authme/service/bungeecord/BungeeReceiver.java b/src/main/java/fr/xephi/authme/service/bungeecord/BungeeReceiver.java index 7c832a336..fd38d50b3 100644 --- a/src/main/java/fr/xephi/authme/service/bungeecord/BungeeReceiver.java +++ b/src/main/java/fr/xephi/authme/service/bungeecord/BungeeReceiver.java @@ -6,6 +6,7 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.SettingsDependent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.process.Management; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; @@ -18,6 +19,8 @@ import javax.inject.Inject; import java.util.Optional; public class BungeeReceiver implements PluginMessageListener, SettingsDependent { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(BungeeReceiver.class); private final AuthMe plugin; private final BukkitService bukkitService; @@ -59,7 +62,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent final String typeId = dataIn.readUTF(); final Optional type = MessageType.fromId(typeId); if (!type.isPresent()) { - ConsoleLogger.debug("Received unsupported forwarded bungeecord message type! ({0})", typeId); + logger.debug("Received unsupported forwarded bungeecord message type! ({0})", typeId); return; } @@ -68,7 +71,8 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent try { argument = dataIn.readUTF(); } catch (IllegalStateException e) { - ConsoleLogger.warning("Received invalid forwarded plugin message of type " + type.get().name() + ": argument is missing!"); + logger.warning("Received invalid forwarded plugin message of type " + type.get().name() + + ": argument is missing!"); return; } @@ -92,7 +96,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent final String typeId = in.readUTF(); final Optional type = MessageType.fromId(typeId); if (!type.isPresent()) { - ConsoleLogger.debug("Received unsupported bungeecord message type! ({0})", typeId); + logger.debug("Received unsupported bungeecord message type! ({0})", typeId); return; } @@ -101,7 +105,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent try { argument = in.readUTF(); } catch (IllegalStateException e) { - ConsoleLogger.warning("Received invalid plugin message of type " + type.get().name() + logger.warning("Received invalid plugin message of type " + type.get().name() + ": argument is missing!"); return; } @@ -136,7 +140,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent Player player = bukkitService.getPlayerExact(name); if (player != null && player.isOnline()) { management.forceLogin(player); - ConsoleLogger.info("The user " + player.getName() + " has been automatically logged in, " + logger.info("The user " + player.getName() + " has been automatically logged in, " + "as requested via plugin messaging."); } } diff --git a/src/main/java/fr/xephi/authme/service/bungeecord/BungeeSender.java b/src/main/java/fr/xephi/authme/service/bungeecord/BungeeSender.java index 5e3508abf..b99bb1b8e 100644 --- a/src/main/java/fr/xephi/authme/service/bungeecord/BungeeSender.java +++ b/src/main/java/fr/xephi/authme/service/bungeecord/BungeeSender.java @@ -6,6 +6,7 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.SettingsDependent; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.HooksSettings; @@ -16,6 +17,7 @@ import javax.inject.Inject; public class BungeeSender implements SettingsDependent { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(BungeeSender.class); private final AuthMe plugin; private final BukkitService bukkitService; private final DataSource dataSource; @@ -97,7 +99,7 @@ public class BungeeSender implements SettingsDependent { public void sendAuthMeBungeecordMessage(final MessageType type, final String playerName) { if (isEnabled) { if (!plugin.isEnabled()) { - ConsoleLogger.debug("Tried to send a " + type + " bungeecord message but the plugin was disabled!"); + logger.debug("Tried to send a " + type + " bungeecord message but the plugin was disabled!"); return; } if (type.isRequiresCaching() && !dataSource.isCached()) { diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index 5465875dc..ab33a7e8d 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -6,6 +6,7 @@ import ch.jalu.configme.migration.MigrationService; import ch.jalu.configme.resource.PropertyResource; import com.google.common.io.Files; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import java.io.File; import java.io.IOException; @@ -18,6 +19,7 @@ import static fr.xephi.authme.util.FileUtils.copyFileFromResource; */ public class Settings extends SettingsManagerImpl { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(Settings.class); private final File pluginFolder; private String passwordEmailMessage; private String verificationEmailMessage; @@ -89,10 +91,10 @@ public class Settings extends SettingsManagerImpl { try { return Files.asCharSource(file, StandardCharsets.UTF_8).read(); } catch (IOException e) { - ConsoleLogger.logException("Failed to read file '" + filename + "':", e); + logger.logException("Failed to read file '" + filename + "':", e); } } else { - ConsoleLogger.warning("Failed to copy file '" + filename + "' from JAR"); + logger.warning("Failed to copy file '" + filename + "' from JAR"); } return ""; } diff --git a/src/main/java/fr/xephi/authme/settings/SettingsMigrationService.java b/src/main/java/fr/xephi/authme/settings/SettingsMigrationService.java index 6bd9e5eb9..23168d530 100644 --- a/src/main/java/fr/xephi/authme/settings/SettingsMigrationService.java +++ b/src/main/java/fr/xephi/authme/settings/SettingsMigrationService.java @@ -6,6 +6,7 @@ import ch.jalu.configme.properties.Property; import ch.jalu.configme.resource.PropertyReader; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.process.register.RegisterSecondaryArgument; import fr.xephi.authme.process.register.RegistrationType; @@ -38,7 +39,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.FORCE_SPAW * Service for verifying that the configuration is up-to-date. */ public class SettingsMigrationService extends PlainMigrationService { - + + private static ConsoleLogger logger = ConsoleLoggerFactory.get(SettingsMigrationService.class); private final File pluginFolder; // Stores old "other accounts command" config if present. @@ -141,7 +143,7 @@ public class SettingsMigrationService extends PlainMigrationService { try (FileWriter fw = new FileWriter(emailFile)) { fw.write(mailText); } catch (IOException e) { - ConsoleLogger.logException("Could not create email.html configuration file:", e); + logger.logException("Could not create email.html configuration file:", e); } } return true; @@ -160,7 +162,7 @@ public class SettingsMigrationService extends PlainMigrationService { boolean hasMigrated = moveProperty(oldDelayJoinProperty, DELAY_JOIN_MESSAGE, reader, configData); if (hasMigrated) { - ConsoleLogger.info(String.format("Note that we now also have the settings %s and %s", + logger.info(String.format("Note that we now also have the settings %s and %s", REMOVE_JOIN_MESSAGE.getPath(), REMOVE_LEAVE_MESSAGE.getPath())); } return hasMigrated; @@ -213,7 +215,7 @@ public class SettingsMigrationService extends PlainMigrationService { final String oldPath = "Security.console.noConsoleSpam"; final Property newProperty = PluginSettings.LOG_LEVEL; if (!newProperty.isPresent(reader) && reader.contains(oldPath)) { - ConsoleLogger.info("Moving '" + oldPath + "' to '" + newProperty.getPath() + "'"); + logger.info("Moving '" + oldPath + "' to '" + newProperty.getPath() + "'"); boolean oldValue = Optional.ofNullable(reader.getBoolean(oldPath)).orElse(false); LogLevel level = oldValue ? LogLevel.INFO : LogLevel.FINE; configData.setValue(newProperty, level); @@ -224,7 +226,7 @@ public class SettingsMigrationService extends PlainMigrationService { private static boolean hasOldHelpHeaderProperty(PropertyReader reader) { if (reader.contains("settings.helpHeader")) { - ConsoleLogger.warning("Help header setting is now in messages/help_xx.yml, " + logger.warning("Help header setting is now in messages/help_xx.yml, " + "please check the file to set it again"); return true; } @@ -234,7 +236,7 @@ public class SettingsMigrationService extends PlainMigrationService { private static boolean hasSupportOldPasswordProperty(PropertyReader reader) { String path = "settings.security.supportOldPasswordHash"; if (reader.contains(path)) { - ConsoleLogger.warning("Property '" + path + "' is no longer supported. " + logger.warning("Property '" + path + "' is no longer supported. " + "Use '" + SecuritySettings.LEGACY_HASHES.getPath() + "' instead."); return true; } @@ -265,7 +267,7 @@ public class SettingsMigrationService extends PlainMigrationService { ? RegisterSecondaryArgument.CONFIRMATION : RegisterSecondaryArgument.NONE; - ConsoleLogger.warning("Merging old registration settings into '" + logger.warning("Merging old registration settings into '" + RegistrationSettings.REGISTRATION_TYPE.getPath() + "'"); configData.setValue(RegistrationSettings.REGISTRATION_TYPE, registrationType); configData.setValue(RegistrationSettings.REGISTER_SECOND_ARGUMENT, secondaryArgument); @@ -318,7 +320,7 @@ public class SettingsMigrationService extends PlainMigrationService { Set legacyHashes = SecuritySettings.LEGACY_HASHES.determineValue(reader); legacyHashes.add(currentHash); configData.setValue(SecuritySettings.LEGACY_HASHES, legacyHashes); - ConsoleLogger.warning("The hash algorithm '" + currentHash + logger.warning("The hash algorithm '" + currentHash + "' is no longer supported for active use. New hashes will be in SHA256."); return true; } @@ -372,9 +374,9 @@ public class SettingsMigrationService extends PlainMigrationService { ConfigurationData configData) { if (reader.contains(oldProperty.getPath())) { if (reader.contains(newProperty.getPath())) { - ConsoleLogger.info("Detected deprecated property " + oldProperty.getPath()); + logger.info("Detected deprecated property " + oldProperty.getPath()); } else { - ConsoleLogger.info("Renaming " + oldProperty.getPath() + " to " + newProperty.getPath()); + logger.info("Renaming " + oldProperty.getPath() + " to " + newProperty.getPath()); configData.setValue(newProperty, oldProperty.determineValue(reader)); } return true; diff --git a/src/main/java/fr/xephi/authme/settings/SettingsWarner.java b/src/main/java/fr/xephi/authme/settings/SettingsWarner.java index d055dd0fd..c51bdf6b3 100644 --- a/src/main/java/fr/xephi/authme/settings/SettingsWarner.java +++ b/src/main/java/fr/xephi/authme/settings/SettingsWarner.java @@ -2,6 +2,7 @@ package fr.xephi.authme.settings; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.crypts.Argon2; import fr.xephi.authme.service.BukkitService; @@ -22,6 +23,8 @@ import java.util.Optional; * see {@link SettingsMigrationService}. */ public class SettingsWarner { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(SettingsWarner.class); @Inject private Settings settings; @@ -41,25 +44,25 @@ public class SettingsWarner { public void logWarningsForMisconfigurations() { // Force single session disabled if (!settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)) { - ConsoleLogger.warning("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); + logger.warning("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); } // Use TLS property only affects port 25 if (!settings.getProperty(EmailSettings.PORT25_USE_TLS) && settings.getProperty(EmailSettings.SMTP_PORT) != 25) { - ConsoleLogger.warning("Note: You have set Email.useTls to false but this only affects mail over port 25"); + logger.warning("Note: You have set Email.useTls to false but this only affects mail over port 25"); } // Output hint if sessions are enabled that the timeout must be positive if (settings.getProperty(PluginSettings.SESSIONS_ENABLED) && settings.getProperty(PluginSettings.SESSIONS_TIMEOUT) <= 0) { - ConsoleLogger.warning("Warning: Session timeout needs to be positive in order to work!"); + logger.warning("Warning: Session timeout needs to be positive in order to work!"); } // Warn if spigot.yml has settings.bungeecord set to true but config.yml has Hooks.bungeecord set to false if (isTrue(bukkitService.isBungeeCordConfiguredForSpigot()) && !settings.getProperty(HooksSettings.BUNGEECORD)) { - ConsoleLogger.warning("Note: Hooks.bungeecord is set to false but your server appears to be running in" + logger.warning("Note: Hooks.bungeecord is set to false but your server appears to be running in" + " bungeecord mode (see your spigot.yml). In order to allow the datasource caching and the" + " AuthMeBungee add-on to work properly you have to enable this option!"); } @@ -67,7 +70,7 @@ public class SettingsWarner { // Check if argon2 library is present and can be loaded if (settings.getProperty(SecuritySettings.PASSWORD_HASH).equals(HashAlgorithm.ARGON2) && !Argon2.isLibraryLoaded()) { - ConsoleLogger.warning("WARNING!!! You use Argon2 Hash Algorithm method but we can't find the Argon2 " + logger.warning("WARNING!!! You use Argon2 Hash Algorithm method but we can't find the Argon2 " + "library on your system! See https://github.com/AuthMe/AuthMeReloaded/wiki/Argon2-as-Password-Hash"); authMe.stopOrUnload(); } diff --git a/src/main/java/fr/xephi/authme/settings/SpawnLoader.java b/src/main/java/fr/xephi/authme/settings/SpawnLoader.java index d2f2edbf7..403b058cf 100644 --- a/src/main/java/fr/xephi/authme/settings/SpawnLoader.java +++ b/src/main/java/fr/xephi/authme/settings/SpawnLoader.java @@ -3,6 +3,7 @@ package fr.xephi.authme.settings; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; @@ -29,6 +30,8 @@ import java.io.IOException; */ public class SpawnLoader implements Reloadable { + private final ConsoleLogger logger = ConsoleLoggerFactory.get(SpawnLoader.class); + private final File authMeConfigurationFile; private final Settings settings; private final PluginHookService pluginHookService; @@ -120,7 +123,7 @@ public class SpawnLoader implements Reloadable { YamlConfiguration.loadConfiguration(essentialsSpawnFile), "spawns.default"); } else { essentialsSpawn = null; - ConsoleLogger.info("Essentials spawn file not found: '" + essentialsSpawnFile.getAbsolutePath() + "'"); + logger.info("Essentials spawn file not found: '" + essentialsSpawnFile.getAbsolutePath() + "'"); } } @@ -145,7 +148,7 @@ public class SpawnLoader implements Reloadable { cmiSpawn = getLocationFromCmiConfiguration(YamlConfiguration.loadConfiguration(cmiConfig)); } else { cmiSpawn = null; - ConsoleLogger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'"); + logger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'"); } } @@ -198,11 +201,11 @@ public class SpawnLoader implements Reloadable { // ignore } if (spawnLoc != null) { - ConsoleLogger.debug("Spawn location determined as `{0}` for world `{1}`", spawnLoc, world.getName()); + logger.debug("Spawn location determined as `{0}` for world `{1}`", spawnLoc, world.getName()); return spawnLoc; } } - ConsoleLogger.debug("Fall back to default world spawn location. World: `{0}`", world.getName()); + logger.debug("Fall back to default world spawn location. World: `{0}`", world.getName()); return world.getSpawnLocation(); // return default location } @@ -232,7 +235,7 @@ public class SpawnLoader implements Reloadable { authMeConfiguration.save(authMeConfigurationFile); return true; } catch (IOException e) { - ConsoleLogger.logException("Could not save spawn config (" + authMeConfigurationFile + ")", e); + logger.logException("Could not save spawn config (" + authMeConfigurationFile + ")", e); } return false; } diff --git a/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java b/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java index 0838314a1..36cdff015 100644 --- a/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java +++ b/src/main/java/fr/xephi/authme/settings/WelcomeMessageConfiguration.java @@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.GeoIpService; @@ -35,6 +36,8 @@ import static fr.xephi.authme.util.lazytags.TagBuilder.createTag; * Configuration for the welcome message (welcome.txt). */ public class WelcomeMessageConfiguration implements Reloadable { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(WelcomeMessageConfiguration.class); @DataFolder @Inject @@ -125,10 +128,10 @@ public class WelcomeMessageConfiguration implements Reloadable { try { return Files.readAllLines(welcomeFile.toPath(), StandardCharsets.UTF_8); } catch (IOException e) { - ConsoleLogger.logException("Failed to read welcome.txt file:", e); + logger.logException("Failed to read welcome.txt file:", e); } } else { - ConsoleLogger.warning("Failed to copy welcome.txt from JAR"); + logger.warning("Failed to copy welcome.txt from JAR"); } return Collections.emptyList(); } diff --git a/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java b/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java index 73a33b21b..399ff3985 100644 --- a/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java +++ b/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java @@ -2,6 +2,7 @@ package fr.xephi.authme.task.purge; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.PluginHookService; @@ -21,6 +22,8 @@ import static fr.xephi.authme.util.FileUtils.makePath; * Executes the purge operations. */ public class PurgeExecutor { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PurgeExecutor.class); @Inject private Settings settings; @@ -85,7 +88,7 @@ public class PurgeExecutor { } } - ConsoleLogger.info("AutoPurge: Removed " + i + " AntiXRayData Files"); + logger.info("AutoPurge: Removed " + i + " AntiXRayData Files"); } /** @@ -96,7 +99,7 @@ public class PurgeExecutor { synchronized void purgeFromAuthMe(Collection names) { dataSource.purgeRecords(names); //TODO ljacqu 20160717: We shouldn't output namedBanned.size() but the actual total that was deleted - ConsoleLogger.info(ChatColor.GOLD + "Deleted " + names.size() + " user accounts"); + logger.info(ChatColor.GOLD + "Deleted " + names.size() + " user accounts"); } /** @@ -141,7 +144,7 @@ public class PurgeExecutor { } } } - ConsoleLogger.info("AutoPurge: Removed " + i + " LimitedCreative Survival, Creative and Adventure files"); + logger.info("AutoPurge: Removed " + i + " LimitedCreative Survival, Creative and Adventure files"); } /** @@ -165,7 +168,7 @@ public class PurgeExecutor { } } - ConsoleLogger.info("AutoPurge: Removed " + i + " .dat Files"); + logger.info("AutoPurge: Removed " + i + " .dat Files"); } /** @@ -180,7 +183,7 @@ public class PurgeExecutor { File essentialsDataFolder = pluginHookService.getEssentialsDataFolder(); if (essentialsDataFolder == null) { - ConsoleLogger.info("Cannot purge Essentials: plugin is not loaded"); + logger.info("Cannot purge Essentials: plugin is not loaded"); return; } @@ -197,7 +200,7 @@ public class PurgeExecutor { } } - ConsoleLogger.info("AutoPurge: Removed " + deletedFiles + " EssentialsFiles"); + logger.info("AutoPurge: Removed " + deletedFiles + " EssentialsFiles"); } /** @@ -212,12 +215,12 @@ public class PurgeExecutor { for (OfflinePlayer offlinePlayer : cleared) { if (!permissionsManager.loadUserData(offlinePlayer)) { - ConsoleLogger.warning("Unable to purge the permissions of user " + offlinePlayer + "!"); + logger.warning("Unable to purge the permissions of user " + offlinePlayer + "!"); continue; } permissionsManager.removeAllGroups(offlinePlayer); } - ConsoleLogger.info("AutoPurge: Removed permissions from " + cleared.size() + " player(s)."); + logger.info("AutoPurge: Removed permissions from " + cleared.size() + " player(s)."); } } diff --git a/src/main/java/fr/xephi/authme/task/purge/PurgeService.java b/src/main/java/fr/xephi/authme/task/purge/PurgeService.java index c9ba7251f..489262883 100644 --- a/src/main/java/fr/xephi/authme/task/purge/PurgeService.java +++ b/src/main/java/fr/xephi/authme/task/purge/PurgeService.java @@ -2,6 +2,7 @@ package fr.xephi.authme.task.purge; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; @@ -21,6 +22,8 @@ import static fr.xephi.authme.util.Utils.logAndSendMessage; * Initiates purge tasks. */ public class PurgeService { + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PurgeService.class); @Inject private BukkitService bukkitService; @@ -51,11 +54,11 @@ public class PurgeService { if (!settings.getProperty(PurgeSettings.USE_AUTO_PURGE)) { return; } else if (daysBeforePurge <= 0) { - ConsoleLogger.warning("Did not run auto purge: configured days before purging must be positive"); + logger.warning("Did not run auto purge: configured days before purging must be positive"); return; } - ConsoleLogger.info("Automatically purging the database..."); + logger.info("Automatically purging the database..."); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -daysBeforePurge); long until = calendar.getTimeInMillis(); diff --git a/src/main/java/fr/xephi/authme/task/purge/PurgeTask.java b/src/main/java/fr/xephi/authme/task/purge/PurgeTask.java index 06bf06f50..f29d6f71d 100644 --- a/src/main/java/fr/xephi/authme/task/purge/PurgeTask.java +++ b/src/main/java/fr/xephi/authme/task/purge/PurgeTask.java @@ -1,6 +1,7 @@ package fr.xephi.authme.task.purge; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; import org.bukkit.Bukkit; @@ -19,6 +20,7 @@ class PurgeTask extends BukkitRunnable { //how many players we should check for each tick private static final int INTERVAL_CHECK = 5; + private final ConsoleLogger logger = ConsoleLoggerFactory.get(PurgeTask.class); private final PurgeService purgeService; private final PermissionsManager permissionsManager; private final UUID sender; @@ -74,7 +76,7 @@ class PurgeTask extends BukkitRunnable { OfflinePlayer offlinePlayer = offlinePlayers[nextPosition]; if (offlinePlayer.getName() != null && toPurge.remove(offlinePlayer.getName().toLowerCase())) { if (!permissionsManager.loadUserData(offlinePlayer)) { - ConsoleLogger.warning("Unable to check if the user " + offlinePlayer.getName() + " can be purged!"); + logger.warning("Unable to check if the user " + offlinePlayer.getName() + " can be purged!"); continue; } if (!permissionsManager.hasPermissionOffline(offlinePlayer, PlayerStatePermission.BYPASS_PURGE)) { @@ -85,7 +87,7 @@ class PurgeTask extends BukkitRunnable { } if (!toPurge.isEmpty() && playerPortion.isEmpty()) { - ConsoleLogger.info("Finished lookup of offlinePlayers. Begin looking purging player names only"); + logger.info("Finished lookup of offlinePlayers. Begin looking purging player names only"); //we went through all offlineplayers but there are still names remaining for (String name : toPurge) { @@ -110,7 +112,7 @@ class PurgeTask extends BukkitRunnable { // Show a status message sendMessage(ChatColor.GREEN + "[AuthMe] Database has been purged successfully"); - ConsoleLogger.info("Purge finished!"); + logger.info("Purge finished!"); purgeService.setPurging(false); } diff --git a/src/main/java/fr/xephi/authme/util/FileUtils.java b/src/main/java/fr/xephi/authme/util/FileUtils.java index bc1bef41c..7f7ee4aaa 100644 --- a/src/main/java/fr/xephi/authme/util/FileUtils.java +++ b/src/main/java/fr/xephi/authme/util/FileUtils.java @@ -3,6 +3,7 @@ package fr.xephi.authme.util; import com.google.common.io.Files; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import java.io.File; import java.io.IOException; @@ -20,6 +21,8 @@ public final class FileUtils { private static final DateTimeFormatter CURRENT_DATE_STRING_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd_HHmm"); + private static ConsoleLogger logger = ConsoleLoggerFactory.get(FileUtils.class); + // Utility class private FileUtils() { } @@ -36,20 +39,20 @@ public final class FileUtils { if (destinationFile.exists()) { return true; } else if (!createDirectory(destinationFile.getParentFile())) { - ConsoleLogger.warning("Cannot create parent directories for '" + destinationFile + "'"); + logger.warning("Cannot create parent directories for '" + destinationFile + "'"); return false; } try (InputStream is = getResourceFromJar(resourcePath)) { if (is == null) { - ConsoleLogger.warning(format("Cannot copy resource '%s' to file '%s': cannot load resource", + logger.warning(format("Cannot copy resource '%s' to file '%s': cannot load resource", resourcePath, destinationFile.getPath())); } else { java.nio.file.Files.copy(is, destinationFile.toPath()); return true; } } catch (IOException e) { - ConsoleLogger.logException(format("Cannot copy resource '%s' to file '%s':", + logger.logException(format("Cannot copy resource '%s' to file '%s':", resourcePath, destinationFile.getPath()), e); } return false; @@ -63,7 +66,7 @@ public final class FileUtils { */ public static boolean createDirectory(File dir) { if (!dir.exists() && !dir.mkdirs()) { - ConsoleLogger.warning("Could not create directory '" + dir + "'"); + logger.warning("Could not create directory '" + dir + "'"); return false; } return dir.isDirectory(); @@ -112,7 +115,7 @@ public final class FileUtils { if (file != null) { boolean result = file.delete(); if (!result) { - ConsoleLogger.warning("Could not delete file '" + file + "'"); + logger.warning("Could not delete file '" + file + "'"); } } } diff --git a/src/main/java/fr/xephi/authme/util/Utils.java b/src/main/java/fr/xephi/authme/util/Utils.java index 4db7f61bc..74c3088e3 100644 --- a/src/main/java/fr/xephi/authme/util/Utils.java +++ b/src/main/java/fr/xephi/authme/util/Utils.java @@ -1,6 +1,7 @@ package fr.xephi.authme.util; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; @@ -15,8 +16,8 @@ public final class Utils { /** Number of milliseconds in a minute. */ public static final long MILLIS_PER_MINUTE = 60_000L; - /** Number of milliseconds in an hour. */ - public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; + + private static ConsoleLogger logger = ConsoleLoggerFactory.get(Utils.class); // Utility class private Utils() { @@ -33,7 +34,7 @@ public final class Utils { try { return Pattern.compile(pattern); } catch (Exception e) { - ConsoleLogger.warning("Failed to compile pattern '" + pattern + "' - defaulting to allowing everything"); + logger.warning("Failed to compile pattern '" + pattern + "' - defaulting to allowing everything"); return Pattern.compile(".*?"); } } @@ -63,7 +64,7 @@ public final class Utils { * @param message the message to log and send */ public static void logAndSendMessage(CommandSender sender, String message) { - ConsoleLogger.info(message); + logger.info(message); // Make sure sender is not console user, which will see the message from ConsoleLogger already if (sender != null && !(sender instanceof ConsoleCommandSender)) { sender.sendMessage(message); @@ -79,7 +80,7 @@ public final class Utils { * @param message the warning to log and send */ public static void logAndSendWarning(CommandSender sender, String message) { - ConsoleLogger.warning(message); + logger.warning(message); // Make sure sender is not console user, which will see the message from ConsoleLogger already if (sender != null && !(sender instanceof ConsoleCommandSender)) { sender.sendMessage(ChatColor.RED + message); diff --git a/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java b/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java index b8deb9349..2fb5a05a8 100644 --- a/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java +++ b/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java @@ -15,6 +15,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -28,9 +29,11 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -42,6 +45,8 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; @RunWith(MockitoJUnitRunner.class) public class ConsoleLoggerTest { + private ConsoleLogger consoleLogger; + @Mock private Logger logger; @@ -52,19 +57,19 @@ public class ConsoleLoggerTest { @Before public void setMockLogger() throws IOException { - ConsoleLogger.setLogger(logger); File folder = temporaryFolder.newFolder(); File logFile = new File(folder, "authme.log"); if (!logFile.createNewFile()) { throw new IOException("Could not create file '" + logFile.getPath() + "'"); } - ConsoleLogger.setLogFile(logFile); + ConsoleLogger.initialize(logger, logFile); this.logFile = logFile; + this.consoleLogger = new ConsoleLogger("test"); } @After public void closeFileHandlers() { - ConsoleLogger.close(); + ConsoleLogger.closeFileWriter(); } /** @@ -74,18 +79,20 @@ public class ConsoleLoggerTest { */ @AfterClass public static void resetConsoleToDefault() { - ConsoleLogger.setLoggingOptions(newSettings(false, LogLevel.FINE)); + ConsoleLogger.initializeSharedSettings(newSettings(false, LogLevel.INFO)); } @Test public void shouldLogToFile() throws IOException { // given - ConsoleLogger.setLoggingOptions(newSettings(true, LogLevel.FINE)); + Settings settings = newSettings(true, LogLevel.FINE); + ConsoleLogger.initializeSharedSettings(settings); + consoleLogger.initializeSettings(settings); // when - ConsoleLogger.fine("Logging a FINE message"); - ConsoleLogger.debug("Logging a DEBUG message"); - ConsoleLogger.info("This is an INFO message"); + consoleLogger.fine("Logging a FINE message"); + consoleLogger.debug("Logging a DEBUG message"); + consoleLogger.info("This is an INFO message"); // then verify(logger, times(2)).info(anyString()); @@ -97,13 +104,15 @@ public class ConsoleLoggerTest { } @Test - public void shouldNotLogToFile() throws IOException { + public void shouldNotLogToFile() { // given - ConsoleLogger.setLoggingOptions(newSettings(false, LogLevel.DEBUG)); + Settings settings = newSettings(false, LogLevel.DEBUG); + ConsoleLogger.initializeSharedSettings(settings); + consoleLogger.initializeSettings(settings); // when - ConsoleLogger.debug("Created test"); - ConsoleLogger.warning("Encountered a warning"); + consoleLogger.debug("Created test"); + consoleLogger.warning("Encountered a warning"); // then verify(logger).info("[DEBUG] Created test"); @@ -115,14 +124,15 @@ public class ConsoleLoggerTest { @Test public void shouldLogStackTraceToFile() throws IOException { // given - ConsoleLogger.setLoggingOptions(newSettings(true, LogLevel.INFO)); + Settings settings = newSettings(true, LogLevel.INFO); + ConsoleLogger.initializeSharedSettings(settings); Exception e = new IllegalStateException("Test exception message"); // when - ConsoleLogger.info("Info text"); - ConsoleLogger.debug("Debug message"); - ConsoleLogger.fine("Fine-level message"); - ConsoleLogger.logException("Exception occurred:", e); + consoleLogger.info("Info text"); + consoleLogger.debug("Debug message"); + consoleLogger.fine("Fine-level message"); + consoleLogger.logException("Exception occurred:", e); // then verify(logger).info("Info text"); @@ -140,13 +150,15 @@ public class ConsoleLoggerTest { @Test public void shouldSupportVariousDebugMethods() throws IOException { // given - ConsoleLogger.setLoggingOptions(newSettings(true, LogLevel.DEBUG)); + Settings settings = newSettings(true, LogLevel.DEBUG); + ConsoleLogger.initializeSharedSettings(settings); + consoleLogger.initializeSettings(settings); // when - ConsoleLogger.debug("Got {0} entries", 17); - ConsoleLogger.debug("Player `{0}` is in world `{1}`", "Bobby", new World("world")); - ConsoleLogger.debug("{0} quick {1} jump over {2} lazy {3} (reason: {4})", 5, "foxes", 3, "dogs", null); - ConsoleLogger.debug(() -> "Too little too late"); + consoleLogger.debug("Got {0} entries", 17); + consoleLogger.debug("Player `{0}` is in world `{1}`", "Bobby", new World("world")); + consoleLogger.debug("{0} quick {1} jump over {2} lazy {3} (reason: {4})", 5, "foxes", 3, "dogs", null); + consoleLogger.debug(() -> "Too little too late"); // then verify(logger).log(Level.INFO, "[DEBUG] Got {0} entries", 17); @@ -164,8 +176,35 @@ public class ConsoleLoggerTest { } @Test - public void shouldHaveHiddenConstructor() { - TestHelper.validateHasOnlyPrivateEmptyConstructor(ConsoleLogger.class); + public void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException { + // given + FileWriter fileWriter = mock(FileWriter.class); + doThrow(new IOException("Error during flush")).when(fileWriter).flush(); + ReflectionTestUtils.setField(ConsoleLogger.class, null, "fileWriter", fileWriter); + + // when + ConsoleLogger.closeFileWriter(); + + // then + verify(fileWriter).flush(); + verify(fileWriter).close(); + assertThat(ReflectionTestUtils.getFieldValue(ConsoleLogger.class, null, "fileWriter"), nullValue()); + } + + @Test + public void shouldHandleExceptionOnFileWriterClose() throws IOException { + // given + FileWriter fileWriter = mock(FileWriter.class); + doThrow(new IOException("Cannot close")).when(fileWriter).close(); + ReflectionTestUtils.setField(ConsoleLogger.class, null, "fileWriter", fileWriter); + + // when + ConsoleLogger.closeFileWriter(); + + // then + verify(fileWriter).flush(); + verify(fileWriter).close(); + assertThat(ReflectionTestUtils.getFieldValue(ConsoleLogger.class, null, "fileWriter"), nullValue()); } private static Settings newSettings(boolean logToFile, LogLevel logLevel) { diff --git a/src/test/java/fr/xephi/authme/TestHelper.java b/src/test/java/fr/xephi/authme/TestHelper.java index d9213c62e..9e846d0f3 100644 --- a/src/test/java/fr/xephi/authme/TestHelper.java +++ b/src/test/java/fr/xephi/authme/TestHelper.java @@ -80,7 +80,7 @@ public final class TestHelper { */ public static Logger setupLogger() { Logger logger = Mockito.mock(Logger.class); - ConsoleLogger.setLogger(logger); + ConsoleLogger.initialize(logger, null); return logger; } @@ -91,7 +91,7 @@ public final class TestHelper { */ public static Logger setRealLogger() { Logger logger = Logger.getAnonymousLogger(); - ConsoleLogger.setLogger(logger); + ConsoleLogger.initialize(logger, null); return logger; } diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java index 8b10de64c..679b5e527 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java @@ -118,9 +118,8 @@ public class ReloadCommandTest { verify(authMe).stopOrUnload(); } - @SuppressWarnings("unchecked") @Test - public void shouldIssueWarningForChangedDatasourceSetting() { + public void shouldIssueWarningForChangedDataSourceSetting() { // given CommandSender sender = mock(CommandSender.class); given(settings.getProperty(DatabaseSettings.BACKEND)).willReturn(DataSourceType.MYSQL); diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java index fe798facc..da3bc00f8 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java @@ -1,6 +1,8 @@ package fr.xephi.authme.data.limbo; +import fr.xephi.authme.TestHelper; import org.bukkit.Location; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -26,6 +28,11 @@ public class LimboServiceHelperTest { @InjectMocks private LimboServiceHelper limboServiceHelper; + @BeforeClass + public static void initLogger() { + TestHelper.setupLogger(); + } + @Test public void shouldMergeLimboPlayers() { // given diff --git a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java index d57e29fec..bc1e9769d 100644 --- a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java @@ -12,6 +12,7 @@ import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.expiring.Duration; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; @@ -78,6 +79,11 @@ public class MessagesIntegrationTest { messages = new Messages(messagesFileHandler); } + @AfterClass + public static void removeLoggerReferences() { + ConsoleLogger.initialize(null, null); + } + @Test public void shouldLoadMessageAndSplitAtNewLines() { // given @@ -216,7 +222,7 @@ public class MessagesIntegrationTest { public void shouldLogErrorForInvalidReplacementCount() { // given Logger logger = mock(Logger.class); - ConsoleLogger.setLogger(logger); + ConsoleLogger.initialize(logger, null); MessageKey key = MessageKey.CAPTCHA_WRONG_ERROR; CommandSender sender = mock(CommandSender.class); given(sender.getName()).willReturn("Tester"); @@ -232,7 +238,7 @@ public class MessagesIntegrationTest { public void shouldSendErrorForReplacementsOnKeyWithNoTags() { // given Logger logger = mock(Logger.class); - ConsoleLogger.setLogger(logger); + ConsoleLogger.initialize(logger, null); MessageKey key = MessageKey.UNKNOWN_USER; CommandSender sender = mock(CommandSender.class); given(sender.getName()).willReturn("Tester"); diff --git a/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java b/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java new file mode 100644 index 000000000..c1042ae97 --- /dev/null +++ b/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java @@ -0,0 +1,94 @@ +package fr.xephi.authme.output; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.ReflectionTestUtils; +import fr.xephi.authme.TestHelper; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.properties.PluginSettings; +import fr.xephi.authme.settings.properties.SecuritySettings; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Map; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.sameInstance; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * Test for {@link ConsoleLoggerFactory}. + */ +public class ConsoleLoggerFactoryTest { + + @BeforeClass + public static void initLogger() { + removeSettingsAndClearMap(); + TestHelper.setupLogger(); + } + + @After + public void resetConsoleLoggerFactoryToDefaults() { + removeSettingsAndClearMap(); + } + + private static void removeSettingsAndClearMap() { + setSettings(null); + getConsoleLoggerMap().clear(); + } + + @Test + public void shouldCreateLoggerWithProperNameAndDefaultLogLevel() { + // given / when + ConsoleLogger logger = ConsoleLoggerFactory.get(AuthMe.class); + + // then + assertThat(logger.getName(), equalTo("fr.xephi.authme.AuthMe")); + assertThat(logger.getLogLevel(), equalTo(LogLevel.INFO)); + assertThat(getConsoleLoggerMap().keySet(), contains("fr.xephi.authme.AuthMe")); + } + + @Test + public void shouldReturnSameInstanceForName() { + // given / when + ConsoleLogger logger1 = ConsoleLoggerFactory.get(String.class); + ConsoleLogger logger2 = ConsoleLoggerFactory.get(Number.class); + ConsoleLogger logger3 = ConsoleLoggerFactory.get(String.class); + + // then + assertThat(getConsoleLoggerMap().keySet(), containsInAnyOrder("java.lang.String", "java.lang.Number")); + assertThat(logger3, sameInstance(logger1)); + assertThat(logger2, not(sameInstance(logger1))); + } + + @Test + public void shouldInitializeAccordingToSettings() { + // given + Settings settings = mock(Settings.class); + given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.FINE); + given(settings.getProperty(SecuritySettings.USE_LOGGING)).willReturn(false); + ConsoleLogger existingLogger = ConsoleLoggerFactory.get(String.class); + + // when + ConsoleLoggerFactory.reloadSettings(settings); + ConsoleLogger newLogger = ConsoleLoggerFactory.get(AuthMe.class); + + // then + assertThat(existingLogger.getLogLevel(), equalTo(LogLevel.FINE)); + assertThat(newLogger.getLogLevel(), equalTo(LogLevel.FINE)); + } + + private static void setSettings(Settings settings) { + ReflectionTestUtils.setField(ConsoleLoggerFactory.class, null, "settings", settings); + } + + private static Map getConsoleLoggerMap() { + return ReflectionTestUtils.getFieldValue(ConsoleLoggerFactory.class, null, "consoleLoggers"); + } +} diff --git a/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java b/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java index 29b03c947..5972ba749 100644 --- a/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java +++ b/src/test/java/tools/docs/hashmethods/EncryptionMethodInfoGatherer.java @@ -38,7 +38,7 @@ public class EncryptionMethodInfoGatherer { private Map descriptions; public EncryptionMethodInfoGatherer() { - ConsoleLogger.setLogger(Logger.getAnonymousLogger()); // set logger because of Argon2.isLibraryLoaded() + ConsoleLogger.initialize(Logger.getAnonymousLogger(), null); // set logger because of Argon2.isLibraryLoaded() descriptions = new LinkedHashMap<>(); constructDescriptions(); } From d87fa860e68a80eb8eab66e8ae9327305f8d0e9e Mon Sep 17 00:00:00 2001 From: ljacqu Date: Tue, 6 Aug 2019 19:42:06 +0200 Subject: [PATCH 79/83] Add test for UuidUtils --- .../java/fr/xephi/authme/util/UuidUtils.java | 8 ++--- .../fr/xephi/authme/util/UuidUtilsTest.java | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 src/test/java/fr/xephi/authme/util/UuidUtilsTest.java diff --git a/src/main/java/fr/xephi/authme/util/UuidUtils.java b/src/main/java/fr/xephi/authme/util/UuidUtils.java index 4a2306af6..be35a9351 100644 --- a/src/main/java/fr/xephi/authme/util/UuidUtils.java +++ b/src/main/java/fr/xephi/authme/util/UuidUtils.java @@ -12,15 +12,15 @@ public final class UuidUtils { } /** - * Returns whether the given string as an UUID or null + * Returns the given string as an UUID or null. * * @param string the uuid to parse - * @return parsed UUID if succeed or null + * @return parsed UUID if succeeded or null */ public static UUID parseUuidSafely(String string) { try { - return UUID.fromString(string); - } catch (IllegalArgumentException | NullPointerException ex) { + return string == null ? null : UUID.fromString(string); + } catch (IllegalArgumentException ex) { return null; } } diff --git a/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java b/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java new file mode 100644 index 000000000..b98bdba99 --- /dev/null +++ b/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java @@ -0,0 +1,29 @@ +package fr.xephi.authme.util; + +import org.junit.Test; + +import java.util.UUID; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +/** + * Test for {@link UuidUtils}. + */ +public class UuidUtilsTest { + + @Test + public void shouldParseUuidSafely() { + // given + UUID correctUuid = UUID.fromString("8e0a9aaa-5eda-42ef-8daf-e6c6359f607e"); + + // when / then + assertThat(UuidUtils.parseUuidSafely("8e0a9aaa-5eda-42ef-8daf-e6c6359f607e"), equalTo(correctUuid)); + + assertThat(UuidUtils.parseUuidSafely(null), nullValue()); + assertThat(UuidUtils.parseUuidSafely(""), nullValue()); + assertThat(UuidUtils.parseUuidSafely("foo"), nullValue()); + assertThat(UuidUtils.parseUuidSafely("8e0a9aaa-5eda-42ef-InvalidEnding"), nullValue()); + } +} From fadda43d133831bcde29f5884c4339cc81e58577 Mon Sep 17 00:00:00 2001 From: Hex3l <5870241+Hex3l@users.noreply.github.com> Date: Wed, 7 Aug 2019 01:01:55 +0200 Subject: [PATCH 80/83] Improves spawn choice if undefined (#1880) * Improves spawn choice if undefined #1700 * Just a missing line <.< * Moves the checks into the "default" case --- .../fr/xephi/authme/settings/SpawnLoader.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/main/java/fr/xephi/authme/settings/SpawnLoader.java b/src/main/java/fr/xephi/authme/settings/SpawnLoader.java index 403b058cf..7b3fc1385 100644 --- a/src/main/java/fr/xephi/authme/settings/SpawnLoader.java +++ b/src/main/java/fr/xephi/authme/settings/SpawnLoader.java @@ -180,6 +180,16 @@ public class SpawnLoader implements Reloadable { switch (priority.toLowerCase().trim()) { case "default": if (world.getSpawnLocation() != null) { + if (!isValidSpawnPoint(world.getSpawnLocation())) { + for (World spawnWorld : Bukkit.getWorlds()) { + if (isValidSpawnPoint(spawnWorld.getSpawnLocation())) { + world = spawnWorld; + break; + } + } + logger.warning("Seems like AuthMe is unable to find a proper spawn location. " + + "Set a location with the command '/authme setspawn'"); + } spawnLoc = world.getSpawnLocation(); } break; @@ -206,9 +216,24 @@ public class SpawnLoader implements Reloadable { } } logger.debug("Fall back to default world spawn location. World: `{0}`", world.getName()); + return world.getSpawnLocation(); // return default location } + /** + * Checks if a given location is a valid spawn point [!= (0,0,0)]. + * + * @param location The location to check + * + * @return True upon success, false otherwise + */ + private boolean isValidSpawnPoint(Location location) { + if (location.getX() == 0 && location.getY() == 0 && location.getZ() == 0) { + return false; + } + return true; + } + /** * Save the location under the given prefix. * From db3acce70c2096054e7854d318cf29688280a6fd Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Wed, 7 Aug 2019 06:47:00 +0200 Subject: [PATCH 81/83] Packet based movement freeze (#1879) * Remove unused files * Remove walk/fly speed from limbo player * Implement packet based movement freeze --- docs/config.md | 17 +- samples/NewConfig.yml | 570 ------------------ samples/NewPlugin.yml | 199 ------ .../authme/debug/LimboPlayerViewer.java | 2 - .../xephi/authme/data/limbo/LimboPlayer.java | 18 +- .../xephi/authme/data/limbo/LimboService.java | 4 - .../authme/data/limbo/LimboServiceHelper.java | 15 +- .../data/limbo/WalkFlySpeedRestoreType.java | 123 ---- .../persistence/LimboPlayerDeserializer.java | 6 +- .../persistence/LimboPlayerSerializer.java | 4 - .../protocollib/FreezePacketAdapter.java | 128 ++++ .../protocollib/ProtocolLibService.java | 55 +- .../process/login/ProcessSyncPlayerLogin.java | 8 + .../logout/ProcessSyncPlayerLogout.java | 3 + .../settings/properties/LimboSettings.java | 22 +- .../data/limbo/LimboPlayerMatchers.java | 18 +- .../limbo/LimboPlayerTaskManagerTest.java | 6 +- .../data/limbo/LimboServiceHelperTest.java | 12 +- .../authme/data/limbo/LimboServiceTest.java | 27 +- .../limbo/WalkFlySpeedRestoreTypeTest.java | 108 ---- ...istributedFilesPersistenceHandlerTest.java | 12 +- ...IndividualFilesPersistenceHandlerTest.java | 4 +- .../data/backup/sample-folder/data.json | 2 - .../authme/data/limbo/seg16-8-limbo.json | 8 +- .../authme/data/limbo/seg16-f-limbo.json | 4 +- .../authme/data/limbo/seg32-10110-limbo.json | 4 +- 26 files changed, 234 insertions(+), 1145 deletions(-) delete mode 100644 samples/NewConfig.yml delete mode 100644 samples/NewPlugin.yml delete mode 100644 src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java create mode 100644 src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java delete mode 100644 src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java diff --git a/docs/config.md b/docs/config.md index 811481d5e..b621a87e8 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1,5 +1,5 @@ - + ## AuthMe Configuration The first time you run AuthMe it will create a config.yml file in the plugins/AuthMe folder, @@ -501,7 +501,7 @@ Security: # Minutes after which a verification code will expire verificationCodeExpiration: 10 # Before a user logs in, various properties are temporarily removed from the player, -# such as OP status, ability to fly, and walk/fly speed. +# such as OP status and the ability to fly. # Once the user is logged in, we add back the properties we previously saved. # In this section, you may define how these properties should be handled. # Read more at https://github.com/AuthMe/AuthMeReloaded/wiki/Limbo-players @@ -509,7 +509,7 @@ limbo: persistence: # Besides storing the data in memory, you can define if/how the data should be persisted # on disk. This is useful in case of a server crash, so next time the server starts we can - # properly restore things like OP status, ability to fly, and walk/fly speed. + # properly restore things like OP status and the ability to fly # DISABLED: no disk storage, # INDIVIDUAL_FILES: each player data in its own file, # DISTRIBUTED_FILES: distributes players into different files based on their UUID, see below @@ -528,15 +528,6 @@ limbo: # RESTORE sets back the old property from the player. NOTHING will prevent AuthMe # from modifying the 'allow flight' property on the player. restoreAllowFlight: RESTORE - # Restore fly speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO. - # RESTORE: restore the speed the player had; - # DEFAULT: always set to default speed; - # MAX_RESTORE: take the maximum of the player's current speed and the previous one - # RESTORE_NO_ZERO: Like 'restore' but sets speed to default if the player's speed was 0 - restoreFlySpeed: RESTORE_NO_ZERO - # Restore walk speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO. - # See above for a description of the values. - restoreWalkSpeed: RESTORE_NO_ZERO BackupSystem: # General configuration for backups: if false, no backups are possible ActivateBackup: false @@ -578,4 +569,4 @@ To change settings on a running server, save your changes to config.yml and use --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Tue Apr 23 17:17:02 CEST 2019 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Mon Aug 05 18:57:10 CEST 2019 diff --git a/samples/NewConfig.yml b/samples/NewConfig.yml deleted file mode 100644 index 91e063d08..000000000 --- a/samples/NewConfig.yml +++ /dev/null @@ -1,570 +0,0 @@ -# ======================================================================================================= -# _____ __ .__ _____ __________ .__ .___ .___ -# / _ \ __ ___/ |_| |__ / \ ____\______ \ ____ | | _________ __| _/____ __| _/ -# / /_\ \| | \ __| | \ / \ / \_/ __ \| __/ __ \| | / _ \__ \ / __ _/ __ \ / __ | -# / | | | /| | | Y / Y \ ___/| | \ ___/| |_( <_> / __ \/ /_/ \ ___// /_/ | -# \____|__ |____/ |__| |___| \____|__ /\___ |____|_ /\___ |____/\____(____ \____ |\___ \____ | -# \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ -# -# ======================================================================================================= -# -# Authme Main Configuration File. -# -# ======================================================================================================= - -# Plugin infos (overwritten on start, just a simple way to find out your plugin version). -authors: ${pluginAuthors} -version: ${project.version} -buildNumber: ${buildNumber} - -# Set this setting to true when you have configured the plugin, -# when false the server will be stopped with a warning message. -enabled: false - -# Database settings. -data_source: - # =========================== - # Database general settings. - # =========================== - - # Database backend (sqlite, mysql). - backend: sqlite - # Enable database queries caching, should improve performance. - caching: true - - # =========================== - # SqLite db parameters. - # =========================== - - sqlite: - # The name of the database storage file. - filename: 'authme.db' - - # =========================== - # MySql db parameters. - # =========================== - - mysql: - # Connection parameters. - host: '127.0.0.1' - port: 3306 - username: 'change_me' - password: 'change_me' - database: 'my_minecraft_server' - tablename: 'authme' - - # Column names. - column_names: - id: id - # Column for storing nicknames (ignore case nickname). - name: username - # Column for storing the realname (case sensitive nickname). - real_name: realname - # Column for storing passwords. - password: password - # Column for storing email addresses. - email: email - # Column for storing the authentication status (logged or not). - login_status: isLogged - # Column for storing player IPs. - ip: ip - # Column for storing lastlogins date and time. - last_login_timestamp: lastlogin - # Latest logout location of the players. - last_location: - world: world - x: x - y: y - z: z - # Enabled only if the bungeecord integration is activated. - server: world - - # Support for registrations via WebInterfaces/CSM. - # Disable some backend caching parameters. - disableAggressiveCaching: false - -# Main settings -settings: - - # =========================== - # Bungeecord integration - # =========================== - - bungeecord: - # Enable bungeecord integration features - enabled: true - - # Server name (must be unique, please use the name in the bungeecord configuration). - # Use 'auto' for auto configuration (requires the bungeecord module). - serverName: LoginLobby1 - # Keep the auth status when the player moves between servers. - # Required if you're using the bungeecord module. - keepAuthBetweenServers: true - - # Target server after login - send_after_login: - enabled: false - message: '' - delay: 5 - # Server name ("ServerName") or group ("G:GroupName") - # Groups are avariable only when the bungeecord module is avariable. - # If the server change fails the player will be kicked. - target: Lobby1 - failKickMessage: 'Failed to connect to the lobby! Please try to join the server again!' - # Target server after logout - send_after_logout: - enabled: false - message: '' - delay: 5 - # Server name ("ServerName") or group ("G:GroupName") - # Groups are avariable only when the bungeecord module is avariable. - # If the server change fails the player will be kicked. - target: LoginLobby1 - failKickMessage: 'Failed to connect to the lobby! Please try to join the server again!' - - # Variables: - # %p playername - bungee_commands: - player_command_after_register: - enabled: false - cmd: '' - console_command_after_register: - enabled: false - cmd: 'alert %p joined for the first time the network!' - player_command_after_login: - enabled: false - cmd: 'glist' - console_command_after_login: - enabled: false - cmd: 'alert %p logged in correctly!' - player_command_after_join: - enabled: false - cmd: '' - console_command_after_join: - enabled: false - cmd: 'alert %p joined the network!' - player_command_first_join: - enabled: false - cmd: '' - console_command_first_join: - enabled: false - cmd: 'alert %p joined for the first time the network!' - - # =========================== - # Sessions configuration. - # =========================== - - sessions: - # Enable sessions. - # When a player is authenticated, his IP and his nickname is saved. - # The next time the player will join the server, if his IP is the same - # of the last time, and the timeout time hasn't expired, he will be - # automatically authenticated. - enabled: false - # Session timeout. - # 0 for unlimited time (Very dangerous, use it at your own risk!) - # Consider that if player's ip has changed but the timeout hasn't - # expired, player will be kicked out of the sever! - timeout: 10 - # When enabled a player's session will expire if someone tries to - # login with a different IP Address. - expire_on_ip_change: true - - # =========================== - # Registration settings. - # =========================== - - registration: - # After how many time unregistered players should be kicked? - # Set to 0 to disable. (default: 30) - timeout: 30 - - nickname: - min_length: 4 - max_lenght: 16 - # Regex syntax. - allowed_characters: '[a-zA-Z0-9_]*' - - password: - # Enable double check of password on registration: - # /register - double_check: true - # Minimum password lenght. - min_length: 5 - # Regex syntax. - allowed_characters: '[\x21-\x7E]*' - # Denied unsafe passwords. - unsafePasswords: - - '123456' - - 'password' - - 'qwerty' - - '12345' - - '54321' - - # =========================== - # Login settings. - # =========================== - - login: - # After how many time unlogged players should be kicked? - # Set to 0 to disable. (default: 30) - timeout: 30 - - - - # =========================== - # Encryption parameters. - # =========================== - - password_encryption: - # The hashing algorithm. - # Possible values: MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, MYBB, IPB3, - # PHPFUSION, SMF, XENFORO, SALTED2MD5, JOOMLA, BCRYPT, WBB3, SHA512, DOUBLEMD5, - # PBKDF2, PBKDF2DJANGO, WORDPRESS, ROYALAUTH, CUSTOM (developpers only). - encryption_algorithm: SHA256 - # The salt length for the SALTED2MD5 and MD5(MD5(password)+salt) algorithms. - md5_salt_length: 8 - # If password check fails try all the other hash algorithm. - # AuthMe will update the password to the new passwordHash. - enable_convertion: false - - # =========================== - # Unlogged user restrictions. - # =========================== - - unlogged_restrictions: - # Deny chat messages send for unlogged users. - deny_chat: true - # Hide chat to unlogged users. - # Only player messages, plugins will be able to send messages to the player anyway. - hide_chat: false - - # Deny any command message not in the whitelist below. - deny_commands: true - command_whitelist: - - /login - - /register - - /l - - /reg - - /email - - /captcha - - movements: - # Restrict player movements. - restrict: true - # Allowed radius. - allowed_radius: 0 - # Should unlogged players have speed = 0? - # After the login the walking/flying speeed will be reset to the default value. - removeSpeed: true - - # End is there atm xD - - # This option will save the quit location of the players. - SaveQuitLocation: false - # Should not logged in players be teleported to the spawn? - # After the authentication, if SaveQuitLocation is enabled, - # they will be teleported back to their normal position. - teleportUnAuthedToSpawn: false - - # If enabled, after the login, if the ForceSpawnOnTheseWorlds setting contains - # the player's world, he will be teleported to the world spawnpoint. - # The quit location of the player will be overwritten. - # This is different from "teleportUnAuthedToSpawn" that teleports player - # back to his quit location after the authentication. - ForceSpawnLocOnJoinEnabled: false - # WorldNames where we need to force the spawn location - # Warning: This setting is Case Sensitive! - ForceSpawnOnTheseWorlds: - - world - - world_nether - - world_the_end - - # this is very important options, - # every time player join the server, - # if they are registered, AuthMe will switch him - # to unLoggedInGroup, this - # should prevent all major exploit. - # So you can set up on your Permission Plugin - # this special group with 0 permissions, or permissions to chat, - # or permission to - # send private message or all other perms that you want, - # the better way is to set up - # this group with few permissions, - # so if player try to exploit some account, - # they can - # do anything except what you set in perm Group. - # After a correct logged-in player will be - # moved to his correct permissions group! - # Pay attention group name is case sensitive, - # so Admin is different from admin, - # otherwise your group will be wiped, - # and player join in default group []! - # Example unLoggedinGroup: NotLogged - unLoggedinGroup: unLoggedinGroup - - # =========================== - # Address restrictions - # =========================== - - # Max number of registrations per IP (default: 1) - maxRegPerIp: 1 - # Maximum allowed number of Logins per IP, 0 to disable (default: 0) - maxLoginPerIp: 0 - # Maximum allowed number of Joins per IP, 0 to disable (default: 0) - maxJoinPerIp: 0 - - # When this setting is enabled, online players can't be kicked out - # due to "Logged in from another Location" - # This setting will prevent potetial security exploits. - ForceSingleSession: true - - # To activate the restricted user feature you need - # to enable this option and configure the - # AllowedRestrctedUser field. - AllowRestrictedUser: false - # The restricted user feature will kick players listed below - # if they dont match of the defined ip address. - # Example: - # AllowedRestrictedUser: - # - playername;127.0.0.1 - AllowedRestrictedUser: - - playername;127.0.0. - # Ban ip when the ip is not the ip registered in database - banUnsafedIP: false - - - - # =============================== - # Other restrictions - # =============================== - - # Should we protect the player inventory before logging in? - # Warning: Requires the latest version of ProtocolLib! - ProtectInventoryBeforeLogIn: true - - # Should unregistered players be kicked immediately? - kickNonRegistered: false - # Should players be kicked on wrong password? - kickOnWrongPassword: false - - # Should we display all other accounts of a player when he joins? - # Required permission: authme.admin.accounts - displayOtherAccounts: true - - # =============================== - # Restrictions compatibility - # =============================== - - # Spawn Priority. Avariable values : authme, essentials, multiverse, default - spawnPriority: authme,essentials,multiverse,default - # AuthMe will NEVER teleport players! - noTeleport: false - - GameMode: - # Do you want to set player's gamemode to survival when he joins? - # This enables also the settings below. - ForceSurvivalMode: false - # Do you want to reset player's inventory if player joins with creative mode? - ResetInventoryIfCreative: false - # Do you want to force the survival mode ONLY after the /login process? - ForceOnlyAfterLogin: false - - # sgdc3: Ok, our configuration is shit.... xD Today I will stop there - - - registration: - # enable registration on the server? - enabled: true - # Send every X seconds a message to a player to - # remind him that he has to login/register - messageInterval: 5 - # Only registered and logged in players can play. - # See restrictions for exceptions - force: true - # Does we replace password registration by an Email registration method ? - enableEmailRegistrationSystem: false - # Enable double check of email when you register - # when it's true, registration require that kind of command: - # /register - doubleEmailCheck: false - # Do we force kicking player after a successful registration ? - # Do not use with login feature below - forceKickAfterRegister: false - # Does AuthMe need to enforce a /login after a successful registration ? - forceLoginAfterRegister: false - unrestrictions: - # below you can list all your account name, that - # AuthMe will ignore for registration or login, configure it - # at your own risk!! Remember that if you are going to add - # nickname with [], you have to delimit name with ' '. - # this option add compatibility with BuildCraft and some - # other mods. - # It is CaseSensitive! - UnrestrictedName: [] - # Message language, available : en, de, br, cz, pl, fr, ru, hu, sk, es, zhtw, fi, zhcn, lt, it, ko, pt - messagesLanguage: en - # Force these commands after /login, without any '/', use %p for replace with player name - forceCommands: [] - # Force these commands after /login as a server console, without any '/', use %p for replace with player name - forceCommandsAsConsole: [] - # Force these commands after /register, without any '/', use %p for replace with player name - forceRegisterCommands: [] - # Force these commands after /register as a server console, without any '/', use %p for replace with player name - forceRegisterCommandsAsConsole: [] - # Do we need to display the welcome message (welcome.txt) after a register or a login? - # You can use colors in this welcome.txt + some replaced strings : - # {PLAYER} : player name, {ONLINE} : display number of online players, {MAXPLAYERS} : display server slots, - # {IP} : player ip, {LOGINS} : number of players logged, {WORLD} : player current world, {SERVER} : server name - # {VERSION} : get current bukkit version, {COUNTRY} : player country - useWelcomeMessage: true - # Do we need to broadcast the welcome message to all server or only to the player? set true for server or false for player - broadcastWelcomeMessage: false - # Do we need to delay the join/leave message to be displayed only when the player is authenticated ? - delayJoinMessage: false - removeJoinMessage: false - removeLeaveMessage: false - # Do we need to add potion effect Blinding before login/register ? - applyBlindEffect: false -ExternalBoardOptions: - # MySQL column for the salt , needed for some forum/cms support - mySQLColumnSalt: '' - # MySQL column for the group, needed for some forum/cms support - mySQLColumnGroup: '' - # -1 mean disabled. If u want that only - # activated player can login in your server - # u can put in this options the group number - # of unactivated user, needed for some forum/cms support - nonActivedUserGroup: -1 - # Other MySQL columns where we need to put the Username (case sensitive) - mySQLOtherUsernameColumns: [] - # How much Log to Round needed in BCrypt(do not change it if you do not know what's your doing) - bCryptLog2Round: 10 - # phpBB prefix defined during phpbb installation process - phpbbTablePrefix: 'phpbb_' - # phpBB activated group id , 2 is default registered group defined by phpbb - phpbbActivatedGroupId: 2 - # WordPress prefix defined during WordPress installation process - wordpressTablePrefix: 'wp_' -permission: - # Take care with this options, if you dont want - # to use Vault and Group Switching of - # AuthMe for unloggedIn players put true - # below, default is false. - EnablePermissionCheck: false -BackupSystem: - # Enable or Disable Automatic Backup - ActivateBackup: false - # set Backup at every start of Server - OnServerStart: false - # set Backup at every stop of Server - OnServerStop: true - # Windows only mysql installation Path - MysqlWindowsPath: 'C:\\Program Files\\MySQL\\MySQL Server 5.1\\' -Security: - SQLProblem: - # Stop the server if we can't contact the sql database - # Take care with this, if you set that to false, - # AuthMe automatically disable and the server is not protected! - stopServer: true - ReloadCommand: - # /reload support - useReloadCommandSupport: true - console: - # Remove spam console - noConsoleSpam: false - captcha: - # Player need to put a captcha when he fails too lot the password - useCaptcha: false - # Max allowed tries before request a captcha - maxLoginTry: 5 - # Captcha length - captchaLength: 5 -Converter: - Rakamak: - # Rakamak file name - fileName: users.rak - # Rakamak use ip ? - useIP: false - # IP file name for rakamak - ipFileName: UsersIp.rak - CrazyLogin: - # CrazyLogin database file - fileName: accounts.db -Email: - # Email SMTP server host - mailSMTP: smtp.gmail.com - # Email SMTP server port - mailPort: 465 - # Email account that send the mail - mailAccount: '' - # Email account password - mailPassword: '' - # Custom SenderName, that replace the mailAccount name in the email - mailSenderName: '' - # Random password length - RecoveryPasswordLength: 8 - # Email subject of password get - mailSubject: 'Your new AuthMe Password' - # Email text here - mailText: 'Dear ,

This is your new AuthMe password for the server

:



Do not forget to change password after login!
/changepassword newPassword' - # Like maxRegPerIp but with email - maxRegPerEmail: 1 - # Recall players to add an email ? - recallPlayers: false - # Delay in minute for the recall scheduler - delayRecall: 5 - # Blacklist these domains for emails - emailBlacklisted: - - 10minutemail.com - # WhiteList only these domains for emails - emailWhitelisted: [] - # Do we need to send new password draw in an image ? - generateImage: false -Hooks: - # Do we need to hook with multiverse for spawn checking? - multiverse: true - # Do we need to hook with BungeeCord for get the real Player ip ? - bungeecord: false - # Do we need to disable Essentials SocialSpy on join ? - disableSocialSpy: true - # Do we need to force /motd Essentials command on join ? - useEssentialsMotd: false - # Do we need to cache custom Attributes ? - customAttributes: false -Purge: - # On Enable , does AuthMe need to purge automatically old accounts unused ? - useAutoPurge: false - # Number of Days an account become Unused - daysBeforeRemovePlayer: 60 - # Do we need to remove the player.dat file during purge process ? - removePlayerDat: false - # Do we need to remove the Essentials/users/player.yml file during purge process ? - removeEssentialsFile: false - # World where are players.dat stores - defaultWorld: 'world' - # Do we need to remove LimitedCreative/inventories/player.yml , player_creative.yml files during purge process ? - removeLimitedCreativesInventories: false - # Do we need to remove the AntiXRayData/PlayerData/player file during purge process ? - removeAntiXRayFile: false - # Do we need to remove permissions ? - removePermissions: false -Protection: - # Enable some servers protection ( country based login, antibot ) - enableProtection: false - # Countries allowed to join the server and register, see http://dev.bukkit.org/bukkit-plugins/authme-reloaded/pages/countries-codes/ for countries' codes - countries: - - US - - GB - # Countries blacklisted automatically ( without any needed to enable protection ) - countriesBlacklist: - - A1 - # Do we need to enable automatic antibot system? - enableAntiBot: false - # Max number of player allowed to login in 5 secs before enable AntiBot system automatically - antiBotSensibility: 5 - # Duration in minutes of the antibot automatic system - antiBotDuration: 10 -VeryGames: - # These features are only available on VeryGames Server Provider - enableIpCheck: false diff --git a/samples/NewPlugin.yml b/samples/NewPlugin.yml deleted file mode 100644 index f403da60b..000000000 --- a/samples/NewPlugin.yml +++ /dev/null @@ -1,199 +0,0 @@ -name: ${pluginName} -authors: [${pluginAuthors}] -website: ${project.url} -description: ${project.description} -main: ${mainClass} -version: ${project.version}-b${buildNumber} -softdepend: - - Vault - - PermissionsBukkit - - PermissionsEX - - EssentialsGroupManager - - Multiverse-Core - - Essentials - - EssentialsSpawn - - ProtocolLib -commands: - authme: - description: AuthMe admin commands - usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version|converter datatype' - permission: authme.admin - register: - description: Register an account - usage: /register password confirmpassword - aliases: [reg] - permission: authme.player.register - login: - description: Login into a account - usage: /login password - aliases: [l,log] - permission: authme.player.login - changepassword: - description: Change password of a account - usage: /changepassword oldPassword newPassword - permission: authme.player.changepassword - logout: - description: Logout from the server - usage: /logout - permission: authme.player.logout - unregister: - description: unregister your account - usage: /unregister password - permission: authme.player.unregister - email: - description: Add Email or recover password - usage: '/email add your@email.com your@email.com|change oldEmail newEmail|recovery your@email.com' - permission: authme.player.email - captcha: - description: Captcha command - usage: /captcha theCaptcha - permission: authme.player.captcha -permissions: - authme.canbeforced: - description: Allow the user to be forced-logged via API - default: true - authme.player: - description: Gives access to all authme player commands - default: true - children: - authme.player.login: true - authme.player.logout: true - authme.player.register: true - authme.player.unregister: true - authme.player.changepassword: true - authme.player.captcha: true - authme.player.email: true - authme.player.register: - description: Register your account - default: false - authme.player.unregister: - description: Unregister your account - default: false - authme.player.login: - description: Login into your account - default: false - authme.player.logout: - description: Logout from your account - default: false - authme.player.changepassword: - description: Change password of your account - default: false - authme.player.email: - description: Gives access to player's email commands - default: false - children: - authme.player.email.add: true - authme.player.email.change: true - authme.player.email.recover: true - authme.player.email.add: - description: Add an email to your account - default: false - authme.player.email.change: - description: Change email of your account - default: false - authme.player.email.recover: - description: Recover your account - default: false - authme.player.captcha: - description: Captcha command - default: false - authme.admin: - description: Gives access to all authme admin commands - default: op - children: - authme.admin.forcelogin: true - authme.admin.forcelogout: true - authme.admin.register: true - authme.admin.unregister: true - authme.admin.changemail: true - authme.admin.changepassword: true - authme.admin.lastlogin: true - authme.admin.accounts: true - authme.admin.getemail: true - authme.admin.getip: true - authme.admin.setspawn: true - authme.admin.spawn: true - authme.admin.setfirstspawn: true - authme.admin.firstspawn: true - authme.admin.purge: true - authme.admin.purgebannedplayers: true - authme.admin.purgelastpos: true - authme.admin.converter: true - authme.admin.reload: true - authme.admin.switchantibot: true - authme.admin.seeotheraccounts: true - authme.admin.register: - description: Register an account - default: false - authme.admin.unregister: - description: Unregister an account - default: false - authme.admin.forcelogin: - description: Force login for that player - default: false - authme.admin.forcelogout: - description: Force logout for that player - default: false - authme.admin.changepassword: - description: Change the password of an account - default: false - authme.admin.getemail: - description: Get last email about a player - default: false - authme.admin.changeemail: - description: Change a player email - default: false - authme.admin.accounts: - description: Display Players Accounts - default: false - authme.admin.seeotheraccounts: - description: Display other accounts about a player when he logs in - default: false - authme.admin.lastlogin: - description: Get last login date about a player - default: false - authme.admin.getip: - description: Get IP from a player (fake and real) - default: false - authme.admin.setspawn: - description: Set the AuthMe spawn point - default: false - authme.admin.spawn: - description: Teleport to AuthMe spawn point - default: false - authme.admin.setfirstspawn: - description: Set the AuthMe First Spawn Point - default: false - authme.admin.firstspawn: - description: Teleport to AuthMe First Spawn Point - default: false - authme.admin.switchantibot: - description: Switch AntiBot mode on/off - default: false - authme.admin.purge: - description: Database purge command - default: false - authme.admin.purgebannedplayers: - description: Purge banned players - default: false - authme.admin.purgelastpos: - description: Purge last position of a player/players - default: false - authme.admin.converter: - description: Allow the /authme converter command - default: false - authme.admin.reload: - description: Reload the plugin - default: false - authme.vip: - description: Allow vip slot when the server is full - default: false - authme.bypassantibot: - description: Bypass the AntiBot check - default: false - authme.allowmultipleaccounts: - description: Allow more accounts for same ip - default: false - authme.bypassforcesurvival: - description: Bypass all ForceSurvival features - default: false diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java b/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java index 7338c8686..0f66647be 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java @@ -68,9 +68,7 @@ class LimboPlayerViewer implements DebugSection { sender.sendMessage(ChatColor.BLUE + "Player / limbo / disk limbo info for '" + arguments.get(0) + "'"); new InfoDisplayer(sender, player, memoryLimbo, diskLimbo) .sendEntry("Is op", Player::isOp, LimboPlayer::isOperator) - .sendEntry("Walk speed", Player::getWalkSpeed, LimboPlayer::getWalkSpeed) .sendEntry("Can fly", Player::getAllowFlight, LimboPlayer::isCanFly) - .sendEntry("Fly speed", Player::getFlySpeed, LimboPlayer::getFlySpeed) .sendEntry("Location", p -> formatLocation(p.getLocation()), l -> formatLocation(l.getLocation())) .sendEntry("Prim. group", p -> permissionsManager.hasGroupSupport() ? permissionsManager.getPrimaryGroup(p) : "N/A", diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java b/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java index 03c3ea138..c6cfb8693 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java @@ -12,27 +12,19 @@ import java.util.Collection; */ public class LimboPlayer { - public static final float DEFAULT_WALK_SPEED = 0.2f; - public static final float DEFAULT_FLY_SPEED = 0.1f; - private final boolean canFly; private final boolean operator; private final Collection groups; private final Location loc; - private final float walkSpeed; - private final float flySpeed; private BukkitTask timeoutTask = null; private MessageTask messageTask = null; private LimboPlayerState state = LimboPlayerState.PASSWORD_REQUIRED; - public LimboPlayer(Location loc, boolean operator, Collection groups, boolean fly, float walkSpeed, - float flySpeed) { + public LimboPlayer(Location loc, boolean operator, Collection groups, boolean fly) { this.loc = loc; this.operator = operator; this.groups = groups; this.canFly = fly; - this.walkSpeed = walkSpeed; - this.flySpeed = flySpeed; } /** @@ -66,14 +58,6 @@ public class LimboPlayer { return canFly; } - public float getWalkSpeed() { - return walkSpeed; - } - - public float getFlySpeed() { - return flySpeed; - } - /** * Return the timeout task, which kicks the player if he hasn't registered or logged in * after a configurable amount of time. diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboService.java b/src/main/java/fr/xephi/authme/data/limbo/LimboService.java index 937ed912d..0df992104 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboService.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboService.java @@ -14,8 +14,6 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_ALLOW_FLIGHT; -import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_FLY_SPEED; -import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_WALK_SPEED; /** * Service for managing players that are in "limbo," a temporary state players are @@ -119,8 +117,6 @@ public class LimboService { } else { player.setOp(limbo.isOperator()); settings.getProperty(RESTORE_ALLOW_FLIGHT).restoreAllowFlight(player, limbo); - settings.getProperty(RESTORE_FLY_SPEED).restoreFlySpeed(player, limbo); - settings.getProperty(RESTORE_WALK_SPEED).restoreWalkSpeed(player, limbo); limbo.clearTasks(); logger.debug("Restored LimboPlayer stats for `{0}`", lowerName); persistence.removeLimboPlayer(player); diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java b/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java index d51afbef7..1b1d33533 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java @@ -5,7 +5,6 @@ import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; -import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -40,13 +39,11 @@ class LimboServiceHelper { // For safety reasons an unregistered player should not have OP status after registration boolean isOperator = isRegistered && player.isOp(); boolean flyEnabled = player.getAllowFlight(); - float walkSpeed = player.getWalkSpeed(); - float flySpeed = player.getFlySpeed(); Collection playerGroups = permissionsManager.hasGroupSupport() ? permissionsManager.getGroups(player) : Collections.emptyList(); logger.debug("Player `{0}` has groups `{1}`", player.getName(), String.join(", ", playerGroups)); - return new LimboPlayer(location, isOperator, playerGroups, flyEnabled, walkSpeed, flySpeed); + return new LimboPlayer(location, isOperator, playerGroups, flyEnabled); } /** @@ -61,18 +58,12 @@ class LimboServiceHelper { player.setOp(false); settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT) .processPlayer(player); - - if (!settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)) { - player.setFlySpeed(0.0f); - player.setWalkSpeed(0.0f); - } } /** * Merges two existing LimboPlayer instances of a player. Merging is done the following way: *
    *
  • isOperator, allowFlight: true if either limbo has true
  • - *
  • flySpeed, walkSpeed: maximum value of either limbo player
  • *
  • groups, location: from old limbo if not empty/null, otherwise from new limbo
  • *
* @@ -89,12 +80,10 @@ class LimboServiceHelper { boolean isOperator = newLimbo.isOperator() || oldLimbo.isOperator(); boolean canFly = newLimbo.isCanFly() || oldLimbo.isCanFly(); - float flySpeed = Math.max(newLimbo.getFlySpeed(), oldLimbo.getFlySpeed()); - float walkSpeed = Math.max(newLimbo.getWalkSpeed(), oldLimbo.getWalkSpeed()); Collection groups = getLimboGroups(oldLimbo.getGroups(), newLimbo.getGroups()); Location location = firstNotNull(oldLimbo.getLocation(), newLimbo.getLocation()); - return new LimboPlayer(location, isOperator, groups, canFly, walkSpeed, flySpeed); + return new LimboPlayer(location, isOperator, groups, canFly); } private static Location firstNotNull(Location first, Location second) { diff --git a/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java b/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java deleted file mode 100644 index f4a249017..000000000 --- a/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java +++ /dev/null @@ -1,123 +0,0 @@ -package fr.xephi.authme.data.limbo; - -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.output.ConsoleLoggerFactory; -import org.bukkit.entity.Player; - -/** - * Possible types to restore the walk and fly speed from LimboPlayer - * back to Bukkit Player. - */ -public enum WalkFlySpeedRestoreType { - - /** - * Restores from LimboPlayer to Player. - */ - RESTORE { - @Override - public void restoreFlySpeed(Player player, LimboPlayer limbo) { - logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " - + limbo.getFlySpeed() + " (RESTORE mode)"); - player.setFlySpeed(limbo.getFlySpeed()); - } - - @Override - public void restoreWalkSpeed(Player player, LimboPlayer limbo) { - logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " - + limbo.getWalkSpeed() + " (RESTORE mode)"); - player.setWalkSpeed(limbo.getWalkSpeed()); - } - }, - - /** - * Restores from LimboPlayer, using the default speed if the speed on LimboPlayer is 0. - */ - RESTORE_NO_ZERO { - @Override - public void restoreFlySpeed(Player player, LimboPlayer limbo) { - float limboFlySpeed = limbo.getFlySpeed(); - if (limboFlySpeed > 0.01f) { - logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " - + limboFlySpeed + " (RESTORE_NO_ZERO mode)"); - player.setFlySpeed(limboFlySpeed); - } else { - logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() - + " to DEFAULT, it was 0! (RESTORE_NO_ZERO mode)"); - player.setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); - } - } - - @Override - public void restoreWalkSpeed(Player player, LimboPlayer limbo) { - float limboWalkSpeed = limbo.getWalkSpeed(); - if (limboWalkSpeed > 0.01f) { - logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " - + limboWalkSpeed + " (RESTORE_NO_ZERO mode)"); - player.setWalkSpeed(limboWalkSpeed); - } else { - logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + "" - + " to DEFAULT, it was 0! (RESTORE_NO_ZERO mode)"); - player.setWalkSpeed(LimboPlayer.DEFAULT_WALK_SPEED); - } - } - }, - - /** - * Uses the max speed of Player (current speed) and the LimboPlayer. - */ - MAX_RESTORE { - @Override - public void restoreFlySpeed(Player player, LimboPlayer limbo) { - float newSpeed = Math.max(player.getFlySpeed(), limbo.getFlySpeed()); - logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " + newSpeed - + " (Current: " + player.getFlySpeed() + ", Limbo: " + limbo.getFlySpeed() + ") (MAX_RESTORE mode)"); - player.setFlySpeed(newSpeed); - } - - @Override - public void restoreWalkSpeed(Player player, LimboPlayer limbo) { - float newSpeed = Math.max(player.getWalkSpeed(), limbo.getWalkSpeed()); - logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " + newSpeed - + " (Current: " + player.getWalkSpeed() + ", Limbo: " + limbo.getWalkSpeed() + ") (MAX_RESTORE mode)"); - player.setWalkSpeed(newSpeed); - } - }, - - /** - * Always sets the default speed to the player. - */ - DEFAULT { - @Override - public void restoreFlySpeed(Player player, LimboPlayer limbo) { - logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() - + " to DEFAULT (DEFAULT mode)"); - player.setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); - } - - @Override - public void restoreWalkSpeed(Player player, LimboPlayer limbo) { - logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() - + " to DEFAULT (DEFAULT mode)"); - player.setWalkSpeed(LimboPlayer.DEFAULT_WALK_SPEED); - } - }; - - private static final ConsoleLogger logger = ConsoleLoggerFactory.get(WalkFlySpeedRestoreType.class); - - /** - * Restores the fly speed from Limbo to Player according to the restoration type. - * - * @param player the player to modify - * @param limbo the limbo player to read from - */ - public abstract void restoreFlySpeed(Player player, LimboPlayer limbo); - - /** - * Restores the walk speed from Limbo to Player according to the restoration type. - * - * @param player the player to modify - * @param limbo the limbo player to read from - */ - public abstract void restoreWalkSpeed(Player player, LimboPlayer limbo); - -} diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java index c56885413..fe876bea4 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java @@ -18,7 +18,6 @@ import java.util.List; import java.util.function.Function; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.CAN_FLY; -import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.FLY_SPEED; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.GROUPS; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.IS_OP; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOCATION; @@ -28,7 +27,6 @@ import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_X import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_Y; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_YAW; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_Z; -import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.WALK_SPEED; import static java.util.Optional.ofNullable; /** @@ -56,10 +54,8 @@ class LimboPlayerDeserializer implements JsonDeserializer { Collection groups = getLimboGroups(jsonObject); boolean canFly = getBoolean(jsonObject, CAN_FLY); - float walkSpeed = getFloat(jsonObject, WALK_SPEED, LimboPlayer.DEFAULT_WALK_SPEED); - float flySpeed = getFloat(jsonObject, FLY_SPEED, LimboPlayer.DEFAULT_FLY_SPEED); - return new LimboPlayer(loc, operator, groups, canFly, walkSpeed, flySpeed); + return new LimboPlayer(loc, operator, groups, canFly); } private Location deserializeLocation(JsonObject jsonObject) { diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java index 5f9b40ede..1192aa515 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java @@ -26,8 +26,6 @@ class LimboPlayerSerializer implements JsonSerializer { static final String GROUPS = "groups"; static final String IS_OP = "operator"; static final String CAN_FLY = "can-fly"; - static final String WALK_SPEED = "walk-speed"; - static final String FLY_SPEED = "fly-speed"; private static final Gson GSON = new Gson(); @@ -49,8 +47,6 @@ class LimboPlayerSerializer implements JsonSerializer { obj.addProperty(IS_OP, limboPlayer.isOperator()); obj.addProperty(CAN_FLY, limboPlayer.isCanFly()); - obj.addProperty(WALK_SPEED, limboPlayer.getWalkSpeed()); - obj.addProperty(FLY_SPEED, limboPlayer.getFlySpeed()); return obj; } } diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java b/src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java new file mode 100644 index 000000000..5b6dd9ab1 --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2015 AuthMe-Team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package fr.xephi.authme.listener.protocollib; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; +import com.comphenix.protocol.wrappers.WrappedAttribute; +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.data.auth.PlayerCache; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.service.BukkitService; +import org.bukkit.entity.Player; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +class FreezePacketAdapter extends PacketAdapter { + + private static final String ATTRIBUTE_MOVEMENT_SPEED = "generic.movementSpeed"; + private static final String ATTRIBUTE_FLYING_SPEED = "generic.flyingSpeed"; + + private final ConsoleLogger logger = ConsoleLoggerFactory.get(FreezePacketAdapter.class); + private final PlayerCache playerCache; + private final DataSource dataSource; + + FreezePacketAdapter(AuthMe plugin, PlayerCache playerCache, DataSource dataSource) { + super(plugin, PacketType.Play.Server.UPDATE_ATTRIBUTES); + this.playerCache = playerCache; + this.dataSource = dataSource; + } + + @Override + public void onPacketSending(PacketEvent packetEvent) { + Player player = packetEvent.getPlayer(); + PacketContainer packet = packetEvent.getPacket(); + + int entityId = packet.getIntegers().read(0); + if (entityId != player.getEntityId()) { + return; + } + + if (!shouldFreeze(player.getName())) { + return; + } + + List newAttributes = new ArrayList<>(); + for (WrappedAttribute attribute : packet.getAttributeCollectionModifier().read(0)) { + if (ATTRIBUTE_MOVEMENT_SPEED.equals(attribute.getAttributeKey()) + || ATTRIBUTE_FLYING_SPEED.equals(attribute.getAttributeKey())) { + newAttributes.add(WrappedAttribute.newBuilder(attribute) + .baseValue(0.0f).modifiers(Collections.emptyList()).build()); + } else { + newAttributes.add(attribute); + } + } + packet.getAttributeCollectionModifier().write(0, newAttributes); + } + + protected void register(BukkitService bukkitService) { + ProtocolLibrary.getProtocolManager().addPacketListener(this); + + bukkitService.getOnlinePlayers().stream() + .filter(player -> shouldFreeze(player.getName())) + .forEach(this::sendFreezePacket); + } + + private boolean shouldFreeze(String playerName) { + return !playerCache.isAuthenticated(playerName) && dataSource.isAuthAvailable(playerName); + } + + public void unregister() { + ProtocolLibrary.getProtocolManager().removePacketListener(this); + } + + protected void sendFreezePacket(Player player) { + ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); + PacketContainer attributesPacket = protocolManager.createPacket(PacketType.Play.Server.UPDATE_ATTRIBUTES); + + attributesPacket.getIntegers().write(0, player.getEntityId()); + attributesPacket.getAttributeCollectionModifier().write(0, Arrays.asList( + WrappedAttribute.newBuilder() + .packet(attributesPacket) + .attributeKey(ATTRIBUTE_MOVEMENT_SPEED) + .baseValue(0.0f) + .build(), + WrappedAttribute.newBuilder() + .packet(attributesPacket) + .attributeKey(ATTRIBUTE_FLYING_SPEED) + .baseValue(0.0f) + .build() + )); + + try { + protocolManager.sendServerPacket(player, attributesPacket, false); + } catch (InvocationTargetException invocationExc) { + logger.logException("Error during sending freeze packet", invocationExc); + } + } + + public void sendUnFreezePacket(Player player) { + player.setWalkSpeed(player.getWalkSpeed()); + player.setFlySpeed(player.getFlySpeed()); + } +} diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java index 024077570..a56a72fc5 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java @@ -22,10 +22,12 @@ public class ProtocolLibService implements SettingsDependent { /* Packet Adapters */ private InventoryPacketAdapter inventoryPacketAdapter; private TabCompletePacketAdapter tabCompletePacketAdapter; + private FreezePacketAdapter freezePacketAdapter; /* Settings */ private boolean protectInvBeforeLogin; private boolean denyTabCompleteBeforeLogin; + private boolean freezePlayerBeforeLogin; /* Service */ private boolean isEnabled; @@ -58,6 +60,11 @@ public class ProtocolLibService implements SettingsDependent { logger.warning("WARNING! The denyTabComplete feature requires ProtocolLib! Disabling it..."); } + if (freezePlayerBeforeLogin) { + logger.warning("WARNING! In oder to prevent player movements in a nicer way consider" + + " installing ProtocolLib!"); + } + this.isEnabled = false; return; } @@ -84,6 +91,16 @@ public class ProtocolLibService implements SettingsDependent { tabCompletePacketAdapter = null; } + if (freezePlayerBeforeLogin) { + if (freezePacketAdapter == null) { + freezePacketAdapter = new FreezePacketAdapter(plugin, playerCache, dataSource); + freezePacketAdapter.register(bukkitService); + } + } else if (freezePacketAdapter != null) { + freezePacketAdapter.unregister(); + freezePacketAdapter = null; + } + this.isEnabled = true; } @@ -101,6 +118,10 @@ public class ProtocolLibService implements SettingsDependent { tabCompletePacketAdapter.unregister(); tabCompletePacketAdapter = null; } + if (freezePacketAdapter != null) { + freezePacketAdapter.unregister(); + freezePacketAdapter = null; + } } /** @@ -114,12 +135,36 @@ public class ProtocolLibService implements SettingsDependent { } } + /** + * Send a packet to the player to freeze any movement. + * + * @param player The player to send the packet to. + */ + public void sendFreezePacket(Player player) { + if (isEnabled && freezePacketAdapter != null) { + freezePacketAdapter.sendFreezePacket(player); + } + } + + /** + * Send a packet to the player to unfreeze movements. + * + * @param player The player to send the packet to. + */ + public void sendUnFreezePacket(Player player) { + if (isEnabled && freezePacketAdapter != null) { + freezePacketAdapter.sendUnFreezePacket(player); + } + } + @Override public void reload(Settings settings) { - boolean oldProtectInventory = this.protectInvBeforeLogin; + final boolean oldProtectInventory = this.protectInvBeforeLogin; + final boolean oldFreezePlayer = this.freezePlayerBeforeLogin; this.protectInvBeforeLogin = settings.getProperty(RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN); this.denyTabCompleteBeforeLogin = settings.getProperty(RestrictionSettings.DENY_TABCOMPLETE_BEFORE_LOGIN); + this.freezePlayerBeforeLogin = !settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT); //it was true and will be deactivated now, so we need to restore the inventory for every player if (oldProtectInventory && !protectInvBeforeLogin && inventoryPacketAdapter != null) { @@ -130,6 +175,14 @@ public class ProtocolLibService implements SettingsDependent { } } } + if (oldFreezePlayer && !freezePlayerBeforeLogin && freezePacketAdapter != null) { + freezePacketAdapter.unregister(); + for (Player onlinePlayer : bukkitService.getOnlinePlayers()) { + if (!playerCache.isAuthenticated(onlinePlayer.getName())) { + freezePacketAdapter.sendUnFreezePacket(onlinePlayer); + } + } + } setup(); } diff --git a/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java b/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java index 29bbe720d..67da62882 100644 --- a/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java @@ -6,6 +6,7 @@ import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.LoginEvent; import fr.xephi.authme.events.RestoreInventoryEvent; +import fr.xephi.authme.listener.protocollib.ProtocolLibService; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.process.SynchronousProcess; @@ -23,6 +24,7 @@ import org.bukkit.potion.PotionEffectType; import javax.inject.Inject; import java.util.List; +import static fr.xephi.authme.settings.properties.RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT; import static fr.xephi.authme.settings.properties.RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN; public class ProcessSyncPlayerLogin implements SynchronousProcess { @@ -57,6 +59,9 @@ public class ProcessSyncPlayerLogin implements SynchronousProcess { @Inject private PermissionsManager permissionsManager; + @Inject + private ProtocolLibService protocolLibService; + ProcessSyncPlayerLogin() { } @@ -87,6 +92,9 @@ public class ProcessSyncPlayerLogin implements SynchronousProcess { if (commonService.getProperty(PROTECT_INVENTORY_BEFORE_LOGIN)) { restoreInventory(player); } + if (!commonService.getProperty(ALLOW_UNAUTHED_MOVEMENT)) { + protocolLibService.sendUnFreezePacket(player); + } final PlayerAuth auth = dataSource.getAuth(name); teleportationService.teleportOnLogin(player, auth, limbo); diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java index 46fd7fefc..55b22228a 100644 --- a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java @@ -56,6 +56,9 @@ public class ProcessSyncPlayerLogout implements SynchronousProcess { if (service.getProperty(RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN)) { protocolLibService.sendBlankInventoryPacket(player); } + if (!service.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)){ + protocolLibService.sendFreezePacket(player); + } applyLogoutEffect(player); commandManager.runCommandsOnLogout(player); diff --git a/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java b/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java index 309b69231..4f0bfabe7 100644 --- a/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java +++ b/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java @@ -5,7 +5,6 @@ import ch.jalu.configme.SettingsHolder; import ch.jalu.configme.configurationdata.CommentsConfiguration; import ch.jalu.configme.properties.Property; import fr.xephi.authme.data.limbo.AllowFlightRestoreType; -import fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType; import fr.xephi.authme.data.limbo.persistence.LimboPersistenceType; import fr.xephi.authme.data.limbo.persistence.SegmentSize; @@ -19,7 +18,7 @@ public final class LimboSettings implements SettingsHolder { @Comment({ "Besides storing the data in memory, you can define if/how the data should be persisted", "on disk. This is useful in case of a server crash, so next time the server starts we can", - "properly restore things like OP status, ability to fly, and walk/fly speed.", + "properly restore things like OP status and the ability to fly", "DISABLED: no disk storage,", "INDIVIDUAL_FILES: each player data in its own file,", "DISTRIBUTED_FILES: distributes players into different files based on their UUID, see below" @@ -49,23 +48,6 @@ public final class LimboSettings implements SettingsHolder { public static final Property RESTORE_ALLOW_FLIGHT = newProperty(AllowFlightRestoreType.class, "limbo.restoreAllowFlight", AllowFlightRestoreType.RESTORE); - @Comment({ - "Restore fly speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO.", - "RESTORE: restore the speed the player had;", - "DEFAULT: always set to default speed;", - "MAX_RESTORE: take the maximum of the player's current speed and the previous one", - "RESTORE_NO_ZERO: Like 'restore' but sets speed to default if the player's speed was 0" - }) - public static final Property RESTORE_FLY_SPEED = - newProperty(WalkFlySpeedRestoreType.class, "limbo.restoreFlySpeed", WalkFlySpeedRestoreType.RESTORE_NO_ZERO); - - @Comment({ - "Restore walk speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO.", - "See above for a description of the values." - }) - public static final Property RESTORE_WALK_SPEED = - newProperty(WalkFlySpeedRestoreType.class, "limbo.restoreWalkSpeed", WalkFlySpeedRestoreType.RESTORE_NO_ZERO); - private LimboSettings() { } @@ -73,7 +55,7 @@ public final class LimboSettings implements SettingsHolder { public void registerComments(CommentsConfiguration conf) { String[] limboExplanation = { "Before a user logs in, various properties are temporarily removed from the player,", - "such as OP status, ability to fly, and walk/fly speed.", + "such as OP status and the ability to fly.", "Once the user is logged in, we add back the properties we previously saved.", "In this section, you may define how these properties should be handled.", "Read more at https://github.com/AuthMe/AuthMeReloaded/wiki/Limbo-players" diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java index 78386e2d3..e5184d965 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java @@ -22,32 +22,28 @@ public final class LimboPlayerMatchers { public static Matcher isLimbo(LimboPlayer limbo) { String[] groups = limbo.getGroups().toArray(new String[limbo.getGroups().size()]); - return isLimbo(limbo.isOperator(), limbo.isCanFly(), limbo.getWalkSpeed(), limbo.getFlySpeed(), groups); + return isLimbo(limbo.isOperator(), limbo.isCanFly(), groups); } - public static Matcher isLimbo(boolean isOp, boolean canFly, float walkSpeed, float flySpeed, - String... groups) { + public static Matcher isLimbo(boolean isOp, boolean canFly, String... groups) { return new TypeSafeMatcher() { @Override protected boolean matchesSafely(LimboPlayer item) { return item.isOperator() == isOp && collectionContains(item.getGroups(), groups) - && item.isCanFly() == canFly - && walkSpeed == item.getWalkSpeed() - && flySpeed == item.getFlySpeed(); + && item.isCanFly() == canFly; } @Override public void describeTo(Description description) { - description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s, walkSpeed=%f, flySpeed=%f", - isOp, String.join(" ,", groups), canFly, walkSpeed, flySpeed)); + description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s", + isOp, String.join(" ,", groups), canFly)); } @Override public void describeMismatchSafely(LimboPlayer item, Description description) { - description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s, walkSpeed=%f, flySpeed=%f", - item.isOperator(), String.join(" ,", item.getGroups()), item.isCanFly(), - item.getWalkSpeed(), item.getFlySpeed())); + description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s", + item.isOperator(), String.join(" ,", item.getGroups()), item.isCanFly())); } }; } diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java index ff0743001..c85078e2e 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java @@ -106,7 +106,7 @@ public class LimboPlayerTaskManagerTest { String name = "rats"; Player player = mock(Player.class); given(player.getName()).willReturn(name); - LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false, 0.1f, 0.0f); + LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false); MessageTask existingMessageTask = mock(MessageTask.class); limboPlayer.setMessageTask(existingMessageTask); given(settings.getProperty(RegistrationSettings.MESSAGE_INTERVAL)).willReturn(8); @@ -129,7 +129,7 @@ public class LimboPlayerTaskManagerTest { String name = "race"; Player player = mock(Player.class); given(player.getName()).willReturn(name); - LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false, 0.1f, 0.0f); + LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false); given(settings.getProperty(RegistrationSettings.MESSAGE_INTERVAL)).willReturn(12); given(registrationCaptchaManager.isCaptchaRequired(name)).willReturn(true); String captcha = "M032"; @@ -180,7 +180,7 @@ public class LimboPlayerTaskManagerTest { public void shouldCancelExistingTimeoutTask() { // given Player player = mock(Player.class); - LimboPlayer limboPlayer = new LimboPlayer(null, false, Collections.emptyList(), true, 0.3f, 0.1f); + LimboPlayer limboPlayer = new LimboPlayer(null, false, Collections.emptyList(), true); BukkitTask existingTask = mock(BukkitTask.class); limboPlayer.setTimeoutTask(existingTask); given(settings.getProperty(RestrictionSettings.TIMEOUT)).willReturn(18); diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java index da3bc00f8..17e4dc121 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java @@ -37,9 +37,9 @@ public class LimboServiceHelperTest { public void shouldMergeLimboPlayers() { // given Location newLocation = mock(Location.class); - LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), false, 0.0f, 0.0f); + LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), false); Location oldLocation = mock(Location.class); - LimboPlayer oldLimbo = new LimboPlayer(oldLocation, true, Collections.singletonList("grp-old"), true, 0.1f, 0.8f); + LimboPlayer oldLimbo = new LimboPlayer(oldLocation, true, Collections.singletonList("grp-old"), true); // when LimboPlayer result = limboServiceHelper.merge(newLimbo, oldLimbo); @@ -49,16 +49,14 @@ public class LimboServiceHelperTest { assertThat(result.isOperator(), equalTo(true)); assertThat(result.getGroups(), contains("grp-old")); assertThat(result.isCanFly(), equalTo(true)); - assertThat(result.getWalkSpeed(), equalTo(0.1f)); - assertThat(result.getFlySpeed(), equalTo(0.8f)); } @Test public void shouldFallBackToNewLimboForMissingData() { // given Location newLocation = mock(Location.class); - LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), true, 0.3f, 0.0f); - LimboPlayer oldLimbo = new LimboPlayer(null, false, Collections.emptyList(), false, 0.1f, 0.1f); + LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), true); + LimboPlayer oldLimbo = new LimboPlayer(null, false, Collections.emptyList(), false); // when LimboPlayer result = limboServiceHelper.merge(newLimbo, oldLimbo); @@ -68,8 +66,6 @@ public class LimboServiceHelperTest { assertThat(result.isOperator(), equalTo(false)); assertThat(result.getGroups(), contains("grp-new")); assertThat(result.isCanFly(), equalTo(true)); - assertThat(result.getWalkSpeed(), equalTo(0.3f)); - assertThat(result.getFlySpeed(), equalTo(0.1f)); } @Test diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java index 8bcfaff79..e3084a4a4 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java @@ -79,7 +79,7 @@ public class LimboServiceTest { @Test public void shouldCreateLimboPlayer() { // given - Player player = newPlayer("Bobby", true, 0.3f, false, 0.2f); + Player player = newPlayer("Bobby", true, false); Location playerLoc = mock(Location.class); given(spawnLoader.getPlayerLocationOrSpawn(player)).willReturn(playerLoc); given(permissionsManager.hasGroupSupport()).willReturn(true); @@ -93,17 +93,13 @@ public class LimboServiceTest { verify(taskManager).registerMessageTask(eq(player), any(LimboPlayer.class), eq(LimboMessageType.LOG_IN)); verify(taskManager).registerTimeoutTask(eq(player), any(LimboPlayer.class)); verify(player).setAllowFlight(false); - verify(player).setFlySpeed(0.0f); - verify(player).setWalkSpeed(0.0f); assertThat(limboService.hasLimboPlayer("Bobby"), equalTo(true)); LimboPlayer limbo = limboService.getLimboPlayer("Bobby"); verify(authGroupHandler).setGroup(player, limbo, AuthGroupType.REGISTERED_UNAUTHENTICATED); assertThat(limbo, not(nullValue())); assertThat(limbo.isOperator(), equalTo(true)); - assertThat(limbo.getWalkSpeed(), equalTo(0.3f)); assertThat(limbo.isCanFly(), equalTo(false)); - assertThat(limbo.getFlySpeed(), equalTo(0.2f)); assertThat(limbo.getLocation(), equalTo(playerLoc)); assertThat(limbo.getGroups(), equalTo(Collections.singletonList("permgrwp"))); } @@ -111,7 +107,7 @@ public class LimboServiceTest { @Test public void shouldNotKeepOpStatusForUnregisteredPlayer() { // given - Player player = newPlayer("CharleS", true, 0.1f, true, 0.4f); + Player player = newPlayer("CharleS", true, true); Location playerLoc = mock(Location.class); given(spawnLoader.getPlayerLocationOrSpawn(player)).willReturn(playerLoc); given(permissionsManager.hasGroupSupport()).willReturn(false); @@ -125,16 +121,12 @@ public class LimboServiceTest { verify(taskManager).registerTimeoutTask(eq(player), any(LimboPlayer.class)); verify(permissionsManager, only()).hasGroupSupport(); verify(player).setAllowFlight(false); - verify(player).setFlySpeed(0.0f); - verify(player).setWalkSpeed(0.0f); LimboPlayer limbo = limboService.getLimboPlayer("charles"); verify(authGroupHandler).setGroup(player, limbo, AuthGroupType.UNREGISTERED); assertThat(limbo, not(nullValue())); assertThat(limbo.isOperator(), equalTo(false)); - assertThat(limbo.getWalkSpeed(), equalTo(0.1f)); assertThat(limbo.isCanFly(), equalTo(true)); - assertThat(limbo.getFlySpeed(), equalTo(0.4f)); assertThat(limbo.getLocation(), equalTo(playerLoc)); assertThat(limbo.getGroups(), equalTo(Collections.emptyList())); } @@ -162,22 +154,18 @@ public class LimboServiceTest { public void shouldRestoreData() { // given LimboPlayer limbo = Mockito.spy(convertToLimboPlayer( - newPlayer("John", true, 0.4f, false, 0.0f), null, Collections.emptyList())); + newPlayer("John", true, false), null, Collections.emptyList())); getLimboMap().put("john", limbo); - Player player = newPlayer("John", false, 0.2f, false, 0.7f); + Player player = newPlayer("John", false, false); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.ENABLE); - given(settings.getProperty(LimboSettings.RESTORE_WALK_SPEED)).willReturn(WalkFlySpeedRestoreType.RESTORE); - given(settings.getProperty(LimboSettings.RESTORE_FLY_SPEED)).willReturn(WalkFlySpeedRestoreType.RESTORE_NO_ZERO); // when limboService.restoreData(player); // then verify(player).setOp(true); - verify(player).setWalkSpeed(0.4f); verify(player).setAllowFlight(true); - verify(player).setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); verify(limbo).clearTasks(); verify(authGroupHandler).setGroup(player, limbo, AuthGroupType.LOGGED_IN); assertThat(limboService.hasLimboPlayer("John"), equalTo(false)); @@ -232,18 +220,15 @@ public class LimboServiceTest { return player; } - private static Player newPlayer(String name, boolean isOp, float walkSpeed, boolean canFly, float flySpeed) { + private static Player newPlayer(String name, boolean isOp, boolean canFly) { Player player = newPlayer(name); given(player.isOp()).willReturn(isOp); - given(player.getWalkSpeed()).willReturn(walkSpeed); given(player.getAllowFlight()).willReturn(canFly); - given(player.getFlySpeed()).willReturn(flySpeed); return player; } private static LimboPlayer convertToLimboPlayer(Player player, Location location, Collection groups) { - return new LimboPlayer(location, player.isOp(), groups, player.getAllowFlight(), - player.getWalkSpeed(), player.getFlySpeed()); + return new LimboPlayer(location, player.isOp(), groups, player.getAllowFlight()); } private Map getLimboMap() { diff --git a/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java b/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java deleted file mode 100644 index f8aa2719c..000000000 --- a/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package fr.xephi.authme.data.limbo; - -import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static fr.xephi.authme.data.limbo.LimboPlayer.DEFAULT_FLY_SPEED; -import static fr.xephi.authme.data.limbo.LimboPlayer.DEFAULT_WALK_SPEED; -import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.DEFAULT; -import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.MAX_RESTORE; -import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.RESTORE; -import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.RESTORE_NO_ZERO; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -/** - * Test for {@link WalkFlySpeedRestoreType}. - */ -@RunWith(Parameterized.class) -public class WalkFlySpeedRestoreTypeTest { - - private final TestParameters parameters; - - public WalkFlySpeedRestoreTypeTest(TestParameters parameters) { - this.parameters = parameters; - } - - @Test - public void shouldRestoreToExpectedValue() { - // given - LimboPlayer limbo = mock(LimboPlayer.class); - given(limbo.getWalkSpeed()).willReturn(parameters.givenLimboWalkSpeed); - given(limbo.getFlySpeed()).willReturn(parameters.givenLimboFlySpeed); - - Player player = mock(Player.class); - given(player.getWalkSpeed()).willReturn(parameters.givenPlayerWalkSpeed); - given(player.getFlySpeed()).willReturn(parameters.givenPlayerFlySpeed); - - // when - parameters.testedType.restoreWalkSpeed(player, limbo); - parameters.testedType.restoreFlySpeed(player, limbo); - - // then - verify(player).setWalkSpeed(parameters.expectedWalkSpeed); - verify(player).setFlySpeed(parameters.expectedFlySpeed); - } - - @Parameterized.Parameters(name = "{0}") - public static List buildParams() { - List parameters = Arrays.asList( - create(RESTORE).withLimbo(0.1f, 0.4f).withPlayer(0.3f, 0.9f).expect(0.1f, 0.4f), - create(RESTORE).withLimbo(0.9f, 0.2f).withPlayer(0.3f, 0.0f).expect(0.9f, 0.2f), - create(MAX_RESTORE).withLimbo(0.3f, 0.8f).withPlayer(0.5f, 0.2f).expect(0.5f, 0.8f), - create(MAX_RESTORE).withLimbo(0.4f, 0.2f).withPlayer(0.1f, 0.4f).expect(0.4f, 0.4f), - create(RESTORE_NO_ZERO).withLimbo(0.1f, 0.2f).withPlayer(0.5f, 0.1f).expect(0.1f, 0.2f), - create(RESTORE_NO_ZERO).withLimbo(0.0f, 0.005f).withPlayer(0.4f, 0.8f).expect(DEFAULT_WALK_SPEED, DEFAULT_FLY_SPEED), - create(DEFAULT).withLimbo(0.1f, 0.7f).withPlayer(0.4f, 0.0f).expect(DEFAULT_WALK_SPEED, DEFAULT_FLY_SPEED) - ); - - // Convert List to List - return parameters.stream().map(p -> new Object[]{p}).collect(Collectors.toList()); - } - - private static TestParameters create(WalkFlySpeedRestoreType testedType) { - TestParameters params = new TestParameters(); - params.testedType = testedType; - return params; - } - - private static final class TestParameters { - private WalkFlySpeedRestoreType testedType; - private float givenLimboWalkSpeed; - private float givenLimboFlySpeed; - private float givenPlayerWalkSpeed; - private float givenPlayerFlySpeed; - private float expectedWalkSpeed; - private float expectedFlySpeed; - - TestParameters withLimbo(float walkSpeed, float flySpeed) { - this.givenLimboWalkSpeed = walkSpeed; - this.givenLimboFlySpeed = flySpeed; - return this; - } - - TestParameters withPlayer(float walkSpeed, float flySpeed) { - this.givenPlayerWalkSpeed = walkSpeed; - this.givenPlayerFlySpeed = flySpeed; - return this; - } - - TestParameters expect(float walkSpeed, float flySpeed) { - this.expectedWalkSpeed = walkSpeed; - this.expectedFlySpeed = flySpeed; - return this; - } - - @Override - public String toString() { - return testedType + " {" + expectedWalkSpeed + ", " + expectedFlySpeed + "}"; - } - } -} diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index fd41134a1..191c3d282 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -48,22 +48,22 @@ public class DistributedFilesPersistenceHandlerTest { /** Player is in seg32-10110 and should be migrated into seg16-f. */ private static final UUID MIGRATED_UUID = fromString("f6a97c88-7c8f-c12e-4931-6206d4ca067d"); private static final Matcher MIGRATED_LIMBO_MATCHER = - isLimbo(false, true, 0.2f, 0.1f, "noob"); + isLimbo(false, true, "noob"); /** Existing player in seg16-f. */ private static final UUID UUID_FAB69 = fromString("fab69c88-2cd0-1fed-f00d-dead14ca067d"); private static final Matcher FAB69_MATCHER = - isLimbo(false, false, 0.2f, 0.1f, ""); + isLimbo(false, false, ""); /** Player in seg16-8. */ private static final UUID UUID_STAFF = fromString("88897c88-7c8f-c12e-4931-6206d4ca067d"); private static final Matcher STAFF_MATCHER = - isLimbo(true, false, 0.3f, 0.1f, "staff", "mod"); + isLimbo(true, false, "staff", "mod"); /** Player in seg16-8. */ private static final UUID UUID_8C679 = fromString("8c679491-1234-abcd-9102-1fa6e0cc3f81"); private static final Matcher SC679_MATCHER = - isLimbo(false, true, 0.1f, 0.0f, "primary"); + isLimbo(false, true, "primary"); /** UUID for which no data is stored (belongs to a segment file that does not exist, seg16-4). */ private static final UUID UNKNOWN_UUID = fromString("42d1cc0b-8f12-d04a-e7ba-a067d05cdc39"); @@ -156,10 +156,10 @@ public class DistributedFilesPersistenceHandlerTest { // given Player uuidToAdd1 = mockPlayerWithUuid(UNKNOWN_UUID); Location location1 = mockLocation("1world"); - LimboPlayer limbo1 = new LimboPlayer(location1, false, Collections.singletonList("group-1"), true, 0.1f, 0.2f); + LimboPlayer limbo1 = new LimboPlayer(location1, false, Collections.singletonList("group-1"), true); Player uuidToAdd2 = mockPlayerWithUuid(UNKNOWN_UUID2); Location location2 = mockLocation("2world"); - LimboPlayer limbo2 = new LimboPlayer(location2, true, Collections.emptyList(), false, 0.0f, 0.25f); + LimboPlayer limbo2 = new LimboPlayer(location2, true, Collections.emptyList(), false); // when persistenceHandler.saveLimboPlayer(uuidToAdd1, limbo1); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java index 06df57bf0..b62e96991 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java @@ -78,8 +78,6 @@ public class IndividualFilesPersistenceHandlerTest { assertThat(data, not(nullValue())); assertThat(data.isOperator(), equalTo(true)); assertThat(data.isCanFly(), equalTo(true)); - assertThat(data.getWalkSpeed(), equalTo(0.2f)); - assertThat(data.getFlySpeed(), equalTo(0.1f)); assertThat(data.getGroups(), contains("players")); Location location = data.getLocation(); assertThat(location.getX(), equalTo(-113.219)); @@ -114,7 +112,7 @@ public class IndividualFilesPersistenceHandlerTest { World world = mock(World.class); given(world.getName()).willReturn("player-world"); Location location = new Location(world, 0.2, 102.25, -89.28, 3.02f, 90.13f); - LimboPlayer limbo = new LimboPlayer(location, true, Collections.singletonList("primary-grp"), true, 1.2f, 0.8f); + LimboPlayer limbo = new LimboPlayer(location, true, Collections.singletonList("primary-grp"), true); // when handler.saveLimboPlayer(player, limbo); diff --git a/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json b/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json index ee1ae20ad..976dca0af 100644 --- a/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json +++ b/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json @@ -9,7 +9,5 @@ }, "operator": true, "can-fly": true, - "walk-speed": 0.2, - "fly-speed": 0.1, "group": "players" } diff --git a/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json b/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json index f22e472a1..7ed70b206 100644 --- a/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json +++ b/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json @@ -13,9 +13,7 @@ "mod" ], "operator": true, - "can-fly": false, - "walk-speed": 0.3, - "fly-speed": 0.1 + "can-fly": false }, "8c679491-1234-abcd-9102-1fa6e0cc3f81": { "location": { @@ -28,8 +26,6 @@ }, "group": "primary", "operator": false, - "can-fly": true, - "walk-speed": 0.1, - "fly-speed": 0.0 + "can-fly": true } } diff --git a/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json b/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json index 9f2562622..e72f81abf 100644 --- a/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json +++ b/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json @@ -10,8 +10,6 @@ }, "group": "", "operator": false, - "can-fly": false, - "walk-speed": 0.2, - "fly-speed": 0.1 + "can-fly": false } } diff --git a/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json b/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json index b50fb8bda..d7371b974 100644 --- a/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json +++ b/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json @@ -10,8 +10,6 @@ }, "group": "noob", "operator": false, - "can-fly": true, - "walk-speed": 0.2, - "fly-speed": 0.1 + "can-fly": true } } From 48357831cdd29608f18db4ae678bb6705c5d9aea Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Wed, 7 Aug 2019 10:49:23 +0200 Subject: [PATCH 82/83] Revert "Packet based movement freeze (#1879)" (#1882) This reverts commit db3acce70c2096054e7854d318cf29688280a6fd. --- docs/config.md | 17 +- samples/NewConfig.yml | 570 ++++++++++++++++++ samples/NewPlugin.yml | 199 ++++++ .../authme/debug/LimboPlayerViewer.java | 2 + .../xephi/authme/data/limbo/LimboPlayer.java | 18 +- .../xephi/authme/data/limbo/LimboService.java | 4 + .../authme/data/limbo/LimboServiceHelper.java | 15 +- .../data/limbo/WalkFlySpeedRestoreType.java | 123 ++++ .../persistence/LimboPlayerDeserializer.java | 6 +- .../persistence/LimboPlayerSerializer.java | 4 + .../protocollib/FreezePacketAdapter.java | 128 ---- .../protocollib/ProtocolLibService.java | 55 +- .../process/login/ProcessSyncPlayerLogin.java | 8 - .../logout/ProcessSyncPlayerLogout.java | 3 - .../settings/properties/LimboSettings.java | 22 +- .../data/limbo/LimboPlayerMatchers.java | 18 +- .../limbo/LimboPlayerTaskManagerTest.java | 6 +- .../data/limbo/LimboServiceHelperTest.java | 12 +- .../authme/data/limbo/LimboServiceTest.java | 27 +- .../limbo/WalkFlySpeedRestoreTypeTest.java | 108 ++++ ...istributedFilesPersistenceHandlerTest.java | 12 +- ...IndividualFilesPersistenceHandlerTest.java | 4 +- .../data/backup/sample-folder/data.json | 2 + .../authme/data/limbo/seg16-8-limbo.json | 8 +- .../authme/data/limbo/seg16-f-limbo.json | 4 +- .../authme/data/limbo/seg32-10110-limbo.json | 4 +- 26 files changed, 1145 insertions(+), 234 deletions(-) create mode 100644 samples/NewConfig.yml create mode 100644 samples/NewPlugin.yml create mode 100644 src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java delete mode 100644 src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java create mode 100644 src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java diff --git a/docs/config.md b/docs/config.md index b621a87e8..811481d5e 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1,5 +1,5 @@ - + ## AuthMe Configuration The first time you run AuthMe it will create a config.yml file in the plugins/AuthMe folder, @@ -501,7 +501,7 @@ Security: # Minutes after which a verification code will expire verificationCodeExpiration: 10 # Before a user logs in, various properties are temporarily removed from the player, -# such as OP status and the ability to fly. +# such as OP status, ability to fly, and walk/fly speed. # Once the user is logged in, we add back the properties we previously saved. # In this section, you may define how these properties should be handled. # Read more at https://github.com/AuthMe/AuthMeReloaded/wiki/Limbo-players @@ -509,7 +509,7 @@ limbo: persistence: # Besides storing the data in memory, you can define if/how the data should be persisted # on disk. This is useful in case of a server crash, so next time the server starts we can - # properly restore things like OP status and the ability to fly + # properly restore things like OP status, ability to fly, and walk/fly speed. # DISABLED: no disk storage, # INDIVIDUAL_FILES: each player data in its own file, # DISTRIBUTED_FILES: distributes players into different files based on their UUID, see below @@ -528,6 +528,15 @@ limbo: # RESTORE sets back the old property from the player. NOTHING will prevent AuthMe # from modifying the 'allow flight' property on the player. restoreAllowFlight: RESTORE + # Restore fly speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO. + # RESTORE: restore the speed the player had; + # DEFAULT: always set to default speed; + # MAX_RESTORE: take the maximum of the player's current speed and the previous one + # RESTORE_NO_ZERO: Like 'restore' but sets speed to default if the player's speed was 0 + restoreFlySpeed: RESTORE_NO_ZERO + # Restore walk speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO. + # See above for a description of the values. + restoreWalkSpeed: RESTORE_NO_ZERO BackupSystem: # General configuration for backups: if false, no backups are possible ActivateBackup: false @@ -569,4 +578,4 @@ To change settings on a running server, save your changes to config.yml and use --- -This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Mon Aug 05 18:57:10 CEST 2019 +This page was automatically generated on the [AuthMe/AuthMeReloaded repository](https://github.com/AuthMe/AuthMeReloaded/tree/master/docs/) on Tue Apr 23 17:17:02 CEST 2019 diff --git a/samples/NewConfig.yml b/samples/NewConfig.yml new file mode 100644 index 000000000..91e063d08 --- /dev/null +++ b/samples/NewConfig.yml @@ -0,0 +1,570 @@ +# ======================================================================================================= +# _____ __ .__ _____ __________ .__ .___ .___ +# / _ \ __ ___/ |_| |__ / \ ____\______ \ ____ | | _________ __| _/____ __| _/ +# / /_\ \| | \ __| | \ / \ / \_/ __ \| __/ __ \| | / _ \__ \ / __ _/ __ \ / __ | +# / | | | /| | | Y / Y \ ___/| | \ ___/| |_( <_> / __ \/ /_/ \ ___// /_/ | +# \____|__ |____/ |__| |___| \____|__ /\___ |____|_ /\___ |____/\____(____ \____ |\___ \____ | +# \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ +# +# ======================================================================================================= +# +# Authme Main Configuration File. +# +# ======================================================================================================= + +# Plugin infos (overwritten on start, just a simple way to find out your plugin version). +authors: ${pluginAuthors} +version: ${project.version} +buildNumber: ${buildNumber} + +# Set this setting to true when you have configured the plugin, +# when false the server will be stopped with a warning message. +enabled: false + +# Database settings. +data_source: + # =========================== + # Database general settings. + # =========================== + + # Database backend (sqlite, mysql). + backend: sqlite + # Enable database queries caching, should improve performance. + caching: true + + # =========================== + # SqLite db parameters. + # =========================== + + sqlite: + # The name of the database storage file. + filename: 'authme.db' + + # =========================== + # MySql db parameters. + # =========================== + + mysql: + # Connection parameters. + host: '127.0.0.1' + port: 3306 + username: 'change_me' + password: 'change_me' + database: 'my_minecraft_server' + tablename: 'authme' + + # Column names. + column_names: + id: id + # Column for storing nicknames (ignore case nickname). + name: username + # Column for storing the realname (case sensitive nickname). + real_name: realname + # Column for storing passwords. + password: password + # Column for storing email addresses. + email: email + # Column for storing the authentication status (logged or not). + login_status: isLogged + # Column for storing player IPs. + ip: ip + # Column for storing lastlogins date and time. + last_login_timestamp: lastlogin + # Latest logout location of the players. + last_location: + world: world + x: x + y: y + z: z + # Enabled only if the bungeecord integration is activated. + server: world + + # Support for registrations via WebInterfaces/CSM. + # Disable some backend caching parameters. + disableAggressiveCaching: false + +# Main settings +settings: + + # =========================== + # Bungeecord integration + # =========================== + + bungeecord: + # Enable bungeecord integration features + enabled: true + + # Server name (must be unique, please use the name in the bungeecord configuration). + # Use 'auto' for auto configuration (requires the bungeecord module). + serverName: LoginLobby1 + # Keep the auth status when the player moves between servers. + # Required if you're using the bungeecord module. + keepAuthBetweenServers: true + + # Target server after login + send_after_login: + enabled: false + message: '' + delay: 5 + # Server name ("ServerName") or group ("G:GroupName") + # Groups are avariable only when the bungeecord module is avariable. + # If the server change fails the player will be kicked. + target: Lobby1 + failKickMessage: 'Failed to connect to the lobby! Please try to join the server again!' + # Target server after logout + send_after_logout: + enabled: false + message: '' + delay: 5 + # Server name ("ServerName") or group ("G:GroupName") + # Groups are avariable only when the bungeecord module is avariable. + # If the server change fails the player will be kicked. + target: LoginLobby1 + failKickMessage: 'Failed to connect to the lobby! Please try to join the server again!' + + # Variables: + # %p playername + bungee_commands: + player_command_after_register: + enabled: false + cmd: '' + console_command_after_register: + enabled: false + cmd: 'alert %p joined for the first time the network!' + player_command_after_login: + enabled: false + cmd: 'glist' + console_command_after_login: + enabled: false + cmd: 'alert %p logged in correctly!' + player_command_after_join: + enabled: false + cmd: '' + console_command_after_join: + enabled: false + cmd: 'alert %p joined the network!' + player_command_first_join: + enabled: false + cmd: '' + console_command_first_join: + enabled: false + cmd: 'alert %p joined for the first time the network!' + + # =========================== + # Sessions configuration. + # =========================== + + sessions: + # Enable sessions. + # When a player is authenticated, his IP and his nickname is saved. + # The next time the player will join the server, if his IP is the same + # of the last time, and the timeout time hasn't expired, he will be + # automatically authenticated. + enabled: false + # Session timeout. + # 0 for unlimited time (Very dangerous, use it at your own risk!) + # Consider that if player's ip has changed but the timeout hasn't + # expired, player will be kicked out of the sever! + timeout: 10 + # When enabled a player's session will expire if someone tries to + # login with a different IP Address. + expire_on_ip_change: true + + # =========================== + # Registration settings. + # =========================== + + registration: + # After how many time unregistered players should be kicked? + # Set to 0 to disable. (default: 30) + timeout: 30 + + nickname: + min_length: 4 + max_lenght: 16 + # Regex syntax. + allowed_characters: '[a-zA-Z0-9_]*' + + password: + # Enable double check of password on registration: + # /register + double_check: true + # Minimum password lenght. + min_length: 5 + # Regex syntax. + allowed_characters: '[\x21-\x7E]*' + # Denied unsafe passwords. + unsafePasswords: + - '123456' + - 'password' + - 'qwerty' + - '12345' + - '54321' + + # =========================== + # Login settings. + # =========================== + + login: + # After how many time unlogged players should be kicked? + # Set to 0 to disable. (default: 30) + timeout: 30 + + + + # =========================== + # Encryption parameters. + # =========================== + + password_encryption: + # The hashing algorithm. + # Possible values: MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, MYBB, IPB3, + # PHPFUSION, SMF, XENFORO, SALTED2MD5, JOOMLA, BCRYPT, WBB3, SHA512, DOUBLEMD5, + # PBKDF2, PBKDF2DJANGO, WORDPRESS, ROYALAUTH, CUSTOM (developpers only). + encryption_algorithm: SHA256 + # The salt length for the SALTED2MD5 and MD5(MD5(password)+salt) algorithms. + md5_salt_length: 8 + # If password check fails try all the other hash algorithm. + # AuthMe will update the password to the new passwordHash. + enable_convertion: false + + # =========================== + # Unlogged user restrictions. + # =========================== + + unlogged_restrictions: + # Deny chat messages send for unlogged users. + deny_chat: true + # Hide chat to unlogged users. + # Only player messages, plugins will be able to send messages to the player anyway. + hide_chat: false + + # Deny any command message not in the whitelist below. + deny_commands: true + command_whitelist: + - /login + - /register + - /l + - /reg + - /email + - /captcha + + movements: + # Restrict player movements. + restrict: true + # Allowed radius. + allowed_radius: 0 + # Should unlogged players have speed = 0? + # After the login the walking/flying speeed will be reset to the default value. + removeSpeed: true + + # End is there atm xD + + # This option will save the quit location of the players. + SaveQuitLocation: false + # Should not logged in players be teleported to the spawn? + # After the authentication, if SaveQuitLocation is enabled, + # they will be teleported back to their normal position. + teleportUnAuthedToSpawn: false + + # If enabled, after the login, if the ForceSpawnOnTheseWorlds setting contains + # the player's world, he will be teleported to the world spawnpoint. + # The quit location of the player will be overwritten. + # This is different from "teleportUnAuthedToSpawn" that teleports player + # back to his quit location after the authentication. + ForceSpawnLocOnJoinEnabled: false + # WorldNames where we need to force the spawn location + # Warning: This setting is Case Sensitive! + ForceSpawnOnTheseWorlds: + - world + - world_nether + - world_the_end + + # this is very important options, + # every time player join the server, + # if they are registered, AuthMe will switch him + # to unLoggedInGroup, this + # should prevent all major exploit. + # So you can set up on your Permission Plugin + # this special group with 0 permissions, or permissions to chat, + # or permission to + # send private message or all other perms that you want, + # the better way is to set up + # this group with few permissions, + # so if player try to exploit some account, + # they can + # do anything except what you set in perm Group. + # After a correct logged-in player will be + # moved to his correct permissions group! + # Pay attention group name is case sensitive, + # so Admin is different from admin, + # otherwise your group will be wiped, + # and player join in default group []! + # Example unLoggedinGroup: NotLogged + unLoggedinGroup: unLoggedinGroup + + # =========================== + # Address restrictions + # =========================== + + # Max number of registrations per IP (default: 1) + maxRegPerIp: 1 + # Maximum allowed number of Logins per IP, 0 to disable (default: 0) + maxLoginPerIp: 0 + # Maximum allowed number of Joins per IP, 0 to disable (default: 0) + maxJoinPerIp: 0 + + # When this setting is enabled, online players can't be kicked out + # due to "Logged in from another Location" + # This setting will prevent potetial security exploits. + ForceSingleSession: true + + # To activate the restricted user feature you need + # to enable this option and configure the + # AllowedRestrctedUser field. + AllowRestrictedUser: false + # The restricted user feature will kick players listed below + # if they dont match of the defined ip address. + # Example: + # AllowedRestrictedUser: + # - playername;127.0.0.1 + AllowedRestrictedUser: + - playername;127.0.0. + # Ban ip when the ip is not the ip registered in database + banUnsafedIP: false + + + + # =============================== + # Other restrictions + # =============================== + + # Should we protect the player inventory before logging in? + # Warning: Requires the latest version of ProtocolLib! + ProtectInventoryBeforeLogIn: true + + # Should unregistered players be kicked immediately? + kickNonRegistered: false + # Should players be kicked on wrong password? + kickOnWrongPassword: false + + # Should we display all other accounts of a player when he joins? + # Required permission: authme.admin.accounts + displayOtherAccounts: true + + # =============================== + # Restrictions compatibility + # =============================== + + # Spawn Priority. Avariable values : authme, essentials, multiverse, default + spawnPriority: authme,essentials,multiverse,default + # AuthMe will NEVER teleport players! + noTeleport: false + + GameMode: + # Do you want to set player's gamemode to survival when he joins? + # This enables also the settings below. + ForceSurvivalMode: false + # Do you want to reset player's inventory if player joins with creative mode? + ResetInventoryIfCreative: false + # Do you want to force the survival mode ONLY after the /login process? + ForceOnlyAfterLogin: false + + # sgdc3: Ok, our configuration is shit.... xD Today I will stop there + + + registration: + # enable registration on the server? + enabled: true + # Send every X seconds a message to a player to + # remind him that he has to login/register + messageInterval: 5 + # Only registered and logged in players can play. + # See restrictions for exceptions + force: true + # Does we replace password registration by an Email registration method ? + enableEmailRegistrationSystem: false + # Enable double check of email when you register + # when it's true, registration require that kind of command: + # /register + doubleEmailCheck: false + # Do we force kicking player after a successful registration ? + # Do not use with login feature below + forceKickAfterRegister: false + # Does AuthMe need to enforce a /login after a successful registration ? + forceLoginAfterRegister: false + unrestrictions: + # below you can list all your account name, that + # AuthMe will ignore for registration or login, configure it + # at your own risk!! Remember that if you are going to add + # nickname with [], you have to delimit name with ' '. + # this option add compatibility with BuildCraft and some + # other mods. + # It is CaseSensitive! + UnrestrictedName: [] + # Message language, available : en, de, br, cz, pl, fr, ru, hu, sk, es, zhtw, fi, zhcn, lt, it, ko, pt + messagesLanguage: en + # Force these commands after /login, without any '/', use %p for replace with player name + forceCommands: [] + # Force these commands after /login as a server console, without any '/', use %p for replace with player name + forceCommandsAsConsole: [] + # Force these commands after /register, without any '/', use %p for replace with player name + forceRegisterCommands: [] + # Force these commands after /register as a server console, without any '/', use %p for replace with player name + forceRegisterCommandsAsConsole: [] + # Do we need to display the welcome message (welcome.txt) after a register or a login? + # You can use colors in this welcome.txt + some replaced strings : + # {PLAYER} : player name, {ONLINE} : display number of online players, {MAXPLAYERS} : display server slots, + # {IP} : player ip, {LOGINS} : number of players logged, {WORLD} : player current world, {SERVER} : server name + # {VERSION} : get current bukkit version, {COUNTRY} : player country + useWelcomeMessage: true + # Do we need to broadcast the welcome message to all server or only to the player? set true for server or false for player + broadcastWelcomeMessage: false + # Do we need to delay the join/leave message to be displayed only when the player is authenticated ? + delayJoinMessage: false + removeJoinMessage: false + removeLeaveMessage: false + # Do we need to add potion effect Blinding before login/register ? + applyBlindEffect: false +ExternalBoardOptions: + # MySQL column for the salt , needed for some forum/cms support + mySQLColumnSalt: '' + # MySQL column for the group, needed for some forum/cms support + mySQLColumnGroup: '' + # -1 mean disabled. If u want that only + # activated player can login in your server + # u can put in this options the group number + # of unactivated user, needed for some forum/cms support + nonActivedUserGroup: -1 + # Other MySQL columns where we need to put the Username (case sensitive) + mySQLOtherUsernameColumns: [] + # How much Log to Round needed in BCrypt(do not change it if you do not know what's your doing) + bCryptLog2Round: 10 + # phpBB prefix defined during phpbb installation process + phpbbTablePrefix: 'phpbb_' + # phpBB activated group id , 2 is default registered group defined by phpbb + phpbbActivatedGroupId: 2 + # WordPress prefix defined during WordPress installation process + wordpressTablePrefix: 'wp_' +permission: + # Take care with this options, if you dont want + # to use Vault and Group Switching of + # AuthMe for unloggedIn players put true + # below, default is false. + EnablePermissionCheck: false +BackupSystem: + # Enable or Disable Automatic Backup + ActivateBackup: false + # set Backup at every start of Server + OnServerStart: false + # set Backup at every stop of Server + OnServerStop: true + # Windows only mysql installation Path + MysqlWindowsPath: 'C:\\Program Files\\MySQL\\MySQL Server 5.1\\' +Security: + SQLProblem: + # Stop the server if we can't contact the sql database + # Take care with this, if you set that to false, + # AuthMe automatically disable and the server is not protected! + stopServer: true + ReloadCommand: + # /reload support + useReloadCommandSupport: true + console: + # Remove spam console + noConsoleSpam: false + captcha: + # Player need to put a captcha when he fails too lot the password + useCaptcha: false + # Max allowed tries before request a captcha + maxLoginTry: 5 + # Captcha length + captchaLength: 5 +Converter: + Rakamak: + # Rakamak file name + fileName: users.rak + # Rakamak use ip ? + useIP: false + # IP file name for rakamak + ipFileName: UsersIp.rak + CrazyLogin: + # CrazyLogin database file + fileName: accounts.db +Email: + # Email SMTP server host + mailSMTP: smtp.gmail.com + # Email SMTP server port + mailPort: 465 + # Email account that send the mail + mailAccount: '' + # Email account password + mailPassword: '' + # Custom SenderName, that replace the mailAccount name in the email + mailSenderName: '' + # Random password length + RecoveryPasswordLength: 8 + # Email subject of password get + mailSubject: 'Your new AuthMe Password' + # Email text here + mailText: 'Dear ,

This is your new AuthMe password for the server

:



Do not forget to change password after login!
/changepassword newPassword' + # Like maxRegPerIp but with email + maxRegPerEmail: 1 + # Recall players to add an email ? + recallPlayers: false + # Delay in minute for the recall scheduler + delayRecall: 5 + # Blacklist these domains for emails + emailBlacklisted: + - 10minutemail.com + # WhiteList only these domains for emails + emailWhitelisted: [] + # Do we need to send new password draw in an image ? + generateImage: false +Hooks: + # Do we need to hook with multiverse for spawn checking? + multiverse: true + # Do we need to hook with BungeeCord for get the real Player ip ? + bungeecord: false + # Do we need to disable Essentials SocialSpy on join ? + disableSocialSpy: true + # Do we need to force /motd Essentials command on join ? + useEssentialsMotd: false + # Do we need to cache custom Attributes ? + customAttributes: false +Purge: + # On Enable , does AuthMe need to purge automatically old accounts unused ? + useAutoPurge: false + # Number of Days an account become Unused + daysBeforeRemovePlayer: 60 + # Do we need to remove the player.dat file during purge process ? + removePlayerDat: false + # Do we need to remove the Essentials/users/player.yml file during purge process ? + removeEssentialsFile: false + # World where are players.dat stores + defaultWorld: 'world' + # Do we need to remove LimitedCreative/inventories/player.yml , player_creative.yml files during purge process ? + removeLimitedCreativesInventories: false + # Do we need to remove the AntiXRayData/PlayerData/player file during purge process ? + removeAntiXRayFile: false + # Do we need to remove permissions ? + removePermissions: false +Protection: + # Enable some servers protection ( country based login, antibot ) + enableProtection: false + # Countries allowed to join the server and register, see http://dev.bukkit.org/bukkit-plugins/authme-reloaded/pages/countries-codes/ for countries' codes + countries: + - US + - GB + # Countries blacklisted automatically ( without any needed to enable protection ) + countriesBlacklist: + - A1 + # Do we need to enable automatic antibot system? + enableAntiBot: false + # Max number of player allowed to login in 5 secs before enable AntiBot system automatically + antiBotSensibility: 5 + # Duration in minutes of the antibot automatic system + antiBotDuration: 10 +VeryGames: + # These features are only available on VeryGames Server Provider + enableIpCheck: false diff --git a/samples/NewPlugin.yml b/samples/NewPlugin.yml new file mode 100644 index 000000000..f403da60b --- /dev/null +++ b/samples/NewPlugin.yml @@ -0,0 +1,199 @@ +name: ${pluginName} +authors: [${pluginAuthors}] +website: ${project.url} +description: ${project.description} +main: ${mainClass} +version: ${project.version}-b${buildNumber} +softdepend: + - Vault + - PermissionsBukkit + - PermissionsEX + - EssentialsGroupManager + - Multiverse-Core + - Essentials + - EssentialsSpawn + - ProtocolLib +commands: + authme: + description: AuthMe admin commands + usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version|converter datatype' + permission: authme.admin + register: + description: Register an account + usage: /register password confirmpassword + aliases: [reg] + permission: authme.player.register + login: + description: Login into a account + usage: /login password + aliases: [l,log] + permission: authme.player.login + changepassword: + description: Change password of a account + usage: /changepassword oldPassword newPassword + permission: authme.player.changepassword + logout: + description: Logout from the server + usage: /logout + permission: authme.player.logout + unregister: + description: unregister your account + usage: /unregister password + permission: authme.player.unregister + email: + description: Add Email or recover password + usage: '/email add your@email.com your@email.com|change oldEmail newEmail|recovery your@email.com' + permission: authme.player.email + captcha: + description: Captcha command + usage: /captcha theCaptcha + permission: authme.player.captcha +permissions: + authme.canbeforced: + description: Allow the user to be forced-logged via API + default: true + authme.player: + description: Gives access to all authme player commands + default: true + children: + authme.player.login: true + authme.player.logout: true + authme.player.register: true + authme.player.unregister: true + authme.player.changepassword: true + authme.player.captcha: true + authme.player.email: true + authme.player.register: + description: Register your account + default: false + authme.player.unregister: + description: Unregister your account + default: false + authme.player.login: + description: Login into your account + default: false + authme.player.logout: + description: Logout from your account + default: false + authme.player.changepassword: + description: Change password of your account + default: false + authme.player.email: + description: Gives access to player's email commands + default: false + children: + authme.player.email.add: true + authme.player.email.change: true + authme.player.email.recover: true + authme.player.email.add: + description: Add an email to your account + default: false + authme.player.email.change: + description: Change email of your account + default: false + authme.player.email.recover: + description: Recover your account + default: false + authme.player.captcha: + description: Captcha command + default: false + authme.admin: + description: Gives access to all authme admin commands + default: op + children: + authme.admin.forcelogin: true + authme.admin.forcelogout: true + authme.admin.register: true + authme.admin.unregister: true + authme.admin.changemail: true + authme.admin.changepassword: true + authme.admin.lastlogin: true + authme.admin.accounts: true + authme.admin.getemail: true + authme.admin.getip: true + authme.admin.setspawn: true + authme.admin.spawn: true + authme.admin.setfirstspawn: true + authme.admin.firstspawn: true + authme.admin.purge: true + authme.admin.purgebannedplayers: true + authme.admin.purgelastpos: true + authme.admin.converter: true + authme.admin.reload: true + authme.admin.switchantibot: true + authme.admin.seeotheraccounts: true + authme.admin.register: + description: Register an account + default: false + authme.admin.unregister: + description: Unregister an account + default: false + authme.admin.forcelogin: + description: Force login for that player + default: false + authme.admin.forcelogout: + description: Force logout for that player + default: false + authme.admin.changepassword: + description: Change the password of an account + default: false + authme.admin.getemail: + description: Get last email about a player + default: false + authme.admin.changeemail: + description: Change a player email + default: false + authme.admin.accounts: + description: Display Players Accounts + default: false + authme.admin.seeotheraccounts: + description: Display other accounts about a player when he logs in + default: false + authme.admin.lastlogin: + description: Get last login date about a player + default: false + authme.admin.getip: + description: Get IP from a player (fake and real) + default: false + authme.admin.setspawn: + description: Set the AuthMe spawn point + default: false + authme.admin.spawn: + description: Teleport to AuthMe spawn point + default: false + authme.admin.setfirstspawn: + description: Set the AuthMe First Spawn Point + default: false + authme.admin.firstspawn: + description: Teleport to AuthMe First Spawn Point + default: false + authme.admin.switchantibot: + description: Switch AntiBot mode on/off + default: false + authme.admin.purge: + description: Database purge command + default: false + authme.admin.purgebannedplayers: + description: Purge banned players + default: false + authme.admin.purgelastpos: + description: Purge last position of a player/players + default: false + authme.admin.converter: + description: Allow the /authme converter command + default: false + authme.admin.reload: + description: Reload the plugin + default: false + authme.vip: + description: Allow vip slot when the server is full + default: false + authme.bypassantibot: + description: Bypass the AntiBot check + default: false + authme.allowmultipleaccounts: + description: Allow more accounts for same ip + default: false + authme.bypassforcesurvival: + description: Bypass all ForceSurvival features + default: false diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java b/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java index 0f66647be..7338c8686 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/debug/LimboPlayerViewer.java @@ -68,7 +68,9 @@ class LimboPlayerViewer implements DebugSection { sender.sendMessage(ChatColor.BLUE + "Player / limbo / disk limbo info for '" + arguments.get(0) + "'"); new InfoDisplayer(sender, player, memoryLimbo, diskLimbo) .sendEntry("Is op", Player::isOp, LimboPlayer::isOperator) + .sendEntry("Walk speed", Player::getWalkSpeed, LimboPlayer::getWalkSpeed) .sendEntry("Can fly", Player::getAllowFlight, LimboPlayer::isCanFly) + .sendEntry("Fly speed", Player::getFlySpeed, LimboPlayer::getFlySpeed) .sendEntry("Location", p -> formatLocation(p.getLocation()), l -> formatLocation(l.getLocation())) .sendEntry("Prim. group", p -> permissionsManager.hasGroupSupport() ? permissionsManager.getPrimaryGroup(p) : "N/A", diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java b/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java index c6cfb8693..03c3ea138 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboPlayer.java @@ -12,19 +12,27 @@ import java.util.Collection; */ public class LimboPlayer { + public static final float DEFAULT_WALK_SPEED = 0.2f; + public static final float DEFAULT_FLY_SPEED = 0.1f; + private final boolean canFly; private final boolean operator; private final Collection groups; private final Location loc; + private final float walkSpeed; + private final float flySpeed; private BukkitTask timeoutTask = null; private MessageTask messageTask = null; private LimboPlayerState state = LimboPlayerState.PASSWORD_REQUIRED; - public LimboPlayer(Location loc, boolean operator, Collection groups, boolean fly) { + public LimboPlayer(Location loc, boolean operator, Collection groups, boolean fly, float walkSpeed, + float flySpeed) { this.loc = loc; this.operator = operator; this.groups = groups; this.canFly = fly; + this.walkSpeed = walkSpeed; + this.flySpeed = flySpeed; } /** @@ -58,6 +66,14 @@ public class LimboPlayer { return canFly; } + public float getWalkSpeed() { + return walkSpeed; + } + + public float getFlySpeed() { + return flySpeed; + } + /** * Return the timeout task, which kicks the player if he hasn't registered or logged in * after a configurable amount of time. diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboService.java b/src/main/java/fr/xephi/authme/data/limbo/LimboService.java index 0df992104..937ed912d 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboService.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboService.java @@ -14,6 +14,8 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_ALLOW_FLIGHT; +import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_FLY_SPEED; +import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_WALK_SPEED; /** * Service for managing players that are in "limbo," a temporary state players are @@ -117,6 +119,8 @@ public class LimboService { } else { player.setOp(limbo.isOperator()); settings.getProperty(RESTORE_ALLOW_FLIGHT).restoreAllowFlight(player, limbo); + settings.getProperty(RESTORE_FLY_SPEED).restoreFlySpeed(player, limbo); + settings.getProperty(RESTORE_WALK_SPEED).restoreWalkSpeed(player, limbo); limbo.clearTasks(); logger.debug("Restored LimboPlayer stats for `{0}`", lowerName); persistence.removeLimboPlayer(player); diff --git a/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java b/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java index 1b1d33533..d51afbef7 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java +++ b/src/main/java/fr/xephi/authme/data/limbo/LimboServiceHelper.java @@ -5,6 +5,7 @@ import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; +import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -39,11 +40,13 @@ class LimboServiceHelper { // For safety reasons an unregistered player should not have OP status after registration boolean isOperator = isRegistered && player.isOp(); boolean flyEnabled = player.getAllowFlight(); + float walkSpeed = player.getWalkSpeed(); + float flySpeed = player.getFlySpeed(); Collection playerGroups = permissionsManager.hasGroupSupport() ? permissionsManager.getGroups(player) : Collections.emptyList(); logger.debug("Player `{0}` has groups `{1}`", player.getName(), String.join(", ", playerGroups)); - return new LimboPlayer(location, isOperator, playerGroups, flyEnabled); + return new LimboPlayer(location, isOperator, playerGroups, flyEnabled, walkSpeed, flySpeed); } /** @@ -58,12 +61,18 @@ class LimboServiceHelper { player.setOp(false); settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT) .processPlayer(player); + + if (!settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)) { + player.setFlySpeed(0.0f); + player.setWalkSpeed(0.0f); + } } /** * Merges two existing LimboPlayer instances of a player. Merging is done the following way: *
    *
  • isOperator, allowFlight: true if either limbo has true
  • + *
  • flySpeed, walkSpeed: maximum value of either limbo player
  • *
  • groups, location: from old limbo if not empty/null, otherwise from new limbo
  • *
* @@ -80,10 +89,12 @@ class LimboServiceHelper { boolean isOperator = newLimbo.isOperator() || oldLimbo.isOperator(); boolean canFly = newLimbo.isCanFly() || oldLimbo.isCanFly(); + float flySpeed = Math.max(newLimbo.getFlySpeed(), oldLimbo.getFlySpeed()); + float walkSpeed = Math.max(newLimbo.getWalkSpeed(), oldLimbo.getWalkSpeed()); Collection groups = getLimboGroups(oldLimbo.getGroups(), newLimbo.getGroups()); Location location = firstNotNull(oldLimbo.getLocation(), newLimbo.getLocation()); - return new LimboPlayer(location, isOperator, groups, canFly); + return new LimboPlayer(location, isOperator, groups, canFly, walkSpeed, flySpeed); } private static Location firstNotNull(Location first, Location second) { diff --git a/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java b/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java new file mode 100644 index 000000000..f4a249017 --- /dev/null +++ b/src/main/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreType.java @@ -0,0 +1,123 @@ +package fr.xephi.authme.data.limbo; + +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.output.ConsoleLoggerFactory; +import org.bukkit.entity.Player; + +/** + * Possible types to restore the walk and fly speed from LimboPlayer + * back to Bukkit Player. + */ +public enum WalkFlySpeedRestoreType { + + /** + * Restores from LimboPlayer to Player. + */ + RESTORE { + @Override + public void restoreFlySpeed(Player player, LimboPlayer limbo) { + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " + + limbo.getFlySpeed() + " (RESTORE mode)"); + player.setFlySpeed(limbo.getFlySpeed()); + } + + @Override + public void restoreWalkSpeed(Player player, LimboPlayer limbo) { + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " + + limbo.getWalkSpeed() + " (RESTORE mode)"); + player.setWalkSpeed(limbo.getWalkSpeed()); + } + }, + + /** + * Restores from LimboPlayer, using the default speed if the speed on LimboPlayer is 0. + */ + RESTORE_NO_ZERO { + @Override + public void restoreFlySpeed(Player player, LimboPlayer limbo) { + float limboFlySpeed = limbo.getFlySpeed(); + if (limboFlySpeed > 0.01f) { + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " + + limboFlySpeed + " (RESTORE_NO_ZERO mode)"); + player.setFlySpeed(limboFlySpeed); + } else { + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + + " to DEFAULT, it was 0! (RESTORE_NO_ZERO mode)"); + player.setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); + } + } + + @Override + public void restoreWalkSpeed(Player player, LimboPlayer limbo) { + float limboWalkSpeed = limbo.getWalkSpeed(); + if (limboWalkSpeed > 0.01f) { + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " + + limboWalkSpeed + " (RESTORE_NO_ZERO mode)"); + player.setWalkSpeed(limboWalkSpeed); + } else { + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + "" + + " to DEFAULT, it was 0! (RESTORE_NO_ZERO mode)"); + player.setWalkSpeed(LimboPlayer.DEFAULT_WALK_SPEED); + } + } + }, + + /** + * Uses the max speed of Player (current speed) and the LimboPlayer. + */ + MAX_RESTORE { + @Override + public void restoreFlySpeed(Player player, LimboPlayer limbo) { + float newSpeed = Math.max(player.getFlySpeed(), limbo.getFlySpeed()); + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + " to " + newSpeed + + " (Current: " + player.getFlySpeed() + ", Limbo: " + limbo.getFlySpeed() + ") (MAX_RESTORE mode)"); + player.setFlySpeed(newSpeed); + } + + @Override + public void restoreWalkSpeed(Player player, LimboPlayer limbo) { + float newSpeed = Math.max(player.getWalkSpeed(), limbo.getWalkSpeed()); + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + " to " + newSpeed + + " (Current: " + player.getWalkSpeed() + ", Limbo: " + limbo.getWalkSpeed() + ") (MAX_RESTORE mode)"); + player.setWalkSpeed(newSpeed); + } + }, + + /** + * Always sets the default speed to the player. + */ + DEFAULT { + @Override + public void restoreFlySpeed(Player player, LimboPlayer limbo) { + logger.debug(() -> "Restoring fly speed for LimboPlayer " + player.getName() + + " to DEFAULT (DEFAULT mode)"); + player.setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); + } + + @Override + public void restoreWalkSpeed(Player player, LimboPlayer limbo) { + logger.debug(() -> "Restoring walk speed for LimboPlayer " + player.getName() + + " to DEFAULT (DEFAULT mode)"); + player.setWalkSpeed(LimboPlayer.DEFAULT_WALK_SPEED); + } + }; + + private static final ConsoleLogger logger = ConsoleLoggerFactory.get(WalkFlySpeedRestoreType.class); + + /** + * Restores the fly speed from Limbo to Player according to the restoration type. + * + * @param player the player to modify + * @param limbo the limbo player to read from + */ + public abstract void restoreFlySpeed(Player player, LimboPlayer limbo); + + /** + * Restores the walk speed from Limbo to Player according to the restoration type. + * + * @param player the player to modify + * @param limbo the limbo player to read from + */ + public abstract void restoreWalkSpeed(Player player, LimboPlayer limbo); + +} diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java index fe876bea4..c56885413 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerDeserializer.java @@ -18,6 +18,7 @@ import java.util.List; import java.util.function.Function; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.CAN_FLY; +import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.FLY_SPEED; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.GROUPS; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.IS_OP; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOCATION; @@ -27,6 +28,7 @@ import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_X import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_Y; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_YAW; import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.LOC_Z; +import static fr.xephi.authme.data.limbo.persistence.LimboPlayerSerializer.WALK_SPEED; import static java.util.Optional.ofNullable; /** @@ -54,8 +56,10 @@ class LimboPlayerDeserializer implements JsonDeserializer { Collection groups = getLimboGroups(jsonObject); boolean canFly = getBoolean(jsonObject, CAN_FLY); + float walkSpeed = getFloat(jsonObject, WALK_SPEED, LimboPlayer.DEFAULT_WALK_SPEED); + float flySpeed = getFloat(jsonObject, FLY_SPEED, LimboPlayer.DEFAULT_FLY_SPEED); - return new LimboPlayer(loc, operator, groups, canFly); + return new LimboPlayer(loc, operator, groups, canFly, walkSpeed, flySpeed); } private Location deserializeLocation(JsonObject jsonObject) { diff --git a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java index 1192aa515..5f9b40ede 100644 --- a/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java +++ b/src/main/java/fr/xephi/authme/data/limbo/persistence/LimboPlayerSerializer.java @@ -26,6 +26,8 @@ class LimboPlayerSerializer implements JsonSerializer { static final String GROUPS = "groups"; static final String IS_OP = "operator"; static final String CAN_FLY = "can-fly"; + static final String WALK_SPEED = "walk-speed"; + static final String FLY_SPEED = "fly-speed"; private static final Gson GSON = new Gson(); @@ -47,6 +49,8 @@ class LimboPlayerSerializer implements JsonSerializer { obj.addProperty(IS_OP, limboPlayer.isOperator()); obj.addProperty(CAN_FLY, limboPlayer.isCanFly()); + obj.addProperty(WALK_SPEED, limboPlayer.getWalkSpeed()); + obj.addProperty(FLY_SPEED, limboPlayer.getFlySpeed()); return obj; } } diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java b/src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java deleted file mode 100644 index 5b6dd9ab1..000000000 --- a/src/main/java/fr/xephi/authme/listener/protocollib/FreezePacketAdapter.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 AuthMe-Team - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package fr.xephi.authme.listener.protocollib; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.wrappers.WrappedAttribute; -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.data.auth.PlayerCache; -import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.output.ConsoleLoggerFactory; -import fr.xephi.authme.service.BukkitService; -import org.bukkit.entity.Player; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -class FreezePacketAdapter extends PacketAdapter { - - private static final String ATTRIBUTE_MOVEMENT_SPEED = "generic.movementSpeed"; - private static final String ATTRIBUTE_FLYING_SPEED = "generic.flyingSpeed"; - - private final ConsoleLogger logger = ConsoleLoggerFactory.get(FreezePacketAdapter.class); - private final PlayerCache playerCache; - private final DataSource dataSource; - - FreezePacketAdapter(AuthMe plugin, PlayerCache playerCache, DataSource dataSource) { - super(plugin, PacketType.Play.Server.UPDATE_ATTRIBUTES); - this.playerCache = playerCache; - this.dataSource = dataSource; - } - - @Override - public void onPacketSending(PacketEvent packetEvent) { - Player player = packetEvent.getPlayer(); - PacketContainer packet = packetEvent.getPacket(); - - int entityId = packet.getIntegers().read(0); - if (entityId != player.getEntityId()) { - return; - } - - if (!shouldFreeze(player.getName())) { - return; - } - - List newAttributes = new ArrayList<>(); - for (WrappedAttribute attribute : packet.getAttributeCollectionModifier().read(0)) { - if (ATTRIBUTE_MOVEMENT_SPEED.equals(attribute.getAttributeKey()) - || ATTRIBUTE_FLYING_SPEED.equals(attribute.getAttributeKey())) { - newAttributes.add(WrappedAttribute.newBuilder(attribute) - .baseValue(0.0f).modifiers(Collections.emptyList()).build()); - } else { - newAttributes.add(attribute); - } - } - packet.getAttributeCollectionModifier().write(0, newAttributes); - } - - protected void register(BukkitService bukkitService) { - ProtocolLibrary.getProtocolManager().addPacketListener(this); - - bukkitService.getOnlinePlayers().stream() - .filter(player -> shouldFreeze(player.getName())) - .forEach(this::sendFreezePacket); - } - - private boolean shouldFreeze(String playerName) { - return !playerCache.isAuthenticated(playerName) && dataSource.isAuthAvailable(playerName); - } - - public void unregister() { - ProtocolLibrary.getProtocolManager().removePacketListener(this); - } - - protected void sendFreezePacket(Player player) { - ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); - PacketContainer attributesPacket = protocolManager.createPacket(PacketType.Play.Server.UPDATE_ATTRIBUTES); - - attributesPacket.getIntegers().write(0, player.getEntityId()); - attributesPacket.getAttributeCollectionModifier().write(0, Arrays.asList( - WrappedAttribute.newBuilder() - .packet(attributesPacket) - .attributeKey(ATTRIBUTE_MOVEMENT_SPEED) - .baseValue(0.0f) - .build(), - WrappedAttribute.newBuilder() - .packet(attributesPacket) - .attributeKey(ATTRIBUTE_FLYING_SPEED) - .baseValue(0.0f) - .build() - )); - - try { - protocolManager.sendServerPacket(player, attributesPacket, false); - } catch (InvocationTargetException invocationExc) { - logger.logException("Error during sending freeze packet", invocationExc); - } - } - - public void sendUnFreezePacket(Player player) { - player.setWalkSpeed(player.getWalkSpeed()); - player.setFlySpeed(player.getFlySpeed()); - } -} diff --git a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java index a56a72fc5..024077570 100644 --- a/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java +++ b/src/main/java/fr/xephi/authme/listener/protocollib/ProtocolLibService.java @@ -22,12 +22,10 @@ public class ProtocolLibService implements SettingsDependent { /* Packet Adapters */ private InventoryPacketAdapter inventoryPacketAdapter; private TabCompletePacketAdapter tabCompletePacketAdapter; - private FreezePacketAdapter freezePacketAdapter; /* Settings */ private boolean protectInvBeforeLogin; private boolean denyTabCompleteBeforeLogin; - private boolean freezePlayerBeforeLogin; /* Service */ private boolean isEnabled; @@ -60,11 +58,6 @@ public class ProtocolLibService implements SettingsDependent { logger.warning("WARNING! The denyTabComplete feature requires ProtocolLib! Disabling it..."); } - if (freezePlayerBeforeLogin) { - logger.warning("WARNING! In oder to prevent player movements in a nicer way consider" - + " installing ProtocolLib!"); - } - this.isEnabled = false; return; } @@ -91,16 +84,6 @@ public class ProtocolLibService implements SettingsDependent { tabCompletePacketAdapter = null; } - if (freezePlayerBeforeLogin) { - if (freezePacketAdapter == null) { - freezePacketAdapter = new FreezePacketAdapter(plugin, playerCache, dataSource); - freezePacketAdapter.register(bukkitService); - } - } else if (freezePacketAdapter != null) { - freezePacketAdapter.unregister(); - freezePacketAdapter = null; - } - this.isEnabled = true; } @@ -118,10 +101,6 @@ public class ProtocolLibService implements SettingsDependent { tabCompletePacketAdapter.unregister(); tabCompletePacketAdapter = null; } - if (freezePacketAdapter != null) { - freezePacketAdapter.unregister(); - freezePacketAdapter = null; - } } /** @@ -135,36 +114,12 @@ public class ProtocolLibService implements SettingsDependent { } } - /** - * Send a packet to the player to freeze any movement. - * - * @param player The player to send the packet to. - */ - public void sendFreezePacket(Player player) { - if (isEnabled && freezePacketAdapter != null) { - freezePacketAdapter.sendFreezePacket(player); - } - } - - /** - * Send a packet to the player to unfreeze movements. - * - * @param player The player to send the packet to. - */ - public void sendUnFreezePacket(Player player) { - if (isEnabled && freezePacketAdapter != null) { - freezePacketAdapter.sendUnFreezePacket(player); - } - } - @Override public void reload(Settings settings) { - final boolean oldProtectInventory = this.protectInvBeforeLogin; - final boolean oldFreezePlayer = this.freezePlayerBeforeLogin; + boolean oldProtectInventory = this.protectInvBeforeLogin; this.protectInvBeforeLogin = settings.getProperty(RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN); this.denyTabCompleteBeforeLogin = settings.getProperty(RestrictionSettings.DENY_TABCOMPLETE_BEFORE_LOGIN); - this.freezePlayerBeforeLogin = !settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT); //it was true and will be deactivated now, so we need to restore the inventory for every player if (oldProtectInventory && !protectInvBeforeLogin && inventoryPacketAdapter != null) { @@ -175,14 +130,6 @@ public class ProtocolLibService implements SettingsDependent { } } } - if (oldFreezePlayer && !freezePlayerBeforeLogin && freezePacketAdapter != null) { - freezePacketAdapter.unregister(); - for (Player onlinePlayer : bukkitService.getOnlinePlayers()) { - if (!playerCache.isAuthenticated(onlinePlayer.getName())) { - freezePacketAdapter.sendUnFreezePacket(onlinePlayer); - } - } - } setup(); } diff --git a/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java b/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java index 67da62882..29bbe720d 100644 --- a/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/ProcessSyncPlayerLogin.java @@ -6,7 +6,6 @@ import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.LoginEvent; import fr.xephi.authme.events.RestoreInventoryEvent; -import fr.xephi.authme.listener.protocollib.ProtocolLibService; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.process.SynchronousProcess; @@ -24,7 +23,6 @@ import org.bukkit.potion.PotionEffectType; import javax.inject.Inject; import java.util.List; -import static fr.xephi.authme.settings.properties.RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT; import static fr.xephi.authme.settings.properties.RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN; public class ProcessSyncPlayerLogin implements SynchronousProcess { @@ -59,9 +57,6 @@ public class ProcessSyncPlayerLogin implements SynchronousProcess { @Inject private PermissionsManager permissionsManager; - @Inject - private ProtocolLibService protocolLibService; - ProcessSyncPlayerLogin() { } @@ -92,9 +87,6 @@ public class ProcessSyncPlayerLogin implements SynchronousProcess { if (commonService.getProperty(PROTECT_INVENTORY_BEFORE_LOGIN)) { restoreInventory(player); } - if (!commonService.getProperty(ALLOW_UNAUTHED_MOVEMENT)) { - protocolLibService.sendUnFreezePacket(player); - } final PlayerAuth auth = dataSource.getAuth(name); teleportationService.teleportOnLogin(player, auth, limbo); diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java index 55b22228a..46fd7fefc 100644 --- a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncPlayerLogout.java @@ -56,9 +56,6 @@ public class ProcessSyncPlayerLogout implements SynchronousProcess { if (service.getProperty(RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN)) { protocolLibService.sendBlankInventoryPacket(player); } - if (!service.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)){ - protocolLibService.sendFreezePacket(player); - } applyLogoutEffect(player); commandManager.runCommandsOnLogout(player); diff --git a/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java b/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java index 4f0bfabe7..309b69231 100644 --- a/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java +++ b/src/main/java/fr/xephi/authme/settings/properties/LimboSettings.java @@ -5,6 +5,7 @@ import ch.jalu.configme.SettingsHolder; import ch.jalu.configme.configurationdata.CommentsConfiguration; import ch.jalu.configme.properties.Property; import fr.xephi.authme.data.limbo.AllowFlightRestoreType; +import fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType; import fr.xephi.authme.data.limbo.persistence.LimboPersistenceType; import fr.xephi.authme.data.limbo.persistence.SegmentSize; @@ -18,7 +19,7 @@ public final class LimboSettings implements SettingsHolder { @Comment({ "Besides storing the data in memory, you can define if/how the data should be persisted", "on disk. This is useful in case of a server crash, so next time the server starts we can", - "properly restore things like OP status and the ability to fly", + "properly restore things like OP status, ability to fly, and walk/fly speed.", "DISABLED: no disk storage,", "INDIVIDUAL_FILES: each player data in its own file,", "DISTRIBUTED_FILES: distributes players into different files based on their UUID, see below" @@ -48,6 +49,23 @@ public final class LimboSettings implements SettingsHolder { public static final Property RESTORE_ALLOW_FLIGHT = newProperty(AllowFlightRestoreType.class, "limbo.restoreAllowFlight", AllowFlightRestoreType.RESTORE); + @Comment({ + "Restore fly speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO.", + "RESTORE: restore the speed the player had;", + "DEFAULT: always set to default speed;", + "MAX_RESTORE: take the maximum of the player's current speed and the previous one", + "RESTORE_NO_ZERO: Like 'restore' but sets speed to default if the player's speed was 0" + }) + public static final Property RESTORE_FLY_SPEED = + newProperty(WalkFlySpeedRestoreType.class, "limbo.restoreFlySpeed", WalkFlySpeedRestoreType.RESTORE_NO_ZERO); + + @Comment({ + "Restore walk speed: RESTORE, DEFAULT, MAX_RESTORE, RESTORE_NO_ZERO.", + "See above for a description of the values." + }) + public static final Property RESTORE_WALK_SPEED = + newProperty(WalkFlySpeedRestoreType.class, "limbo.restoreWalkSpeed", WalkFlySpeedRestoreType.RESTORE_NO_ZERO); + private LimboSettings() { } @@ -55,7 +73,7 @@ public final class LimboSettings implements SettingsHolder { public void registerComments(CommentsConfiguration conf) { String[] limboExplanation = { "Before a user logs in, various properties are temporarily removed from the player,", - "such as OP status and the ability to fly.", + "such as OP status, ability to fly, and walk/fly speed.", "Once the user is logged in, we add back the properties we previously saved.", "In this section, you may define how these properties should be handled.", "Read more at https://github.com/AuthMe/AuthMeReloaded/wiki/Limbo-players" diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java index e5184d965..78386e2d3 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerMatchers.java @@ -22,28 +22,32 @@ public final class LimboPlayerMatchers { public static Matcher isLimbo(LimboPlayer limbo) { String[] groups = limbo.getGroups().toArray(new String[limbo.getGroups().size()]); - return isLimbo(limbo.isOperator(), limbo.isCanFly(), groups); + return isLimbo(limbo.isOperator(), limbo.isCanFly(), limbo.getWalkSpeed(), limbo.getFlySpeed(), groups); } - public static Matcher isLimbo(boolean isOp, boolean canFly, String... groups) { + public static Matcher isLimbo(boolean isOp, boolean canFly, float walkSpeed, float flySpeed, + String... groups) { return new TypeSafeMatcher() { @Override protected boolean matchesSafely(LimboPlayer item) { return item.isOperator() == isOp && collectionContains(item.getGroups(), groups) - && item.isCanFly() == canFly; + && item.isCanFly() == canFly + && walkSpeed == item.getWalkSpeed() + && flySpeed == item.getFlySpeed(); } @Override public void describeTo(Description description) { - description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s", - isOp, String.join(" ,", groups), canFly)); + description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s, walkSpeed=%f, flySpeed=%f", + isOp, String.join(" ,", groups), canFly, walkSpeed, flySpeed)); } @Override public void describeMismatchSafely(LimboPlayer item, Description description) { - description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s", - item.isOperator(), String.join(" ,", item.getGroups()), item.isCanFly())); + description.appendText(format("Limbo with isOp=%s, groups={%s}, canFly=%s, walkSpeed=%f, flySpeed=%f", + item.isOperator(), String.join(" ,", item.getGroups()), item.isCanFly(), + item.getWalkSpeed(), item.getFlySpeed())); } }; } diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java index c85078e2e..ff0743001 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java @@ -106,7 +106,7 @@ public class LimboPlayerTaskManagerTest { String name = "rats"; Player player = mock(Player.class); given(player.getName()).willReturn(name); - LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false); + LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false, 0.1f, 0.0f); MessageTask existingMessageTask = mock(MessageTask.class); limboPlayer.setMessageTask(existingMessageTask); given(settings.getProperty(RegistrationSettings.MESSAGE_INTERVAL)).willReturn(8); @@ -129,7 +129,7 @@ public class LimboPlayerTaskManagerTest { String name = "race"; Player player = mock(Player.class); given(player.getName()).willReturn(name); - LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false); + LimboPlayer limboPlayer = new LimboPlayer(null, true, Collections.singletonList("grp"), false, 0.1f, 0.0f); given(settings.getProperty(RegistrationSettings.MESSAGE_INTERVAL)).willReturn(12); given(registrationCaptchaManager.isCaptchaRequired(name)).willReturn(true); String captcha = "M032"; @@ -180,7 +180,7 @@ public class LimboPlayerTaskManagerTest { public void shouldCancelExistingTimeoutTask() { // given Player player = mock(Player.class); - LimboPlayer limboPlayer = new LimboPlayer(null, false, Collections.emptyList(), true); + LimboPlayer limboPlayer = new LimboPlayer(null, false, Collections.emptyList(), true, 0.3f, 0.1f); BukkitTask existingTask = mock(BukkitTask.class); limboPlayer.setTimeoutTask(existingTask); given(settings.getProperty(RestrictionSettings.TIMEOUT)).willReturn(18); diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java index 17e4dc121..da3bc00f8 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java @@ -37,9 +37,9 @@ public class LimboServiceHelperTest { public void shouldMergeLimboPlayers() { // given Location newLocation = mock(Location.class); - LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), false); + LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), false, 0.0f, 0.0f); Location oldLocation = mock(Location.class); - LimboPlayer oldLimbo = new LimboPlayer(oldLocation, true, Collections.singletonList("grp-old"), true); + LimboPlayer oldLimbo = new LimboPlayer(oldLocation, true, Collections.singletonList("grp-old"), true, 0.1f, 0.8f); // when LimboPlayer result = limboServiceHelper.merge(newLimbo, oldLimbo); @@ -49,14 +49,16 @@ public class LimboServiceHelperTest { assertThat(result.isOperator(), equalTo(true)); assertThat(result.getGroups(), contains("grp-old")); assertThat(result.isCanFly(), equalTo(true)); + assertThat(result.getWalkSpeed(), equalTo(0.1f)); + assertThat(result.getFlySpeed(), equalTo(0.8f)); } @Test public void shouldFallBackToNewLimboForMissingData() { // given Location newLocation = mock(Location.class); - LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), true); - LimboPlayer oldLimbo = new LimboPlayer(null, false, Collections.emptyList(), false); + LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), true, 0.3f, 0.0f); + LimboPlayer oldLimbo = new LimboPlayer(null, false, Collections.emptyList(), false, 0.1f, 0.1f); // when LimboPlayer result = limboServiceHelper.merge(newLimbo, oldLimbo); @@ -66,6 +68,8 @@ public class LimboServiceHelperTest { assertThat(result.isOperator(), equalTo(false)); assertThat(result.getGroups(), contains("grp-new")); assertThat(result.isCanFly(), equalTo(true)); + assertThat(result.getWalkSpeed(), equalTo(0.3f)); + assertThat(result.getFlySpeed(), equalTo(0.1f)); } @Test diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java index e3084a4a4..8bcfaff79 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java @@ -79,7 +79,7 @@ public class LimboServiceTest { @Test public void shouldCreateLimboPlayer() { // given - Player player = newPlayer("Bobby", true, false); + Player player = newPlayer("Bobby", true, 0.3f, false, 0.2f); Location playerLoc = mock(Location.class); given(spawnLoader.getPlayerLocationOrSpawn(player)).willReturn(playerLoc); given(permissionsManager.hasGroupSupport()).willReturn(true); @@ -93,13 +93,17 @@ public class LimboServiceTest { verify(taskManager).registerMessageTask(eq(player), any(LimboPlayer.class), eq(LimboMessageType.LOG_IN)); verify(taskManager).registerTimeoutTask(eq(player), any(LimboPlayer.class)); verify(player).setAllowFlight(false); + verify(player).setFlySpeed(0.0f); + verify(player).setWalkSpeed(0.0f); assertThat(limboService.hasLimboPlayer("Bobby"), equalTo(true)); LimboPlayer limbo = limboService.getLimboPlayer("Bobby"); verify(authGroupHandler).setGroup(player, limbo, AuthGroupType.REGISTERED_UNAUTHENTICATED); assertThat(limbo, not(nullValue())); assertThat(limbo.isOperator(), equalTo(true)); + assertThat(limbo.getWalkSpeed(), equalTo(0.3f)); assertThat(limbo.isCanFly(), equalTo(false)); + assertThat(limbo.getFlySpeed(), equalTo(0.2f)); assertThat(limbo.getLocation(), equalTo(playerLoc)); assertThat(limbo.getGroups(), equalTo(Collections.singletonList("permgrwp"))); } @@ -107,7 +111,7 @@ public class LimboServiceTest { @Test public void shouldNotKeepOpStatusForUnregisteredPlayer() { // given - Player player = newPlayer("CharleS", true, true); + Player player = newPlayer("CharleS", true, 0.1f, true, 0.4f); Location playerLoc = mock(Location.class); given(spawnLoader.getPlayerLocationOrSpawn(player)).willReturn(playerLoc); given(permissionsManager.hasGroupSupport()).willReturn(false); @@ -121,12 +125,16 @@ public class LimboServiceTest { verify(taskManager).registerTimeoutTask(eq(player), any(LimboPlayer.class)); verify(permissionsManager, only()).hasGroupSupport(); verify(player).setAllowFlight(false); + verify(player).setFlySpeed(0.0f); + verify(player).setWalkSpeed(0.0f); LimboPlayer limbo = limboService.getLimboPlayer("charles"); verify(authGroupHandler).setGroup(player, limbo, AuthGroupType.UNREGISTERED); assertThat(limbo, not(nullValue())); assertThat(limbo.isOperator(), equalTo(false)); + assertThat(limbo.getWalkSpeed(), equalTo(0.1f)); assertThat(limbo.isCanFly(), equalTo(true)); + assertThat(limbo.getFlySpeed(), equalTo(0.4f)); assertThat(limbo.getLocation(), equalTo(playerLoc)); assertThat(limbo.getGroups(), equalTo(Collections.emptyList())); } @@ -154,18 +162,22 @@ public class LimboServiceTest { public void shouldRestoreData() { // given LimboPlayer limbo = Mockito.spy(convertToLimboPlayer( - newPlayer("John", true, false), null, Collections.emptyList())); + newPlayer("John", true, 0.4f, false, 0.0f), null, Collections.emptyList())); getLimboMap().put("john", limbo); - Player player = newPlayer("John", false, false); + Player player = newPlayer("John", false, 0.2f, false, 0.7f); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.ENABLE); + given(settings.getProperty(LimboSettings.RESTORE_WALK_SPEED)).willReturn(WalkFlySpeedRestoreType.RESTORE); + given(settings.getProperty(LimboSettings.RESTORE_FLY_SPEED)).willReturn(WalkFlySpeedRestoreType.RESTORE_NO_ZERO); // when limboService.restoreData(player); // then verify(player).setOp(true); + verify(player).setWalkSpeed(0.4f); verify(player).setAllowFlight(true); + verify(player).setFlySpeed(LimboPlayer.DEFAULT_FLY_SPEED); verify(limbo).clearTasks(); verify(authGroupHandler).setGroup(player, limbo, AuthGroupType.LOGGED_IN); assertThat(limboService.hasLimboPlayer("John"), equalTo(false)); @@ -220,15 +232,18 @@ public class LimboServiceTest { return player; } - private static Player newPlayer(String name, boolean isOp, boolean canFly) { + private static Player newPlayer(String name, boolean isOp, float walkSpeed, boolean canFly, float flySpeed) { Player player = newPlayer(name); given(player.isOp()).willReturn(isOp); + given(player.getWalkSpeed()).willReturn(walkSpeed); given(player.getAllowFlight()).willReturn(canFly); + given(player.getFlySpeed()).willReturn(flySpeed); return player; } private static LimboPlayer convertToLimboPlayer(Player player, Location location, Collection groups) { - return new LimboPlayer(location, player.isOp(), groups, player.getAllowFlight()); + return new LimboPlayer(location, player.isOp(), groups, player.getAllowFlight(), + player.getWalkSpeed(), player.getFlySpeed()); } private Map getLimboMap() { diff --git a/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java b/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java new file mode 100644 index 000000000..f8aa2719c --- /dev/null +++ b/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java @@ -0,0 +1,108 @@ +package fr.xephi.authme.data.limbo; + +import org.bukkit.entity.Player; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static fr.xephi.authme.data.limbo.LimboPlayer.DEFAULT_FLY_SPEED; +import static fr.xephi.authme.data.limbo.LimboPlayer.DEFAULT_WALK_SPEED; +import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.DEFAULT; +import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.MAX_RESTORE; +import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.RESTORE; +import static fr.xephi.authme.data.limbo.WalkFlySpeedRestoreType.RESTORE_NO_ZERO; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Test for {@link WalkFlySpeedRestoreType}. + */ +@RunWith(Parameterized.class) +public class WalkFlySpeedRestoreTypeTest { + + private final TestParameters parameters; + + public WalkFlySpeedRestoreTypeTest(TestParameters parameters) { + this.parameters = parameters; + } + + @Test + public void shouldRestoreToExpectedValue() { + // given + LimboPlayer limbo = mock(LimboPlayer.class); + given(limbo.getWalkSpeed()).willReturn(parameters.givenLimboWalkSpeed); + given(limbo.getFlySpeed()).willReturn(parameters.givenLimboFlySpeed); + + Player player = mock(Player.class); + given(player.getWalkSpeed()).willReturn(parameters.givenPlayerWalkSpeed); + given(player.getFlySpeed()).willReturn(parameters.givenPlayerFlySpeed); + + // when + parameters.testedType.restoreWalkSpeed(player, limbo); + parameters.testedType.restoreFlySpeed(player, limbo); + + // then + verify(player).setWalkSpeed(parameters.expectedWalkSpeed); + verify(player).setFlySpeed(parameters.expectedFlySpeed); + } + + @Parameterized.Parameters(name = "{0}") + public static List buildParams() { + List parameters = Arrays.asList( + create(RESTORE).withLimbo(0.1f, 0.4f).withPlayer(0.3f, 0.9f).expect(0.1f, 0.4f), + create(RESTORE).withLimbo(0.9f, 0.2f).withPlayer(0.3f, 0.0f).expect(0.9f, 0.2f), + create(MAX_RESTORE).withLimbo(0.3f, 0.8f).withPlayer(0.5f, 0.2f).expect(0.5f, 0.8f), + create(MAX_RESTORE).withLimbo(0.4f, 0.2f).withPlayer(0.1f, 0.4f).expect(0.4f, 0.4f), + create(RESTORE_NO_ZERO).withLimbo(0.1f, 0.2f).withPlayer(0.5f, 0.1f).expect(0.1f, 0.2f), + create(RESTORE_NO_ZERO).withLimbo(0.0f, 0.005f).withPlayer(0.4f, 0.8f).expect(DEFAULT_WALK_SPEED, DEFAULT_FLY_SPEED), + create(DEFAULT).withLimbo(0.1f, 0.7f).withPlayer(0.4f, 0.0f).expect(DEFAULT_WALK_SPEED, DEFAULT_FLY_SPEED) + ); + + // Convert List to List + return parameters.stream().map(p -> new Object[]{p}).collect(Collectors.toList()); + } + + private static TestParameters create(WalkFlySpeedRestoreType testedType) { + TestParameters params = new TestParameters(); + params.testedType = testedType; + return params; + } + + private static final class TestParameters { + private WalkFlySpeedRestoreType testedType; + private float givenLimboWalkSpeed; + private float givenLimboFlySpeed; + private float givenPlayerWalkSpeed; + private float givenPlayerFlySpeed; + private float expectedWalkSpeed; + private float expectedFlySpeed; + + TestParameters withLimbo(float walkSpeed, float flySpeed) { + this.givenLimboWalkSpeed = walkSpeed; + this.givenLimboFlySpeed = flySpeed; + return this; + } + + TestParameters withPlayer(float walkSpeed, float flySpeed) { + this.givenPlayerWalkSpeed = walkSpeed; + this.givenPlayerFlySpeed = flySpeed; + return this; + } + + TestParameters expect(float walkSpeed, float flySpeed) { + this.expectedWalkSpeed = walkSpeed; + this.expectedFlySpeed = flySpeed; + return this; + } + + @Override + public String toString() { + return testedType + " {" + expectedWalkSpeed + ", " + expectedFlySpeed + "}"; + } + } +} diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index 191c3d282..fd41134a1 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -48,22 +48,22 @@ public class DistributedFilesPersistenceHandlerTest { /** Player is in seg32-10110 and should be migrated into seg16-f. */ private static final UUID MIGRATED_UUID = fromString("f6a97c88-7c8f-c12e-4931-6206d4ca067d"); private static final Matcher MIGRATED_LIMBO_MATCHER = - isLimbo(false, true, "noob"); + isLimbo(false, true, 0.2f, 0.1f, "noob"); /** Existing player in seg16-f. */ private static final UUID UUID_FAB69 = fromString("fab69c88-2cd0-1fed-f00d-dead14ca067d"); private static final Matcher FAB69_MATCHER = - isLimbo(false, false, ""); + isLimbo(false, false, 0.2f, 0.1f, ""); /** Player in seg16-8. */ private static final UUID UUID_STAFF = fromString("88897c88-7c8f-c12e-4931-6206d4ca067d"); private static final Matcher STAFF_MATCHER = - isLimbo(true, false, "staff", "mod"); + isLimbo(true, false, 0.3f, 0.1f, "staff", "mod"); /** Player in seg16-8. */ private static final UUID UUID_8C679 = fromString("8c679491-1234-abcd-9102-1fa6e0cc3f81"); private static final Matcher SC679_MATCHER = - isLimbo(false, true, "primary"); + isLimbo(false, true, 0.1f, 0.0f, "primary"); /** UUID for which no data is stored (belongs to a segment file that does not exist, seg16-4). */ private static final UUID UNKNOWN_UUID = fromString("42d1cc0b-8f12-d04a-e7ba-a067d05cdc39"); @@ -156,10 +156,10 @@ public class DistributedFilesPersistenceHandlerTest { // given Player uuidToAdd1 = mockPlayerWithUuid(UNKNOWN_UUID); Location location1 = mockLocation("1world"); - LimboPlayer limbo1 = new LimboPlayer(location1, false, Collections.singletonList("group-1"), true); + LimboPlayer limbo1 = new LimboPlayer(location1, false, Collections.singletonList("group-1"), true, 0.1f, 0.2f); Player uuidToAdd2 = mockPlayerWithUuid(UNKNOWN_UUID2); Location location2 = mockLocation("2world"); - LimboPlayer limbo2 = new LimboPlayer(location2, true, Collections.emptyList(), false); + LimboPlayer limbo2 = new LimboPlayer(location2, true, Collections.emptyList(), false, 0.0f, 0.25f); // when persistenceHandler.saveLimboPlayer(uuidToAdd1, limbo1); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java index b62e96991..06df57bf0 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java @@ -78,6 +78,8 @@ public class IndividualFilesPersistenceHandlerTest { assertThat(data, not(nullValue())); assertThat(data.isOperator(), equalTo(true)); assertThat(data.isCanFly(), equalTo(true)); + assertThat(data.getWalkSpeed(), equalTo(0.2f)); + assertThat(data.getFlySpeed(), equalTo(0.1f)); assertThat(data.getGroups(), contains("players")); Location location = data.getLocation(); assertThat(location.getX(), equalTo(-113.219)); @@ -112,7 +114,7 @@ public class IndividualFilesPersistenceHandlerTest { World world = mock(World.class); given(world.getName()).willReturn("player-world"); Location location = new Location(world, 0.2, 102.25, -89.28, 3.02f, 90.13f); - LimboPlayer limbo = new LimboPlayer(location, true, Collections.singletonList("primary-grp"), true); + LimboPlayer limbo = new LimboPlayer(location, true, Collections.singletonList("primary-grp"), true, 1.2f, 0.8f); // when handler.saveLimboPlayer(player, limbo); diff --git a/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json b/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json index 976dca0af..ee1ae20ad 100644 --- a/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json +++ b/src/test/resources/fr/xephi/authme/data/backup/sample-folder/data.json @@ -9,5 +9,7 @@ }, "operator": true, "can-fly": true, + "walk-speed": 0.2, + "fly-speed": 0.1, "group": "players" } diff --git a/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json b/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json index 7ed70b206..f22e472a1 100644 --- a/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json +++ b/src/test/resources/fr/xephi/authme/data/limbo/seg16-8-limbo.json @@ -13,7 +13,9 @@ "mod" ], "operator": true, - "can-fly": false + "can-fly": false, + "walk-speed": 0.3, + "fly-speed": 0.1 }, "8c679491-1234-abcd-9102-1fa6e0cc3f81": { "location": { @@ -26,6 +28,8 @@ }, "group": "primary", "operator": false, - "can-fly": true + "can-fly": true, + "walk-speed": 0.1, + "fly-speed": 0.0 } } diff --git a/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json b/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json index e72f81abf..9f2562622 100644 --- a/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json +++ b/src/test/resources/fr/xephi/authme/data/limbo/seg16-f-limbo.json @@ -10,6 +10,8 @@ }, "group": "", "operator": false, - "can-fly": false + "can-fly": false, + "walk-speed": 0.2, + "fly-speed": 0.1 } } diff --git a/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json b/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json index d7371b974..b50fb8bda 100644 --- a/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json +++ b/src/test/resources/fr/xephi/authme/data/limbo/seg32-10110-limbo.json @@ -10,6 +10,8 @@ }, "group": "noob", "operator": false, - "can-fly": true + "can-fly": true, + "walk-speed": 0.2, + "fly-speed": 0.1 } } From 28c02fc9e9aa3fda82699015ad08b938e66cc7ee Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Thu, 8 Aug 2019 17:25:16 +0200 Subject: [PATCH 83/83] Bump slf4j-simple from 1.7.26 to 1.7.27 (#1881) Bumps [slf4j-simple](https://github.com/qos-ch/slf4j) from 1.7.26 to 1.7.27. - [Release notes](https://github.com/qos-ch/slf4j/releases) - [Commits](https://github.com/qos-ch/slf4j/compare/v_1.7.26...v_1.7.27) Signed-off-by: dependabot-preview[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b378bf874..e99e52728 100644 --- a/pom.xml +++ b/pom.xml @@ -582,7 +582,7 @@ org.slf4j slf4j-simple - 1.7.26 + 1.7.27 true