From 1f9bf3875584516ef836239e9e56d65c1df48eb4 Mon Sep 17 00:00:00 2001 From: Tony Date: Tue, 3 Apr 2018 09:45:27 -0600 Subject: [PATCH 01/14] Added EmailChangedEvent (#1549) * Added EmailChangedEvent * Fix failing tests Silly. * Documented the EmailChangedEvent * Separate messages for cancelled email event * Added lang todos for all the languages I can't speak I wish I could though. * Checkstyle satisfaction * Changed log level to info for cancelled events --- .../authme/data/VerificationCodeManager.java | 2 +- .../authme/events/EmailChangedEvent.java | 87 +++++++++++++++++++ .../fr/xephi/authme/message/MessageKey.java | 6 ++ .../authme/process/email/AsyncAddEmail.java | 12 +++ .../process/email/AsyncChangeEmail.java | 18 +++- src/main/resources/messages/messages_bg.yml | 2 + src/main/resources/messages/messages_br.yml | 2 + src/main/resources/messages/messages_cz.yml | 2 + src/main/resources/messages/messages_de.yml | 2 + src/main/resources/messages/messages_en.yml | 2 + src/main/resources/messages/messages_eo.yml | 2 + src/main/resources/messages/messages_es.yml | 2 + src/main/resources/messages/messages_et.yml | 2 + src/main/resources/messages/messages_eu.yml | 2 + src/main/resources/messages/messages_fi.yml | 2 + src/main/resources/messages/messages_fr.yml | 2 + src/main/resources/messages/messages_gl.yml | 2 + src/main/resources/messages/messages_hu.yml | 2 + src/main/resources/messages/messages_id.yml | 2 + src/main/resources/messages/messages_it.yml | 2 + src/main/resources/messages/messages_ko.yml | 2 + src/main/resources/messages/messages_lt.yml | 2 + src/main/resources/messages/messages_nl.yml | 2 + src/main/resources/messages/messages_pl.yml | 2 + src/main/resources/messages/messages_pt.yml | 2 + src/main/resources/messages/messages_ro.yml | 2 + src/main/resources/messages/messages_ru.yml | 8 +- src/main/resources/messages/messages_sk.yml | 2 + src/main/resources/messages/messages_tr.yml | 2 + src/main/resources/messages/messages_uk.yml | 4 +- src/main/resources/messages/messages_vn.yml | 2 + src/main/resources/messages/messages_zhcn.yml | 2 + src/main/resources/messages/messages_zhhk.yml | 2 + src/main/resources/messages/messages_zhmc.yml | 2 + src/main/resources/messages/messages_zhtw.yml | 2 + .../process/email/AsyncAddEmailTest.java | 34 ++++++++ .../process/email/AsyncChangeEmailTest.java | 40 ++++++++- 37 files changed, 259 insertions(+), 8 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/events/EmailChangedEvent.java diff --git a/src/main/java/fr/xephi/authme/data/VerificationCodeManager.java b/src/main/java/fr/xephi/authme/data/VerificationCodeManager.java index c5c2d7257..1cd176684 100644 --- a/src/main/java/fr/xephi/authme/data/VerificationCodeManager.java +++ b/src/main/java/fr/xephi/authme/data/VerificationCodeManager.java @@ -162,7 +162,7 @@ public class VerificationCodeManager implements SettingsDependent, HasCleanup { * * @param name the name of the player to generate a code for */ - public void verify(String name){ + public void verify(String name) { verifiedPlayers.add(name.toLowerCase()); } diff --git a/src/main/java/fr/xephi/authme/events/EmailChangedEvent.java b/src/main/java/fr/xephi/authme/events/EmailChangedEvent.java new file mode 100644 index 000000000..7d9468cab --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/EmailChangedEvent.java @@ -0,0 +1,87 @@ +package fr.xephi.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import javax.annotation.Nullable; + +/** + * This event is called when a player adds or changes his email address. + */ +public class EmailChangedEvent extends CustomEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private final String oldEmail; + private final String newEmail; + private boolean isCancelled; + + /** + * Constructor + * + * @param player The player that changed email + * @param oldEmail Old email player had on file. Can be null when user adds an email + * @param newEmail New email that player tries to set. In case of adding email, this will contain + * the email is trying to set. + * @param isAsync should this event be called asynchronously? + */ + public EmailChangedEvent(Player player, @Nullable String oldEmail, String newEmail, boolean isAsync) { + super(isAsync); + this.player = player; + this.oldEmail = oldEmail; + this.newEmail = newEmail; + } + + @Override + public boolean isCancelled() { + return isCancelled; + } + + /** + * Gets the player who changes the email + * + * @return The player who changed the email + */ + public Player getPlayer() { + return player; + } + + /** + * Gets the old email in case user tries to change existing email. + * + * @return old email stored on file. Can be null when user never had an email and adds a new one. + */ + public @Nullable String getOldEmail() { + return this.oldEmail; + } + + /** + * Gets the new email. + * + * @return the email user is trying to set. If user adds email and never had one before, + * this is where such email can be found. + */ + public String getNewEmail() { + return this.newEmail; + } + + @Override + public void setCancelled(boolean cancelled) { + this.isCancelled = cancelled; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + /** + * Return the list of handlers, equivalent to {@link #getHandlers()} and required by {@link Event}. + * + * @return The list of handlers + */ + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/fr/xephi/authme/message/MessageKey.java b/src/main/java/fr/xephi/authme/message/MessageKey.java index 355f14a9a..357e7d8cc 100644 --- a/src/main/java/fr/xephi/authme/message/MessageKey.java +++ b/src/main/java/fr/xephi/authme/message/MessageKey.java @@ -167,12 +167,18 @@ public enum MessageKey { /** Email address successfully added to your account! */ EMAIL_ADDED_SUCCESS("email.added"), + /** Adding email was not allowed */ + EMAIL_ADD_NOT_ALLOWED("email.add_not_allowed"), + /** Please confirm your email address! */ CONFIRM_EMAIL_MESSAGE("email.request_confirmation"), /** Email address changed correctly! */ EMAIL_CHANGED_SUCCESS("email.changed"), + /** Changing email was not allowed */ + EMAIL_CHANGE_NOT_ALLOWED("email.change_not_allowed"), + /** Your current email address is: %email */ EMAIL_SHOW("email.email_show", "%email"), 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 016d6169d..1896bfd3b 100644 --- a/src/main/java/fr/xephi/authme/process/email/AsyncAddEmail.java +++ b/src/main/java/fr/xephi/authme/process/email/AsyncAddEmail.java @@ -4,8 +4,10 @@ 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.events.EmailChangedEvent; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.AsynchronousProcess; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.service.bungeecord.BungeeSender; @@ -35,6 +37,9 @@ public class AsyncAddEmail implements AsynchronousProcess { @Inject private BungeeSender bungeeSender; + @Inject + private BukkitService bukkitService; + AsyncAddEmail() { } /** @@ -57,6 +62,13 @@ public class AsyncAddEmail implements AsynchronousProcess { } else if (!validationService.isEmailFreeForRegistration(email, player)) { service.send(player, MessageKey.EMAIL_ALREADY_USED_ERROR); } else { + 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"); + service.send(player, MessageKey.EMAIL_ADD_NOT_ALLOWED); + return; + } auth.setEmail(email); if (dataSource.updateEmail(auth)) { playerCache.updatePlayer(auth); 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 8edd94961..26a5da9e7 100644 --- a/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java +++ b/src/main/java/fr/xephi/authme/process/email/AsyncChangeEmail.java @@ -1,10 +1,13 @@ package fr.xephi.authme.process.email; +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.events.EmailChangedEvent; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.AsynchronousProcess; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.service.bungeecord.BungeeSender; @@ -32,6 +35,9 @@ public class AsyncChangeEmail implements AsynchronousProcess { @Inject private BungeeSender bungeeSender; + + @Inject + private BukkitService bukkitService; AsyncChangeEmail() { } @@ -57,14 +63,22 @@ public class AsyncChangeEmail implements AsynchronousProcess { } else if (!validationService.isEmailFreeForRegistration(newEmail, player)) { service.send(player, MessageKey.EMAIL_ALREADY_USED_ERROR); } else { - saveNewEmail(auth, player, newEmail); + saveNewEmail(auth, player, oldEmail, newEmail); } } else { outputUnloggedMessage(player); } } - private void saveNewEmail(PlayerAuth auth, Player player, String newEmail) { + private void saveNewEmail(PlayerAuth auth, Player player, String oldEmail, String newEmail) { + 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"); + service.send(player, MessageKey.EMAIL_CHANGE_NOT_ALLOWED); + return; + } + auth.setEmail(newEmail); if (dataSource.updateEmail(auth)) { playerCache.updatePlayer(auth); diff --git a/src/main/resources/messages/messages_bg.yml b/src/main/resources/messages/messages_bg.yml index 8b073bd96..3a6f34948 100644 --- a/src/main/resources/messages/messages_bg.yml +++ b/src/main/resources/messages/messages_bg.yml @@ -99,6 +99,8 @@ email: send_failure: 'Съобщението не беше изпратено. Моля свържете се с администратора.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' email_cooldown_error: '&cВече е бил изпратен имейл адрес. Трябва а изчакаш %time преди да пратиш нов.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_br.yml b/src/main/resources/messages/messages_br.yml index 69f5e3954..69062b23c 100644 --- a/src/main/resources/messages/messages_br.yml +++ b/src/main/resources/messages/messages_br.yml @@ -102,6 +102,8 @@ email: send_failure: '&cO e-mail não pôde ser enviado, reporte isso a um administrador!' change_password_expired: 'Você não pode mais usar esse comando de recuperação de senha!' email_cooldown_error: '&cUm e-mail já foi enviado, espere mais %time antes de enviar novamente!' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_cz.yml b/src/main/resources/messages/messages_cz.yml index 5ed2ceb41..e3bd5c35f 100644 --- a/src/main/resources/messages/messages_cz.yml +++ b/src/main/resources/messages/messages_cz.yml @@ -99,6 +99,8 @@ email: send_failure: 'Email nemohl být odeslán. Kontaktujte prosím admina.' change_password_expired: 'Nemůžeš si změnit heslo pomocí toho příkazu.' email_cooldown_error: '&cEmail už byl nedávno odeslán. Musíš čekat %time před odesláním nového.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_de.yml b/src/main/resources/messages/messages_de.yml index 84679c486..97639a9af 100644 --- a/src/main/resources/messages/messages_de.yml +++ b/src/main/resources/messages/messages_de.yml @@ -99,6 +99,8 @@ email: send_failure: 'Die E-Mail konnte nicht gesendet werden. Bitte kontaktiere einen Administrator.' change_password_expired: 'Mit diesem Befehl kannst du dein Passwort nicht mehr ändern.' email_cooldown_error: '&cEine E-Mail wurde erst kürzlich versendet. Du musst %time warten, bevor du eine neue anfordern kannst.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_en.yml b/src/main/resources/messages/messages_en.yml index 6d9d28798..971945afc 100644 --- a/src/main/resources/messages/messages_en.yml +++ b/src/main/resources/messages/messages_en.yml @@ -98,6 +98,8 @@ email: add_email_request: '&3Please add your email to your account with the command: /email add ' change_password_expired: 'You cannot change your password using this command anymore.' email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + add_not_allowed: '&cAdding email was not allowed' + change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_eo.yml b/src/main/resources/messages/messages_eo.yml index c5783c831..390acdca8 100644 --- a/src/main/resources/messages/messages_eo.yml +++ b/src/main/resources/messages/messages_eo.yml @@ -99,6 +99,8 @@ email: send_failure: 'La retpoŝto ne estis sendita. Bonvolu kontakti administranto.' change_password_expired: 'Vi ne povas ŝanĝi vian pasvorton per tiu ĉi komando plu.' email_cooldown_error: '&cRetmesaĝon jam sendita lastatempe. Vi devas atendi %time antaŭ vi povas sendi novan.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_es.yml b/src/main/resources/messages/messages_es.yml index 50363ead1..bde1f29ea 100644 --- a/src/main/resources/messages/messages_es.yml +++ b/src/main/resources/messages/messages_es.yml @@ -100,6 +100,8 @@ email: send_failure: 'No se ha podido enviar el correo electrónico. Por favor, contacta con un administrador.' change_password_expired: 'No puedes cambiar la contraseña utilizando este comando.' email_cooldown_error: '&cEl correo ha sido enviado recientemente. Debes esperar %time antes de volver a enviar uno nuevo.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_et.yml b/src/main/resources/messages/messages_et.yml index 68ce520f5..ba5e0b15e 100644 --- a/src/main/resources/messages/messages_et.yml +++ b/src/main/resources/messages/messages_et.yml @@ -99,6 +99,8 @@ email: send_failure: 'Meili ei õnnestunud saata. Kontakteeru meeskonnaga.' change_password_expired: '&3Enam ei saa vahetada oma parooli kasutades seda käsklust.' email_cooldown_error: '&cEmail juba saadeti. Sa pead ootama %time ennem, kui saad uuesti saata.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_eu.yml b/src/main/resources/messages/messages_eu.yml index 0507d1042..65bd5575f 100644 --- a/src/main/resources/messages/messages_eu.yml +++ b/src/main/resources/messages/messages_eu.yml @@ -99,6 +99,8 @@ email: # TODO send_failure: 'The email could not be sent. Please contact an administrator.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' # TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_fi.yml b/src/main/resources/messages/messages_fi.yml index b0b4f3032..95d0a7320 100644 --- a/src/main/resources/messages/messages_fi.yml +++ b/src/main/resources/messages/messages_fi.yml @@ -99,6 +99,8 @@ email: # TODO send_failure: 'The email could not be sent. Please contact an administrator.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' # TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_fr.yml b/src/main/resources/messages/messages_fr.yml index 52fd4c882..710da4d7f 100644 --- a/src/main/resources/messages/messages_fr.yml +++ b/src/main/resources/messages/messages_fr.yml @@ -102,6 +102,8 @@ email: send_failure: '&cLe mail n''a pas pu être envoyé. Veuillez contacter un admin.' change_password_expired: 'Vous ne pouvez pas changer votre mot de passe avec cette commande.' email_cooldown_error: '&cUn mail de récupération a déjà été envoyé récemment. Veuillez attendre %time pour le demander de nouveau.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_gl.yml b/src/main/resources/messages/messages_gl.yml index d22caa7cb..fb79b6646 100644 --- a/src/main/resources/messages/messages_gl.yml +++ b/src/main/resources/messages/messages_gl.yml @@ -99,6 +99,8 @@ email: # TODO send_failure: 'The email could not be sent. Please contact an administrator.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' # TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_hu.yml b/src/main/resources/messages/messages_hu.yml index 1d420b746..72f8a15be 100644 --- a/src/main/resources/messages/messages_hu.yml +++ b/src/main/resources/messages/messages_hu.yml @@ -99,6 +99,8 @@ email: send_failure: 'Nem sikerült elküldeni az emailt. Lépj kapcsolatba egy adminnal.' change_password_expired: 'Ezzel a paranccsal már nem módosíthatja jelszavát.' email_cooldown_error: '&cEgy emailt már kiküldtünk. Következő email küldése előtt várnod kell: %time.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_id.yml b/src/main/resources/messages/messages_id.yml index 65e84cd9c..5e5b3f3cd 100644 --- a/src/main/resources/messages/messages_id.yml +++ b/src/main/resources/messages/messages_id.yml @@ -99,6 +99,8 @@ email: # TODO send_failure: 'The email could not be sent. Please contact an administrator.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' # TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_it.yml b/src/main/resources/messages/messages_it.yml index 22354cda8..70162b775 100644 --- a/src/main/resources/messages/messages_it.yml +++ b/src/main/resources/messages/messages_it.yml @@ -102,6 +102,8 @@ email: send_failure: 'Non è stato possibile inviare l''email di recupero. Per favore contatta un amministratore.' change_password_expired: 'Non puoi più cambiare la tua password con questo comando.' email_cooldown_error: '&cUna email di recupero ti è già stata inviata recentemente. Devi attendere %time prima di poterne richiedere una nuova.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_ko.yml b/src/main/resources/messages/messages_ko.yml index 41049b884..5d875932e 100644 --- a/src/main/resources/messages/messages_ko.yml +++ b/src/main/resources/messages/messages_ko.yml @@ -101,6 +101,8 @@ email: send_failure: '이메일을 보낼 수 없습니다. 관리자에게 알려주세요.' change_password_expired: '더 이상 이 명령어를 통해 비밀번호를 변경할 수 없습니다.' email_cooldown_error: '&c이메일을 이미 발송했습니다. %time 후에 다시 발송할 수 있습니다.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_lt.yml b/src/main/resources/messages/messages_lt.yml index 15eea3048..3df013699 100644 --- a/src/main/resources/messages/messages_lt.yml +++ b/src/main/resources/messages/messages_lt.yml @@ -99,6 +99,8 @@ email: # TODO send_failure: 'The email could not be sent. Please contact an administrator.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' # TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_nl.yml b/src/main/resources/messages/messages_nl.yml index b8fc40950..86f7b8ff2 100644 --- a/src/main/resources/messages/messages_nl.yml +++ b/src/main/resources/messages/messages_nl.yml @@ -99,6 +99,8 @@ email: send_failure: 'De e-mail kon niet verzonden worden. Neem contact op met een administrator.' change_password_expired: 'Je kunt je wachtwoord niet meer veranderen met dit commando.' email_cooldown_error: '&cEr is recent al een e-mail verzonden. Je moet %time wachten voordat je een nieuw bericht kunt versturen.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_pl.yml b/src/main/resources/messages/messages_pl.yml index cc512acc3..41272a082 100644 --- a/src/main/resources/messages/messages_pl.yml +++ b/src/main/resources/messages/messages_pl.yml @@ -99,6 +99,8 @@ email: send_failure: 'Nie można wysłać e-maila. Skontaktuj się z administracją.' change_password_expired: 'Nie zmienisz już hasła przy użyciu tej komendy.' email_cooldown_error: '&cE-mail został wysłany, musisz poczekać %time przed wysłaniem następnego.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_pt.yml b/src/main/resources/messages/messages_pt.yml index 2fb0ad2c4..b7cabdc8b 100644 --- a/src/main/resources/messages/messages_pt.yml +++ b/src/main/resources/messages/messages_pt.yml @@ -99,6 +99,8 @@ email: send_failure: 'Não foi possivel enviar o email. Por favor contate um administrador.' change_password_expired: 'Você não pode mais alterar a sua password usando este comando.' email_cooldown_error: '&cUm email já foi enviado recentemente.Por favor, espere %time antes de enviar novamente' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_ro.yml b/src/main/resources/messages/messages_ro.yml index 6fcacb052..4d40556d1 100644 --- a/src/main/resources/messages/messages_ro.yml +++ b/src/main/resources/messages/messages_ro.yml @@ -99,6 +99,8 @@ email: send_failure: 'Email-ul nu a putut fi trimis. Ta rugam contactatezi un administrator.' change_password_expired: 'Nu mai iti poti schimba parola folosind aceasta comanda.' email_cooldown_error: '&cAi primit deja un mail pentru schimbarea parolei. Trebuie sa astepti %time inainte de a trimite unul nou.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_ru.yml b/src/main/resources/messages/messages_ru.yml index 25a8ca032..81d5c6f6b 100644 --- a/src/main/resources/messages/messages_ru.yml +++ b/src/main/resources/messages/messages_ru.yml @@ -79,7 +79,7 @@ on_join_validation: country_banned: '&4Вход с IP-адресов вашей страны запрещён на этом сервере.' not_owner_error: 'Вы не являетесь владельцем данной уч. записи. Выберите себе другое имя!' invalid_name_case: 'Неверное имя! Зайдите под именем %valid, а не %invalid.' - # TODO quick_command: 'You used a command too fast! Please, join the server again and wait more before using any command.' + quick_command: 'Вы вводили команды слишком часто! Пожалуйста заходите снова и вводите команды помедленнее.' # Email email: @@ -99,6 +99,8 @@ email: send_failure: 'Письмо не может быть отправлено. Свяжитесь в администратором.' change_password_expired: 'Больше нельзя сменить свой пароль, используя эту команду.' email_cooldown_error: '&cПисьмо было отправлено недавно. Подождите %time, прежде чем отправить новое.' + add_not_allowed: '&cДобавление электронной почты не было разрешено.' + change_not_allowed: '&cИзменение электронной почты не было разрешено.' # Password recovery by email recovery: @@ -117,8 +119,8 @@ captcha: usage_captcha: '&3Необходимо ввести текст с каптчи. Используйте «/captcha %captcha_code»' wrong_captcha: '&cНеверно! Используйте «/captcha %captcha_code».' valid_captcha: '&2Вы успешно решили каптчу!' - # TODO captcha_for_registration: 'To register you have to solve a captcha first, please use the command: /captcha %captcha_code' - # TODO register_captcha_valid: '&2Valid captcha! You may now register with /register' + captcha_for_registration: 'Чтобы зарегистрироваться, решите каптчу используя команду: «/captcha %captcha_code»' + register_captcha_valid: '&2Вы успешно решили каптчу! Теперь вы можете зарегистрироваться командой «/register»' # Verification code verification: diff --git a/src/main/resources/messages/messages_sk.yml b/src/main/resources/messages/messages_sk.yml index 5af6e5030..2553fc0dd 100644 --- a/src/main/resources/messages/messages_sk.yml +++ b/src/main/resources/messages/messages_sk.yml @@ -105,6 +105,8 @@ email: send_failure: 'Email nemohol byť poslaný. Prosím kontaktuj Administrátora.' change_password_expired: 'Už nemôžeš zmeniť svoje heslo týmto príkazom.' email_cooldown_error: '&cEmail bol nedávno poslaný. Musíš počkať %time predtým ako ti pošleme nový.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_tr.yml b/src/main/resources/messages/messages_tr.yml index b9aff0ae9..fd7d5e292 100644 --- a/src/main/resources/messages/messages_tr.yml +++ b/src/main/resources/messages/messages_tr.yml @@ -99,6 +99,8 @@ email: send_failure: 'Eposta gonderilemedi. Yetkili ile iletisime gec.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' email_cooldown_error: '&cKisa bir sure once eposta gonderildi. Yeni bir eposta almak icin %time beklemelisin.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_uk.yml b/src/main/resources/messages/messages_uk.yml index 3ecf52905..d509d4ebe 100644 --- a/src/main/resources/messages/messages_uk.yml +++ b/src/main/resources/messages/messages_uk.yml @@ -95,10 +95,12 @@ email: # TODO email_show: '&2Your current email address is: &f%email' # TODO no_email_for_account: '&2You currently don''t have email address associated with this account.' already_used: '&4До цієї електронної пошти прив’язано забагато акаунтів!' - incomplete_settings: '&4[AuthMe] Error: Не всі необхідні налаштування є встановленими, щоб надсилати електронну пошту. Будь ласка, повідомте адміністратора!' + incomplete_settings: '&4Не всі необхідні налаштування є встановленими, щоб надсилати електронну пошту. Будь ласка, повідомте адміністратора!' # TODO send_failure: 'The email could not be sent. Please contact an administrator.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' # TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_vn.yml b/src/main/resources/messages/messages_vn.yml index 5e138f4f6..8fc170c04 100644 --- a/src/main/resources/messages/messages_vn.yml +++ b/src/main/resources/messages/messages_vn.yml @@ -99,6 +99,8 @@ email: send_failure: 'Không thể gửi thư. Vui lòng liên hệ với ban quản trị.' change_password_expired: '&cBạn không thể thay đổi mật khẩu bằng lệnh này từ nay.' email_cooldown_error: '&cMột bức thư đã được gửi gần đây. Bạn phải chờ %time trước khi có thể gửi một bức thư mới.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_zhcn.yml b/src/main/resources/messages/messages_zhcn.yml index 78c3c89b6..70193285b 100644 --- a/src/main/resources/messages/messages_zhcn.yml +++ b/src/main/resources/messages/messages_zhcn.yml @@ -99,6 +99,8 @@ email: send_failure: '邮件发送失败,请联系管理员' change_password_expired: '您不能使用此命令更改密码' email_cooldown_error: '&c邮件已在几分钟前发送,您需要等待 %time 后才能再次请求发送' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_zhhk.yml b/src/main/resources/messages/messages_zhhk.yml index 9d080748b..694d532eb 100644 --- a/src/main/resources/messages/messages_zhhk.yml +++ b/src/main/resources/messages/messages_zhhk.yml @@ -102,6 +102,8 @@ email: send_failure: '&8[&6用戶系統&8] &c電郵系統錯誤,請聯絡伺服器管理員。 &7(err: smtperr)' change_password_expired: '&8[&6用戶系統&8] 此指令已過期,請重新辦理。' email_cooldown_error: '&8[&6用戶系統&8] &c你已經辦理過重寄郵件,請等待 %time 後再嘗試吧。' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_zhmc.yml b/src/main/resources/messages/messages_zhmc.yml index a151a8cf8..c0b418025 100644 --- a/src/main/resources/messages/messages_zhmc.yml +++ b/src/main/resources/messages/messages_zhmc.yml @@ -99,6 +99,8 @@ email: # TODO send_failure: 'The email could not be sent. Please contact an administrator.' # TODO change_password_expired: 'You cannot change your password using this command anymore.' # TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/main/resources/messages/messages_zhtw.yml b/src/main/resources/messages/messages_zhtw.yml index 43a7b5338..fa9946bf9 100644 --- a/src/main/resources/messages/messages_zhtw.yml +++ b/src/main/resources/messages/messages_zhtw.yml @@ -101,6 +101,8 @@ email: send_failure: '&b【AuthMe】&4無法傳送電子郵件,請聯絡管理員.' change_password_expired: '&b【AuthMe】&6您現在不能使用這個指令變更密碼了.' email_cooldown_error: '&b【AuthMe】&c電子郵件已經寄出了. 您只能在 %time 後才能傳送.' + # TODO add_not_allowed: '&cAdding email was not allowed' + # TODO change_not_allowed: '&cChanging email was not allowed' # Password recovery by email recovery: diff --git a/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java b/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java index b945e9f93..6d2fdd222 100644 --- a/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java +++ b/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java @@ -4,7 +4,9 @@ import fr.xephi.authme.TestHelper; 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.message.MessageKey; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.service.bungeecord.BungeeSender; @@ -15,11 +17,13 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import java.util.function.Function; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** @@ -49,6 +53,9 @@ public class AsyncAddEmailTest { @Mock private BungeeSender bungeeSender; + @Mock + private BukkitService bukkitService; + @BeforeClass public static void setUp() { TestHelper.setupLogger(); @@ -66,6 +73,8 @@ public class AsyncAddEmailTest { given(dataSource.updateEmail(any(PlayerAuth.class))).willReturn(true); given(validationService.validateEmail(email)).willReturn(true); given(validationService.isEmailFreeForRegistration(email, player)).willReturn(true); + EmailChangedEvent event = spy(new EmailChangedEvent(player, null, email, false)); + given(bukkitService.createAndCallEvent(any(Function.class))).willReturn(event); // when asyncAddEmail.addEmail(player, email); @@ -89,6 +98,8 @@ public class AsyncAddEmailTest { given(dataSource.updateEmail(any(PlayerAuth.class))).willReturn(false); given(validationService.validateEmail(email)).willReturn(true); given(validationService.isEmailFreeForRegistration(email, player)).willReturn(true); + EmailChangedEvent event = spy(new EmailChangedEvent(player, null, email, false)); + given(bukkitService.createAndCallEvent(any(Function.class))).willReturn(event); // when asyncAddEmail.addEmail(player, email); @@ -184,4 +195,27 @@ public class AsyncAddEmailTest { verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); } + @Test + public void shouldNotAddOnCancelledEvent() { + // given + String email = "player@mail.tld"; + given(player.getName()).willReturn("TestName"); + given(playerCache.isAuthenticated("testname")).willReturn(true); + PlayerAuth auth = mock(PlayerAuth.class); + given(auth.getEmail()).willReturn(null); + given(playerCache.getAuth("testname")).willReturn(auth); + given(validationService.validateEmail(email)).willReturn(true); + given(validationService.isEmailFreeForRegistration(email, player)).willReturn(true); + EmailChangedEvent event = spy(new EmailChangedEvent(player, null, email, false)); + event.setCancelled(true); + given(bukkitService.createAndCallEvent(any(Function.class))).willReturn(event); + + // when + asyncAddEmail.addEmail(player, email); + + // then + verify(service).send(player, MessageKey.EMAIL_ADD_NOT_ALLOWED); + verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); + } + } diff --git a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java index 4427c45d6..23fb01e69 100644 --- a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java +++ b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java @@ -3,7 +3,9 @@ package fr.xephi.authme.process.email; 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.message.MessageKey; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.service.bungeecord.BungeeSender; @@ -14,10 +16,13 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import java.util.function.Function; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -48,6 +53,9 @@ public class AsyncChangeEmailTest { @Mock private BungeeSender bungeeSender; + @Mock + private BukkitService bukkitService; + @Test public void shouldChangeEmail() { // given @@ -59,7 +67,9 @@ public class AsyncChangeEmailTest { given(dataSource.updateEmail(auth)).willReturn(true); given(validationService.validateEmail(newEmail)).willReturn(true); given(validationService.isEmailFreeForRegistration(newEmail, player)).willReturn(true); - + EmailChangedEvent event = spy(new EmailChangedEvent(player, "old@mail.tld", newEmail, false)); + given(bukkitService.createAndCallEvent(any(Function.class))).willReturn(event); + // when process.changeEmail(player, "old@mail.tld", newEmail); @@ -81,6 +91,8 @@ public class AsyncChangeEmailTest { given(dataSource.updateEmail(auth)).willReturn(true); given(validationService.validateEmail(newEmail)).willReturn(true); given(validationService.isEmailFreeForRegistration(newEmail, player)).willReturn(true); + EmailChangedEvent event = spy(new EmailChangedEvent(player, oldEmail, newEmail, false)); + given(bukkitService.createAndCallEvent(any(Function.class))).willReturn(event); // when process.changeEmail(player, "old-mail@example.org", newEmail); @@ -102,6 +114,8 @@ public class AsyncChangeEmailTest { given(dataSource.updateEmail(auth)).willReturn(false); given(validationService.validateEmail(newEmail)).willReturn(true); given(validationService.isEmailFreeForRegistration(newEmail, player)).willReturn(true); + EmailChangedEvent event = spy(new EmailChangedEvent(player, "old@mail.tld", newEmail, false)); + given(bukkitService.createAndCallEvent(any(Function.class))).willReturn(event); // when process.changeEmail(player, "old@mail.tld", newEmail); @@ -219,6 +233,30 @@ public class AsyncChangeEmailTest { verify(service).send(player, MessageKey.REGISTER_MESSAGE); } + @Test + public void shouldNotChangeOnCancelledEvent() { + // given + String newEmail = "new@example.com"; + String oldEmail = "old@example.com"; + given(player.getName()).willReturn("Username"); + given(playerCache.isAuthenticated("username")).willReturn(true); + PlayerAuth auth = authWithMail(oldEmail); + given(playerCache.getAuth("username")).willReturn(auth); + given(validationService.validateEmail(newEmail)).willReturn(true); + given(validationService.isEmailFreeForRegistration(newEmail, player)).willReturn(true); + EmailChangedEvent event = spy(new EmailChangedEvent(player, oldEmail, newEmail, false)); + event.setCancelled(true); + given(bukkitService.createAndCallEvent(any(Function.class))).willReturn(event); + + // when + process.changeEmail(player, oldEmail, newEmail); + + // then + verify(dataSource, never()).updateEmail(any(PlayerAuth.class)); + verify(playerCache, never()).updatePlayer(any(PlayerAuth.class)); + verify(service).send(player, MessageKey.EMAIL_CHANGE_NOT_ALLOWED); + } + private static PlayerAuth authWithMail(String email) { PlayerAuth auth = mock(PlayerAuth.class); when(auth.getEmail()).thenReturn(email); From 80538b4bb24f6cdf512a19cbff8fc86374a769bd Mon Sep 17 00:00:00 2001 From: games647 Date: Thu, 5 Apr 2018 15:16:46 +0200 Subject: [PATCH 02/14] Force english language during unit testing Fixes #1536 --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a76536998..a04861c22 100644 --- a/pom.xml +++ b/pom.xml @@ -172,7 +172,8 @@ 2.20.1 - -Dfile.encoding=${project.build.sourceEncoding} @{argLine} + + -Dfile.encoding=${project.build.sourceEncoding} -Duser.language=en @{argLine} ${project.skipExtendedHashTests} From b56133fe8f4808bc122c25a954deeedd197d9c9f Mon Sep 17 00:00:00 2001 From: RatchetCinemaESP Date: Thu, 12 Apr 2018 15:58:28 +0200 Subject: [PATCH 03/14] Update messages_es.yml (#1553) Translated lines: - 83 - 103 - 104 --- src/main/resources/messages/messages_es.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/resources/messages/messages_es.yml b/src/main/resources/messages/messages_es.yml index bde1f29ea..899631cce 100644 --- a/src/main/resources/messages/messages_es.yml +++ b/src/main/resources/messages/messages_es.yml @@ -80,7 +80,7 @@ on_join_validation: country_banned: '¡Tu país ha sido baneado de este servidor!' not_owner_error: 'No eres el propietario de esta cuenta. ¡Por favor, elije otro nombre!' invalid_name_case: 'Solo puedes unirte mediante el nombre de usuario %valid, no %invalid.' - # TODO quick_command: 'You used a command too fast! Please, join the server again and wait more before using any command.' + quick_command: 'Has usado el comando demasiado rápido! Porfavor, entra al servidor de nuevo y espera un poco antes de usar cualquier comando.' # Email email: @@ -100,8 +100,8 @@ email: send_failure: 'No se ha podido enviar el correo electrónico. Por favor, contacta con un administrador.' change_password_expired: 'No puedes cambiar la contraseña utilizando este comando.' email_cooldown_error: '&cEl correo ha sido enviado recientemente. Debes esperar %time antes de volver a enviar uno nuevo.' - # TODO add_not_allowed: '&cAdding email was not allowed' - # TODO change_not_allowed: '&cChanging email was not allowed' + add_not_allowed: '&cNo se permite añadir un Email' + change_not_allowed: '&cNo se permite el cambio de Email' # Password recovery by email recovery: From 71826db23d376a8d394499f8df3e9fdaf2776fb3 Mon Sep 17 00:00:00 2001 From: Maxetto Date: Fri, 13 Apr 2018 19:34:29 +0200 Subject: [PATCH 04/14] Update messages_it.yml --- src/main/resources/messages/messages_it.yml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/resources/messages/messages_it.yml b/src/main/resources/messages/messages_it.yml index 70162b775..d99cae84c 100644 --- a/src/main/resources/messages/messages_it.yml +++ b/src/main/resources/messages/messages_it.yml @@ -4,8 +4,6 @@ # %username% - Sostituisce il nome dell'utente che riceve il messaggio. # %displayname% - Sostituisce il nickname (e i colori) dell'utente che riceve il messaggio. -# Registrazione - # Registration registration: disabled: '&cLa registrazione tramite i comandi di gioco è disabilitata.' @@ -82,7 +80,7 @@ on_join_validation: country_banned: '&4Il tuo paese è bandito da questo server!' not_owner_error: 'Non sei il proprietario di questo account. Per favore scegli un altro nome!' invalid_name_case: 'Dovresti entrare con questo nome utente "%valid", al posto di "%invalid".' - # TODO quick_command: 'You used a command too fast! Please, join the server again and wait more before using any command.' + quick_command: 'Hai usato un comando troppo velocemente dal tuo accesso! Per favore, rientra nel server e aspetta un po'' di più prima di usare un qualsiasi comando.' # Email email: @@ -102,12 +100,12 @@ email: send_failure: 'Non è stato possibile inviare l''email di recupero. Per favore contatta un amministratore.' change_password_expired: 'Non puoi più cambiare la tua password con questo comando.' email_cooldown_error: '&cUna email di recupero ti è già stata inviata recentemente. Devi attendere %time prima di poterne richiedere una nuova.' - # TODO add_not_allowed: '&cAdding email was not allowed' - # TODO change_not_allowed: '&cChanging email was not allowed' + add_not_allowed: '&cNon hai il permesso di aggiungere un indirizzo email' + change_not_allowed: '&cNon hai il permesso di cambiare l''indirizzo email' # Password recovery by email recovery: - forgot_password_hint: '&3Hai dimenticato la tua password? Puoi recuperarla eseguendo il comando: /email recovery ' + forgot_password_hint: '&3Hai dimenticato la tua password? Puoi recuperarla usando il comando: /email recovery ' command_usage: '&cUtilizzo: /email recovery ' email_sent: '&2Una email di recupero è stata appena inviata al tuo indirizzo email!' code: From 5cc58da85f49e6b994fe73d04917709112b1233b Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 11:02:20 +0200 Subject: [PATCH 05/14] Update HikariCP --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 21910e4ef..1688990cc 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ | **Code quality:** | [![Code Climate](https://codeclimate.com/github/AuthMe/AuthMeReloaded/badges/gpa.svg)](https://codeclimate.com/github/AuthMe/AuthMeReloaded) [![Coverage status](https://coveralls.io/repos/AuthMe-Team/AuthMeReloaded/badge.svg?branch=master&service=github)](https://coveralls.io/github/AuthMe-Team/AuthMeReloaded?branch=master) | | **Jenkins CI:** | [![Jenkins Status](https://img.shields.io/website-up-down-green-red/http/shields.io.svg?label=ci.codemc.org)](https://ci.codemc.org/) [![Build Status](https://ci.codemc.org/buildStatus/icon?job=AuthMe/AuthMeReloaded)](https://ci.codemc.org/job/AuthMe/job/AuthMeReloaded) ![Build Tests](https://img.shields.io/jenkins/t/https/ci.codemc.org/job/AuthMe/job/AuthMeReloaded.svg) | | **Other CIs:** | [![CircleCI](https://circleci.com/gh/AuthMe/AuthMeReloaded.svg?style=svg)](https://circleci.com/gh/AuthMe/AuthMeReloaded) | -| **Dependencies:** | [![Dependency Status](https://gemnasium.com/badges/github.com/AuthMe/AuthMeReloaded.svg)](https://gemnasium.com/github.com/AuthMe/AuthMeReloaded) | +| **Dependencies:** | [![Dependency Status](https://beta.gemnasium.com/badges/github.com/AuthMe/AuthMeReloaded.svg)](https://beta.gemnasium.com/projects/github.com/AuthMe/AuthMeReloaded) | ## Description diff --git a/pom.xml b/pom.xml index a04861c22..7182cfbbf 100644 --- a/pom.xml +++ b/pom.xml @@ -441,7 +441,7 @@ com.zaxxer HikariCP - 2.7.8 + 3.1.0 true From ba4ed7bdd97355ef24bdb72c8aaa961bce5f79b5 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 11:10:02 +0200 Subject: [PATCH 06/14] Update Mockito --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7182cfbbf..c971d156b 100644 --- a/pom.xml +++ b/pom.xml @@ -820,7 +820,7 @@ org.mockito mockito-core test - 2.16.0 + 2.18.0 hamcrest-core @@ -839,7 +839,7 @@ com.h2database h2 - 1.4.196 + 1.4.197 test From 6e16abc34e2d417982a80167e970c7e4d7012039 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 11:45:21 +0200 Subject: [PATCH 07/14] Don't purge users if unable to load permission data --- .../xephi/authme/listener/PlayerListener.java | 12 +++- .../authme/permission/PermissionsManager.java | 62 +++++++++++++++---- .../permission/handlers/LuckPermsHandler.java | 9 ++- .../handlers/PermissionHandler.java | 5 +- .../handlers/PermissionLoadUserException.java | 13 ++++ .../authme/task/purge/PurgeExecutor.java | 10 ++- .../fr/xephi/authme/task/purge/PurgeTask.java | 8 +-- 7 files changed, 85 insertions(+), 34 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/permission/handlers/PermissionLoadUserException.java diff --git a/src/main/java/fr/xephi/authme/listener/PlayerListener.java b/src/main/java/fr/xephi/authme/listener/PlayerListener.java index 7857114e3..5b6327127 100644 --- a/src/main/java/fr/xephi/authme/listener/PlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/PlayerListener.java @@ -1,11 +1,13 @@ package fr.xephi.authme.listener; +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.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionsManager; +import fr.xephi.authme.permission.handlers.PermissionLoadUserException; import fr.xephi.authme.process.Management; import fr.xephi.authme.service.AntiBotService; import fr.xephi.authme.service.BukkitService; @@ -260,9 +262,13 @@ public class PlayerListener implements Listener { // Keep pre-UUID compatibility try { - permissionsManager.loadUserData(event.getUniqueId()); - } catch (NoSuchMethodError e) { - permissionsManager.loadUserData(name); + try { + permissionsManager.loadUserData(event.getUniqueId()); + } catch (NoSuchMethodError e) { + permissionsManager.loadUserData(name); + } + } catch (PermissionLoadUserException e) { + ConsoleLogger.logException("Unable to load the permission data of user " + name, e); } try { diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java index 55845f745..ec1fff9bb 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java @@ -8,6 +8,7 @@ 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; +import fr.xephi.authme.permission.handlers.PermissionLoadUserException; import fr.xephi.authme.permission.handlers.PermissionsExHandler; import fr.xephi.authme.permission.handlers.VaultHandler; import fr.xephi.authme.permission.handlers.ZPermissionsHandler; @@ -110,7 +111,9 @@ public class PermissionsManager implements Reloadable { * Creates a permission handler for the provided permission systems if possible. * * @param type the permission systems type for which to create a corresponding permission handler + * * @return the permission handler, or {@code null} if not possible + * * @throws PermissionHandlerException during initialization of the permission handler */ private PermissionHandler createPermissionHandler(PermissionsSystemType type) throws PermissionHandlerException { @@ -228,8 +231,9 @@ public class PermissionsManager implements Reloadable { /** * Check if the given player has permission for the given permission node. * - * @param joiningPlayer The player to check + * @param joiningPlayer The player to check * @param permissionNode The permission node to verify + * * @return true if the player has permission, false otherwise */ public boolean hasPermission(JoiningPlayer joiningPlayer, PermissionNode permissionNode) { @@ -262,7 +266,7 @@ public class PermissionsManager implements Reloadable { * Check whether the offline player with the given name has permission for the given permission node. * This method is used as a last resort when nothing besides the name is known. * - * @param name The name of the player + * @param name The name of the player * @param permissionNode The permission node to verify * * @return true if the player has permission, false otherwise @@ -317,7 +321,7 @@ public class PermissionsManager implements Reloadable { * @param groupName The group name. * * @return True if the player is in the specified group, false otherwise. - * False is also returned if groups aren't supported by the used permissions system. + * False is also returned if groups aren't supported by the used permissions system. */ public boolean isInGroup(OfflinePlayer player, String groupName) { return isEnabled() && handler.isInGroup(player, groupName); @@ -330,7 +334,7 @@ public class PermissionsManager implements Reloadable { * @param groupName The name of the group. * * @return True if succeed, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ public boolean addGroup(OfflinePlayer player, String groupName) { if (!isEnabled() || StringUtils.isEmpty(groupName)) { @@ -346,7 +350,7 @@ public class PermissionsManager implements Reloadable { * @param groupNames The name of the groups to add. * * @return True if at least one group was added, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ public boolean addGroups(OfflinePlayer player, Collection groupNames) { // If no permissions system is used, return false @@ -373,7 +377,7 @@ public class PermissionsManager implements Reloadable { * @param groupName The name of the group. * * @return True if succeed, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ public boolean removeGroup(OfflinePlayer player, String groupName) { return isEnabled() && handler.removeFromGroup(player, groupName); @@ -386,7 +390,7 @@ public class PermissionsManager implements Reloadable { * @param groupNames The name of the groups to remove. * * @return True if at least one group was removed, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ public boolean removeGroups(OfflinePlayer player, Collection groupNames) { // If no permissions system is used, return false @@ -414,7 +418,7 @@ public class PermissionsManager implements Reloadable { * @param groupName The name of the group. * * @return True if succeed, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ public boolean setGroup(OfflinePlayer player, String groupName) { return isEnabled() && handler.setGroup(player, groupName); @@ -428,7 +432,7 @@ public class PermissionsManager implements Reloadable { * @param player The player to remove all groups from. * * @return True if succeed, false otherwise. - * False will also be returned if this feature isn't supported for the used permissions system. + * False will also be returned if this feature isn't supported for the used permissions system. */ public boolean removeAllGroups(OfflinePlayer player) { // If no permissions system is used, return false @@ -443,15 +447,47 @@ public class PermissionsManager implements Reloadable { return removeGroups(player, groupNames); } - public void loadUserData(UUID uuid) { - if(!isEnabled()) { + /** + * Loads the permission data of the given player. + * + * @param offlinePlayer the offline player. + * @return true if the load was successful. + */ + public boolean loadUserData(OfflinePlayer offlinePlayer) { + try { + try { + loadUserData(offlinePlayer.getUniqueId()); + } catch (NoSuchMethodError e) { + loadUserData(offlinePlayer.getName()); + } + } catch (PermissionLoadUserException e) { + ConsoleLogger.logException("Unable to load the permission data of user " + offlinePlayer.getName(), e); + return false; + } + return true; + } + + /** + * Loads the permission data of the given player unique identifier. + * + * @param uuid the {@link UUID} of the player. + * @throws PermissionLoadUserException if the action failed. + */ + public void loadUserData(UUID uuid) throws PermissionLoadUserException { + if (!isEnabled()) { return; } handler.loadUserData(uuid); } - public void loadUserData(String name) { - if(!isEnabled()) { + /** + * Loads the permission data of the given player name. + * + * @param name the name of the player. + * @throws PermissionLoadUserException if the action failed. + */ + public void loadUserData(String name) throws PermissionLoadUserException { + if (!isEnabled()) { return; } handler.loadUserData(name); 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 f01f14c34..0d465ef3c 100644 --- a/src/main/java/fr/xephi/authme/permission/handlers/LuckPermsHandler.java +++ b/src/main/java/fr/xephi/authme/permission/handlers/LuckPermsHandler.java @@ -189,22 +189,21 @@ public class LuckPermsHandler implements PermissionHandler { } @Override - public void loadUserData(UUID uuid) { + public void loadUserData(UUID uuid) throws PermissionLoadUserException { try { luckPermsApi.getUserManager().loadUser(uuid).get(5, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { - e.printStackTrace(); + throw new PermissionLoadUserException("Unable to load the permission data of the user " + uuid, e); } } @Override - public void loadUserData(String name) { + public void loadUserData(String name) throws PermissionLoadUserException { try { UUID uuid = luckPermsApi.getStorage().getUUID(name).get(5, TimeUnit.SECONDS); loadUserData(uuid); } catch (InterruptedException | ExecutionException | TimeoutException e) { - e.printStackTrace(); + throw new PermissionLoadUserException("Unable to load the permission data of the user " + name, e); } } - } diff --git a/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java b/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java index fe3f54057..831bc583f 100644 --- a/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java +++ b/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java @@ -107,10 +107,9 @@ public interface PermissionHandler { */ PermissionsSystemType getPermissionSystem(); - default void loadUserData(UUID uuid) { + default void loadUserData(UUID uuid) throws PermissionLoadUserException { } - default void loadUserData(String name) { + default void loadUserData(String name) throws PermissionLoadUserException { } - } diff --git a/src/main/java/fr/xephi/authme/permission/handlers/PermissionLoadUserException.java b/src/main/java/fr/xephi/authme/permission/handlers/PermissionLoadUserException.java new file mode 100644 index 000000000..697b49182 --- /dev/null +++ b/src/main/java/fr/xephi/authme/permission/handlers/PermissionLoadUserException.java @@ -0,0 +1,13 @@ +package fr.xephi.authme.permission.handlers; + +import java.util.UUID; + +/** + * Exception thrown when a {@link PermissionHandler#loadUserData(UUID uuid)} request fails. + */ +public class PermissionLoadUserException extends Exception { + + public PermissionLoadUserException(String message, Throwable cause) { + super(message, cause); + } +} 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 a3e42f756..36c951ffc 100644 --- a/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java +++ b/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java @@ -49,7 +49,7 @@ public class PurgeExecutor { * players and names. * * @param players the players to purge - * @param names names to purge + * @param names names to purge */ public void executePurge(Collection players, Collection names) { // Purge other data @@ -212,15 +212,13 @@ public class PurgeExecutor { } for (OfflinePlayer offlinePlayer : cleared) { - try { - permissionsManager.loadUserData(offlinePlayer.getUniqueId()); - } catch (NoSuchMethodError e) { - permissionsManager.loadUserData(offlinePlayer.getName()); + if (!permissionsManager.loadUserData(offlinePlayer)) { + ConsoleLogger.warning("Unable to purge the permissions of user " + offlinePlayer + "!"); + continue; } permissionsManager.removeAllGroups(offlinePlayer); } ConsoleLogger.info("AutoPurge: Removed permissions from " + cleared.size() + " player(s)."); } - } 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 27b424150..686bab86d 100644 --- a/src/main/java/fr/xephi/authme/task/purge/PurgeTask.java +++ b/src/main/java/fr/xephi/authme/task/purge/PurgeTask.java @@ -3,6 +3,7 @@ package fr.xephi.authme.task.purge; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; +import fr.xephi.authme.permission.handlers.PermissionLoadUserException; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; @@ -73,10 +74,9 @@ class PurgeTask extends BukkitRunnable { OfflinePlayer offlinePlayer = offlinePlayers[nextPosition]; if (offlinePlayer.getName() != null && toPurge.remove(offlinePlayer.getName().toLowerCase())) { - try { - permissionsManager.loadUserData(offlinePlayer.getUniqueId()); - } catch (NoSuchMethodError e) { - permissionsManager.loadUserData(offlinePlayer.getName()); + if(!permissionsManager.loadUserData(offlinePlayer)) { + ConsoleLogger.warning("Unable to check if the user " + offlinePlayer.getName() + " can be purged!"); + continue; } if (!permissionsManager.hasPermissionOffline(offlinePlayer, PlayerStatePermission.BYPASS_PURGE)) { playerPortion.add(offlinePlayer); From d533f8e19c1af8d3788efb77ea0cb7a27263ec7f Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 12:09:07 +0200 Subject: [PATCH 08/14] Fix unit testing whoops --- .../xephi/authme/task/purge/PurgeTaskTest.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java b/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java index 93538c858..2ecf6a13a 100644 --- a/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java +++ b/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java @@ -216,18 +216,16 @@ public class PurgeTaskTest { private void setPermissionsBehavior() { given(permissionsManager.hasPermissionOffline(any(OfflinePlayer.class), eq(BYPASS_NODE))) - .willAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable { - OfflinePlayer player = invocationOnMock.getArgument(0); - Boolean hasPermission = playerBypassAssignments.get(player); - if (hasPermission == null) { - throw new IllegalStateException("Unexpected check of '" + BYPASS_NODE - + "' with player = " + player); - } - return hasPermission; + .willAnswer((Answer) invocationOnMock -> { + OfflinePlayer player = invocationOnMock.getArgument(0); + Boolean hasPermission = playerBypassAssignments.get(player); + if (hasPermission == null) { + throw new IllegalStateException("Unexpected check of '" + BYPASS_NODE + + "' with player = " + player); } + return hasPermission; }); + given(permissionsManager.loadUserData(any(OfflinePlayer.class))).willReturn(true); } private void assertRanPurgeWithPlayers(OfflinePlayer... players) { From bebff1c0c87d2302d82335768eeed80f897e305f Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 12:17:08 +0200 Subject: [PATCH 09/14] Actually provide a config to circleci Epic fail xD --- .circleci/{circle.yml => config.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .circleci/{circle.yml => config.yml} (100%) diff --git a/.circleci/circle.yml b/.circleci/config.yml similarity index 100% rename from .circleci/circle.yml rename to .circleci/config.yml From 65a1438c479b600161dce827a27ce49e603b5078 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 12:19:59 +0200 Subject: [PATCH 10/14] Fix circleci config format --- .circleci/config.yml | 92 ++++++++++++++++++++++---------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index cb1e2ba61..b544c67ad 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,49 +1,49 @@ version: 2 jobs: - build_and_test_jdk8: - working_directory: ~/authmereloaded-jdk8 - docker: - - image: circleci/openjdk:8-jdk - environment: - MAVEN_OPTS: -Xmx2048m - steps: - - checkout - - restore_cache: - keys: - - authmereloaded-{{ checksum "pom.xml" }} - - authmereloaded- - - run: mvn -T 2 dependency:go-offline - - save_cache: - paths: - - ~/.m2 - key: authmereloaded-{{ checksum "pom.xml" }} - - run: mvn -T 2 package - - store_test_results: - path: target/surefire-reports - - store_artifacts: - path: target/*.jar - build_and_test_jdk9: - working_directory: ~/authmereloaded-jdk9 - docker: - - image: circleci/openjdk:9-jdk - environment: - MAVEN_OPTS: -Xmx2048m - steps: - - checkout - - restore_cache: - key: authmereloaded-{{ checksum "pom.xml" }} - - run: mvn -T 2 dependency:go-offline - - save_cache: - paths: - - ~/.m2 - key: authmereloaded-{{ checksum "pom.xml" }} - - run: mvn -T 2 package - - store_test_results: - path: target/surefire-reports - - run: cp ./target/*.jar $CIRCLE_ARTIFACTS + build_and_test_jdk8: + working_directory: ~/authmereloaded-jdk8 + docker: + - image: circleci/openjdk:8-jdk + environment: + MAVEN_OPTS: -Xmx2048m + steps: + - checkout + - restore_cache: + keys: + - authmereloaded-{{ checksum "pom.xml" }} + - authmereloaded- + - run: mvn -T 2 dependency:go-offline + - save_cache: + paths: + - ~/.m2 + key: authmereloaded-{{ checksum "pom.xml" }} + - run: mvn -T 2 package + - store_test_results: + path: target/surefire-reports + - store_artifacts: + path: target/*.jar + build_and_test_jdk9: + working_directory: ~/authmereloaded-jdk9 + docker: + - image: circleci/openjdk:9-jdk + environment: + MAVEN_OPTS: -Xmx2048m + steps: + - checkout + - restore_cache: + key: authmereloaded-{{ checksum "pom.xml" }} + - run: mvn -T 2 dependency:go-offline + - save_cache: + paths: + - ~/.m2 + key: authmereloaded-{{ checksum "pom.xml" }} + - run: mvn -T 2 package + - store_test_results: + path: target/surefire-reports + - run: cp ./target/*.jar $CIRCLE_ARTIFACTS workflows: - version: 2 - build_and_test: - jobs: - - build_and_test_jdk8 - - build_and_test_jdk9 + version: 2 + build_and_test: + jobs: + - build_and_test_jdk8 + - build_and_test_jdk9 From 8722a3dbab42454e4423f82c15e522912478c5af Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 12:29:30 +0200 Subject: [PATCH 11/14] Improve circle configuration file --- .circleci/config.yml | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b544c67ad..3fbbaae46 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -9,41 +9,44 @@ jobs: steps: - checkout - restore_cache: - keys: + keys: - authmereloaded-{{ checksum "pom.xml" }} - authmereloaded- - run: mvn -T 2 dependency:go-offline - save_cache: - paths: - - ~/.m2 - key: authmereloaded-{{ checksum "pom.xml" }} + paths: + - ~/.m2 + key: authmereloaded-{{ checksum "pom.xml" }} - run: mvn -T 2 package - store_test_results: - path: target/surefire-reports + path: target/surefire-reports - store_artifacts: - path: target/*.jar - build_and_test_jdk9: - working_directory: ~/authmereloaded-jdk9 + path: target/*.jar + build_and_test_jdk10: + working_directory: ~/authmereloaded-jdk10 docker: - - image: circleci/openjdk:9-jdk + - image: circleci/openjdk:10-jdk environment: - MAVEN_OPTS: -Xmx2048m + MAVEN_OPTS: -Xmx2048m steps: - checkout - restore_cache: - key: authmereloaded-{{ checksum "pom.xml" }} + keys: + - authmereloaded-{{ checksum "pom.xml" }} + - authmereloaded- - run: mvn -T 2 dependency:go-offline - save_cache: - paths: - - ~/.m2 - key: authmereloaded-{{ checksum "pom.xml" }} + paths: + - ~/.m2 + key: authmereloaded-{{ checksum "pom.xml" }} - run: mvn -T 2 package - store_test_results: - path: target/surefire-reports - - run: cp ./target/*.jar $CIRCLE_ARTIFACTS + path: target/surefire-reports + - store_artifacts: + path: target/*.jar workflows: version: 2 build_and_test: jobs: - build_and_test_jdk8 - - build_and_test_jdk9 + - build_and_test_jdk10 From 65ad91372e05c9ac3525b58cbf347919ce852b3f Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Thu, 19 Apr 2018 12:32:50 +0200 Subject: [PATCH 12/14] Fix JDK 10 surefire plugin, use batch mode in circleci --- .circleci/config.yml | 8 ++++---- pom.xml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 3fbbaae46..c988f79c4 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -12,12 +12,12 @@ jobs: keys: - authmereloaded-{{ checksum "pom.xml" }} - authmereloaded- - - run: mvn -T 2 dependency:go-offline + - run: mvn -T 2 -B dependency:go-offline - save_cache: paths: - ~/.m2 key: authmereloaded-{{ checksum "pom.xml" }} - - run: mvn -T 2 package + - run: mvn -T 2 -B package - store_test_results: path: target/surefire-reports - store_artifacts: @@ -34,12 +34,12 @@ jobs: keys: - authmereloaded-{{ checksum "pom.xml" }} - authmereloaded- - - run: mvn -T 2 dependency:go-offline + - run: mvn -T 2 -B dependency:go-offline - save_cache: paths: - ~/.m2 key: authmereloaded-{{ checksum "pom.xml" }} - - run: mvn -T 2 package + - run: mvn -T 2 -B package - store_test_results: path: target/surefire-reports - store_artifacts: diff --git a/pom.xml b/pom.xml index c971d156b..c6756e67c 100644 --- a/pom.xml +++ b/pom.xml @@ -169,7 +169,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.20.1 + 2.21.0 From 5194f76f39b4d8ad5d01a4c0db00dd5725bdb6d7 Mon Sep 17 00:00:00 2001 From: RikoDEV Date: Sat, 21 Apr 2018 02:24:27 +0200 Subject: [PATCH 13/14] Update of the Polish translation by RikoDEV (#1560) --- src/main/resources/messages/messages_pl.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/messages/messages_pl.yml b/src/main/resources/messages/messages_pl.yml index 41272a082..6184f8e22 100644 --- a/src/main/resources/messages/messages_pl.yml +++ b/src/main/resources/messages/messages_pl.yml @@ -99,8 +99,8 @@ email: send_failure: 'Nie można wysłać e-maila. Skontaktuj się z administracją.' change_password_expired: 'Nie zmienisz już hasła przy użyciu tej komendy.' email_cooldown_error: '&cE-mail został wysłany, musisz poczekać %time przed wysłaniem następnego.' - # TODO add_not_allowed: '&cAdding email was not allowed' - # TODO change_not_allowed: '&cChanging email was not allowed' + add_not_allowed: '&cMożliwość dodania adresu e-mail jest wyłączona.' + change_not_allowed: '&cMożliwość zmiany adresu e-mail jest wyłączona.' # Password recovery by email recovery: From baec0349097c1b88ee44d1b680ee5b57888f435d Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sat, 21 Apr 2018 13:02:14 +0200 Subject: [PATCH 14/14] #1555 Add RegisterEvent and AuthMeAsyncPreRegisterEvent (#1559) * #1555 Add RegisterEvent and AuthMeAsyncPreRegisterEvent * Add missing javadoc --- .../events/AuthMeAsyncPreRegisterEvent.java | 70 +++++++++++++++++++ .../fr/xephi/authme/events/RegisterEvent.java | 47 +++++++++++++ .../process/register/AsyncRegister.java | 30 ++++++-- .../register/ProcessSyncEmailRegister.java | 6 ++ .../register/ProcessSyncPasswordRegister.java | 6 ++ .../process/login/AsynchronousLoginTest.java | 9 +-- .../process/register/AsyncRegisterTest.java | 34 +++++++++ 7 files changed, 191 insertions(+), 11 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/events/AuthMeAsyncPreRegisterEvent.java create mode 100644 src/main/java/fr/xephi/authme/events/RegisterEvent.java diff --git a/src/main/java/fr/xephi/authme/events/AuthMeAsyncPreRegisterEvent.java b/src/main/java/fr/xephi/authme/events/AuthMeAsyncPreRegisterEvent.java new file mode 100644 index 000000000..af26ad518 --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/AuthMeAsyncPreRegisterEvent.java @@ -0,0 +1,70 @@ +package fr.xephi.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * This event is called when a player uses the register command, + * it's fired even when a user does a /register with invalid arguments. + * {@link #setCanRegister(boolean) event.setCanRegister(false)} prevents the player from registering. + */ +public class AuthMeAsyncPreRegisterEvent extends CustomEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private boolean canRegister = true; + + /** + * Constructor. + * + * @param player The player + * @param isAsync True if the event is async, false otherwise + */ + public AuthMeAsyncPreRegisterEvent(Player player, boolean isAsync) { + super(isAsync); + this.player = player; + } + + /** + * Return the player concerned by this event. + * + * @return The player who executed a valid {@code /login} command + */ + public Player getPlayer() { + return player; + } + + /** + * Return whether the player is allowed to register. + * + * @return True if the player can log in, false otherwise + */ + public boolean canRegister() { + return canRegister; + } + + /** + * Define whether or not the player may register. + * + * @param canRegister True to allow the player to log in; false to prevent him + */ + public void setCanRegister(boolean canRegister) { + this.canRegister = canRegister; + } + + /** + * Return the list of handlers, equivalent to {@link #getHandlers()} and required by {@link Event}. + * + * @return The list of handlers + */ + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/fr/xephi/authme/events/RegisterEvent.java b/src/main/java/fr/xephi/authme/events/RegisterEvent.java new file mode 100644 index 000000000..2a98d0544 --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/RegisterEvent.java @@ -0,0 +1,47 @@ +package fr.xephi.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Event fired when a player has successfully registered. + */ +public class RegisterEvent extends CustomEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player player; + + /** + * Constructor. + * + * @param player The player + */ + public RegisterEvent(Player player) { + this.player = player; + } + + /** + * Return the player that has successfully logged in or registered. + * + * @return The player + */ + public Player getPlayer() { + return player; + } + + /** + * Return the list of handlers, equivalent to {@link #getHandlers()} and required by {@link Event}. + * + * @return The list of handlers + */ + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java b/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java index d50fe9a32..78eaa5679 100644 --- a/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/AsyncRegister.java @@ -4,14 +4,17 @@ import ch.jalu.injector.factory.SingletonStore; 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.AuthMeAsyncPreRegisterEvent; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.process.register.executors.RegistrationExecutor; import fr.xephi.authme.process.register.executors.RegistrationMethod; import fr.xephi.authme.process.register.executors.RegistrationParameters; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.bungeecord.BungeeSender; import fr.xephi.authme.service.bungeecord.MessageType; +import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.util.PlayerUtils; @@ -32,6 +35,8 @@ public class AsyncRegister implements AsynchronousProcess { @Inject private PlayerCache playerCache; @Inject + private BukkitService bukkitService; + @Inject private CommonService service; @Inject private SingletonStore registrationExecutorFactory; @@ -44,9 +49,9 @@ public class AsyncRegister implements AsynchronousProcess { /** * Performs the registration process for the given player. * - * @param variant the registration method + * @param variant the registration method * @param parameters the parameters - * @param

parameters type + * @param

parameters type */ public

void register(RegistrationMethod

variant, P parameters) { if (preRegisterCheck(parameters.getPlayer())) { @@ -57,6 +62,13 @@ public class AsyncRegister implements AsynchronousProcess { } } + /** + * Checks if the player is able to register, in that case the {@link AuthMeAsyncPreRegisterEvent} is invoked. + * + * @param player the player which is trying to register. + * + * @return true if the checks are successful and the event hasn't marked the action as denied, false otherwise. + */ private boolean preRegisterCheck(Player player) { final String name = player.getName().toLowerCase(); if (playerCache.isAuthenticated(name)) { @@ -70,6 +82,13 @@ public class AsyncRegister implements AsynchronousProcess { return false; } + boolean isAsync = service.getProperty(PluginSettings.USE_ASYNC_TASKS); + AuthMeAsyncPreRegisterEvent event = new AuthMeAsyncPreRegisterEvent(player, isAsync); + bukkitService.callEvent(event); + if (!event.canRegister()) { + return false; + } + return isPlayerIpAllowedToRegister(player); } @@ -77,11 +96,11 @@ public class AsyncRegister implements AsynchronousProcess { * Executes the registration. * * @param parameters the registration parameters - * @param executor the executor to perform the registration process with - * @param

registration params type + * @param executor the executor to perform the registration process with + * @param

registration params type */ private

- void executeRegistration(P parameters, RegistrationExecutor

executor) { + void executeRegistration(P parameters, RegistrationExecutor

executor) { PlayerAuth auth = executor.buildPlayerAuth(parameters); if (database.saveAuth(auth)) { executor.executePostPersistAction(parameters); @@ -95,6 +114,7 @@ public class AsyncRegister implements AsynchronousProcess { * Checks whether the registration threshold has been exceeded for the given player's IP address. * * @param player the player to check + * * @return true if registration may take place, false otherwise (IP check failed) */ private boolean isPlayerIpAllowedToRegister(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 6ab4a874a..e740a0ded 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncEmailRegister.java @@ -2,8 +2,10 @@ 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.message.MessageKey; import fr.xephi.authme.process.SynchronousProcess; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.util.PlayerUtils; import org.bukkit.entity.Player; @@ -15,6 +17,9 @@ import javax.inject.Inject; */ public class ProcessSyncEmailRegister implements SynchronousProcess { + @Inject + private BukkitService bukkitService; + @Inject private CommonService service; @@ -34,6 +39,7 @@ public class ProcessSyncEmailRegister implements SynchronousProcess { limboService.replaceTasksAfterRegistration(player); player.saveData(); + bukkitService.callEvent(new RegisterEvent(player)); ConsoleLogger.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 30e7f59ae..dc8aa136f 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncPasswordRegister.java @@ -2,8 +2,10 @@ 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.message.MessageKey; import fr.xephi.authme.process.SynchronousProcess; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.bungeecord.BungeeSender; import fr.xephi.authme.settings.commandconfig.CommandManager; @@ -31,6 +33,9 @@ public class ProcessSyncPasswordRegister implements SynchronousProcess { @Inject private CommandManager commandManager; + @Inject + private BukkitService bukkitService; + ProcessSyncPasswordRegister() { } @@ -60,6 +65,7 @@ public class ProcessSyncPasswordRegister implements SynchronousProcess { } player.saveData(); + bukkitService.callEvent(new RegisterEvent(player)); ConsoleLogger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player)); // Kick Player after Registration is enabled, kick the player 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 9f21b7ba4..9b57fb318 100644 --- a/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java +++ b/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java @@ -156,12 +156,9 @@ public class AsynchronousLoginTest { given(commonService.getProperty(DatabaseSettings.MYSQL_COL_GROUP)).willReturn(""); given(commonService.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(true); doReturn(false).when(asynchronousLogin).hasReachedMaxLoggedInPlayersForIp(any(Player.class), anyString()); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - ((AuthMeAsyncPreLoginEvent) invocation.getArgument(0)).setCanLogin(false); - return null; - } + doAnswer((Answer) invocation -> { + ((AuthMeAsyncPreLoginEvent) invocation.getArgument(0)).setCanLogin(false); + return null; }).when(bukkitService).callEvent(any(AuthMeAsyncPreLoginEvent.class)); // when diff --git a/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java b/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java index 77f91ca88..59c384bb1 100644 --- a/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java +++ b/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java @@ -4,12 +4,15 @@ import ch.jalu.injector.factory.SingletonStore; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.events.AuthMeAsyncPreRegisterEvent; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.register.executors.PasswordRegisterParams; import fr.xephi.authme.process.register.executors.RegistrationExecutor; import fr.xephi.authme.process.register.executors.RegistrationMethod; import fr.xephi.authme.process.register.executors.TwoFactorRegisterParams; +import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; +import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.entity.Player; @@ -18,9 +21,11 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; @@ -40,6 +45,8 @@ public class AsyncRegisterTest { @Mock private CommonService commonService; @Mock + private BukkitService bukkitService; + @Mock private DataSource dataSource; @Mock private SingletonStore registrationExecutorStore; @@ -102,6 +109,32 @@ public class AsyncRegisterTest { @Test @SuppressWarnings("unchecked") public void shouldStopForFailedExecutorCheck() { + // given + String name = "edbert"; + Player player = mockPlayerWithName(name); + TestHelper.mockPlayerIp(player, "33.44.55.66"); + given(playerCache.isAuthenticated(name)).willReturn(false); + given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(true); + given(dataSource.isAuthAvailable(name)).willReturn(false); + given(commonService.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(true); + RegistrationExecutor executor = mock(RegistrationExecutor.class); + TwoFactorRegisterParams params = TwoFactorRegisterParams.of(player); + singletonStoreWillReturn(registrationExecutorStore, executor); + doAnswer((Answer) invocation -> { + ((AuthMeAsyncPreRegisterEvent) invocation.getArgument(0)).setCanRegister(false); + return null; + }).when(bukkitService).callEvent(any(AuthMeAsyncPreRegisterEvent.class)); + + // when + asyncRegister.register(RegistrationMethod.TWO_FACTOR_REGISTRATION, params); + + // then + verify(dataSource, only()).isAuthAvailable(name); + } + + @Test + @SuppressWarnings("unchecked") + public void shouldStopForCancelledEvent() { // given String name = "edbert"; Player player = mockPlayerWithName(name); @@ -110,6 +143,7 @@ public class AsyncRegisterTest { given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(true); given(commonService.getProperty(RestrictionSettings.MAX_REGISTRATION_PER_IP)).willReturn(0); given(dataSource.isAuthAvailable(name)).willReturn(false); + given(commonService.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(true); RegistrationExecutor executor = mock(RegistrationExecutor.class); TwoFactorRegisterParams params = TwoFactorRegisterParams.of(player); given(executor.isRegistrationAdmitted(params)).willReturn(false);