Merge branch 'master' of https://github.com/AuthMe/AuthMeReloaded into limbo
# Conflicts: # src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java # src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java
This commit is contained in:
@@ -15,6 +15,7 @@ import fr.xephi.authme.process.login.AsynchronousLogin;
|
||||
import fr.xephi.authme.service.BukkitService;
|
||||
import fr.xephi.authme.service.CommonService;
|
||||
import fr.xephi.authme.service.PluginHookService;
|
||||
import fr.xephi.authme.service.ValidationService;
|
||||
import fr.xephi.authme.settings.commandconfig.CommandManager;
|
||||
import fr.xephi.authme.settings.properties.HooksSettings;
|
||||
import fr.xephi.authme.settings.properties.PluginSettings;
|
||||
@@ -67,6 +68,9 @@ public class AsynchronousJoin implements AsynchronousProcess {
|
||||
@Inject
|
||||
private CommandManager commandManager;
|
||||
|
||||
@Inject
|
||||
private ValidationService validationService;
|
||||
|
||||
AsynchronousJoin() {
|
||||
}
|
||||
|
||||
@@ -87,7 +91,7 @@ public class AsynchronousJoin implements AsynchronousProcess {
|
||||
pluginHookService.setEssentialsSocialSpyStatus(player, false);
|
||||
}
|
||||
|
||||
if (isNameRestricted(name, ip, player.getAddress().getHostName())) {
|
||||
if (!validationService.fulfillsNameRestrictions(player)) {
|
||||
bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -163,36 +167,6 @@ public class AsynchronousJoin implements AsynchronousProcess {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the name is restricted based on the restriction settings.
|
||||
*
|
||||
* @param name The name to check
|
||||
* @param ip The IP address of the player
|
||||
* @param domain The hostname of the IP address
|
||||
*
|
||||
* @return True if the name is restricted (IP/domain is not allowed for the given name),
|
||||
* false if the restrictions are met or if the name has no restrictions to it
|
||||
*/
|
||||
private boolean isNameRestricted(String name, String ip, String domain) {
|
||||
if (!service.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean nameFound = false;
|
||||
for (String entry : service.getProperty(RestrictionSettings.ALLOWED_RESTRICTED_USERS)) {
|
||||
String[] args = entry.split(";");
|
||||
String testName = args[0];
|
||||
String testIp = args[1];
|
||||
if (testName.equalsIgnoreCase(name)) {
|
||||
nameFound = true;
|
||||
if ((ip != null && testIp.equals(ip)) || (domain != null && testIp.equalsIgnoreCase(domain))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return nameFound;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the maximum number of accounts has been exceeded for the given IP address (according to
|
||||
* settings and permissions). If this is the case, the player is kicked.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package fr.xephi.authme.service;
|
||||
|
||||
import ch.jalu.configme.properties.Property;
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import fr.xephi.authme.ConsoleLogger;
|
||||
import fr.xephi.authme.datasource.DataSource;
|
||||
import fr.xephi.authme.initialization.Reloadable;
|
||||
@@ -12,8 +14,10 @@ import fr.xephi.authme.settings.properties.EmailSettings;
|
||||
import fr.xephi.authme.settings.properties.ProtectionSettings;
|
||||
import fr.xephi.authme.settings.properties.RestrictionSettings;
|
||||
import fr.xephi.authme.settings.properties.SecuritySettings;
|
||||
import fr.xephi.authme.util.PlayerUtils;
|
||||
import fr.xephi.authme.util.Utils;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.inject.Inject;
|
||||
@@ -23,6 +27,8 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static fr.xephi.authme.util.StringUtils.isInsideString;
|
||||
|
||||
/**
|
||||
* Validation service.
|
||||
*/
|
||||
@@ -39,6 +45,7 @@ public class ValidationService implements Reloadable {
|
||||
|
||||
private Pattern passwordRegex;
|
||||
private Set<String> unrestrictedNames;
|
||||
private Multimap<String, String> restrictedNames;
|
||||
|
||||
ValidationService() {
|
||||
}
|
||||
@@ -49,6 +56,9 @@ public class ValidationService implements Reloadable {
|
||||
passwordRegex = Utils.safePatternCompile(settings.getProperty(RestrictionSettings.ALLOWED_PASSWORD_REGEX));
|
||||
// Use Set for more efficient contains() lookup
|
||||
unrestrictedNames = new HashSet<>(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES));
|
||||
restrictedNames = settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)
|
||||
? loadNameRestrictions(settings.getProperty(RestrictionSettings.RESTRICTED_USERS))
|
||||
: HashMultimap.create();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,6 +142,24 @@ public class ValidationService implements Reloadable {
|
||||
return unrestrictedNames.contains(name.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the player meets any name restriction if present (IP/domain-based).
|
||||
*
|
||||
* @param player the player to check
|
||||
* @return true if the player may join, false if the player does not satisfy the name restrictions
|
||||
*/
|
||||
public boolean fulfillsNameRestrictions(Player player) {
|
||||
Collection<String> restrictions = restrictedNames.get(player.getName().toLowerCase());
|
||||
if (Utils.isCollectionEmpty(restrictions)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String ip = PlayerUtils.getPlayerIp(player);
|
||||
String domain = player.getAddress().getHostName();
|
||||
return restrictions.stream()
|
||||
.anyMatch(restriction -> ip.equals(restriction) || domain.equalsIgnoreCase(restriction));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies whether the given value is allowed according to the given whitelist and blacklist settings.
|
||||
* Whitelist has precedence over blacklist: if a whitelist is set, the value is rejected if not present
|
||||
@@ -161,6 +189,26 @@ public class ValidationService implements Reloadable {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the configured name restrictions into a Multimap by player name (all-lowercase).
|
||||
*
|
||||
* @param configuredRestrictions the restriction rules to convert to a map
|
||||
* @return map of allowed IPs/domain names by player name
|
||||
*/
|
||||
private Multimap<String, String> loadNameRestrictions(List<String> configuredRestrictions) {
|
||||
Multimap<String, String> restrictions = HashMultimap.create();
|
||||
for (String restriction : configuredRestrictions) {
|
||||
if (isInsideString(';', restriction)) {
|
||||
String[] data = restriction.split(";");
|
||||
restrictions.put(data[0].toLowerCase(), data[1]);
|
||||
} else {
|
||||
ConsoleLogger.warning("Restricted user rule must have a ';' separating name from restriction,"
|
||||
+ " but found: '" + restriction + "'");
|
||||
}
|
||||
}
|
||||
return restrictions;
|
||||
}
|
||||
|
||||
public static final class ValidationResult {
|
||||
private final MessageKey messageKey;
|
||||
private final String[] args;
|
||||
|
||||
@@ -10,7 +10,7 @@ import static ch.jalu.configme.properties.PropertyInitializer.newProperty;
|
||||
public final class DatabaseSettings implements SettingsHolder {
|
||||
|
||||
@Comment({"What type of database do you want to use?",
|
||||
"Valid values: sqlite, mysql"})
|
||||
"Valid values: SQLITE, MYSQL"})
|
||||
public static final Property<DataSourceType> BACKEND =
|
||||
newProperty(DataSourceType.class, "DataSource.backend", DataSourceType.SQLITE);
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ public final class RestrictionSettings implements SettingsHolder {
|
||||
"Example:",
|
||||
" AllowedRestrictedUser:",
|
||||
" - playername;127.0.0.1"})
|
||||
public static final Property<List<String>> ALLOWED_RESTRICTED_USERS =
|
||||
public static final Property<List<String>> RESTRICTED_USERS =
|
||||
newLowercaseListProperty("settings.restrictions.AllowedRestrictedUser");
|
||||
|
||||
@Comment("Ban unknown IPs trying to log in with a restricted username?")
|
||||
|
||||
@@ -76,4 +76,20 @@ public final class StringUtils {
|
||||
public static String formatException(Throwable th) {
|
||||
return "[" + th.getClass().getSimpleName() + "]: " + th.getMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the given needle is in the middle of the haystack, i.e. that the haystack
|
||||
* contains the needle and that it is not at the very start or end.
|
||||
*
|
||||
* @param needle the needle to search for
|
||||
* @param haystack the haystack to search in
|
||||
*
|
||||
* @return true if the needle is in the middle of the word, false otherwise
|
||||
*/
|
||||
// Note ljacqu 20170314: `needle` is restricted to char type intentionally because something like
|
||||
// isInsideString("11", "2211") would unexpectedly return true...
|
||||
public static boolean isInsideString(char needle, String haystack) {
|
||||
int index = haystack.indexOf(needle);
|
||||
return index > 0 && index < haystack.length() - 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
# Registration
|
||||
reg_msg: '&cPor favor registe-se com "/register password confirmePassword"'
|
||||
usage_reg: '&cUse: /register seu@email.com seu@email.com'
|
||||
reg_only: '&fApenas jogadores registados! Visite http://example.com para se registar'
|
||||
# TODO kicked_admin_registered: 'An admin just registered you; please log in again'
|
||||
reg_msg: '&cPor favor registe-se com "/register <password> <confirmePassword>"'
|
||||
usage_reg: '&cUse: /register <password> <confirmePassword>'
|
||||
reg_only: '&fApenas jogadores registados podem entrar no servidor! Visite http://example.com para se registar'
|
||||
kicked_admin_registered: 'Um administrador registou-te, por favor entre novamente'
|
||||
registered: '&cRegistado com sucesso!'
|
||||
reg_disabled: '&cRegito de novos utilizadores desactivado'
|
||||
reg_disabled: '&cRegisto de novos utilizadores desactivado'
|
||||
user_regged: '&cUtilizador já registado'
|
||||
|
||||
# Password errors on registration
|
||||
password_error: '&fAs passwords não coincidem'
|
||||
password_error_nick: '&cNão pode o usar seu nome como senha, por favor, escolha outra ...'
|
||||
password_error_unsafe: '&cA senha escolhida não é segura, por favor, escolha outra ...'
|
||||
password_error_chars: '&4Sua senha contém caracteres ilegais. caracteres permitidos: REG_EX'
|
||||
pass_len: '&fPassword demasiado curta'
|
||||
password_error_chars: '&4Sua senha contém caracteres ilegais. Caracteres permitidos: REG_EX'
|
||||
pass_len: '&fPassword demasiado curta ou longa! Por favor escolhe outra outra!'
|
||||
|
||||
# Login
|
||||
usage_log: '&cUse: /login password'
|
||||
usage_log: '&cUse: /login <password>'
|
||||
wrong_pwd: '&cPassword errada!'
|
||||
login: '&bAutenticado com sucesso!'
|
||||
login_msg: '&cIdentifique-se com "/login password"'
|
||||
login_msg: '&cIdentifique-se com "/login <password>"'
|
||||
timeout: '&fExcedeu o tempo para autenticação'
|
||||
|
||||
# Errors
|
||||
@@ -26,11 +26,11 @@ unknown_user: '&cUsername não registado'
|
||||
denied_command: '&cPara utilizar este comando é necessário estar logado!'
|
||||
denied_chat: '&cPara usar o chat deve estar logado!'
|
||||
not_logged_in: '&cNão autenticado!'
|
||||
# TODO tempban_max_logins: '&cYou have been temporarily banned for failing to log in too many times.'
|
||||
tempban_max_logins: '&cVocê foi temporariamente banido por falhar muitas vezes o login.'
|
||||
# TODO: Missing tags %reg_names
|
||||
max_reg: '&cAtingiu o numero máximo de %reg_count contas registas, maximo de contas %max_acc'
|
||||
no_perm: '&cSem Permissões'
|
||||
error: '&fOcorreu um erro; Por favor contacte um admin'
|
||||
error: '&fOcorreu um erro; Por favor contacte um administrador'
|
||||
unsafe_spawn: '&fA sua localização na saída não é segura, será tele-portado para a Spawn'
|
||||
kick_forvip: '&cUm jogador VIP entrou no servidor cheio!'
|
||||
|
||||
@@ -41,18 +41,18 @@ antibot_auto_disabled: '[AuthMe] AntiBotMod desactivado automaticamente após %m
|
||||
|
||||
# Other messages
|
||||
unregistered: '&cRegisto eliminado com sucesso!'
|
||||
# TODO accounts_owned_self: 'You own %count accounts:'
|
||||
# TODO accounts_owned_other: 'The player %name has %count accounts:'
|
||||
accounts_owned_self: 'Você possui %count contas:'
|
||||
accounts_owned_other: 'O jogador %name possui %count contas:'
|
||||
two_factor_create: '&2O seu código secreto é o %code. Você pode verificá-lo a partir daqui %url'
|
||||
# TODO recovery_code_sent: 'A recovery code to reset your password has been sent to your email.'
|
||||
# TODO recovery_code_incorrect: 'The recovery code is not correct! Use "/email recovery [email]" to generate a new one'
|
||||
recovery_code_sent: 'O codigo para redefinir a senha foi enviado para o seu e-mail.'
|
||||
recovery_code_incorrect: 'O codigo de recuperação está incorreto! Use "/email recovery [email]" para gerar um novo'
|
||||
vb_nonActiv: '&fA sua conta não foi ainda activada, verifique o seu email onde irá receber indicações para activação de conta. '
|
||||
usage_unreg: '&cUse: /unregister password'
|
||||
usage_unreg: '&cUse: /unregister <password>'
|
||||
pwd_changed: '&cPassword alterada!'
|
||||
logged_in: '&cJá se encontra autenticado!'
|
||||
logout: '&cSaida com sucesso'
|
||||
reload: '&fConfiguração e base de dados foram recarregadas'
|
||||
usage_changepassword: '&fUse: /changepassword passwordAntiga passwordNova'
|
||||
usage_changepassword: '&fUse: /changepassword <passwordAntiga> <passwordNova>'
|
||||
|
||||
# Session messages
|
||||
invalid_session: '&fDados de sessão não correspondem. Por favor aguarde o fim da sessão'
|
||||
@@ -80,14 +80,14 @@ email_confirm: 'Confirme o seu email!'
|
||||
email_changed: 'Email alterado com sucesso!'
|
||||
email_send: 'Nova palavra-passe enviada para o seu email!'
|
||||
email_exists: '&cUm e-mail de recuperação já foi enviado! Pode descartá-lo e enviar um novo usando o comando abaixo:'
|
||||
# TODO email_show: '&2Your current email address is: &f%email'
|
||||
# TODO incomplete_email_settings: 'Error: not all required settings are set for sending emails. Please contact an admin.'
|
||||
email_show: '&2O seu endereço de email atual é &f%email'
|
||||
incomplete_email_settings: 'Erro: nem todas as definições necessarias para enviar email foram preenchidas. Por favor contate um administrador.'
|
||||
email_already_used: '&4O endereço de e-mail já está sendo usado'
|
||||
# TODO email_send_failure: 'The email could not be sent. Please contact an administrator.'
|
||||
# TODO show_no_email: '&2You currently don''t have email address associated with this account.'
|
||||
add_email: '&cPor favor adicione o seu email com : /email add seuEmail confirmarSeuEmail'
|
||||
email_send_failure: 'Não foi possivel enviar o email. Por favor contate um administrador.'
|
||||
show_no_email: '&2Você atualmente não tem um endereço de email associado a essa conta.'
|
||||
add_email: '&cPor favor adicione o seu email com : /email add <seuEmail> <confirmarSeuEmail>'
|
||||
recovery_email: '&cPerdeu a sua password? Para a recuperar escreva /email recovery <seuEmail>'
|
||||
# TODO email_cooldown_error: '&cAn email was already sent recently. You must wait %time before you can send a new one.'
|
||||
email_cooldown_error: '&cUm email já foi enviado recentemente.Por favor, espere %time antes de enviar novamente'
|
||||
|
||||
# Captcha
|
||||
usage_captcha: '&cPrecisa digitar um captcha, escreva: /captcha <theCaptcha>'
|
||||
@@ -95,11 +95,11 @@ wrong_captcha: '&cCaptcha errado, por favor escreva: /captcha THE_CAPTCHA'
|
||||
valid_captcha: '&cO seu captcha é válido!'
|
||||
|
||||
# Time units
|
||||
# TODO second: 'second'
|
||||
# TODO seconds: 'seconds'
|
||||
# TODO minute: 'minute'
|
||||
# TODO minutes: 'minutes'
|
||||
# TODO hour: 'hour'
|
||||
# TODO hours: 'hours'
|
||||
# TODO day: 'day'
|
||||
# TODO days: 'days'
|
||||
second: 'segundo'
|
||||
seconds: 'segundos'
|
||||
minute: 'minuto'
|
||||
minutes: 'minutos'
|
||||
hour: 'hora'
|
||||
hours: 'horas'
|
||||
day: 'dia'
|
||||
days: 'dias'
|
||||
|
||||
Reference in New Issue
Block a user