Merge branch 'master' of https://github.com/AuthMe/AuthMeReloaded into 1141-optional-additional-2fa-auth

This commit is contained in:
ljacqu 2018-04-22 07:14:05 +02:00
commit de0e588cf3
56 changed files with 605 additions and 123 deletions

View File

@ -1,49 +0,0 @@
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
workflows:
version: 2
build_and_test:
jobs:
- build_and_test_jdk8
- build_and_test_jdk9

52
.circleci/config.yml Normal file
View File

@ -0,0 +1,52 @@
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 -B dependency:go-offline
- save_cache:
paths:
- ~/.m2
key: authmereloaded-{{ checksum "pom.xml" }}
- run: mvn -T 2 -B package
- store_test_results:
path: target/surefire-reports
- store_artifacts:
path: target/*.jar
build_and_test_jdk10:
working_directory: ~/authmereloaded-jdk10
docker:
- image: circleci/openjdk:10-jdk
environment:
MAVEN_OPTS: -Xmx2048m
steps:
- checkout
- restore_cache:
keys:
- authmereloaded-{{ checksum "pom.xml" }}
- authmereloaded-
- run: mvn -T 2 -B dependency:go-offline
- save_cache:
paths:
- ~/.m2
key: authmereloaded-{{ checksum "pom.xml" }}
- run: mvn -T 2 -B package
- store_test_results:
path: target/surefire-reports
- store_artifacts:
path: target/*.jar
workflows:
version: 2
build_and_test:
jobs:
- build_and_test_jdk8
- build_and_test_jdk10

View File

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

11
pom.xml
View File

@ -169,10 +169,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<version>2.21.0</version>
<configuration>
<!-- Force the right file encoding during unit testing -->
<argLine>-Dfile.encoding=${project.build.sourceEncoding} @{argLine}</argLine>
<!-- Set language to English in order to get consistent results for localized time formatting -->
<argLine>-Dfile.encoding=${project.build.sourceEncoding} -Duser.language=en @{argLine}</argLine>
<systemPropertyVariables>
<project.skipExtendedHashTests>${project.skipExtendedHashTests}</project.skipExtendedHashTests>
</systemPropertyVariables>
@ -436,7 +437,7 @@
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.8</version>
<version>3.1.0</version>
<optional>true</optional>
<exclusions>
<exclusion>
@ -823,7 +824,7 @@
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
<version>2.16.0</version>
<version>2.18.0</version>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
@ -842,7 +843,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196</version>
<version>1.4.197</version>
<scope>test</scope>
</dependency>

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

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

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

View File

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

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

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

View File

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

View File

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

View File

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

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

@ -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<RegistrationExecutor> 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 <P> parameters type
* @param <P> parameters type
*/
public <P extends RegistrationParameters> void register(RegistrationMethod<P> 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 <P> registration params type
* @param executor the executor to perform the registration process with
* @param <P> registration params type
*/
private <P extends RegistrationParameters>
void executeRegistration(P parameters, RegistrationExecutor<P> executor) {
void executeRegistration(P parameters, RegistrationExecutor<P> 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) {

View File

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

View File

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

View File

@ -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<OfflinePlayer> players, Collection<String> 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).");
}
}

View File

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

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

@ -97,6 +97,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

@ -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,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.'
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:

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

@ -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,10 +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.'
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 <email>'
forgot_password_hint: '&3Hai dimenticato la tua password? Puoi recuperarla usando il comando: /email recovery <email>'
command_usage: '&cUtilizzo: /email recovery <email>'
email_sent: '&2Una email di recupero è stata appena inviata al tuo indirizzo email!'
code:

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.'
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:

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

View File

@ -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<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
((AuthMeAsyncPreLoginEvent) invocation.getArgument(0)).setCanLogin(false);
return null;
}
doAnswer((Answer<Void>) invocation -> {
((AuthMeAsyncPreLoginEvent) invocation.getArgument(0)).setCanLogin(false);
return null;
}).when(bukkitService).callEvent(any(AuthMeAsyncPreLoginEvent.class));
// when

View File

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

View File

@ -216,18 +216,16 @@ public class PurgeTaskTest {
private void setPermissionsBehavior() {
given(permissionsManager.hasPermissionOffline(any(OfflinePlayer.class), eq(BYPASS_NODE)))
.willAnswer(new Answer<Boolean>() {
@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<Boolean>) 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) {