Code householding

- Various migrations from legacy settings to new settings
- PlayerListener: use shouldCancelEvent() to see if chat should be canceled
- Merge permission manager listener with general server listener
This commit is contained in:
ljacqu 2016-04-23 00:18:03 +02:00
parent 1182b58b99
commit 0dab887848
10 changed files with 63 additions and 187 deletions

View File

@ -614,7 +614,7 @@ public class AuthMe extends JavaPlugin {
* Set up the permissions manager.
*/
private PermissionsManager initializePermissionsManager() {
PermissionsManager manager = new PermissionsManager(Bukkit.getServer(), this, getLogger());
PermissionsManager manager = new PermissionsManager(Bukkit.getServer(), getLogger());
manager.setup();
return manager;
}

View File

@ -271,7 +271,7 @@ public final class CommandInitializer {
CommandDescription.builder()
.parent(AUTHME_BASE)
.labels("converter", "convert", "conv")
.description("Converter Command")
.description("Converter command")
.detailedDescription("Converter command for AuthMeReloaded.")
.withArgument("job", "Conversion job: xauth / crazylogin / rakamak / " +
"royalauth / vauth / sqlitetosql", false)

View File

@ -75,8 +75,8 @@ public class AuthMePlayerListener implements Listener {
private final Management management;
private final BukkitService bukkitService;
public AuthMePlayerListener(AuthMe plugin, NewSetting settings, Messages messages, DataSource dataSource, AntiBot antiBot,
Management management, BukkitService bukkitService) {
public AuthMePlayerListener(AuthMe plugin, NewSetting settings, Messages messages, DataSource dataSource,
AntiBot antiBot, Management management, BukkitService bukkitService) {
this.plugin = plugin;
this.settings = settings;
this.m = messages;
@ -92,17 +92,15 @@ public class AuthMePlayerListener implements Listener {
}
final Player player = event.getPlayer();
if (Utils.checkAuth(player)) {
if (settings.getProperty(RestrictionSettings.HIDE_CHAT)) {
for (Player p : Utils.getOnlinePlayers()) {
if (!PlayerCache.getInstance().isAuthenticated(p.getName())) {
event.getRecipients().remove(p);
}
}
}
} else {
if (shouldCancelEvent(player)) {
event.setCancelled(true);
sendLoginOrRegisterMessage(player);
} else if (settings.getProperty(RestrictionSettings.HIDE_CHAT)) {
for (Player p : Utils.getOnlinePlayers()) {
if (!PlayerCache.getInstance().isAuthenticated(p.getName())) {
event.getRecipients().remove(p);
}
}
}
}
@ -349,7 +347,7 @@ public class AuthMePlayerListener implements Listener {
final String name = player.getName().toLowerCase();
boolean isAuthAvailable = dataSource.isAuthAvailable(name);
if (antiBot.getAntiBotStatus()==AntiBotStatus.ACTIVE && !isAuthAvailable) {
if (antiBot.getAntiBotStatus() == AntiBotStatus.ACTIVE && !isAuthAvailable) {
event.setKickMessage(m.retrieveSingle(MessageKey.KICK_ANTIBOT));
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;

View File

@ -52,6 +52,9 @@ public class AuthMeServerListener implements Listener {
return;
}
// Call the onPluginDisable method in the permissions manager
plugin.getPermissionsManager().onPluginDisable(event);
final String pluginName = event.getPlugin().getName();
if ("Essentials".equalsIgnoreCase(pluginName)) {
pluginHooks.unhookEssentials();
@ -82,6 +85,9 @@ public class AuthMeServerListener implements Listener {
return;
}
// Call the onPluginEnable method in the permissions manager
plugin.getPermissionsManager().onPluginEnable(event);
final String pluginName = event.getPlugin().getName();
if ("Essentials".equalsIgnoreCase(pluginName)) {
pluginHooks.tryHookToEssentials();

View File

@ -1,11 +1,10 @@
package fr.xephi.authme.permission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import de.bananaco.bpermissions.api.ApiLayer;
import de.bananaco.bpermissions.api.CalculableType;
import fr.xephi.authme.command.CommandDescription;
import fr.xephi.authme.util.CollectionUtils;
import net.milkbowl.vault.permission.Permission;
import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler;
import org.bukkit.Bukkit;
@ -18,15 +17,15 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.tyrannyofheaven.bukkit.zPermissions.ZPermissionsService;
import de.bananaco.bpermissions.api.ApiLayer;
import de.bananaco.bpermissions.api.CalculableType;
import fr.xephi.authme.command.CommandDescription;
import fr.xephi.authme.util.CollectionUtils;
import net.milkbowl.vault.permission.Permission;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* <p>
* PermissionsManager.
@ -49,18 +48,10 @@ public class PermissionsManager implements PermissionsService {
* Server instance.
*/
private final Server server;
/**
* Plugin instance.
*/
private final Plugin plugin;
/**
* Logger instance.
*/
private Logger log;
/**
* The permissions manager Bukkit listener instance.
*/
private PermissionsManagerBukkitListener bukkitListener;
/**
* Type of permissions system that is currently used.
* Null if no permissions system is hooked and/or used.
@ -79,28 +70,11 @@ public class PermissionsManager implements PermissionsService {
* Constructor.
*
* @param server Server instance
* @param plugin Plugin instance
* @param log Logger
*/
public PermissionsManager(Server server, Plugin plugin, Logger log) {
public PermissionsManager(Server server, Logger log) {
this.server = server;
this.plugin = plugin;
this.log = log;
// Create and register the Bukkit listener on the server if it's valid
if(this.server != null) {
// Create the Bukkit listener
this.bukkitListener = new PermissionsManagerBukkitListener(this);
// Get the plugin manager instance
PluginManager pluginManager = this.server.getPluginManager();
// Register the Bukkit listener
pluginManager.registerEvents(this.bukkitListener, this.plugin);
// Show a status message.
//this.log.info("Started permission plugins state listener!");
}
}
/**
@ -282,15 +256,6 @@ public class PermissionsManager implements PermissionsService {
}
}
/**
* Get the permissions manager Bukkit listener instance.
*
* @return Listener instance.
*/
public PermissionsManagerBukkitListener getListener() {
return this.bukkitListener;
}
/**
* Check if the command sender has permission for the given permissions node. If no permissions system is used or
* if the sender is not a player (e.g. console user), the player has to be OP in order to have the permission.

View File

@ -1,85 +0,0 @@
package fr.xephi.authme.permission;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
public class PermissionsManagerBukkitListener implements Listener {
/**
* The permissions manager instance.
*/
private PermissionsManager permissionsManager;
/**
* Whether the listener is enabled or not.
*/
private boolean enabled = true;
/**
* Constructor.\
*
* @param permissionsManager Permissions manager instance.
*/
public PermissionsManagerBukkitListener(PermissionsManager permissionsManager) {
this.permissionsManager = permissionsManager;
}
/**
* Check whether the listener is enabled.
*
* @return True if the listener is enabled.
*/
public boolean isEnabled() {
return this.enabled;
}
/**
* Set whether the listener is enabled.
* Disabling the listener will stop the event handling until it's enabled again.
*
* @param enabled True if enabled, false if disabled.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Called when a plugin is enabled.
*
* @param event Event reference.
*/
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
// Make sure the listener is enabled
if(!isEnabled())
return;
// Make sure the permissions manager is set
if(this.permissionsManager == null)
return;
// Call the onPluginEnable method in the permissions manager
permissionsManager.onPluginEnable(event);
}
/**
* Called when a plugin is disabled.
*
* @param event Event reference.
*/
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
// Make sure the listener is enabled
if(!isEnabled())
return;
// Make sure the permissions manager is set
if(this.permissionsManager == null)
return;
// Call the onPluginDisable method in the permissions manager
permissionsManager.onPluginDisable(event);
}
}

View File

@ -14,26 +14,26 @@ import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.process.Process;
import fr.xephi.authme.process.ProcessService;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.HooksSettings;
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.settings.properties.SecuritySettings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
import fr.xephi.authme.util.Utils;
import fr.xephi.authme.util.Utils.GroupType;
import org.apache.commons.lang.reflect.MethodUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitTask;
import org.apache.commons.lang.reflect.MethodUtils;
import static fr.xephi.authme.settings.properties.RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN;
/**
*/
@ -70,13 +70,13 @@ public class AsynchronousJoin implements Process {
}
final String ip = Utils.getPlayerIp(player);
if (isNameRestricted(name, ip, player.getAddress().getHostName(), service.getSettings())) {
if (isNameRestricted(name, ip, player.getAddress().getHostName())) {
service.scheduleSyncDelayedTask(new Runnable() {
@Override
public void run() {
AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
player.kickPlayer(service.retrieveSingleMessage(MessageKey.NOT_OWNER_ERROR));
if (Settings.banUnsafeIp) {
if (service.getProperty(RestrictionSettings.BAN_UNKNOWN_IP)) {
plugin.getServer().banIP(ip);
}
}
@ -87,7 +87,7 @@ public class AsynchronousJoin implements Process {
&& !plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)
&& !"127.0.0.1".equalsIgnoreCase(ip)
&& !"localhost".equalsIgnoreCase(ip)
&& hasJoinedIp(player.getName(), ip, service.getSettings())) {
&& hasJoinedIp(player.getName(), ip)) {
service.scheduleSyncDelayedTask(new Runnable() {
@Override
public void run() {
@ -103,7 +103,7 @@ public class AsynchronousJoin implements Process {
final Location spawnLoc = service.getSpawnLoader().getSpawnLocation(player);
final boolean isAuthAvailable = database.isAuthAvailable(name);
if (isAuthAvailable) {
if (!Settings.noTeleport) {
if (!service.getProperty(RestrictionSettings.NO_TELEPORT)) {
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) {
service.scheduleSyncDelayedTask(new Runnable() {
@Override
@ -122,12 +122,12 @@ public class AsynchronousJoin implements Process {
LimboCache.getInstance().updateLimboPlayer(player);
// protect inventory
if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) {
if (service.getProperty(PROTECT_INVENTORY_BEFORE_LOGIN) && plugin.inventoryProtector != null) {
ProtectInventoryEvent ev = new ProtectInventoryEvent(player);
plugin.getServer().getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
plugin.inventoryProtector.sendInventoryPacket(player);
if (!Settings.noConsoleSpam) {
if (!service.getProperty(SecuritySettings.REMOVE_SPAM_FROM_CONSOLE)) {
ConsoleLogger.info("ProtectInventoryEvent has been cancelled for " + player.getName() + "...");
}
}
@ -145,7 +145,7 @@ public class AsynchronousJoin implements Process {
service.send(player, MessageKey.SESSION_RECONNECTION);
plugin.getManagement().performLogin(player, "dontneed", true);
return;
} else if (Settings.sessionExpireOnIpChange) {
} else if (service.getProperty(PluginSettings.SESSIONS_EXPIRE_ON_IP_CHANGE)) {
service.send(player, MessageKey.SESSION_EXPIRED);
}
}
@ -153,7 +153,7 @@ public class AsynchronousJoin implements Process {
if (!Settings.unRegisteredGroup.isEmpty()) {
Utils.setGroup(player, Utils.GroupType.UNREGISTERED);
}
if (!Settings.isForcedRegistrationEnabled) {
if (!service.getProperty(RegistrationSettings.FORCE)) {
return;
}
@ -184,7 +184,8 @@ public class AsynchronousJoin implements Process {
@Override
public void run() {
player.setOp(false);
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
if (!service.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)
&& service.getProperty(RestrictionSettings.REMOVE_SPEED)) {
player.setFlySpeed(0.0f);
player.setWalkSpeed(0.0f);
}
@ -211,7 +212,7 @@ public class AsynchronousJoin implements Process {
if (isAuthAvailable) {
msg = MessageKey.LOGIN_MESSAGE;
} else {
msg = Settings.emailRegistration
msg = service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)
? MessageKey.REGISTER_EMAIL_MESSAGE
: MessageKey.REGISTER_MESSAGE;
}
@ -277,24 +278,22 @@ public class AsynchronousJoin implements Process {
* @param name The name to check
* @param ip The IP address of the player
* @param domain The hostname of the IP address
* @param settings The settings instance
* @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 static boolean isNameRestricted(String name, String ip, String domain, NewSetting settings) {
if (!settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)) {
private boolean isNameRestricted(String name, String ip, String domain) {
if (!service.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)) {
return false;
}
boolean nameFound = false;
for (String entry : settings.getProperty(RestrictionSettings.ALLOWED_RESTRICTED_USERS)) {
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))) {
if ((ip != null && testIp.equals(ip)) || (domain != null && testIp.equalsIgnoreCase(domain))) {
return false;
}
}
@ -302,7 +301,7 @@ public class AsynchronousJoin implements Process {
return nameFound;
}
private boolean hasJoinedIp(String name, String ip, NewSetting settings) {
private boolean hasJoinedIp(String name, String ip) {
int count = 0;
for (Player player : Utils.getOnlinePlayers()) {
if (ip.equalsIgnoreCase(Utils.getPlayerIp(player))
@ -310,6 +309,6 @@ public class AsynchronousJoin implements Process {
count++;
}
}
return count >= settings.getProperty(RestrictionSettings.MAX_JOIN_PER_IP);
return count >= service.getProperty(RestrictionSettings.MAX_JOIN_PER_IP);
}
}

View File

@ -17,6 +17,7 @@ import fr.xephi.authme.process.ProcessService;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.settings.properties.SecuritySettings;
@ -166,11 +167,12 @@ public class AsynchronousLogin implements Process {
displayOtherAccounts(auth);
if (Settings.recallEmail && (StringUtils.isEmpty(email) || "your@email.com".equalsIgnoreCase(email))) {
if (service.getProperty(EmailSettings.RECALL_PLAYERS)
&& (StringUtils.isEmpty(email) || "your@email.com".equalsIgnoreCase(email))) {
service.send(player, MessageKey.ADD_EMAIL_MESSAGE);
}
if (!Settings.noConsoleSpam) {
if (!service.getProperty(SecuritySettings.REMOVE_SPAM_FROM_CONSOLE)) {
ConsoleLogger.info(realName + " logged in!");
}
@ -212,7 +214,7 @@ public class AsynchronousLogin implements Process {
}
private void displayOtherAccounts(PlayerAuth auth) {
if (!Settings.displayOtherAccounts || auth == null) {
if (!service.getProperty(RestrictionSettings.DISPLAY_OTHER_ACCOUNTS) || auth == null) {
return;
}

View File

@ -31,15 +31,14 @@ public final class Settings {
public static List<String> countriesBlacklist;
public static HashAlgorithm getPasswordHash;
public static Pattern nickPattern;
public static boolean isChatAllowed, isPermissionCheckEnabled,
public static boolean isPermissionCheckEnabled,
isForcedRegistrationEnabled, isTeleportToSpawnEnabled,
isSessionsEnabled, isAllowRestrictedIp, isMovementAllowed,
isSessionsEnabled, isAllowRestrictedIp,
isForceSingleSessionEnabled, isForceSpawnLocOnJoinEnabled,
isSaveQuitLocationEnabled, protectInventoryBeforeLogInEnabled,
isStopEnabled, reloadSupport, rakamakUseIp, noConsoleSpam,
removePassword, displayOtherAccounts, emailRegistration,
multiverse, bungee, banUnsafeIp, sessionExpireOnIpChange,
enableProtection, recallEmail, forceRegLogin, noTeleport,
isStopEnabled, reloadSupport, rakamakUseIp,
removePassword, multiverse, bungee,
enableProtection, forceRegLogin, noTeleport,
allowAllCommandsIfRegIsOptional, isRemoveSpeedEnabled;
public static String getNickRegex, getUnloggedinGroup,
unRegisteredGroup, backupWindowsPath, getRegisteredGroup,
@ -68,13 +67,11 @@ public final class Settings {
isSessionsEnabled = load(PluginSettings.SESSIONS_ENABLED);
getSessionTimeout = configFile.getInt("settings.sessions.timeout", 10);
getRegistrationTimeout = load(RestrictionSettings.TIMEOUT);
isChatAllowed = load(RestrictionSettings.ALLOW_CHAT);
getMaxNickLength = configFile.getInt("settings.restrictions.maxNicknameLength", 20);
getMinNickLength = configFile.getInt("settings.restrictions.minNicknameLength", 3);
getNickRegex = configFile.getString("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_?]*");
nickPattern = Pattern.compile(getNickRegex);
isAllowRestrictedIp = load(RestrictionSettings.ENABLE_RESTRICTED_USERS);
isMovementAllowed = load(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT);
isRemoveSpeedEnabled = load(RestrictionSettings.REMOVE_SPEED);
isForceSingleSessionEnabled = load(RestrictionSettings.FORCE_SINGLE_SESSION);
isForceSpawnLocOnJoinEnabled = load(RestrictionSettings.FORCE_SPAWN_LOCATION_AFTER_LOGIN);
@ -108,23 +105,17 @@ public final class Settings {
rakamakUsers = configFile.getString("Converter.Rakamak.fileName", "users.rak");
rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName", "UsersIp.rak");
rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false);
noConsoleSpam = load(SecuritySettings.REMOVE_SPAM_FROM_CONSOLE);
removePassword = configFile.getBoolean("Security.console.removePassword", true);
displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true);
maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5);
captchaLength = configFile.getInt("Security.captcha.captchaLength", 5);
emailRegistration = load(RegistrationSettings.USE_EMAIL_REGISTRATION);
saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8);
multiverse = load(HooksSettings.MULTIVERSE);
bungee = load(HooksSettings.BUNGEECORD);
getForcedWorlds = configFile.getStringList("settings.restrictions.ForceSpawnOnTheseWorlds");
banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false);
sessionExpireOnIpChange = configFile.getBoolean("settings.sessions.sessionExpireOnIpChange", true);
bCryptLog2Rounds = configFile.getInt("ExternalBoardOptions.bCryptLog2Round", 10);
defaultWorld = configFile.getString("Purge.defaultWorld", "world");
enableProtection = configFile.getBoolean("Protection.enableProtection", false);
countries = configFile.getStringList("Protection.countries");
recallEmail = configFile.getBoolean("Email.recallPlayers", false);
countriesBlacklist = configFile.getStringList("Protection.countriesBlacklist");
forceRegLogin = load(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER);
getMaxLoginPerIp = load(RestrictionSettings.MAX_LOGIN_PER_IP);

View File

@ -18,13 +18,13 @@ public class RestrictionSettings implements SettingsClass {
public static final Property<Boolean> ALLOW_CHAT =
newProperty("settings.restrictions.allowChat", false);
@Comment("Can not authenticated players see the chat log?")
@Comment("Hide the chat log from players who are not authenticated?")
public static final Property<Boolean> HIDE_CHAT =
newProperty("settings.restrictions.hideChat", false);
@Comment({
"Allow unlogged users to use all the commands if registration is not forced!",
"WARNING: use this only if you need it!)"})
"WARNING: use this only if you need it!"})
public static final Property<Boolean> ALLOW_ALL_COMMANDS_IF_REGISTRATION_IS_OPTIONAL =
newProperty("settings.restrictions.allowAllCommandsIfRegistrationIsOptional", false);