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
This commit is contained in:
Tony 2018-04-03 09:45:27 -06:00 committed by Gabriele C
parent 106dea1611
commit 1f9bf38755
37 changed files with 259 additions and 8 deletions

View File

@ -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());
}

View File

@ -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;
}
}

View File

@ -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"),

View File

@ -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);

View File

@ -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);

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -98,6 +98,8 @@ email:
add_email_request: '&3Please add your email to your account with the command: /email add <yourEmail> <confirmEmail>'
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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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));
}
}

View File

@ -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);