From fec4fb29138686674241fc2a6f471bf20dedf46b Mon Sep 17 00:00:00 2001 From: DNx5 Date: Wed, 23 Sep 2015 17:55:56 +0700 Subject: [PATCH 01/27] projectile issue --- .../fr/xephi/authme/listener/AuthMeEntityListener.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java index da4b43ea..34b3b0f2 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java @@ -9,6 +9,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.*; +import org.bukkit.projectiles.ProjectileSource; public class AuthMeEntityListener implements Listener { @@ -121,13 +122,14 @@ public class AuthMeEntityListener implements Listener { event.setCancelled(true); } - @EventHandler(priority = EventPriority.HIGHEST) + // TODO: Need to check this, player can't throw snowball but the item is taken. + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onProjectileLaunch(ProjectileLaunchEvent event) { Projectile projectile = event.getEntity(); if (projectile == null) return; - Entity shooter = (Entity) projectile.getShooter(); + ProjectileSource shooter = projectile.getShooter(); if (shooter == null || !(shooter instanceof Player)) { return; } @@ -139,7 +141,7 @@ public class AuthMeEntityListener implements Listener { event.setCancelled(true); } - @EventHandler + @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) public void onShoot(EntityShootBowEvent event) { Entity entity = event.getEntity(); if (entity == null || !(entity instanceof Player)) { From 10580e3447017f09c6bd5212f64ec5f123754a1d Mon Sep 17 00:00:00 2001 From: DNx5 Date: Wed, 23 Sep 2015 21:50:17 +0700 Subject: [PATCH 02/27] cleanup converters --- .../xephi/authme/commands/AdminCommand.java | 2 +- .../authme/converter/CrazyLoginConverter.java | 34 ++--- .../fr/xephi/authme/converter/FlatToSql.java | 16 +-- .../xephi/authme/converter/FlatToSqlite.java | 116 +++++++----------- .../authme/converter/ForceFlatToSqlite.java | 3 +- .../authme/converter/RakamakConverter.java | 46 +++---- .../authme/converter/RoyalAuthConverter.java | 12 +- .../authme/converter/RoyalAuthYamlReader.java | 4 +- .../fr/xephi/authme/converter/SqlToFlat.java | 9 +- .../authme/converter/vAuthConverter.java | 3 +- .../authme/converter/vAuthFileReader.java | 32 +++-- .../authme/converter/xAuthConverter.java | 3 +- .../xephi/authme/converter/xAuthToFlat.java | 21 ++-- .../fr/xephi/authme/settings/Settings.java | 26 ++-- 14 files changed, 134 insertions(+), 193 deletions(-) diff --git a/src/main/java/fr/xephi/authme/commands/AdminCommand.java b/src/main/java/fr/xephi/authme/commands/AdminCommand.java index 7a562ea5..eab60353 100644 --- a/src/main/java/fr/xephi/authme/commands/AdminCommand.java +++ b/src/main/java/fr/xephi/authme/commands/AdminCommand.java @@ -109,7 +109,7 @@ public class AdminCommand implements CommandExecutor { } } else if (args[0].equalsIgnoreCase("reload")) { try { - plugin.getSettings().reload(); + Settings.reload(); m.reloadMessages(); plugin.database.close(); plugin.setupDatabase(); diff --git a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java index dbb247d0..7ba5742a 100644 --- a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java +++ b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java @@ -1,20 +1,18 @@ package fr.xephi.authme.converter; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -import org.bukkit.command.CommandSender; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.settings.Settings; +import org.bukkit.command.CommandSender; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; /** - * * @author Xephi59 */ public class CrazyLoginConverter implements Converter { @@ -33,22 +31,17 @@ public class CrazyLoginConverter implements Converter { return this; } - private static String fileName; - private static File source; - @Override public void run() { - fileName = Settings.crazyloginFileName; + String fileName = Settings.crazyloginFileName; try { - source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName); + File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName); if (!source.exists()) { sender.sendMessage("Error while trying to import datas, please put " + fileName + " in AuthMe folder!"); return; } - source.createNewFile(); - BufferedReader users = null; String line; - users = new BufferedReader(new FileReader(source)); + BufferedReader users = new BufferedReader(new FileReader(source)); while ((line = users.readLine()) != null) { if (line.contains("|")) { String[] args = line.split("\\|"); @@ -58,12 +51,9 @@ public class CrazyLoginConverter implements Converter { continue; String player = args[0].toLowerCase(); String psw = args[1]; - try { - if (player != null && psw != null) { - PlayerAuth auth = new PlayerAuth(player, psw, "127.0.0.1", System.currentTimeMillis(), player); - database.saveAuth(auth); - } - } catch (Exception e) { + if (psw != null) { + PlayerAuth auth = new PlayerAuth(player, psw, "127.0.0.1", System.currentTimeMillis(), player); + database.saveAuth(auth); } } } diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSql.java b/src/main/java/fr/xephi/authme/converter/FlatToSql.java index 0f0b7bf8..17a5701a 100644 --- a/src/main/java/fr/xephi/authme/converter/FlatToSql.java +++ b/src/main/java/fr/xephi/authme/converter/FlatToSql.java @@ -1,18 +1,12 @@ package fr.xephi.authme.converter; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.settings.Settings; +import java.io.*; + /** - * * @author Xephi59 */ public class FlatToSql implements Converter { @@ -29,8 +23,6 @@ public class FlatToSql implements Converter { private static String columnEmail; private static String columnLogged; private static String columnID; - private static File source; - private static File output; public FlatToSql() { tableName = Settings.getMySQLTablename; @@ -50,9 +42,9 @@ public class FlatToSql implements Converter { @Override public void run() { try { - source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); + File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); source.createNewFile(); - output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql"); + File output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql"); output.createNewFile(); BufferedReader br = new BufferedReader(new FileReader(source)); BufferedWriter sql = new BufferedWriter(new FileWriter(output)); diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java index f81d4a69..fb77d492 100644 --- a/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java +++ b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java @@ -1,44 +1,44 @@ package fr.xephi.authme.converter; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.Settings; +import org.bukkit.command.CommandSender; + import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import org.bukkit.command.CommandSender; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.settings.Settings; +import java.sql.*; public class FlatToSqlite implements Converter { public CommandSender sender; - + private String tableName; + private String columnName; + private String columnPassword; + private String columnIp; + private String columnLastLogin; + private String lastlocX; + private String lastlocY; + private String lastlocZ; + private String lastlocWorld; + private String columnEmail; + private String database; + private String columnID; + private Connection con; public FlatToSqlite(CommandSender sender) { this.sender = sender; } - private static String tableName; - private static String columnName; - private static String columnPassword; - private static String columnIp; - private static String columnLastLogin; - private static String lastlocX; - private static String lastlocY; - private static String lastlocZ; - private static String lastlocWorld; - private static String columnEmail; - private static File source; - private static String database; - private static String columnID; - private static Connection con; + private static void close(AutoCloseable o) { + if (o != null) { + try { + o.close(); + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + } + } + } @Override public void run() { @@ -55,6 +55,12 @@ public class FlatToSqlite implements Converter { columnEmail = Settings.getMySQLColumnEmail; columnID = Settings.getMySQLColumnId; + File source = new File(Settings.PLUGIN_FOLDER, "auths.db"); + if (!source.exists()) { + sender.sendMessage("Source file for FlatFile database not found... Aborting"); + return; + } + try { connect(); setup(); @@ -62,14 +68,12 @@ public class FlatToSqlite implements Converter { sender.sendMessage("Some error appeared while trying to setup and connect to sqlite database... Aborting"); return; } - try { - source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); - source.createNewFile(); - BufferedReader br = new BufferedReader(new FileReader(source)); + + try (BufferedReader reader = new BufferedReader(new FileReader(source))) { String line; int i = 1; String newline; - while ((line = br.readLine()) != null) { + while ((line = reader.readLine()) != null) { String[] args = line.split(":"); if (args.length == 4) newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0, 0, 0, 'world', 'your@email.com');"; @@ -84,25 +88,23 @@ public class FlatToSqlite implements Converter { saveAuth(newline); i = i + 1; } - br.close(); - ConsoleLogger.info("The FlatFile has been converted to " + database + ".db file"); - close(); - sender.sendMessage("The FlatFile has been converted to " + database + ".db file"); - return; + String resp = "The FlatFile has been converted to " + database + ".db file"; + ConsoleLogger.info(resp); + sender.sendMessage(resp); } catch (IOException ex) { ConsoleLogger.showError(ex.getMessage()); - sender.sendMessage("Can't open the flat database file! Does it exist?"); + sender.sendMessage("Can't open the flat database file!"); + } finally { + close(con); } - return; } - private synchronized static void connect() - throws ClassNotFoundException, SQLException { + private synchronized void connect() throws ClassNotFoundException, SQLException { Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db"); } - private synchronized static void setup() throws SQLException { + private synchronized void setup() throws SQLException { Statement st = null; ResultSet rs = null; try { @@ -145,7 +147,7 @@ public class FlatToSqlite implements Converter { } } - private static synchronized boolean saveAuth(String s) { + private synchronized boolean saveAuth(String s) { PreparedStatement pst = null; try { pst = con.prepareStatement(s); @@ -158,32 +160,4 @@ public class FlatToSqlite implements Converter { } return true; } - - private static void close(Statement st) { - if (st != null) { - try { - st.close(); - } catch (SQLException ex) { - ConsoleLogger.showError(ex.getMessage()); - } - } - } - - private static void close(ResultSet rs) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException ex) { - ConsoleLogger.showError(ex.getMessage()); - } - } - } - - public synchronized static void close() { - try { - con.close(); - } catch (SQLException ex) { - ConsoleLogger.showError(ex.getMessage()); - } - } } diff --git a/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java index f2bbd204..b25e7110 100644 --- a/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java +++ b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java @@ -5,6 +5,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.SQLite; +import fr.xephi.authme.settings.Settings; public class ForceFlatToSqlite implements Converter { @@ -25,7 +26,7 @@ public class ForceFlatToSqlite implements Converter { auth.setRealName("Player"); sqlite.saveAuth(auth); } - plugin.getSettings().setValue("DataSource.backend", "sqlite"); + Settings.setValue("DataSource.backend", "sqlite"); ConsoleLogger.info("Database successfully converted to sqlite !"); } catch (Exception e) { ConsoleLogger.showError("An error appeared while trying to convert flatfile to sqlite ..."); diff --git a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java index 38697dbb..3f8cc0c0 100644 --- a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java +++ b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java @@ -1,5 +1,14 @@ package fr.xephi.authme.converter; +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.security.HashAlgorithm; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Settings; +import org.bukkit.command.CommandSender; + import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -8,18 +17,7 @@ import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map.Entry; -import org.bukkit.command.CommandSender; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.security.HashAlgorithm; -import fr.xephi.authme.security.PasswordSecurity; -import fr.xephi.authme.settings.Settings; - /** - * * @author Xephi59 */ public class RakamakConverter implements Converter { @@ -38,27 +36,19 @@ public class RakamakConverter implements Converter { return this; } - private static Boolean useIP; - private static String fileName; - private static String ipFileName; - private static File source; - private static File ipfiles; - @Override public void run() { HashAlgorithm hash = Settings.getPasswordHash; - useIP = Settings.rakamakUseIp; - fileName = Settings.rakamakUsers; - ipFileName = Settings.rakamakUsersIp; - HashMap playerIP = new HashMap(); - HashMap playerPSW = new HashMap(); + boolean useIP = Settings.rakamakUseIp; + String fileName = Settings.rakamakUsers; + String ipFileName = Settings.rakamakUsersIp; + File source = new File(Settings.PLUGIN_FOLDER, fileName); + File ipfiles = new File(Settings.PLUGIN_FOLDER, ipFileName); + HashMap playerIP = new HashMap<>(); + HashMap playerPSW = new HashMap<>(); try { - source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName); - ipfiles = new File(AuthMe.getInstance().getDataFolder() + File.separator + ipFileName); - source.createNewFile(); - ipfiles.createNewFile(); - BufferedReader users = null; - BufferedReader ipFile = null; + BufferedReader users; + BufferedReader ipFile; ipFile = new BufferedReader(new FileReader(ipfiles)); String line; if (useIP) { diff --git a/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java index c39984d8..78a32aee 100644 --- a/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java +++ b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java @@ -1,13 +1,12 @@ package fr.xephi.authme.converter; -import java.io.File; - -import org.bukkit.OfflinePlayer; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; +import org.bukkit.OfflinePlayer; + +import java.io.File; public class RoyalAuthConverter implements Converter { @@ -24,8 +23,8 @@ public class RoyalAuthConverter implements Converter { for (OfflinePlayer o : plugin.getServer().getOfflinePlayers()) { try { String name = o.getName().toLowerCase(); - String separator = File.separator; - File file = new File("." + separator + "plugins" + separator + "RoyalAuth" + separator + "userdata" + separator + name + ".yml"); + String sp = File.separator; + File file = new File("." + sp + "plugins" + sp + "RoyalAuth" + sp + "userdata" + sp + name + ".yml"); if (data.isAuthAvailable(name)) continue; if (!file.exists()) @@ -34,6 +33,7 @@ public class RoyalAuthConverter implements Converter { PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com"); data.saveAuth(auth); } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); ConsoleLogger.showError("Error while trying to import " + o.getName() + " RoyalAuth datas"); } } diff --git a/src/main/java/fr/xephi/authme/converter/RoyalAuthYamlReader.java b/src/main/java/fr/xephi/authme/converter/RoyalAuthYamlReader.java index cebbee0d..f0510c75 100644 --- a/src/main/java/fr/xephi/authme/converter/RoyalAuthYamlReader.java +++ b/src/main/java/fr/xephi/authme/converter/RoyalAuthYamlReader.java @@ -1,9 +1,9 @@ package fr.xephi.authme.converter; -import java.io.File; - import fr.xephi.authme.settings.CustomConfiguration; +import java.io.File; + public class RoyalAuthYamlReader extends CustomConfiguration { public RoyalAuthYamlReader(File file) { diff --git a/src/main/java/fr/xephi/authme/converter/SqlToFlat.java b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java index 4dccbd43..bc8b0834 100644 --- a/src/main/java/fr/xephi/authme/converter/SqlToFlat.java +++ b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java @@ -1,15 +1,14 @@ package fr.xephi.authme.converter; -import java.util.List; - -import org.bukkit.command.CommandSender; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.FlatFile; import fr.xephi.authme.settings.Messages; +import org.bukkit.command.CommandSender; + +import java.util.List; public class SqlToFlat implements Converter { @@ -38,11 +37,9 @@ public class SqlToFlat implements Converter { } } sender.sendMessage("Successfully convert from SQL table to file auths.db"); - return; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); Messages.getInstance().send(sender, "error"); - return; } } diff --git a/src/main/java/fr/xephi/authme/converter/vAuthConverter.java b/src/main/java/fr/xephi/authme/converter/vAuthConverter.java index 1939c6c1..1de9f104 100644 --- a/src/main/java/fr/xephi/authme/converter/vAuthConverter.java +++ b/src/main/java/fr/xephi/authme/converter/vAuthConverter.java @@ -1,10 +1,9 @@ package fr.xephi.authme.converter; -import org.bukkit.command.CommandSender; - import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.datasource.DataSource; +import org.bukkit.command.CommandSender; public class vAuthConverter implements Converter { diff --git a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java index 5b2a0be9..0fb2c73e 100644 --- a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java +++ b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java @@ -1,18 +1,18 @@ package fr.xephi.authme.converter; +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; + import java.io.File; import java.io.IOException; import java.util.Scanner; import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.datasource.DataSource; - public class vAuthFileReader { public AuthMe plugin; @@ -27,21 +27,19 @@ public class vAuthFileReader { public void convert() throws IOException { final File file = new File(plugin.getDataFolder().getParent() + "" + File.separator + "vAuth" + File.separator + "passwords.yml"); - Scanner scanner = null; + Scanner scanner; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String name = line.split(": ")[0]; String password = line.split(": ")[1]; - PlayerAuth auth = null; + PlayerAuth auth; if (isUUIDinstance(password)) { - String pname = null; + String pname; try { pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName(); - } catch (Exception e) { - pname = getName(UUID.fromString(name)); - } catch (NoSuchMethodError e) { + } catch (Exception | NoSuchMethodError e) { pname = getName(UUID.fromString(name)); } if (pname == null) @@ -50,10 +48,10 @@ public class vAuthFileReader { } else { auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com"); } - if (auth != null) - database.saveAuth(auth); + database.saveAuth(auth); } } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); } } @@ -70,7 +68,7 @@ public class vAuthFileReader { if (op.getUniqueId().compareTo(uuid) == 0) return op.getName(); } - } catch (Exception e) { + } catch (Exception ignored) { } return null; } diff --git a/src/main/java/fr/xephi/authme/converter/xAuthConverter.java b/src/main/java/fr/xephi/authme/converter/xAuthConverter.java index 1f813668..a5c063fd 100644 --- a/src/main/java/fr/xephi/authme/converter/xAuthConverter.java +++ b/src/main/java/fr/xephi/authme/converter/xAuthConverter.java @@ -1,8 +1,7 @@ package fr.xephi.authme.converter; -import org.bukkit.command.CommandSender; - import fr.xephi.authme.AuthMe; +import org.bukkit.command.CommandSender; public class xAuthConverter implements Converter { diff --git a/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java b/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java index 61be7cb8..0c6d62fd 100644 --- a/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java +++ b/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java @@ -1,5 +1,13 @@ package fr.xephi.authme.converter; +import de.luricos.bukkit.xAuth.database.DatabaseTables; +import de.luricos.bukkit.xAuth.utils.xAuthLog; +import de.luricos.bukkit.xAuth.xAuth; +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import org.bukkit.command.CommandSender; + import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; @@ -8,15 +16,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import org.bukkit.command.CommandSender; - -import de.luricos.bukkit.xAuth.xAuth; -import de.luricos.bukkit.xAuth.database.DatabaseTables; -import de.luricos.bukkit.xAuth.utils.xAuthLog; -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.datasource.DataSource; - public class xAuthToFlat { public AuthMe instance; @@ -82,7 +81,7 @@ public class xAuthToFlat { } public List getXAuthPlayers() { - List xP = new ArrayList(); + List xP = new ArrayList<>(); Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); PreparedStatement ps = null; ResultSet rs = null; @@ -95,7 +94,7 @@ public class xAuthToFlat { } } catch (SQLException e) { xAuthLog.severe("Cannot import xAuthPlayers", e); - return new ArrayList(); + return new ArrayList<>(); } finally { xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); } diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index f3f437be..8576b3ce 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -14,7 +14,8 @@ import java.util.List; public final class Settings extends YamlConfiguration { - private AuthMe plugin; + private static AuthMe plugin; + private static Settings instance; // This is not an option! public static Boolean antiBotInAction = false; @@ -94,24 +95,25 @@ public final class Settings extends YamlConfiguration { protected static YamlConfiguration configFile; - public Settings(AuthMe plugin) { + public Settings(AuthMe pl) { configFile = (YamlConfiguration) plugin.getConfig(); - this.plugin = plugin; + plugin = pl; + instance = this; } - public final void reload() throws Exception { + public static void reload() throws Exception { plugin.getLogger().info("Loading Configuration File..."); boolean exist = SETTINGS_FILE.exists(); if (!exist) { plugin.saveDefaultConfig(); } - load(SETTINGS_FILE); + instance.load(SETTINGS_FILE); if (exist) { - mergeConfig(); + instance.mergeConfig(); } loadVariables(); if (exist) { - saveDefaults(); + instance.saveDefaults(); } messageFile = new File(PLUGIN_FOLDER, "messages" + File.separator + "messages_" + messagesLanguage + ".yml"); } @@ -481,9 +483,9 @@ public final class Settings extends YamlConfiguration { } } - public void setValue(String key, Object value) { - this.set(key, value); - this.save(); + public static void setValue(String key, Object value) { + instance.set(key, value); + save(); } private static HashAlgorithm getPasswordHash() { @@ -539,9 +541,9 @@ public final class Settings extends YamlConfiguration { * * @return True if saved successfully */ - public final boolean save() { + public static boolean save() { try { - save(SETTINGS_FILE); + instance.save(SETTINGS_FILE); return true; } catch (Exception ex) { return false; From 53f3ad114b604e0f450c569e1d884bfc5612d461 Mon Sep 17 00:00:00 2001 From: DNx5 Date: Thu, 24 Sep 2015 00:55:01 +0700 Subject: [PATCH 03/27] re-add geoip methods and set as deprecated --- src/main/java/fr/xephi/authme/AuthMe.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 170e6d7d..dc797d0c 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -64,7 +64,6 @@ public class AuthMe extends JavaPlugin { private JsonCache playerBackup; public OtherAccounts otherAccounts; public Location essentialsSpawn; - public LookupService lookupService; public boolean legacyChestShop = false; public boolean antibotMod = false; public boolean delayedAntiBot = true; @@ -768,5 +767,14 @@ public class AuthMe extends JavaPlugin { return realIP; } + @Deprecated + public String getCountryCode(String ip) { + return Utils.getCountryCode(ip); + } + + @Deprecated + public String getCountryName(String ip) { + return Utils.getCountryName(ip); + } } From 8f446fa6af459411635b9299c4ee5c209244ad80 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Wed, 23 Sep 2015 22:10:11 +0200 Subject: [PATCH 04/27] Fix settings (i hope) --- src/main/java/fr/xephi/authme/AuthMe.java | 3 +-- src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java | 3 --- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index dc797d0c..6e11d612 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -1,7 +1,6 @@ package fr.xephi.authme; import com.earth2me.essentials.Essentials; -import com.maxmind.geoip.LookupService; import com.onarandombox.MultiverseCore.MultiverseCore; import fr.xephi.authme.api.API; import fr.xephi.authme.api.NewAPI; @@ -119,7 +118,7 @@ public class AuthMe extends JavaPlugin { // TODO: new configuration style (more files) try { settings = new Settings(this); - settings.reload(); + Settings.reload(); } catch (Exception e) { ConsoleLogger.writeStackTrace(e); ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!"); diff --git a/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java index b25e7110..2c95d1cd 100644 --- a/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java +++ b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java @@ -10,11 +10,8 @@ import fr.xephi.authme.settings.Settings; public class ForceFlatToSqlite implements Converter { private DataSource data; - private AuthMe plugin; - public ForceFlatToSqlite(DataSource data, AuthMe plugin) { this.data = data; - this.plugin = plugin; } @Override From 8b71f964dad4ea2e5af5bf6c8cbcd1ea9be1acd1 Mon Sep 17 00:00:00 2001 From: DNx5 Date: Thu, 24 Sep 2015 18:30:24 +0700 Subject: [PATCH 05/27] fix changepassword issue. #190 #218 --- .../commands/ChangePasswordCommand.java | 2 +- .../xephi/authme/task/ChangePasswordTask.java | 20 +++++++++++-------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java index 6d3c1f2f..54626d77 100644 --- a/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java +++ b/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java @@ -62,7 +62,7 @@ public class ChangePasswordCommand implements CommandExecutor { return true; } } - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, args[0])); + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, args[0], args[1])); return true; } } diff --git a/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java b/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java index c9cb72d6..2cf21d19 100644 --- a/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java +++ b/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java @@ -15,12 +15,14 @@ public class ChangePasswordTask implements Runnable { private final AuthMe plugin; private final Player player; - private String password; + private final String oldPassword; + private final String newPassword; - public ChangePasswordTask(AuthMe plugin, Player player, String password) { + public ChangePasswordTask(AuthMe plugin, Player player, String oldPassword, String newPassword) { this.plugin = plugin; this.player = player; - this.password = password; + this.oldPassword = oldPassword; + this.newPassword = newPassword; } @Override @@ -28,13 +30,15 @@ public class ChangePasswordTask implements Runnable { Messages m = Messages.getInstance(); try { String name = player.getName().toLowerCase(); - String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); - if (PasswordSecurity.comparePasswordWithHash(password, PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) { - PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, newPassword, name); + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + if (PasswordSecurity.comparePasswordWithHash(oldPassword, auth.getHash(), player.getName())) { auth.setHash(hashnew); - if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) + if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) { auth.setSalt(PasswordSecurity.userSalt.get(name)); - else auth.setSalt(""); + } else { + auth.setSalt(""); + } if (!plugin.database.updatePassword(auth)) { m.send(player, "error"); return; From 45d939f0f53718e39824d7e8b5b2e6235e1b9f63 Mon Sep 17 00:00:00 2001 From: DNx5 Date: Fri, 25 Sep 2015 01:06:58 +0700 Subject: [PATCH 06/27] init field first, fix #221 --- src/main/java/fr/xephi/authme/settings/Settings.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index 8576b3ce..f79d4e24 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -96,9 +96,9 @@ public final class Settings extends YamlConfiguration { protected static YamlConfiguration configFile; public Settings(AuthMe pl) { - configFile = (YamlConfiguration) plugin.getConfig(); - plugin = pl; instance = this; + plugin = pl; + configFile = (YamlConfiguration) plugin.getConfig(); } public static void reload() throws Exception { From f88e197863779cf0c4150956a7d6f87b0f9885af Mon Sep 17 00:00:00 2001 From: DNx5 Date: Fri, 25 Sep 2015 05:21:32 +0700 Subject: [PATCH 07/27] cleanup Settings --- .../java/fr/xephi/authme/settings/Settings.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index f79d4e24..24a72173 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -18,7 +18,7 @@ public final class Settings extends YamlConfiguration { private static Settings instance; // This is not an option! - public static Boolean antiBotInAction = false; + public static boolean antiBotInAction = false; public static final File PLUGIN_FOLDER = AuthMe.getInstance().getDataFolder(); public static final File MODULE_FOLDER = new File(PLUGIN_FOLDER, "modules"); @@ -513,11 +513,11 @@ public final class Settings extends YamlConfiguration { * return false if ip and name doesnt amtch with player that join the * server, so player has a restricted access */ - public static Boolean getRestrictedIp(String name, String ip) { + public static boolean getRestrictedIp(String name, String ip) { Iterator iter = getRestrictedIp.iterator(); - Boolean trueonce = false; - Boolean namefound = false; + boolean trueonce = false; + boolean namefound = false; while (iter.hasNext()) { String[] args = iter.next().split(";"); String testname = args[0]; @@ -529,11 +529,7 @@ public final class Settings extends YamlConfiguration { } } } - if (!namefound) { - return true; - } else { - return trueonce; - } + return !namefound || trueonce; } /** From 72604bfdea51a6beb6efbe52b000c5ee0f0b4118 Mon Sep 17 00:00:00 2001 From: DNx5 Date: Fri, 25 Sep 2015 07:20:46 +0700 Subject: [PATCH 08/27] improve cached datasource performance. --- src/main/java/fr/xephi/authme/AuthMe.java | 7 +- .../authme/datasource/CacheDataSource.java | 286 +++++++++++++----- .../authme/datasource/DatabaseCalls.java | 13 +- 3 files changed, 220 insertions(+), 86 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 6e11d612..77a0e5c1 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -37,7 +37,8 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; import org.mcstats.Metrics; -import java.io.*; +import java.io.BufferedReader; +import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Calendar; @@ -382,10 +383,10 @@ public class AuthMe extends JavaPlugin { if (Settings.isCachingEnabled) { database = new CacheDataSource(this, database); + } else { + database = new DatabaseCalls(database); } - database = new DatabaseCalls(database); - if (Settings.getDataSource == DataSource.DataSourceType.FILE) { Converter converter = new ForceFlatToSqlite(database, this); server.getScheduler().runTaskAsynchronously(this, converter); diff --git a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java index d4b0772c..08419710 100644 --- a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java +++ b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java @@ -6,24 +6,31 @@ import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import org.bukkit.entity.Player; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; public class CacheDataSource implements DataSource { private final DataSource source; private final AuthMe plugin; - private ConcurrentHashMap cache = new ConcurrentHashMap<>(); + private final ExecutorService exec; + private final ConcurrentHashMap cache = new ConcurrentHashMap<>(); public CacheDataSource(AuthMe pl, DataSource src) { this.plugin = pl; this.source = src; + this.exec = Executors.newCachedThreadPool(); + /* * We need to load all players in cache ... It will took more time to * load the server, but it will be much easier to check for an * isAuthAvailable ! */ - pl.getServer().getScheduler().runTaskAsynchronously(pl, new Runnable() { + exec.execute(new Runnable() { @Override public void run() { for (PlayerAuth auth : source.getAllAuths()) { @@ -50,7 +57,7 @@ public class CacheDataSource implements DataSource { @Override public synchronized boolean saveAuth(final PlayerAuth auth) { cache.put(auth.getNickname(), auth); - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { + exec.execute(new Runnable() { @Override public void run() { if (!source.saveAuth(auth)) { @@ -62,45 +69,95 @@ public class CacheDataSource implements DataSource { } @Override - public synchronized boolean updatePassword(PlayerAuth auth) { - if (source.updatePassword(auth)) { - if (cache.containsKey(auth.getNickname())) - cache.get(auth.getNickname()).setHash(auth.getHash()); - return true; + public synchronized boolean updatePassword(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; } - return false; + final String oldHash = cache.get(auth.getNickname()).getHash(); + cache.get(auth.getNickname()).setHash(auth.getHash()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updatePassword(auth)) { + if (cache.containsKey(auth.getNickname())) { + cache.get(auth.getNickname()).setHash(oldHash); + } + } + } + }); + return true; } @Override - public boolean updateSession(PlayerAuth auth) { - if (source.updateSession(auth)) { - if (cache.containsKey(auth.getNickname())) { - cache.get(auth.getNickname()).setIp(auth.getIp()); - cache.get(auth.getNickname()).setLastLogin(auth.getLastLogin()); - cache.get(auth.getNickname()).setRealName(auth.getRealName()); - } - return true; + public boolean updateSession(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; } - return false; + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final String oldIp = cachedAuth.getIp(); + final long oldLastLogin = cachedAuth.getLastLogin(); + final String oldRealName = cachedAuth.getRealName(); + + cachedAuth.setIp(auth.getIp()); + cachedAuth.setLastLogin(auth.getLastLogin()); + cachedAuth.setRealName(auth.getRealName()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateSession(auth)) { + if (cache.containsKey(auth.getNickname())) { + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + cachedAuth.setIp(oldIp); + cachedAuth.setLastLogin(oldLastLogin); + cachedAuth.setRealName(oldRealName); + } + } + } + }); + return true; } @Override - public boolean updateQuitLoc(PlayerAuth auth) { - if (source.updateQuitLoc(auth)) { - if (cache.containsKey(auth.getNickname())) { - cache.get(auth.getNickname()).setQuitLocX(auth.getQuitLocX()); - cache.get(auth.getNickname()).setQuitLocY(auth.getQuitLocY()); - cache.get(auth.getNickname()).setQuitLocZ(auth.getQuitLocZ()); - cache.get(auth.getNickname()).setWorld(auth.getWorld()); - } - return true; + public boolean updateQuitLoc(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; } - return false; + final PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final double oldX = cachedAuth.getQuitLocX(); + final double oldY = cachedAuth.getQuitLocY(); + final double oldZ = cachedAuth.getQuitLocZ(); + final String oldWorld = cachedAuth.getWorld(); + + cachedAuth.setQuitLocX(auth.getQuitLocX()); + cachedAuth.setQuitLocY(auth.getQuitLocY()); + cachedAuth.setQuitLocZ(auth.getQuitLocZ()); + cachedAuth.setWorld(auth.getWorld()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateQuitLoc(auth)) { + if (cache.containsKey(auth.getNickname())) { + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + cachedAuth.setQuitLocX(oldX); + cachedAuth.setQuitLocY(oldY); + cachedAuth.setQuitLocZ(oldZ); + cachedAuth.setWorld(oldWorld); + } + } + } + }); + return true; } @Override public int getIps(String ip) { - return source.getIps(ip); + int count = 0; + for (Map.Entry p : cache.entrySet()) { + if (p.getValue().getIp().equals(ip)) { + count++; + } + } + return count; } @Override @@ -130,75 +187,133 @@ public class CacheDataSource implements DataSource { } @Override - public synchronized boolean removeAuth(String user) { - if (source.removeAuth(user)) { - cache.remove(user); - return true; - } - return false; + public synchronized boolean removeAuth(String username) { + final String user = username.toLowerCase(); + final PlayerAuth auth = cache.get(user); + cache.remove(user); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.removeAuth(user)) { + cache.put(user, auth); + } + } + }); + return true; } @Override public synchronized void close() { + exec.shutdown(); source.close(); } @Override public void reload() { - cache.clear(); - source.reload(); - for (Player player : Utils.getOnlinePlayers()) { - String user = player.getName().toLowerCase(); - if (PlayerCache.getInstance().isAuthenticated(user)) { - PlayerAuth auth = source.getAuth(user); - cache.put(user, auth); + exec.execute(new Runnable() { + @Override + public void run() { + cache.clear(); + source.reload(); + for (Player player : Utils.getOnlinePlayers()) { + String user = player.getName().toLowerCase(); + if (PlayerCache.getInstance().isAuthenticated(user)) { + PlayerAuth auth = source.getAuth(user); + cache.put(user, auth); + } + } } - } + }); } @Override - public synchronized boolean updateEmail(PlayerAuth auth) { - if (source.updateEmail(auth)) { - if (cache.containsKey(auth.getNickname())) - cache.get(auth.getNickname()).setEmail(auth.getEmail()); - return true; + public synchronized boolean updateEmail(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; } - return false; + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final String oldEmail = cachedAuth.getEmail(); + cachedAuth.setEmail(auth.getEmail()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateEmail(auth)) { + if (cache.containsKey(auth.getNickname())) { + cache.get(auth.getNickname()).setEmail(oldEmail); + } + } + } + }); + return true; } @Override - public synchronized boolean updateSalt(PlayerAuth auth) { - if (source.updateSalt(auth)) { - if (cache.containsKey(auth.getNickname())) - cache.get(auth.getNickname()).setSalt(auth.getSalt()); - return true; + public synchronized boolean updateSalt(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; } - return false; + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final String oldSalt = cachedAuth.getSalt(); + cachedAuth.setSalt(auth.getSalt()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateSalt(auth)) { + if (cache.containsKey(auth.getNickname())) { + cache.get(auth.getNickname()).setSalt(oldSalt); + } + } + } + }); + return true; } @Override public synchronized List getAllAuthsByName(PlayerAuth auth) { - return source.getAllAuthsByName(auth); + List result = new ArrayList<>(); + for (Map.Entry stringPlayerAuthEntry : cache.entrySet()) { + PlayerAuth p = stringPlayerAuthEntry.getValue(); + if (p.getIp().equals(auth.getIp())) + result.add(p.getNickname()); + } + return result; } @Override public synchronized List getAllAuthsByIp(String ip) { - return source.getAllAuthsByIp(ip); + List result = new ArrayList<>(); + for (Map.Entry stringPlayerAuthEntry : cache.entrySet()) { + PlayerAuth p = stringPlayerAuthEntry.getValue(); + if (p.getIp().equals(ip)) + result.add(p.getNickname()); + } + return result; } @Override public synchronized List getAllAuthsByEmail(String email) { - return source.getAllAuthsByEmail(email); + List result = new ArrayList<>(); + for (Map.Entry stringPlayerAuthEntry : cache.entrySet()) { + PlayerAuth p = stringPlayerAuthEntry.getValue(); + if (p.getEmail().equals(email)) + result.add(p.getNickname()); + } + return result; } @Override - public synchronized void purgeBanned(List banned) { - source.purgeBanned(banned); - for (PlayerAuth auth : cache.values()) { - if (banned.contains(auth.getNickname())) { - cache.remove(auth.getNickname()); + public synchronized void purgeBanned(final List banned) { + exec.execute(new Runnable() { + @Override + public void run() { + source.purgeBanned(banned); + for (PlayerAuth auth : cache.values()) { + if (banned.contains(auth.getNickname())) { + cache.remove(auth.getNickname()); + } + } } - } + }); } @Override @@ -208,45 +323,66 @@ public class CacheDataSource implements DataSource { @Override public boolean isLogged(String user) { - return source.isLogged(user.toLowerCase()); + user = user.toLowerCase(); + return PlayerCache.getInstance().getCache().containsKey(user); } @Override - public void setLogged(String user) { - source.setLogged(user.toLowerCase()); + public void setLogged(final String user) { + exec.execute(new Runnable() { + @Override + public void run() { + source.setLogged(user.toLowerCase()); + } + }); } @Override - public void setUnlogged(String user) { - source.setUnlogged(user.toLowerCase()); + public void setUnlogged(final String user) { + exec.execute(new Runnable() { + @Override + public void run() { + source.setUnlogged(user.toLowerCase()); + } + }); } @Override public void purgeLogged() { - source.purgeLogged(); + exec.execute(new Runnable() { + @Override + public void run() { + source.purgeLogged(); + } + }); } @Override public int getAccountsRegistered() { - return source.getAccountsRegistered(); + return cache.size(); } @Override - public void updateName(String oldone, String newone) { + public void updateName(final String oldone, final String newone) { if (cache.containsKey(oldone)) { cache.put(newone, cache.get(oldone)); cache.remove(oldone); } - source.updateName(oldone, newone); + exec.execute(new Runnable() { + @Override + public void run() { + source.updateName(oldone, newone); + } + }); } @Override public List getAllAuths() { - return source.getAllAuths(); + return new ArrayList<>(cache.values()); } @Override public List getLoggedPlayers() { - return source.getLoggedPlayers(); + return new ArrayList<>(PlayerCache.getInstance().getCache().values()); } } diff --git a/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java index 6b84c7d7..20cd97df 100644 --- a/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java +++ b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java @@ -4,7 +4,9 @@ import fr.xephi.authme.cache.auth.PlayerAuth; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; public class DatabaseCalls implements DataSource { @@ -214,13 +216,8 @@ public class DatabaseCalls implements DataSource { @Override public synchronized void close() { - try { - exec.shutdown(); - exec.awaitTermination(10, TimeUnit.SECONDS); - database.close(); - } catch (Exception e) { - e.printStackTrace(); - } + exec.shutdown(); + database.close(); } @Override From b61db5c56977eada7fd856504f98b2b79f563ff3 Mon Sep 17 00:00:00 2001 From: Ivan Ip Date: Mon, 28 Sep 2015 16:34:07 +0800 Subject: [PATCH 09/27] Simplified and updated strings. Modified some translation and proofread grammars, for players' easy-understanding. Also corrected some typo on color scheme. --- src/main/resources/messages/messages_zhhk.yml | 53 ++++++++++--------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/src/main/resources/messages/messages_zhhk.yml b/src/main/resources/messages/messages_zhhk.yml index b20ec71a..6cd67c6b 100644 --- a/src/main/resources/messages/messages_zhhk.yml +++ b/src/main/resources/messages/messages_zhhk.yml @@ -1,47 +1,48 @@ -# Translator: uSoc_lifehome (http://lifeho.me) # +# Translator: lifehome # +# Last modif: 1443428389 UTC # # -------------------------------------------- # -unknown_user: '&8[&6用戶系統&8] &f用戶資料並不存在於資料庫中。' +unknown_user: '&8[&6用戶系統&8] &f用戶資料並不存在。' unsafe_spawn: '&8[&6用戶系統&8] &f你的登出位置不安全,現在將傳送你到重生點。' not_logged_in: '&8[&6用戶系統&8] &c你還沒有登入 !' -reg_voluntarily: '&8[&6用戶系統&8] &f你可以使用這個的指令來註冊: 《 /register <密碼> <重覆密碼> 》' -usage_log: '&8[&6用戶系統&8] &c用法: 《 /login <密碼> 》' +reg_voluntarily: '&8[&6用戶系統&8] &f你可以使用這個指令來註冊: 《 /register <密碼> <重覆密碼> 》' +usage_log: '&8[&6用戶系統&8] &f用法: 《 /login <密碼> 》' wrong_pwd: '&8[&6用戶系統&8] &c你輸入了錯誤的密碼。' -unregistered: '&8[&6用戶系統&8] &c你已成功取消會員註冊記錄。' +unregistered: '&8[&6用戶系統&8] &c你已成功刪除會員註冊記錄。' reg_disabled: '&8[&6用戶系統&8] &c本伺服器已停止新玩家註冊。' -valid_session: '&8[&6用戶系統&8] &b嗨 ! 我記得你,歡迎回來~' -login: '&8[&6用戶系統&8] &c你成功的登入了。' -password_error_nick: '&fYou can''t use your name as password' -password_error_unsafe: '&fYou can''t use unsafe passwords' +valid_session: '&8[&6用戶系統&8] &b嗨 ! 歡迎回來喔~' +login: '&8[&6用戶系統&8] &c你成功登入了。' +password_error_nick: '&8[&6用戶系統&8] &c這個密碼太不安全了!' +password_error_unsafe: '&8[&6用戶系統&8] &c這個密碼太不安全了!' vb_nonActiv: '&8[&6用戶系統&8] &f你的帳戶還沒有經過電郵驗證 !' user_regged: '&8[&6用戶系統&8] &c此用戶名已經註冊過了。' -usage_reg: '&8[&6用戶系統&8] &c用法: 《 /register <密碼> <重覆密碼> 》' +usage_reg: '&8[&6用戶系統&8] &f用法: 《 /register <密碼> <重覆密碼> 》' max_reg: '&8[&6用戶系統&8] &f你的IP地址已達到註冊數上限。' no_perm: '&8[&6用戶系統&8] &b你可以到 CraftingHK 玩家百科中查看說明文件。' error: '&8[&6用戶系統&8] &f發生錯誤,請與管理員聯絡。' login_msg: '&8[&6用戶系統&8] &c請使用這個指令來登入: 《 /login <密碼> 》' -reg_msg: '&8[&6用戶系統&8] &c請使用這個的指令來註冊: 《 /register <密碼> <重覆密碼> 》' -reg_email_msg: '&8[&6用戶系統&8] &c請使用這個的指令來註冊: 《 /register <電郵> <重覆電郵> 》' -usage_unreg: '&8[&6用戶系統&8] &c用法: 《 /unregister <密碼> 》' -pwd_changed: '&8[&6用戶系統&8] &c你成功的更換了你的密碼 !' +reg_msg: '&8[&6用戶系統&8] &c請使用這個指令來註冊: 《 /register <密碼> <重覆密碼> 》' +reg_email_msg: '&8[&6用戶系統&8] &c請使用這個指令來註冊: 《 /register <電郵> <重覆電郵> 》' +usage_unreg: '&8[&6用戶系統&8] &f用法: 《 /unregister <密碼> 》' +pwd_changed: '&8[&6用戶系統&8] &c你成功更換了你的密碼 !' user_unknown: '&8[&6用戶系統&8] &c此用戶名沒有已登記資料。' password_error: '&8[&6用戶系統&8] &f密碼不符合。' invalid_session: '&8[&6用戶系統&8] &f登入階段資料已損壞,請等待登入階段結束。' -reg_only: '&8[&6用戶系統&8] &f限已註冊會員,請先到 https://www.example.com/ 註冊。' +reg_only: '&8[&6用戶系統&8] &f限已註冊會員,請先到 https://crafting.hk/ 註冊。' logged_in: '&8[&6用戶系統&8] &c你已經登入過了。' -logout: '&8[&6用戶系統&8] &b你成功的登出了。' +logout: '&8[&6用戶系統&8] &b你成功登出了。' same_nick: '&8[&6用戶系統&8] &f同名玩家已在遊玩。' -registered: '&8[&6用戶系統&8] &b你成功的註冊了。' +registered: '&8[&6用戶系統&8] &b你成功註冊了。' pass_len: '&8[&6用戶系統&8] &f你的密碼並不符合規定長度。' reload: '&8[&6用戶系統&8] &b登入系統設定及資料庫重新載入完畢。' timeout: '&8[&6用戶系統&8] &f登入逾時。' usage_changepassword: '&8[&6用戶系統&8] &f用法: 《 /changepassword <舊密碼> <新密碼> 》' name_len: '&8[&6用戶系統&8] &c你的用戶名不符合規定長度。' -regex: '&8[&6用戶系統&8] &c你的用戶名含有不容許之字符。以下為准許之字母: REG_EX' +regex: '&8[&6用戶系統&8] &c用戶名稱錯誤! 登入系統只接受以下字符: REG_EX' add_email: '&8[&6用戶系統&8] &b請為你的帳戶立即添加電郵地址: 《 /email add <電郵地址> <重覆電郵地址> 》' -recovery_email: '&8[&6用戶系統&8] &c忘記密碼 ? 請使用這個的指令來更新密碼: 《 /email recovery <電郵地址> 》' -usage_captcha: '&8[&6用戶系統&8] &c用法: 《 /captcha <驗證碼> 》' -wrong_captcha: '&8[&6用戶系統&8] &c你輸入了錯誤的驗證碼,請使用 《 /captcha <驗證碼> 》 再次輸入。' -valid_captcha: '&8[&6用戶系統&8] &c你所輸入的驗證碼是無效的 !' +recovery_email: '&8[&6用戶系統&8] &c忘記密碼 ? 請使用這個指令來更新密碼: 《 /email recovery <電郵地址> 》' +usage_captcha: '&8[&6用戶系統&8] &f用法: 《 /captcha <驗證碼> 》' +wrong_captcha: '&8[&6用戶系統&8] &c你所輸入的驗證碼無效,請使用 《 /captcha <驗證碼> 》 再次輸入。' +valid_captcha: '&8[&6用戶系統&8] &c你所輸入的驗證碼無效 !' kick_forvip: '&c因為有VIP玩家登入了伺服器。' kick_fullserver: '&c抱歉! 因為伺服器滿人了,所以你目前未能登入伺服器。' usage_email_add: '&8[&6用戶系統&8] &f用法: 《 /email add <電郵> <重覆電郵> 》' @@ -50,10 +51,10 @@ usage_email_recovery: '&8[&6用戶系統&8] &f用法: 《 /email recovery <電 new_email_invalid: '&8[&6用戶系統&8] 你所填寫的新電郵地址並不正確。' old_email_invalid: '&8[&6用戶系統&8] 你所填寫的舊電郵地址並不正確。' email_invalid: '&8[&6用戶系統&8] 你所填寫的電郵地址並不正確。' -email_added: '&8[&6用戶系統&8] 已加入你的電郵地址記錄。' +email_added: '&8[&6用戶系統&8] 已新增你的電郵地址。' email_confirm: '&8[&6用戶系統&8] 請重覆輸入你的電郵地址。' -email_changed: '&8[&6用戶系統&8] 你的電郵地址記錄已更改。' +email_changed: '&8[&6用戶系統&8] 你的電郵地址已更改。' email_send: '&8[&6用戶系統&8] 忘記密碼信件已寄出,請查收。' country_banned: '&8[&6用戶系統&8] 本伺服器已停止對你的國家提供遊戲服務。' -antibot_auto_enabled: '&8[&6用戶系統&8] 防止機械人程序已因應現時大量不尋常的連線而啟用。' -antibot_auto_disabled: '&8[&6用戶系統&8] 防止機械人程序檢查到不正常連接數已減少,並於 %m 分鐘後停止運作。' +antibot_auto_enabled: '&8[&6用戶系統&8] 防止機械人程序已因應現時大量不尋常連線而啟用。' +antibot_auto_disabled: '&8[&6用戶系統&8] 不正常連接數已減少,防止機械人程序將於 %m 分鐘後停止。' From 47f0f0e9271bb3c3bfe4c031a51746b93c6ddfac Mon Sep 17 00:00:00 2001 From: games647 Date: Mon, 28 Sep 2015 20:08:51 +0200 Subject: [PATCH 10/27] Fix duplicate registers --- pom.xml | 4 ++-- .../authme/process/register/AsyncronousRegister.java | 12 ++++-------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/pom.xml b/pom.xml index 87feaae4..da80a0d8 100644 --- a/pom.xml +++ b/pom.xml @@ -127,7 +127,7 @@ ess-repo - https://ci.drtshock.net/plugin/repository/everything + http://ci.drtshock.net/plugin/repository/everything @@ -257,7 +257,7 @@ - org.bukkit diff --git a/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java b/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java index 255c696d..cc516697 100644 --- a/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java @@ -67,14 +67,10 @@ public class AsyncronousRegister { allowRegister = false; } - else if (!Settings.unsafePasswords.isEmpty()) { - if (Settings.unsafePasswords.contains(password.toLowerCase())) { - m.send(player, "password_error_unsafe"); - allowRegister = false; - } - } - - else if (database.isAuthAvailable(name)) { + else if (!Settings.unsafePasswords.isEmpty() && Settings.unsafePasswords.contains(password.toLowerCase())) { + m.send(player, "password_error_unsafe"); + allowRegister = false; + } else if (database.isAuthAvailable(name)) { m.send(player, "user_regged"); allowRegister = false; } From d90183ca02b77bacafd5346f1776f0782de6bd46 Mon Sep 17 00:00:00 2001 From: "Gabriele C." Date: Mon, 28 Sep 2015 21:28:58 +0200 Subject: [PATCH 11/27] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3f12a0cc..bed52462 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@
#####Development tools: +- DEVELOPMENT TEAM REPO (please send PRs here!): Github Development Page + - Developers ChatRoom: [![Join the chat at https://gitter.im/Xephi/AuthMeReloaded](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Xephi/AuthMeReloaded?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - Build status: [![Build Status](https://travis-ci.org/Xephi/AuthMeReloaded.svg?branch=master)](https://travis-ci.org/Xephi/AuthMeReloaded) [![Dependency Status](https://www.versioneye.com/user/projects/55bab9e8653762002000190a/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55bab9e8653762002000190a) From 646eaad2ce7823a20cf7b163ddfbba4ae2da5bb8 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Mon, 28 Sep 2015 21:33:29 +0200 Subject: [PATCH 12/27] cleanup --- src/main/java/fr/xephi/authme/AuthMe.java | 1 + src/main/java/fr/xephi/authme/datasource/CacheDataSource.java | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 77a0e5c1..58d7b39d 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -107,6 +107,7 @@ public class AuthMe extends JavaPlugin { // TODO: split the plugin in more modules moduleManager = new ModuleManager(this); + @SuppressWarnings("unused") int loaded = moduleManager.loadModules(); // TODO: remove vault as hard dependency diff --git a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java index 08419710..f1298065 100644 --- a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java +++ b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java @@ -16,12 +16,10 @@ import java.util.concurrent.Executors; public class CacheDataSource implements DataSource { private final DataSource source; - private final AuthMe plugin; private final ExecutorService exec; private final ConcurrentHashMap cache = new ConcurrentHashMap<>(); public CacheDataSource(AuthMe pl, DataSource src) { - this.plugin = pl; this.source = src; this.exec = Executors.newCachedThreadPool(); From 4b1854c7e26166fda07163e22089718b262e528b Mon Sep 17 00:00:00 2001 From: games647 Date: Mon, 28 Sep 2015 20:06:36 +0200 Subject: [PATCH 13/27] Fix duplicate registers --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index da80a0d8..537a3084 100644 --- a/pom.xml +++ b/pom.xml @@ -121,7 +121,7 @@ spigot-repo - https://hub.spigotmc.org/nexus/content/groups/public + http://hub.spigotmc.org/nexus/content/groups/public From 34cc4ce78e045167b6ff92c12885eafeb25922ac Mon Sep 17 00:00:00 2001 From: games647 Date: Fri, 2 Oct 2015 21:56:46 +0200 Subject: [PATCH 14/27] Fix same nick kick if the name contains an upper case letter --- .../fr/xephi/authme/listener/AuthMePlayerListener.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java index 882ddcbd..6da8fb9d 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java @@ -208,13 +208,12 @@ public class AuthMePlayerListener implements Listener { public void onPreLogin(AsyncPlayerPreLoginEvent event) { final String name = event.getName().toLowerCase(); final Player player = Bukkit.getServer().getPlayer(name); - if (player == null) return; // Check if forceSingleSession is set to true, so kick player that has // joined with same nick of online player - if (plugin.dataManager.isOnline(player, name) && Settings.isForceSingleSessionEnabled) { + if (Settings.isForceSingleSessionEnabled && plugin.dataManager.isOnline(player, name)) { event.setKickMessage(m.send("same_nick")[0]); event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); if (LimboCache.getInstance().hasLimboPlayer(name)) @@ -228,7 +227,6 @@ public class AuthMePlayerListener implements Listener { LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase()); } } - }); } } @@ -283,7 +281,8 @@ public class AuthMePlayerListener implements Listener { if (isAuthAvailable && plugin.database.getType() != DataSource.DataSourceType.FILE) { PlayerAuth auth = plugin.database.getAuth(name); - if (auth.getRealName() != null && !auth.getRealName().isEmpty() && !auth.getRealName().equalsIgnoreCase("Player") && !auth.getRealName().equals(player.getName())) { + if (auth.getRealName() != null && !auth.getRealName().isEmpty() + && !auth.getRealName().equalsIgnoreCase("Player") && !auth.getRealName().equalsIgnoreCase(name)) { event.setKickMessage(m.send("same_nick")[0]); event.setResult(PlayerLoginEvent.Result.KICK_OTHER); if (Settings.banUnsafeIp) From ac92a58b759731459afa56f1e187a543abe0fdf3 Mon Sep 17 00:00:00 2001 From: "Gabriele C." Date: Fri, 2 Oct 2015 23:59:34 +0200 Subject: [PATCH 15/27] Update pom.xml --- pom.xml | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 537a3084..7f69ac97 100644 --- a/pom.xml +++ b/pom.xml @@ -56,7 +56,7 @@ . true - ${basedir}/src/main/resources/ + src/main/resources/ *.yml @@ -64,7 +64,7 @@ ./messages/ false - ${basedir}/src/main/resources/messages/ + src/main/resources/messages/ *.yml @@ -190,12 +190,14 @@ org.slf4j + true
org.slf4j slf4j-simple 1.7.12 compile + true @@ -204,6 +206,7 @@ sqlite-jdbc 3.8.11.1 compile + true @@ -212,6 +215,7 @@ gson 2.3.1 compile + true @@ -220,6 +224,7 @@ javax.mail-api 1.5.4 compile + true com.sun.mail @@ -232,6 +237,7 @@ javax.activation + true @@ -241,6 +247,7 @@ geoip-api 1.2.15 compile + true @@ -255,6 +262,7 @@ bukkit + true @@ -282,6 +291,7 @@ craftbukkit + true @@ -300,6 +310,7 @@ craftbukkit + true @@ -331,6 +342,7 @@ com.pneumaticraft.commandhandler + true @@ -345,6 +357,7 @@ spigot-api + true @@ -419,6 +432,7 @@ org.mcstats.bukkit + true @@ -457,6 +471,7 @@ com.mojang + true @@ -551,6 +566,7 @@ org.yi.acru.bukkit.lockette + true From 683ec09ecf8b1b470aa5f33109f57047f36315ed Mon Sep 17 00:00:00 2001 From: "Gabriele C." Date: Sat, 3 Oct 2015 00:49:59 +0200 Subject: [PATCH 16/27] Update team.txt --- team.txt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/team.txt b/team.txt index bb264888..427516ce 100644 --- a/team.txt +++ b/team.txt @@ -1,9 +1,12 @@ AuthMe-Team: Active staff: -Xephi (Xephi59) - Leader, Main developer -Gabriele C. (sgdc3) - Ticket Manager, Project Page and Structure Manager, Contributor +Xephi (Xephi59) - Leader, Main developer (temporary inactive) DNx5 - Developer +games647 - Developer +Gabriele C. (sgdc3) - Project Manager, Contributor + +Staff to contact: CryLegend - Contributor, AuthMeBridge Developer (Need activation) External Contributors: From a013a6c54f747d469e5bcd13fd1a202b88c5c2ba Mon Sep 17 00:00:00 2001 From: DNx5 Date: Sat, 3 Oct 2015 13:01:44 +0700 Subject: [PATCH 17/27] update Settings --- src/main/java/fr/xephi/authme/Utils.java | 3 ++- src/main/java/fr/xephi/authme/settings/Settings.java | 12 ++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/fr/xephi/authme/Utils.java b/src/main/java/fr/xephi/authme/Utils.java index bdd156ff..4abde79f 100644 --- a/src/main/java/fr/xephi/authme/Utils.java +++ b/src/main/java/fr/xephi/authme/Utils.java @@ -189,7 +189,8 @@ public class Utils { } public static boolean isUnrestricted(Player player) { - return Settings.isAllowRestrictedIp && !(Settings.getUnrestrictedName == null || Settings.getUnrestrictedName.isEmpty()) && (Settings.getUnrestrictedName.contains(player.getName())); + return Settings.isAllowRestrictedIp && !Settings.getUnrestrictedName.isEmpty() + && (Settings.getUnrestrictedName.contains(player.getName())); } private static boolean useGroupSystem() { diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index 24a72173..b43cf29b 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -119,7 +119,6 @@ public final class Settings extends YamlConfiguration { } - @SuppressWarnings("unchecked") public static void loadVariables() { messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en").toLowerCase()); isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false); @@ -185,7 +184,7 @@ public final class Settings extends YamlConfiguration { backupWindowsPath = configFile.getString("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\"); isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer", true); reloadSupport = configFile.getBoolean("Security.ReloadCommand.useReloadCommandSupport", true); - allowCommands = (List) configFile.getList("settings.restrictions.allowCommands"); + allowCommands = configFile.getStringList("settings.restrictions.allowCommands"); if (configFile.contains("allowCommands")) { if (!allowCommands.contains("/login")) allowCommands.add("/login"); @@ -210,7 +209,7 @@ public final class Settings extends YamlConfiguration { getmailSMTP = configFile.getString("Email.mailSMTP", "smtp.gmail.com"); getMailPort = configFile.getInt("Email.mailPort", 465); getRecoveryPassLength = configFile.getInt("Email.RecoveryPasswordLength", 8); - getMySQLOtherUsernameColumn = (List) configFile.getList("ExternalBoardOptions.mySQLOtherUsernameColumns", new ArrayList()); + getMySQLOtherUsernameColumn = configFile.getStringList("ExternalBoardOptions.mySQLOtherUsernameColumns"); displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true); getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id"); getmailSenderName = configFile.getString("Email.mailSenderName", ""); @@ -274,7 +273,7 @@ public final class Settings extends YamlConfiguration { emailBlacklist = configFile.getStringList("Email.emailBlacklisted"); emailWhitelist = configFile.getStringList("Email.emailWhitelisted"); forceRegisterCommands = configFile.getStringList("settings.forceRegisterCommands"); - forceRegisterCommandsAsConsole = (List) configFile.getList("settings.forceRegisterCommandsAsConsole", new ArrayList()); + forceRegisterCommandsAsConsole = configFile.getStringList("settings.forceRegisterCommandsAsConsole"); customAttributes = configFile.getBoolean("Hooks.customAttributes"); generateImage = configFile.getBoolean("Email.generateImage", true); @@ -289,7 +288,8 @@ public final class Settings extends YamlConfiguration { set("Xenoforo.predefinedSalt", null); changes = true; } - if (configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA1") || configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA256")) { + if (configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA1") || + configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA256")) { set("settings.security.passwordHash", "XENFORO"); changes = true; } @@ -462,7 +462,7 @@ public final class Settings extends YamlConfiguration { changes = true; } if (contains("Hooks.chestshop")) { - if(getBoolean("Hooks.chestshop")) { + if (getBoolean("Hooks.chestshop")) { set("Hooks.legacyChestshop", true); } set("Hooks.chestshop", null); From 86ff20b6c904a4d86c54ec52b5939c952b85443a Mon Sep 17 00:00:00 2001 From: games647 Date: Wed, 30 Sep 2015 18:55:41 +0200 Subject: [PATCH 18/27] Replacing old inventory protecting with safe packet modifications using ProtocolLib. Instead of clearing the inventory of players and storing it's contents in a file, we now prevent the server from sending the inventory packet if the player is not logged in. The player will see a empty inventory, but has still his items stored on the server. Therefore we don't need to modify the player's inventory and we won't make any inventory corrupted. Fixes Xephi/AuthMeReloaded#203, Fixes Xephi/AuthMeReloaded#193, Fixes Xephi/AuthMeReloaded#191, Fixes Xephi/AuthMeReloaded#148 Remove dead code + Fix empty inventory on the unregister command Fix NPE if ProtocolLib isn't enabled or installed --- pom.xml | 8 + src/main/java/fr/xephi/authme/AuthMe.java | 1571 +++++++++-------- .../authme/cache/backup/DataFileCache.java | 21 +- .../xephi/authme/cache/backup/JsonCache.java | 92 +- .../xephi/authme/cache/limbo/LimboCache.java | 23 +- .../xephi/authme/cache/limbo/LimboPlayer.java | 33 - .../authme/commands/UnregisterCommand.java | 6 +- .../authme/events/ProtectInventoryEvent.java | 9 +- .../authme/events/RestoreInventoryEvent.java | 16 +- .../authme/events/StoreInventoryEvent.java | 12 +- .../listener/AuthMeInventoryListener.java | 101 ++ .../authme/listener/AuthMeServerListener.java | 7 + .../authme/process/join/AsyncronousJoin.java | 611 ++++--- .../login/ProcessSyncronousPlayerLogin.java | 7 +- .../process/logout/AsyncronousLogout.java | 172 +- .../authme/process/quit/AsyncronousQuit.java | 203 +-- .../quit/ProcessSyncronousPlayerQuit.java | 97 +- .../ProcessSyncronousPasswordRegister.java | 8 +- src/main/resources/plugin.yml | 4 +- 19 files changed, 1464 insertions(+), 1537 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/listener/AuthMeInventoryListener.java diff --git a/pom.xml b/pom.xml index 7f69ac97..f797a2c6 100644 --- a/pom.xml +++ b/pom.xml @@ -294,6 +294,14 @@ true + + + com.comphenix.protocol + ProtocolLib + 3.4.0 + true + + net.milkbowl.vault diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 58d7b39d..efabc5de 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -1,781 +1,790 @@ -package fr.xephi.authme; - -import com.earth2me.essentials.Essentials; -import com.onarandombox.MultiverseCore.MultiverseCore; -import fr.xephi.authme.api.API; -import fr.xephi.authme.api.NewAPI; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.cache.backup.JsonCache; -import fr.xephi.authme.cache.limbo.LimboCache; -import fr.xephi.authme.cache.limbo.LimboPlayer; -import fr.xephi.authme.commands.*; -import fr.xephi.authme.converter.Converter; -import fr.xephi.authme.converter.ForceFlatToSqlite; -import fr.xephi.authme.datasource.*; -import fr.xephi.authme.listener.*; -import fr.xephi.authme.modules.ModuleManager; -import fr.xephi.authme.plugin.manager.BungeeCordMessage; -import fr.xephi.authme.plugin.manager.EssSpawn; -import fr.xephi.authme.process.Management; -import fr.xephi.authme.settings.Messages; -import fr.xephi.authme.settings.OtherAccounts; -import fr.xephi.authme.settings.Settings; -import fr.xephi.authme.settings.Spawn; -import net.milkbowl.vault.permission.Permission; -import net.minelink.ctplus.CombatTagPlus; -import org.apache.logging.log4j.LogManager; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitTask; -import org.mcstats.Metrics; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.net.URLConnection; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; - -public class AuthMe extends JavaPlugin { - - private static AuthMe authme; - - private final Server server = getServer(); - private final Logger authmeLogger = Logger.getLogger("AuthMe"); - public Management management; - public NewAPI api; - public SendMailSSL mail; - private Settings settings; - private Messages m; - public DataManager dataManager; - public DataSource database; - private JsonCache playerBackup; - public OtherAccounts otherAccounts; - public Location essentialsSpawn; - public boolean legacyChestShop = false; - public boolean antibotMod = false; - public boolean delayedAntiBot = true; - - // Hooks TODO: move into modules - public Permission permission; - public Essentials ess; - public MultiverseCore multiverse; - public CombatTagPlus combatTagPlus; - - // Manager - private ModuleManager moduleManager; - - // TODO: Create Manager for fields below - public ConcurrentHashMap sessions = new ConcurrentHashMap<>(); - public ConcurrentHashMap captcha = new ConcurrentHashMap<>(); - public ConcurrentHashMap cap = new ConcurrentHashMap<>(); - public ConcurrentHashMap realIp = new ConcurrentHashMap<>(); - - public static AuthMe getInstance() { - return authme; - } - - public Settings getSettings() { - return settings; - } - - public void setMessages(Messages m) { - this.m = m; - } - - public Messages getMessages() { - return m; - } - - - @Override - public void onEnable() { - // Set the Instance - authme = this; - - // TODO: split the plugin in more modules - moduleManager = new ModuleManager(this); - @SuppressWarnings("unused") - int loaded = moduleManager.loadModules(); - - // TODO: remove vault as hard dependency - PluginManager pm = server.getPluginManager(); - - // Setup the Logger - authmeLogger.setParent(this.getLogger()); - - // Load settings and custom configurations - // TODO: new configuration style (more files) - try { - settings = new Settings(this); - Settings.reload(); - } catch (Exception e) { - ConsoleLogger.writeStackTrace(e); - ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!"); - server.shutdown(); - return; - } - - // Setup otherAccounts file - otherAccounts = OtherAccounts.getInstance(); - - // Setup messages - m = Messages.getInstance(); - - // Start the metrics service - // TODO: add a setting to disable metrics - try { - Metrics metrics = new Metrics(this); - metrics.start(); - ConsoleLogger.info("Metrics started successfully!"); - } catch (Exception e) { - // Failed to submit the metrics data - ConsoleLogger.writeStackTrace(e); - ConsoleLogger.showError("Can't start Metrics! The plugin will work anyway..."); - } - - // Set Console Filter - if (Settings.removePassword) { - ConsoleFilter filter = new ConsoleFilter(); - this.getLogger().setFilter(filter); - Bukkit.getLogger().setFilter(filter); - Logger.getLogger("Minecraft").setFilter(filter); - authmeLogger.setFilter(filter); - // Set Log4J Filter - try { - Class.forName("org.apache.logging.log4j.core.Filter"); - setLog4JFilter(); - } catch (ClassNotFoundException | NoClassDefFoundError e) { - ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); - } - } - - // AntiBot delay - if (Settings.enableAntiBot) { - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { - - @Override - public void run() { - delayedAntiBot = false; - } - }, 2400); - } - - // Download GeoIp.dat file - Utils.checkGeoIP(); - - // Load MailApi if needed - if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty()) { - mail = new SendMailSSL(this); - } - - // Find Permissions - checkVault(); - - // Check Combat Tag Plus Version - checkCombatTagPlus(); - - // Check Multiverse - checkMultiverse(); - - // Check PerWorldInventories Version - checkPerWorldInventories(); - - // Check ChestShop - checkChestShop(); - - // Check Essentials - checkEssentials(); - - // Do backup on start if enabled - if (Settings.isBackupActivated && Settings.isBackupOnStart) { - // Do backup and check return value! - if (new PerformBackup(this).doBackup()) { - ConsoleLogger.info("Backup performed correctly"); - } else { - ConsoleLogger.showError("Error while performing the backup!"); - } - } - - // Connect to the database and setup tables - try { - setupDatabase(); - } catch (Exception e) { - ConsoleLogger.writeStackTrace(e); - ConsoleLogger.showError(e.getMessage()); - ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!"); - stopOrUnload(); - return; - } - - // Setup the inventory backup - playerBackup = new JsonCache(this); - - // Set the DataManager - dataManager = new DataManager(this); - - // Setup the new API - api = new NewAPI(this); - // Setup the old deprecated API - new API(this); - - // Setup Management - management = new Management(this); - - // Bungeecord hook - if (Settings.bungee) { - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); - } - - // Legacy chestshop hook - if (legacyChestShop) { - pm.registerEvents(new AuthMeChestShopListener(this), this); - ConsoleLogger.info("Hooked successfully with ChestShop!"); - } - - // Reload support hook - if (Settings.reloadSupport) { - if (database != null) { - int playersOnline = Utils.getOnlinePlayers().size(); - if (playersOnline < 1) { - database.purgeLogged(); - } else { - for (PlayerAuth auth : database.getLoggedPlayers()) { - if (auth == null) - continue; - auth.setLastLogin(new Date().getTime()); - database.updateSession(auth); - PlayerCache.getInstance().addPlayer(auth); - } - } - } - } - - // Register events - pm.registerEvents(new AuthMePlayerListener(this), this); - pm.registerEvents(new AuthMeBlockListener(this), this); - pm.registerEvents(new AuthMeEntityListener(this), this); - pm.registerEvents(new AuthMeServerListener(this), this); - - // Register commands - getCommand("authme").setExecutor(new AdminCommand(this)); - getCommand("register").setExecutor(new RegisterCommand(this)); - getCommand("login").setExecutor(new LoginCommand(this)); - getCommand("changepassword").setExecutor(new ChangePasswordCommand(this)); - getCommand("logout").setExecutor(new LogoutCommand(this)); - getCommand("unregister").setExecutor(new UnregisterCommand(this)); - getCommand("email").setExecutor(new EmailCommand(this)); - getCommand("captcha").setExecutor(new CaptchaCommand(this)); - getCommand("converter").setExecutor(new ConverterCommand(this)); - - // Purge on start if enabled - autoPurge(); - - // Start Email recall task if needed - recallEmail(); - - // Configuration Security Warnings - if (!Settings.isForceSingleSessionEnabled) { - ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); - } - if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) { - ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!"); - } - - // Sponsor messages - ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!"); - ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt."); - ConsoleLogger.info("Do you want a good gameserver? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!"); - - // Successful message - ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!"); - } - - @Override - public void onDisable() { - // Save player data - Collection players = Utils.getOnlinePlayers(); - if (players != null) { - for (Player player : players) { - this.savePlayer(player); - } - } - - // Close the database - if (database != null) { - database.close(); - } - - // Do backup on stop if enabled - if (Settings.isBackupActivated && Settings.isBackupOnStop) { - boolean Backup = new PerformBackup(this).doBackup(); - if (Backup) - ConsoleLogger.info("Backup performed correctly."); - else ConsoleLogger.showError("Error while performing the backup!"); - } - - // Unload modules - moduleManager.unloadModules(); - - // Disabled correctly - ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!"); - } - - // Stop/unload the server/plugin as defined in the configuration - public void stopOrUnload() { - if (Settings.isStopEnabled) { - ConsoleLogger.showError("THE SERVER IS GOING TO SHUTDOWN AS DEFINED IN THE CONFIGURATION!"); - server.shutdown(); - } else { - server.getPluginManager().disablePlugin(AuthMe.getInstance()); - } - } - - // Show the exception message and stop/unload the server/plugin as defined in the configuration - public void stopOrUnload(Exception e) { - ConsoleLogger.showError(e.getMessage()); - stopOrUnload(); - } - - // Initialize and setup the database - public void setupDatabase() throws Exception { - // Backend MYSQL - FILE - SQLITE - SQLITEHIKARI - boolean isSQLite = false; - switch (Settings.getDataSource) { - case FILE: - database = new FlatFile(); - break; - case MYSQL: - database = new MySQL(); - break; - case SQLITE: - database = new SQLite(); - isSQLite = true; - break; - case SQLITEHIKARI: - database = new SQLite_HIKARI(); - isSQLite = true; - break; - } - - if (isSQLite) { - server.getScheduler().runTaskAsynchronously(this, new Runnable() { - @Override - public void run() { - int accounts = database.getAccountsRegistered(); - if (accounts >= 4000) - ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + accounts + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!"); - } - }); - } - - if (Settings.isCachingEnabled) { - database = new CacheDataSource(this, database); - } else { - database = new DatabaseCalls(database); - } - - if (Settings.getDataSource == DataSource.DataSourceType.FILE) { - Converter converter = new ForceFlatToSqlite(database, this); - server.getScheduler().runTaskAsynchronously(this, converter); - ConsoleLogger.showError("FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !"); - ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart"); - } - } - - // Set the console filter to remove the passwords - private void setLog4JFilter() { - Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { - - @Override - public void run() { - org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); - coreLogger.addFilter(new Log4JFilter()); - } - }); - } - - // Check the presence of the Vault plugin and a permissions provider - public void checkVault() { - if (server.getPluginManager().isPluginEnabled("Vault")) { - RegisteredServiceProvider permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); - if (permissionProvider != null) { - permission = permissionProvider.getProvider(); - ConsoleLogger.info("Vault detected, hooking with the " + permission.getName() + " permissions system..."); - } else { - ConsoleLogger.showError("Vault detected, but I can't find any permissions plugin to hook with!"); - } - } else { - permission = null; - } - } - - // Check the version of the ChestShop plugin - public void checkChestShop() { - if (Settings.legacyChestShop && server.getPluginManager().isPluginEnabled("ChestShop")) { - String rawver = com.Acrobot.ChestShop.ChestShop.getVersion(); - double version; - try { - version = Double.valueOf(rawver.split(" ")[0]); - } catch (NumberFormatException nfe) { - try { - version = Double.valueOf(rawver.split("t")[0]); - } catch (NumberFormatException nfee) { - legacyChestShop = false; - return; - } - } - if (version >= 3.813) { - return; - } - if (version < 3.50) { - ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!"); - return; - } - legacyChestShop = true; - } else { - legacyChestShop = false; - } - } - - // Check PerWorldInventories version - public void checkPerWorldInventories() { - if (server.getPluginManager().isPluginEnabled("PerWorldInventories")) { - double version = 0; - String ver = server.getPluginManager().getPlugin("PerWorldInventories").getDescription().getVersion(); - try { - version = Double.valueOf(ver.split(" ")[0]); - } catch (NumberFormatException nfe) { - try { - version = Double.valueOf(ver.split("t")[0]); - } catch (NumberFormatException ignore) { - } - } - if (version < 1.57) { - ConsoleLogger.showError("Please Update your PerWorldInventories version! INVENTORY WIPE may occur!"); - } - } - } - - // Get the Multiverse plugin - public void checkMultiverse() { - if (Settings.multiverse && server.getPluginManager().isPluginEnabled("Multiverse-Core")) { - try { - multiverse = (MultiverseCore) server.getPluginManager().getPlugin("Multiverse-Core"); - ConsoleLogger.info("Hooked correctly with Multiverse-Core"); - } catch (Exception | NoClassDefFoundError ignored) { - multiverse = null; - } - } else { - multiverse = null; - } - } - - // Get the Essentials plugin - public void checkEssentials() { - if (server.getPluginManager().isPluginEnabled("Essentials")) { - try { - ess = (Essentials) server.getPluginManager().getPlugin("Essentials"); - ConsoleLogger.info("Hooked correctly with Essentials"); - } catch (Exception | NoClassDefFoundError ingnored) { - ess = null; - } - } else { - ess = null; - } - if (server.getPluginManager().isPluginEnabled("EssentialsSpawn")) { - try { - essentialsSpawn = new EssSpawn().getLocation(); - ConsoleLogger.info("Hooked correctly with EssentialsSpawn"); - } catch (Exception e) { - essentialsSpawn = null; - ConsoleLogger.showError("Can't read the /plugins/Essentials/spawn.yml file!"); - } - } else { - essentialsSpawn = null; - } - } - - // Check the presence of CombatTag - public void checkCombatTagPlus() { - if (server.getPluginManager().isPluginEnabled("CombatTagPlus")) { - try { - combatTagPlus = (CombatTagPlus) server.getPluginManager().getPlugin("CombatTagPlus"); - ConsoleLogger.info("Hooked correctly with CombatTagPlus"); - } catch (Exception | NoClassDefFoundError ingnored) { - combatTagPlus = null; - } - } else { - combatTagPlus = null; - } - } - - // Check if a player/command sender have a permission - public boolean authmePermissible(Player player, String perm) { - if (player.hasPermission(perm)) { - return true; - } else if (permission != null) { - return permission.playerHas(player, perm); - } - return false; - } - - public boolean authmePermissible(CommandSender sender, String perm) { - if (sender.hasPermission(perm)) { - return true; - } else if (permission != null) { - return permission.has(sender, perm); - } - return false; - } - - // Save Player Data - public void savePlayer(Player player) { - if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) { - return; - } - String name = player.getName().toLowerCase(); - if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) { - final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(), player.getName()); - database.updateQuitLoc(auth); - } - if (LimboCache.getInstance().hasLimboPlayer(name)) { - LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); - if (Settings.protectInventoryBeforeLogInEnabled) { - player.getInventory().setArmorContents(limbo.getArmour()); - player.getInventory().setContents(limbo.getInventory()); - } - if (!Settings.noTeleport) { - player.teleport(limbo.getLoc()); - } - Utils.addNormal(player, limbo.getGroup()); - player.setOp(limbo.getOperator()); - limbo.getTimeoutTaskId().cancel(); - LimboCache.getInstance().deleteLimboPlayer(name); - if (this.playerBackup.doesCacheExist(player)) { - this.playerBackup.removeCache(player); - } - } - PlayerCache.getInstance().removePlayer(name); - database.setUnlogged(name); - player.saveData(); - } - - // Select the player to kick when a vip player join the server when full - public Player generateKickPlayer(Collection collection) { - Player player = null; - for (Player p : collection) { - if (!(authmePermissible(p, "authme.vip"))) { - player = p; - break; - } - } - return player; - } - - // Purge inactive players from the database, as defined in the configuration - private void autoPurge() { - if (!Settings.usePurge) { - return; - } - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DATE, -(Settings.purgeDelay)); - long until = calendar.getTimeInMillis(); - List cleared = database.autoPurgeDatabase(until); - if (cleared == null) { - return; - } - if (cleared.isEmpty()) { - return; - } - ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!"); - if (Settings.purgeEssentialsFile && this.ess != null) - dataManager.purgeEssentials(cleared); // name to UUID convertion needed with latest versions - if (Settings.purgePlayerDat) - dataManager.purgeDat(cleared); // name to UUID convertion needed with latest versions of MC - if (Settings.purgeLimitedCreative) - dataManager.purgeLimitedCreative(cleared); - if (Settings.purgeAntiXray) - dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or names... (Actually it purges only names!) - if (Settings.purgePermissions) - dataManager.purgePermissions(cleared, permission); - } - - // Return the spawn location of a player - public Location getSpawnLocation(Player player) { - World world = player.getWorld(); - String[] spawnPriority = Settings.spawnPriority.split(","); - Location spawnLoc = world.getSpawnLocation(); - for (int i = spawnPriority.length - 1; i >= 0; i--) { - String s = spawnPriority[i]; - if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) - spawnLoc = getDefaultSpawn(world); - if (s.equalsIgnoreCase("multiverse") && getMultiverseSpawn(world) != null) - spawnLoc = getMultiverseSpawn(world); - if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null) - spawnLoc = getEssentialsSpawn(); - if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null) - spawnLoc = getAuthMeSpawn(player); - } - if (spawnLoc == null) { - spawnLoc = world.getSpawnLocation(); - } - return spawnLoc; - } - - // Return the default spawnpoint of a world - private Location getDefaultSpawn(World world) { - return world.getSpawnLocation(); - } - - // Return the multiverse spawnpoint of a world - private Location getMultiverseSpawn(World world) { - if (multiverse != null && Settings.multiverse) { - try { - return multiverse.getMVWorldManager().getMVWorld(world).getSpawnLocation(); - } catch (Exception e) { - e.printStackTrace(); - } - } - return null; - } - - // Return the essentials spawnpoint - private Location getEssentialsSpawn() { - if (essentialsSpawn != null) { - return essentialsSpawn; - } - return null; - } - - // Return the authme soawnpoint - private Location getAuthMeSpawn(Player player) { - if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) { - return Spawn.getInstance().getFirstSpawn(); - } - if (Spawn.getInstance().getSpawn() != null) { - return Spawn.getInstance().getSpawn(); - } - return player.getWorld().getSpawnLocation(); - } - - public void switchAntiBotMod(boolean mode) { - this.antibotMod = mode; - Settings.switchAntiBotMod(mode); - } - - private void recallEmail() { - if (!Settings.recallEmail) - return; - Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { - - @Override - public void run() { - for (Player player : Utils.getOnlinePlayers()) { - if (player.isOnline()) { - String name = player.getName().toLowerCase(); - if (database.isAuthAvailable(name)) - if (PlayerCache.getInstance().isAuthenticated(name)) { - String email = database.getAuth(name).getEmail(); - if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) - m.send(player, "add_email"); - } - } - } - } - }, 1, 1200 * Settings.delayRecall); - } - - public String replaceAllInfos(String message, Player player) { - int playersOnline = Utils.getOnlinePlayers().size(); - message = message.replace("&", "\u00a7"); - message = message.replace("{PLAYER}", player.getName()); - message = message.replace("{ONLINE}", "" + playersOnline); - message = message.replace("{MAXPLAYERS}", "" + server.getMaxPlayers()); - message = message.replace("{IP}", getIP(player)); - message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged()); - message = message.replace("{WORLD}", player.getWorld().getName()); - message = message.replace("{SERVER}", server.getServerName()); - message = message.replace("{VERSION}", server.getBukkitVersion()); - message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player))); - return message; - } - - public String getIP(Player player) { - String name = player.getName().toLowerCase(); - String ip = player.getAddress().getAddress().getHostAddress(); - if (Settings.bungee) { - if (realIp.containsKey(name)) - ip = realIp.get(name); - } - if (Settings.checkVeryGames) - if (getVeryGamesIP(player) != null) - ip = getVeryGamesIP(player); - return ip; - } - - public boolean isLoggedIp(String name, String ip) { - int count = 0; - for (Player player : Utils.getOnlinePlayers()) { - if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name)) - count++; - } - return count >= Settings.getMaxLoginPerIp; - } - - public boolean hasJoinedIp(String name, String ip) { - int count = 0; - for (Player player : Utils.getOnlinePlayers()) { - if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name)) - count++; - } - return count >= Settings.getMaxJoinPerIp; - } - - /** - * Get Player real IP through VeryGames method - * - * @param player player - */ - @Deprecated - public String getVeryGamesIP(Player player) { - String realIP = player.getAddress().getAddress().getHostAddress(); - String sUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%"; - sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort()); - try { - URL url = new URL(sUrl); - URLConnection urlc = url.openConnection(); - BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); - String inputLine = in.readLine(); - if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error") && !inputLine.contains("error")) { - realIP = inputLine; - } - } catch (Exception ignored) { - } - return realIP; - } - - @Deprecated - public String getCountryCode(String ip) { - return Utils.getCountryCode(ip); - } - - @Deprecated - public String getCountryName(String ip) { - return Utils.getCountryName(ip); - } - -} +package fr.xephi.authme; + +import com.comphenix.protocol.ProtocolLibrary; +import com.earth2me.essentials.Essentials; +import com.onarandombox.MultiverseCore.MultiverseCore; +import fr.xephi.authme.api.API; +import fr.xephi.authme.api.NewAPI; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.backup.JsonCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.commands.*; +import fr.xephi.authme.converter.Converter; +import fr.xephi.authme.converter.ForceFlatToSqlite; +import fr.xephi.authme.datasource.*; +import fr.xephi.authme.listener.*; +import fr.xephi.authme.modules.ModuleManager; +import fr.xephi.authme.plugin.manager.BungeeCordMessage; +import fr.xephi.authme.plugin.manager.EssSpawn; +import fr.xephi.authme.process.Management; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.OtherAccounts; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.Spawn; +import net.milkbowl.vault.permission.Permission; +import net.minelink.ctplus.CombatTagPlus; +import org.apache.logging.log4j.LogManager; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; +import org.mcstats.Metrics; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; + +public class AuthMe extends JavaPlugin { + + private static AuthMe authme; + + private final Server server = getServer(); + private final Logger authmeLogger = Logger.getLogger("AuthMe"); + public Management management; + public NewAPI api; + public SendMailSSL mail; + private Settings settings; + private Messages m; + public DataManager dataManager; + public DataSource database; + private JsonCache playerBackup; + public OtherAccounts otherAccounts; + public Location essentialsSpawn; + public boolean legacyChestShop = false; + public boolean antibotMod = false; + public boolean delayedAntiBot = true; + + // Hooks TODO: move into modules + public Permission permission; + public Essentials ess; + public MultiverseCore multiverse; + public CombatTagPlus combatTagPlus; + public AuthMeInventoryListener inventoryProtector; + + // Manager + private ModuleManager moduleManager; + + // TODO: Create Manager for fields below + public ConcurrentHashMap sessions = new ConcurrentHashMap<>(); + public ConcurrentHashMap captcha = new ConcurrentHashMap<>(); + public ConcurrentHashMap cap = new ConcurrentHashMap<>(); + public ConcurrentHashMap realIp = new ConcurrentHashMap<>(); + + public static AuthMe getInstance() { + return authme; + } + + public Settings getSettings() { + return settings; + } + + public void setMessages(Messages m) { + this.m = m; + } + + public Messages getMessages() { + return m; + } + + + @Override + public void onEnable() { + // Set the Instance + authme = this; + + // TODO: split the plugin in more modules + moduleManager = new ModuleManager(this); + @SuppressWarnings("unused") + int loaded = moduleManager.loadModules(); + + // TODO: remove vault as hard dependency + PluginManager pm = server.getPluginManager(); + + // Setup the Logger + authmeLogger.setParent(this.getLogger()); + + // Load settings and custom configurations + // TODO: new configuration style (more files) + try { + settings = new Settings(this); + Settings.reload(); + } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!"); + server.shutdown(); + return; + } + + // Setup otherAccounts file + otherAccounts = OtherAccounts.getInstance(); + + // Setup messages + m = Messages.getInstance(); + + // Start the metrics service + // TODO: add a setting to disable metrics + try { + Metrics metrics = new Metrics(this); + metrics.start(); + ConsoleLogger.info("Metrics started successfully!"); + } catch (Exception e) { + // Failed to submit the metrics data + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError("Can't start Metrics! The plugin will work anyway..."); + } + + // Set Console Filter + if (Settings.removePassword) { + ConsoleFilter filter = new ConsoleFilter(); + this.getLogger().setFilter(filter); + Bukkit.getLogger().setFilter(filter); + Logger.getLogger("Minecraft").setFilter(filter); + authmeLogger.setFilter(filter); + // Set Log4J Filter + try { + Class.forName("org.apache.logging.log4j.core.Filter"); + setLog4JFilter(); + } catch (ClassNotFoundException | NoClassDefFoundError e) { + ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); + } + } + + // AntiBot delay + if (Settings.enableAntiBot) { + Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + @Override + public void run() { + delayedAntiBot = false; + } + }, 2400); + } + + // Download GeoIp.dat file + Utils.checkGeoIP(); + + // Load MailApi if needed + if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty()) { + mail = new SendMailSSL(this); + } + + // Find Permissions + checkVault(); + + // Check Combat Tag Plus Version + checkCombatTagPlus(); + + // Check Multiverse + checkMultiverse(); + + // Check PerWorldInventories Version + checkPerWorldInventories(); + + // Check ChestShop + checkChestShop(); + + // Check Essentials + checkEssentials(); + + //Check if the protocollib is available. If so we could listen for inventory protection + checkProtocolLib(); + + // Do backup on start if enabled + if (Settings.isBackupActivated && Settings.isBackupOnStart) { + // Do backup and check return value! + if (new PerformBackup(this).doBackup()) { + ConsoleLogger.info("Backup performed correctly"); + } else { + ConsoleLogger.showError("Error while performing the backup!"); + } + } + + // Connect to the database and setup tables + try { + setupDatabase(); + } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError(e.getMessage()); + ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!"); + stopOrUnload(); + return; + } + + // Setup the inventory backup + playerBackup = new JsonCache(); + + // Set the DataManager + dataManager = new DataManager(this); + + // Setup the new API + api = new NewAPI(this); + // Setup the old deprecated API + new API(this); + + // Setup Management + management = new Management(this); + + // Bungeecord hook + if (Settings.bungee) { + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); + } + + // Legacy chestshop hook + if (legacyChestShop) { + pm.registerEvents(new AuthMeChestShopListener(this), this); + ConsoleLogger.info("Hooked successfully with ChestShop!"); + } + + // Reload support hook + if (Settings.reloadSupport) { + if (database != null) { + int playersOnline = Utils.getOnlinePlayers().size(); + if (playersOnline < 1) { + database.purgeLogged(); + } else { + for (PlayerAuth auth : database.getLoggedPlayers()) { + if (auth == null) + continue; + auth.setLastLogin(new Date().getTime()); + database.updateSession(auth); + PlayerCache.getInstance().addPlayer(auth); + } + } + } + } + + // Register events + pm.registerEvents(new AuthMePlayerListener(this), this); + pm.registerEvents(new AuthMeBlockListener(this), this); + pm.registerEvents(new AuthMeEntityListener(this), this); + pm.registerEvents(new AuthMeServerListener(this), this); + + // Register commands + getCommand("authme").setExecutor(new AdminCommand(this)); + getCommand("register").setExecutor(new RegisterCommand(this)); + getCommand("login").setExecutor(new LoginCommand(this)); + getCommand("changepassword").setExecutor(new ChangePasswordCommand(this)); + getCommand("logout").setExecutor(new LogoutCommand(this)); + getCommand("unregister").setExecutor(new UnregisterCommand(this)); + getCommand("email").setExecutor(new EmailCommand(this)); + getCommand("captcha").setExecutor(new CaptchaCommand(this)); + getCommand("converter").setExecutor(new ConverterCommand(this)); + + // Purge on start if enabled + autoPurge(); + + // Start Email recall task if needed + recallEmail(); + + // Configuration Security Warnings + if (!Settings.isForceSingleSessionEnabled) { + ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); + } + if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) { + ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!"); + } + + // Sponsor messages + ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!"); + ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt."); + ConsoleLogger.info("Do you want a good gameserver? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!"); + + // Successful message + ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!"); + } + + @Override + public void onDisable() { + // Save player data + Collection players = Utils.getOnlinePlayers(); + if (players != null) { + for (Player player : players) { + this.savePlayer(player); + } + } + + // Close the database + if (database != null) { + database.close(); + } + + // Do backup on stop if enabled + if (Settings.isBackupActivated && Settings.isBackupOnStop) { + boolean Backup = new PerformBackup(this).doBackup(); + if (Backup) + ConsoleLogger.info("Backup performed correctly."); + else ConsoleLogger.showError("Error while performing the backup!"); + } + + // Unload modules + moduleManager.unloadModules(); + + // Disabled correctly + ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!"); + } + + // Stop/unload the server/plugin as defined in the configuration + public void stopOrUnload() { + if (Settings.isStopEnabled) { + ConsoleLogger.showError("THE SERVER IS GOING TO SHUTDOWN AS DEFINED IN THE CONFIGURATION!"); + server.shutdown(); + } else { + server.getPluginManager().disablePlugin(AuthMe.getInstance()); + } + } + + // Show the exception message and stop/unload the server/plugin as defined in the configuration + public void stopOrUnload(Exception e) { + ConsoleLogger.showError(e.getMessage()); + stopOrUnload(); + } + + // Initialize and setup the database + public void setupDatabase() throws Exception { + // Backend MYSQL - FILE - SQLITE - SQLITEHIKARI + boolean isSQLite = false; + switch (Settings.getDataSource) { + case FILE: + database = new FlatFile(); + break; + case MYSQL: + database = new MySQL(); + break; + case SQLITE: + database = new SQLite(); + isSQLite = true; + break; + case SQLITEHIKARI: + database = new SQLite_HIKARI(); + isSQLite = true; + break; + } + + if (isSQLite) { + server.getScheduler().runTaskAsynchronously(this, new Runnable() { + @Override + public void run() { + int accounts = database.getAccountsRegistered(); + if (accounts >= 4000) + ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + accounts + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!"); + } + }); + } + + if (Settings.isCachingEnabled) { + database = new CacheDataSource(this, database); + } else { + database = new DatabaseCalls(database); + } + + if (Settings.getDataSource == DataSource.DataSourceType.FILE) { + Converter converter = new ForceFlatToSqlite(database, this); + server.getScheduler().runTaskAsynchronously(this, converter); + ConsoleLogger.showError("FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !"); + ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart"); + } + } + + // Set the console filter to remove the passwords + private void setLog4JFilter() { + Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + @Override + public void run() { + org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); + coreLogger.addFilter(new Log4JFilter()); + } + }); + } + + // Check the presence of the Vault plugin and a permissions provider + public void checkVault() { + if (server.getPluginManager().isPluginEnabled("Vault")) { + RegisteredServiceProvider permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); + if (permissionProvider != null) { + permission = permissionProvider.getProvider(); + ConsoleLogger.info("Vault detected, hooking with the " + permission.getName() + " permissions system..."); + } else { + ConsoleLogger.showError("Vault detected, but I can't find any permissions plugin to hook with!"); + } + } else { + permission = null; + } + } + + // Check the version of the ChestShop plugin + public void checkChestShop() { + if (Settings.legacyChestShop && server.getPluginManager().isPluginEnabled("ChestShop")) { + String rawver = com.Acrobot.ChestShop.ChestShop.getVersion(); + double version; + try { + version = Double.valueOf(rawver.split(" ")[0]); + } catch (NumberFormatException nfe) { + try { + version = Double.valueOf(rawver.split("t")[0]); + } catch (NumberFormatException nfee) { + legacyChestShop = false; + return; + } + } + if (version >= 3.813) { + return; + } + if (version < 3.50) { + ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!"); + return; + } + legacyChestShop = true; + } else { + legacyChestShop = false; + } + } + + // Check PerWorldInventories version + public void checkPerWorldInventories() { + if (server.getPluginManager().isPluginEnabled("PerWorldInventories")) { + double version = 0; + String ver = server.getPluginManager().getPlugin("PerWorldInventories").getDescription().getVersion(); + try { + version = Double.valueOf(ver.split(" ")[0]); + } catch (NumberFormatException nfe) { + try { + version = Double.valueOf(ver.split("t")[0]); + } catch (NumberFormatException ignore) { + } + } + if (version < 1.57) { + ConsoleLogger.showError("Please Update your PerWorldInventories version! INVENTORY WIPE may occur!"); + } + } + } + + // Get the Multiverse plugin + public void checkMultiverse() { + if (Settings.multiverse && server.getPluginManager().isPluginEnabled("Multiverse-Core")) { + try { + multiverse = (MultiverseCore) server.getPluginManager().getPlugin("Multiverse-Core"); + ConsoleLogger.info("Hooked correctly with Multiverse-Core"); + } catch (Exception | NoClassDefFoundError ignored) { + multiverse = null; + } + } else { + multiverse = null; + } + } + + // Get the Essentials plugin + public void checkEssentials() { + if (server.getPluginManager().isPluginEnabled("Essentials")) { + try { + ess = (Essentials) server.getPluginManager().getPlugin("Essentials"); + ConsoleLogger.info("Hooked correctly with Essentials"); + } catch (Exception | NoClassDefFoundError ingnored) { + ess = null; + } + } else { + ess = null; + } + if (server.getPluginManager().isPluginEnabled("EssentialsSpawn")) { + try { + essentialsSpawn = new EssSpawn().getLocation(); + ConsoleLogger.info("Hooked correctly with EssentialsSpawn"); + } catch (Exception e) { + essentialsSpawn = null; + ConsoleLogger.showError("Can't read the /plugins/Essentials/spawn.yml file!"); + } + } else { + essentialsSpawn = null; + } + } + + // Check the presence of CombatTag + public void checkCombatTagPlus() { + if (server.getPluginManager().isPluginEnabled("CombatTagPlus")) { + try { + combatTagPlus = (CombatTagPlus) server.getPluginManager().getPlugin("CombatTagPlus"); + ConsoleLogger.info("Hooked correctly with CombatTagPlus"); + } catch (Exception | NoClassDefFoundError ingnored) { + combatTagPlus = null; + } + } else { + combatTagPlus = null; + } + } + + public void checkProtocolLib() { + if (server.getPluginManager().isPluginEnabled("ProtocolLib")) { + inventoryProtector = new AuthMeInventoryListener(this); + ProtocolLibrary.getProtocolManager().addPacketListener(inventoryProtector); + } + } + + // Check if a player/command sender have a permission + public boolean authmePermissible(Player player, String perm) { + if (player.hasPermission(perm)) { + return true; + } else if (permission != null) { + return permission.playerHas(player, perm); + } + return false; + } + + public boolean authmePermissible(CommandSender sender, String perm) { + if (sender.hasPermission(perm)) { + return true; + } else if (permission != null) { + return permission.has(sender, perm); + } + return false; + } + + // Save Player Data + public void savePlayer(Player player) { + if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) { + return; + } + String name = player.getName().toLowerCase(); + if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) { + final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(), player.getName()); + database.updateQuitLoc(auth); + } + if (LimboCache.getInstance().hasLimboPlayer(name)) { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (!Settings.noTeleport) { + player.teleport(limbo.getLoc()); + } + + Utils.addNormal(player, limbo.getGroup()); + player.setOp(limbo.getOperator()); + limbo.getTimeoutTaskId().cancel(); + LimboCache.getInstance().deleteLimboPlayer(name); + if (this.playerBackup.doesCacheExist(player)) { + this.playerBackup.removeCache(player); + } + } + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + player.saveData(); + } + + // Select the player to kick when a vip player join the server when full + public Player generateKickPlayer(Collection collection) { + Player player = null; + for (Player p : collection) { + if (!(authmePermissible(p, "authme.vip"))) { + player = p; + break; + } + } + return player; + } + + // Purge inactive players from the database, as defined in the configuration + private void autoPurge() { + if (!Settings.usePurge) { + return; + } + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.DATE, -(Settings.purgeDelay)); + long until = calendar.getTimeInMillis(); + List cleared = database.autoPurgeDatabase(until); + if (cleared == null) { + return; + } + if (cleared.isEmpty()) { + return; + } + ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!"); + if (Settings.purgeEssentialsFile && this.ess != null) + dataManager.purgeEssentials(cleared); // name to UUID convertion needed with latest versions + if (Settings.purgePlayerDat) + dataManager.purgeDat(cleared); // name to UUID convertion needed with latest versions of MC + if (Settings.purgeLimitedCreative) + dataManager.purgeLimitedCreative(cleared); + if (Settings.purgeAntiXray) + dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or names... (Actually it purges only names!) + if (Settings.purgePermissions) + dataManager.purgePermissions(cleared, permission); + } + + // Return the spawn location of a player + public Location getSpawnLocation(Player player) { + World world = player.getWorld(); + String[] spawnPriority = Settings.spawnPriority.split(","); + Location spawnLoc = world.getSpawnLocation(); + for (int i = spawnPriority.length - 1; i >= 0; i--) { + String s = spawnPriority[i]; + if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) + spawnLoc = getDefaultSpawn(world); + if (s.equalsIgnoreCase("multiverse") && getMultiverseSpawn(world) != null) + spawnLoc = getMultiverseSpawn(world); + if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null) + spawnLoc = getEssentialsSpawn(); + if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null) + spawnLoc = getAuthMeSpawn(player); + } + if (spawnLoc == null) { + spawnLoc = world.getSpawnLocation(); + } + return spawnLoc; + } + + // Return the default spawnpoint of a world + private Location getDefaultSpawn(World world) { + return world.getSpawnLocation(); + } + + // Return the multiverse spawnpoint of a world + private Location getMultiverseSpawn(World world) { + if (multiverse != null && Settings.multiverse) { + try { + return multiverse.getMVWorldManager().getMVWorld(world).getSpawnLocation(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } + + // Return the essentials spawnpoint + private Location getEssentialsSpawn() { + if (essentialsSpawn != null) { + return essentialsSpawn; + } + return null; + } + + // Return the authme soawnpoint + private Location getAuthMeSpawn(Player player) { + if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) { + return Spawn.getInstance().getFirstSpawn(); + } + if (Spawn.getInstance().getSpawn() != null) { + return Spawn.getInstance().getSpawn(); + } + return player.getWorld().getSpawnLocation(); + } + + public void switchAntiBotMod(boolean mode) { + this.antibotMod = mode; + Settings.switchAntiBotMod(mode); + } + + private void recallEmail() { + if (!Settings.recallEmail) + return; + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { + + @Override + public void run() { + for (Player player : Utils.getOnlinePlayers()) { + if (player.isOnline()) { + String name = player.getName().toLowerCase(); + if (database.isAuthAvailable(name)) + if (PlayerCache.getInstance().isAuthenticated(name)) { + String email = database.getAuth(name).getEmail(); + if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) + m.send(player, "add_email"); + } + } + } + } + }, 1, 1200 * Settings.delayRecall); + } + + public String replaceAllInfos(String message, Player player) { + int playersOnline = Utils.getOnlinePlayers().size(); + message = message.replace("&", "\u00a7"); + message = message.replace("{PLAYER}", player.getName()); + message = message.replace("{ONLINE}", "" + playersOnline); + message = message.replace("{MAXPLAYERS}", "" + server.getMaxPlayers()); + message = message.replace("{IP}", getIP(player)); + message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged()); + message = message.replace("{WORLD}", player.getWorld().getName()); + message = message.replace("{SERVER}", server.getServerName()); + message = message.replace("{VERSION}", server.getBukkitVersion()); + message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player))); + return message; + } + + public String getIP(Player player) { + String name = player.getName().toLowerCase(); + String ip = player.getAddress().getAddress().getHostAddress(); + if (Settings.bungee) { + if (realIp.containsKey(name)) + ip = realIp.get(name); + } + if (Settings.checkVeryGames) + if (getVeryGamesIP(player) != null) + ip = getVeryGamesIP(player); + return ip; + } + + public boolean isLoggedIp(String name, String ip) { + int count = 0; + for (Player player : Utils.getOnlinePlayers()) { + if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name)) + count++; + } + return count >= Settings.getMaxLoginPerIp; + } + + public boolean hasJoinedIp(String name, String ip) { + int count = 0; + for (Player player : Utils.getOnlinePlayers()) { + if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name)) + count++; + } + return count >= Settings.getMaxJoinPerIp; + } + + /** + * Get Player real IP through VeryGames method + * + * @param player player + */ + @Deprecated + public String getVeryGamesIP(Player player) { + String realIP = player.getAddress().getAddress().getHostAddress(); + String sUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%"; + sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort()); + try { + URL url = new URL(sUrl); + URLConnection urlc = url.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); + String inputLine = in.readLine(); + if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error") && !inputLine.contains("error")) { + realIP = inputLine; + } + } catch (Exception ignored) { + } + return realIP; + } + + @Deprecated + public String getCountryCode(String ip) { + return Utils.getCountryCode(ip); + } + + @Deprecated + public String getCountryName(String ip) { + return Utils.getCountryName(ip); + } + +} diff --git a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java index 6644166f..5aa40dde 100644 --- a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java +++ b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java @@ -1,36 +1,17 @@ package fr.xephi.authme.cache.backup; -import org.bukkit.inventory.ItemStack; - public class DataFileCache { - private ItemStack[] inventory; - private ItemStack[] armor; private String group; private boolean operator; private boolean flying; - public DataFileCache(ItemStack[] inventory, ItemStack[] armor) { - this(inventory, armor, "", false, false); - } - - public DataFileCache(ItemStack[] inventory, ItemStack[] armor, - String group, boolean operator, boolean flying) { - this.inventory = inventory; - this.armor = armor; + public DataFileCache(String group, boolean operator, boolean flying) { this.group = group; this.operator = operator; this.flying = flying; } - public ItemStack[] getInventory() { - return inventory; - } - - public ItemStack[] getArmour() { - return armor; - } - public String getGroup() { return group; } diff --git a/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java index 760def96..1e66e0aa 100644 --- a/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java +++ b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java @@ -3,20 +3,13 @@ package fr.xephi.authme.cache.backup; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.gson.*; -import fr.xephi.authme.AuthMe; + import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.Utils; import fr.xephi.authme.settings.Settings; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; -import org.bukkit.util.io.BukkitObjectInputStream; -import org.bukkit.util.io.BukkitObjectOutputStream; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import org.bukkit.entity.Player; + import java.io.File; import java.io.IOException; import java.lang.reflect.Type; @@ -24,11 +17,9 @@ import java.lang.reflect.Type; public class JsonCache { private final Gson gson; - private final AuthMe plugin; private final File cacheDir; - public JsonCache(AuthMe plugin) { - this.plugin = plugin; + public JsonCache() { cacheDir = Settings.CACHE_FOLDER; if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) { ConsoleLogger.showError("Failed to create cache directory."); @@ -99,49 +90,8 @@ public class JsonCache { jsonObject.addProperty("operator", dataFileCache.getOperator()); jsonObject.addProperty("flying", dataFileCache.isFlying()); - JsonArray arr; - ItemStack[] contents; - - // inventory - contents = dataFileCache.getInventory(); - arr = new JsonArray(); - putItems(contents, arr); - jsonObject.add("inventory", arr); - - // armour - contents = dataFileCache.getArmour(); - arr = new JsonArray(); - putItems(contents, arr); - jsonObject.add("armour", arr); - return jsonObject; } - - private void putItems(ItemStack[] contents, JsonArray target) { - for (ItemStack item : contents) { - if (item == null) { - item = new ItemStack(Material.AIR); - } - JsonObject val = new JsonObject(); - if (item.getType() == Material.SKULL_ITEM) { - SkullMeta meta = (SkullMeta) item.getItemMeta(); - if (meta.hasOwner() && (meta.getOwner() == null || meta.getOwner().isEmpty())) { - item.setItemMeta(plugin.getServer().getItemFactory().getItemMeta(Material.SKULL_ITEM)); - } - } - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - BukkitObjectOutputStream objectOut = new BukkitObjectOutputStream(baos); - objectOut.writeObject(item); - objectOut.close(); - val.addProperty("item", Base64Coder.encodeLines(baos.toByteArray())); - } catch (IOException e) { - e.printStackTrace(); - continue; - } - target.add(val); - } - } } private static class PlayerDataDeserializer implements JsonDeserializer { @@ -166,39 +116,7 @@ public class JsonCache { flying = e.getAsBoolean(); } - JsonArray arr; - ItemStack[] inv = null; - ItemStack[] armour = null; - - if (jsonObject.has("inventory")) { - arr = jsonObject.get("inventory").getAsJsonArray(); - inv = getItems(arr); - } - - if (jsonObject.has("armour")) { - arr = jsonObject.get("armour").getAsJsonArray(); - armour = getItems(arr); - } - - return new DataFileCache(inv, armour, group, operator, flying); - } - - private ItemStack[] getItems(JsonArray arr) { - ItemStack[] contents = new ItemStack[arr.size()]; - for (int i = 0; i < arr.size(); i++) { - JsonObject item = arr.get(i).getAsJsonObject(); - String encoded = item.get("item").getAsString(); - byte[] decoded = Base64Coder.decodeLines(encoded); - try { - ByteArrayInputStream baos = new ByteArrayInputStream(decoded); - BukkitObjectInputStream objectIn = new BukkitObjectInputStream(baos); - contents[i] = (ItemStack) objectIn.readObject(); - objectIn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - return contents; + return new DataFileCache(group, operator, flying); } } diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java index 366bc60a..1ab123b6 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java @@ -11,7 +11,6 @@ import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import java.util.concurrent.ConcurrentHashMap; @@ -25,15 +24,13 @@ public class LimboCache { private LimboCache(AuthMe plugin) { this.plugin = plugin; this.cache = new ConcurrentHashMap<>(); - this.playerData = new JsonCache(plugin); + this.playerData = new JsonCache(); } public void addLimboPlayer(Player player) { String name = player.getName().toLowerCase(); Location loc = player.getLocation(); GameMode gameMode = player.getGameMode(); - ItemStack[] arm; - ItemStack[] inv; boolean operator = false; String playerGroup = ""; boolean flying = false; @@ -42,12 +39,10 @@ public class LimboCache { final StoreInventoryEvent event = new StoreInventoryEvent(player, playerData); Bukkit.getServer().getPluginManager().callEvent(event); if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) { - inv = event.getInventory(); - arm = event.getArmor(); - } else { - inv = null; - arm = null; + player.getInventory().setContents(event.getInventory()); + player.getInventory().setArmorContents(event.getArmor()); } + DataFileCache cache = playerData.readCache(player); if (cache != null) { playerGroup = cache.getGroup(); @@ -58,12 +53,10 @@ public class LimboCache { StoreInventoryEvent event = new StoreInventoryEvent(player); Bukkit.getServer().getPluginManager().callEvent(event); if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) { - inv = event.getInventory(); - arm = event.getArmor(); - } else { - inv = null; - arm = null; + player.getInventory().setContents(event.getInventory()); + player.getInventory().setArmorContents(event.getArmor()); } + operator = player.isOp(); flying = player.isFlying(); if (plugin.permission != null) { @@ -93,7 +86,7 @@ public class LimboCache { if (player.isDead()) { loc = plugin.getSpawnLocation(player); } - cache.put(name, new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup, flying)); + cache.put(name, new LimboPlayer(name, loc, gameMode, operator, playerGroup, flying)); } public void addLimboPlayer(Player player, String group) { diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java index 702ddb38..f4ae0466 100644 --- a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java @@ -2,14 +2,11 @@ package fr.xephi.authme.cache.limbo; import org.bukkit.GameMode; import org.bukkit.Location; -import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitTask; public class LimboPlayer { private String name; - private ItemStack[] inventory; - private ItemStack[] armour; private Location loc = null; private BukkitTask timeoutTaskId = null; private BukkitTask messageTaskId = null; @@ -18,19 +15,6 @@ public class LimboPlayer { private String group = ""; private boolean flying = false; - public LimboPlayer(String name, Location loc, ItemStack[] inventory, - ItemStack[] armour, GameMode gameMode, boolean operator, - String group, boolean flying) { - this.name = name; - this.loc = loc; - this.inventory = inventory; - this.armour = armour; - this.gameMode = gameMode; - this.operator = operator; - this.group = group; - this.flying = flying; - } - public LimboPlayer(String name, Location loc, GameMode gameMode, boolean operator, String group, boolean flying) { this.name = name; @@ -54,22 +38,6 @@ public class LimboPlayer { return loc; } - public ItemStack[] getArmour() { - return armour; - } - - public ItemStack[] getInventory() { - return inventory; - } - - public void setArmour(ItemStack[] armour) { - this.armour = armour; - } - - public void setInventory(ItemStack[] inventory) { - this.inventory = inventory; - } - public GameMode getGameMode() { return gameMode; } @@ -105,5 +73,4 @@ public class LimboPlayer { public boolean isFlying() { return flying; } - } diff --git a/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java b/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java index 814757e1..06f9b147 100644 --- a/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java +++ b/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java @@ -18,7 +18,6 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; @@ -34,7 +33,7 @@ public class UnregisterCommand implements CommandExecutor { public UnregisterCommand(AuthMe plugin) { this.plugin = plugin; - this.playerCache = new JsonCache(plugin); + this.playerCache = new JsonCache(); } @Override @@ -79,8 +78,7 @@ public class UnregisterCommand implements CommandExecutor { player.teleport(tpEvent.getTo()); } } - player.getInventory().setContents(new ItemStack[36]); - player.getInventory().setArmorContents(new ItemStack[4]); + player.saveData(); PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); if (!Settings.getRegisteredGroup.isEmpty()) diff --git a/src/main/java/fr/xephi/authme/events/ProtectInventoryEvent.java b/src/main/java/fr/xephi/authme/events/ProtectInventoryEvent.java index 10d5636b..a09ad4ea 100644 --- a/src/main/java/fr/xephi/authme/events/ProtectInventoryEvent.java +++ b/src/main/java/fr/xephi/authme/events/ProtectInventoryEvent.java @@ -4,7 +4,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; /** - * + * * This event is call just after store inventory into cache and will empty the * player inventory. * @@ -18,12 +18,11 @@ public class ProtectInventoryEvent extends CustomEvent { private ItemStack[] emptyArmor = null; private Player player; - public ProtectInventoryEvent(Player player, ItemStack[] storedinventory, - ItemStack[] storedarmor) { + public ProtectInventoryEvent(Player player) { super(true); this.player = player; - this.storedinventory = storedinventory; - this.storedarmor = storedarmor; + this.storedinventory = player.getInventory().getContents(); + this.storedarmor = player.getInventory().getArmorContents(); this.emptyInventory = new ItemStack[36]; this.emptyArmor = new ItemStack[4]; } diff --git a/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java b/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java index c2c36ba4..c3069788 100644 --- a/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java +++ b/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java @@ -4,8 +4,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; /** - * - * This event restore the inventory from cache + * This event restore the inventory. * * @author Xephi59 */ @@ -15,16 +14,14 @@ public class RestoreInventoryEvent extends CustomEvent { private ItemStack[] armor; private Player player; - public RestoreInventoryEvent(Player player, ItemStack[] inventory, - ItemStack[] armor) { + public RestoreInventoryEvent(Player player) { this.player = player; - this.inventory = inventory; - this.armor = armor; + this.inventory = player.getInventory().getContents(); + this.armor = player.getInventory().getArmorContents(); } - public RestoreInventoryEvent(Player player, ItemStack[] inventory, - ItemStack[] armor, boolean b) { - super(b); + public RestoreInventoryEvent(Player player, boolean async) { + super(async); this.player = player; this.inventory = inventory; this.armor = armor; @@ -53,5 +50,4 @@ public class RestoreInventoryEvent extends CustomEvent { public void setPlayer(Player player) { this.player = player; } - } diff --git a/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java b/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java index e8a78806..18476525 100644 --- a/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java +++ b/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java @@ -1,6 +1,5 @@ package fr.xephi.authme.events; -import fr.xephi.authme.cache.backup.DataFileCache; import fr.xephi.authme.cache.backup.JsonCache; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -24,14 +23,8 @@ public class StoreInventoryEvent extends CustomEvent { public StoreInventoryEvent(Player player, JsonCache jsonCache) { this.player = player; - DataFileCache cache = jsonCache.readCache(player); - if (cache != null) { - this.inventory = cache.getInventory(); - this.armor = cache.getArmour(); - } else { - this.inventory = player.getInventory().getContents(); - this.armor = player.getInventory().getArmorContents(); - } + this.inventory = player.getInventory().getContents(); + this.armor = player.getInventory().getArmorContents(); } public ItemStack[] getInventory() { @@ -57,5 +50,4 @@ public class StoreInventoryEvent extends CustomEvent { public void setPlayer(Player player) { this.player = player; } - } diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeInventoryListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeInventoryListener.java new file mode 100644 index 00000000..9b59a148 --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMeInventoryListener.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2015 AuthMe-Team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package fr.xephi.authme.listener; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.settings.Settings; + +import java.lang.reflect.InvocationTargetException; + +import java.util.Arrays; +import java.util.Collections; +import java.util.logging.Level; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class AuthMeInventoryListener extends PacketAdapter { + + private static final int PLAYER_INVENTORY = 0; + //http://wiki.vg/Inventory#Inventory (0-4 crafting, 5-8 armor, 9-35 main inventory, 36-44 inventory) + //+1 because an index starts with 0 + private static final int PLAYER_CRAFTING_SIZE = 5; + private static final int HOTBAR_SIZE = 9; + + public AuthMeInventoryListener(AuthMe plugin) { + super(plugin, PacketType.Play.Server.SET_SLOT, PacketType.Play.Server.WINDOW_ITEMS); + } + + @Override + public void onPacketSending(PacketEvent packetEvent) { + Player player = packetEvent.getPlayer(); + PacketContainer packet = packetEvent.getPacket(); + + byte windowId = packet.getIntegers().read(0).byteValue(); + if (windowId == PLAYER_INVENTORY && Settings.protectInventoryBeforeLogInEnabled + && !PlayerCache.getInstance().isAuthenticated(player.getName())) { + packetEvent.setCancelled(true); + } + } + + public void sendInventoryPacket(Player player) { + ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); + PacketContainer inventoryPacket = protocolManager.createPacket(PacketType.Play.Server.WINDOW_ITEMS); + + //we are sending our own inventory + inventoryPacket.getIntegers().write(0, PLAYER_INVENTORY); + + ItemStack[] playerCrafting = new ItemStack[PLAYER_CRAFTING_SIZE]; + ItemStack[] armorContents = player.getInventory().getArmorContents(); + ItemStack[] mainInventory = player.getInventory().getContents(); + + //bukkit saves the armor in reversed order + Collections.reverse(Arrays.asList(armorContents)); + + //same main inventory. The hotbar is at the beginning but it should be at the end of the array + ItemStack[] hotbar = Arrays.copyOfRange(mainInventory, 0, HOTBAR_SIZE); + ItemStack[] storedInventory = Arrays.copyOfRange(mainInventory, HOTBAR_SIZE, mainInventory.length); + + //concat all parts of the inventory together + int inventorySize = playerCrafting.length + armorContents.length + mainInventory.length; + ItemStack[] completeInventory = new ItemStack[inventorySize]; + + System.arraycopy(playerCrafting, 0, completeInventory, 0, playerCrafting.length); + System.arraycopy(armorContents, 0, completeInventory, playerCrafting.length, armorContents.length); + + //storedInventory and hotbar + System.arraycopy(storedInventory, 0, completeInventory + , playerCrafting.length + armorContents.length, storedInventory.length); + System.arraycopy(hotbar, 0, completeInventory + , playerCrafting.length + armorContents.length + storedInventory.length, hotbar.length); + + inventoryPacket.getItemArrayModifier().write(0, completeInventory); + try { + protocolManager.sendServerPacket(player, inventoryPacket, false); + } catch (InvocationTargetException invocationExc) { + plugin.getLogger().log(Level.WARNING, "Error during inventory recovery", invocationExc); + } + } +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java index d13e8738..22f71493 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java @@ -68,6 +68,10 @@ public class AuthMeServerListener implements Listener { plugin.permission = null; ConsoleLogger.showError("Vault has been disabled, unhook permissions!"); } + if (pluginName.equalsIgnoreCase("ProtocolLib")) { + plugin.inventoryProtector = null; + ConsoleLogger.showError("ProtocolLib has been disabled, unhook packet inventory protection!"); + } } @EventHandler(priority = EventPriority.HIGHEST) @@ -83,5 +87,8 @@ public class AuthMeServerListener implements Listener { plugin.checkCombatTagPlus(); if (pluginName.equalsIgnoreCase("Vault")) plugin.checkVault(); + if (pluginName.equalsIgnoreCase("ProtocolLib")) { + plugin.checkProtocolLib(); + } } } diff --git a/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java b/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java index 4df4928e..9a31b835 100644 --- a/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java +++ b/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java @@ -1,315 +1,296 @@ -package fr.xephi.authme.process.join; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.Utils; -import fr.xephi.authme.Utils.GroupType; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.cache.backup.DataFileCache; -import fr.xephi.authme.cache.backup.JsonCache; -import fr.xephi.authme.cache.limbo.LimboCache; -import fr.xephi.authme.cache.limbo.LimboPlayer; -import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.events.FirstSpawnTeleportEvent; -import fr.xephi.authme.events.ProtectInventoryEvent; -import fr.xephi.authme.events.SpawnTeleportEvent; -import fr.xephi.authme.listener.AuthMePlayerListener; -import fr.xephi.authme.settings.Messages; -import fr.xephi.authme.settings.Settings; -import fr.xephi.authme.settings.Spawn; -import fr.xephi.authme.task.MessageTask; -import fr.xephi.authme.task.TimeoutTask; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitScheduler; -import org.bukkit.scheduler.BukkitTask; - -public class AsyncronousJoin { - - protected Player player; - protected DataSource database; - protected AuthMe plugin; - protected String name; - private Messages m = Messages.getInstance(); - private JsonCache playerBackup; - - public AsyncronousJoin(Player player, AuthMe plugin, DataSource database) { - this.player = player; - this.plugin = plugin; - this.database = database; - this.playerBackup = new JsonCache(plugin); - this.name = player.getName().toLowerCase(); - } - - public void process() { - if (AuthMePlayerListener.gameMode.containsKey(name)) - AuthMePlayerListener.gameMode.remove(name); - AuthMePlayerListener.gameMode.putIfAbsent(name, player.getGameMode()); - BukkitScheduler sched = plugin.getServer().getScheduler(); - - if (Utils.isNPC(player) || Utils.isUnrestricted(player)) { - return; - } - - if (plugin.ess != null && Settings.disableSocialSpy) { - plugin.ess.getUser(player).setSocialSpyEnabled(false); - } - - final String ip = plugin.getIP(player); - if (Settings.isAllowRestrictedIp && !Settings.getRestrictedIp(name, ip)) { - final GameMode gM = AuthMePlayerListener.gameMode.get(name); - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); - player.setGameMode(gM); - player.kickPlayer("You are not the Owner of this account, please try another name!"); - if (Settings.banUnsafeIp) - plugin.getServer().banIP(ip); - } - - }); - return; - } - if (Settings.getMaxJoinPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost")) { - if (plugin.hasJoinedIp(player.getName(), ip)) { - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - player.kickPlayer("A player with the same IP is already in game!"); - } - - }); - return; - } - } - final Location spawnLoc = plugin.getSpawnLocation(player); - final boolean isAuthAvailable = database.isAuthAvailable(name); - if (isAuthAvailable) { - if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); - Utils.forceGM(player); - } - - }); - } - if (!Settings.noTeleport) - if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); - plugin.getServer().getPluginManager().callEvent(tpEvent); - if (!tpEvent.isCancelled()) { - if (player.isOnline() && tpEvent.getTo() != null) { - if (tpEvent.getTo().getWorld() != null) - player.teleport(tpEvent.getTo()); - } - } - } - - }); - } - placePlayerSafely(player, spawnLoc); - LimboCache.getInstance().updateLimboPlayer(player); - DataFileCache dataFile = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour()); - playerBackup.createCache(player, dataFile); - // protect inventory - if (Settings.protectInventoryBeforeLogInEnabled) { - LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); - ProtectInventoryEvent ev = new ProtectInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); - plugin.getServer().getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - if (!Settings.noConsoleSpam) - ConsoleLogger.info("ProtectInventoryEvent has been cancelled for " + player.getName() + " ..."); - } else { - final ItemStack[] inv = ev.getEmptyArmor(); - final ItemStack[] armor = ev.getEmptyArmor(); - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - plugin.api.setPlayerInventory(player, inv, armor); - } - - }); - } - } - } else { - if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); - Utils.forceGM(player); - } - - }); - } - if (!Settings.unRegisteredGroup.isEmpty()) { - Utils.setGroup(player, Utils.GroupType.UNREGISTERED); - } - if (!Settings.isForcedRegistrationEnabled) { - return; - } - if (!Settings.noTeleport) - if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { - SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); - plugin.getServer().getPluginManager().callEvent(tpEvent); - if (!tpEvent.isCancelled()) { - if (player.isOnline() && tpEvent.getTo() != null) { - if (tpEvent.getTo().getWorld() != null) - player.teleport(tpEvent.getTo()); - } - } - } - - }); - } - - } - String[] msg; - if (Settings.emailRegistration) { - msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_email_msg"); - } else { - msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_msg"); - } - int time = Settings.getRegistrationTimeout * 20; - int msgInterval = Settings.getWarnMessageInterval; - if (time != 0) { - BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time); - if (!LimboCache.getInstance().hasLimboPlayer(name)) - LimboCache.getInstance().addLimboPlayer(player); - LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); - } - if (!LimboCache.getInstance().hasLimboPlayer(name)) - LimboCache.getInstance().addLimboPlayer(player); - if (isAuthAvailable) { - Utils.setGroup(player, GroupType.NOTLOGGEDIN); - } else { - Utils.setGroup(player, GroupType.UNREGISTERED); - } - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - if (player.isOp()) - player.setOp(false); - if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { - player.setAllowFlight(true); - player.setFlying(true); - } - player.setNoDamageTicks(Settings.getRegistrationTimeout * 20); - if (Settings.useEssentialsMotd) - player.performCommand("motd"); - if (Settings.applyBlindEffect) - player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); - if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { - player.setWalkSpeed(0.0f); - player.setFlySpeed(0.0f); - } - } - - }); - if (Settings.isSessionsEnabled && isAuthAvailable && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) { - if (plugin.sessions.containsKey(name)) - plugin.sessions.get(name).cancel(); - plugin.sessions.remove(name); - PlayerAuth auth = database.getAuth(name); - if (auth != null && auth.getIp().equals(ip)) { - m.send(player, "valid_session"); - PlayerCache.getInstance().removePlayer(name); - database.setUnlogged(name); - plugin.management.performLogin(player, "dontneed", true); - } else if (Settings.sessionExpireOnIpChange) { - PlayerCache.getInstance().removePlayer(name); - database.setUnlogged(name); - m.send(player, "invalid_session"); - } - return; - } - BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, msgInterval)); - LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); - } - - private boolean needFirstspawn() { - if (player.hasPlayedBefore()) - return false; - if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null) - return false; - FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn()); - plugin.getServer().getPluginManager().callEvent(tpEvent); - if (!tpEvent.isCancelled()) { - if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) { - final Location fLoc = tpEvent.getTo(); - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - player.teleport(fLoc); - } - - }); - } - } - return true; - - } - - private void placePlayerSafely(final Player player, - final Location spawnLoc) { - Location loc = null; - if (spawnLoc == null) - return; - if (!Settings.noTeleport) - return; - if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) - return; - if (!player.hasPlayedBefore()) - return; - Block b = player.getLocation().getBlock(); - if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL) { - m.send(player, "unsafe_spawn"); - if (spawnLoc.getWorld() != null) - loc = spawnLoc; - } else { - Block c = player.getLocation().add(0D, 1D, 0D).getBlock(); - if (c.getType() == Material.PORTAL || c.getType() == Material.ENDER_PORTAL) { - m.send(player, "unsafe_spawn"); - if (spawnLoc.getWorld() != null) - loc = spawnLoc; - } - } - if (loc != null) { - final Location floc = loc; - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - player.teleport(floc); - } - - }); - } - } - -} +package fr.xephi.authme.process.join; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.Utils.GroupType; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.events.FirstSpawnTeleportEvent; +import fr.xephi.authme.events.ProtectInventoryEvent; +import fr.xephi.authme.events.SpawnTeleportEvent; +import fr.xephi.authme.listener.AuthMePlayerListener; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.Spawn; +import fr.xephi.authme.task.MessageTask; +import fr.xephi.authme.task.TimeoutTask; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +public class AsyncronousJoin { + + protected Player player; + protected DataSource database; + protected AuthMe plugin; + protected String name; + private Messages m = Messages.getInstance(); + + public AsyncronousJoin(Player player, AuthMe plugin, DataSource database) { + this.player = player; + this.plugin = plugin; + this.database = database; + this.name = player.getName().toLowerCase(); + } + + public void process() { + if (AuthMePlayerListener.gameMode.containsKey(name)) + AuthMePlayerListener.gameMode.remove(name); + AuthMePlayerListener.gameMode.putIfAbsent(name, player.getGameMode()); + BukkitScheduler sched = plugin.getServer().getScheduler(); + + if (Utils.isNPC(player) || Utils.isUnrestricted(player)) { + return; + } + + if (plugin.ess != null && Settings.disableSocialSpy) { + plugin.ess.getUser(player).setSocialSpyEnabled(false); + } + + final String ip = plugin.getIP(player); + if (Settings.isAllowRestrictedIp && !Settings.getRestrictedIp(name, ip)) { + final GameMode gM = AuthMePlayerListener.gameMode.get(name); + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); + player.setGameMode(gM); + player.kickPlayer("You are not the Owner of this account, please try another name!"); + if (Settings.banUnsafeIp) + plugin.getServer().banIP(ip); + } + + }); + return; + } + if (Settings.getMaxJoinPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost")) { + if (plugin.hasJoinedIp(player.getName(), ip)) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + player.kickPlayer("A player with the same IP is already in game!"); + } + + }); + return; + } + } + final Location spawnLoc = plugin.getSpawnLocation(player); + final boolean isAuthAvailable = database.isAuthAvailable(name); + if (isAuthAvailable) { + if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); + Utils.forceGM(player); + } + + }); + } + if (!Settings.noTeleport) + if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (player.isOnline() && tpEvent.getTo() != null) { + if (tpEvent.getTo().getWorld() != null) + player.teleport(tpEvent.getTo()); + } + } + } + + }); + } + placePlayerSafely(player, spawnLoc); + LimboCache.getInstance().updateLimboPlayer(player); + // protect inventory + if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) { + ProtectInventoryEvent ev = new ProtectInventoryEvent(player); + plugin.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + plugin.inventoryProtector.sendInventoryPacket(player); + if (!Settings.noConsoleSpam) + ConsoleLogger.info("ProtectInventoryEvent has been cancelled for " + player.getName() + " ..."); + } + } + } else { + if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); + Utils.forceGM(player); + } + + }); + } + if (!Settings.unRegisteredGroup.isEmpty()) { + Utils.setGroup(player, Utils.GroupType.UNREGISTERED); + } + if (!Settings.isForcedRegistrationEnabled) { + return; + } + if (!Settings.noTeleport) + if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + @Override + public void run() { + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (player.isOnline() && tpEvent.getTo() != null) { + if (tpEvent.getTo().getWorld() != null) + player.teleport(tpEvent.getTo()); + } + } + } + + }); + } + + } + String[] msg; + if (Settings.emailRegistration) { + msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_email_msg"); + } else { + msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_msg"); + } + int time = Settings.getRegistrationTimeout * 20; + int msgInterval = Settings.getWarnMessageInterval; + if (time != 0) { + BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time); + if (!LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().addLimboPlayer(player); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + } + if (!LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().addLimboPlayer(player); + if (isAuthAvailable) { + Utils.setGroup(player, GroupType.NOTLOGGEDIN); + } else { + Utils.setGroup(player, GroupType.UNREGISTERED); + } + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + if (player.isOp()) + player.setOp(false); + if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { + player.setAllowFlight(true); + player.setFlying(true); + } + player.setNoDamageTicks(Settings.getRegistrationTimeout * 20); + if (Settings.useEssentialsMotd) + player.performCommand("motd"); + if (Settings.applyBlindEffect) + player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); + if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { + player.setWalkSpeed(0.0f); + player.setFlySpeed(0.0f); + } + } + + }); + if (Settings.isSessionsEnabled && isAuthAvailable && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) { + if (plugin.sessions.containsKey(name)) + plugin.sessions.get(name).cancel(); + plugin.sessions.remove(name); + PlayerAuth auth = database.getAuth(name); + if (auth != null && auth.getIp().equals(ip)) { + m.send(player, "valid_session"); + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + plugin.management.performLogin(player, "dontneed", true); + } else if (Settings.sessionExpireOnIpChange) { + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + m.send(player, "invalid_session"); + } + return; + } + BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, msgInterval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); + } + + private boolean needFirstspawn() { + if (player.hasPlayedBefore()) + return false; + if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null) + return false; + FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn()); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) { + final Location fLoc = tpEvent.getTo(); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + player.teleport(fLoc); + } + + }); + } + } + return true; + + } + + private void placePlayerSafely(final Player player, + final Location spawnLoc) { + Location loc = null; + if (spawnLoc == null) + return; + if (!Settings.noTeleport) + return; + if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) + return; + if (!player.hasPlayedBefore()) + return; + Block b = player.getLocation().getBlock(); + if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL) { + m.send(player, "unsafe_spawn"); + if (spawnLoc.getWorld() != null) + loc = spawnLoc; + } else { + Block c = player.getLocation().add(0D, 1D, 0D).getBlock(); + if (c.getType() == Material.PORTAL || c.getType() == Material.ENDER_PORTAL) { + m.send(player, "unsafe_spawn"); + if (spawnLoc.getWorld() != null) + loc = spawnLoc; + } + } + if (loc != null) { + final Location floc = loc; + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + player.teleport(floc); + } + + }); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java index 28f9a861..da0a42b2 100644 --- a/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java @@ -42,7 +42,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable { this.name = player.getName().toLowerCase(); this.limbo = LimboCache.getInstance().getLimboPlayer(name); this.auth = database.getAuth(name); - this.playerCache = new JsonCache(plugin); + this.playerCache = new JsonCache(); } public LimboPlayer getLimbo() { @@ -92,10 +92,11 @@ public class ProcessSyncronousPlayerLogin implements Runnable { } protected void restoreInventory() { - RestoreInventoryEvent event = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); + RestoreInventoryEvent event = new RestoreInventoryEvent(player); Bukkit.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { plugin.api.setPlayerInventory(player, event.getInventory(), event.getArmor()); + plugin.inventoryProtector.sendInventoryPacket(player); } } @@ -128,7 +129,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable { // Inventory - Make it after restore GameMode , cause we need to // restore the // right inventory in the right gamemode - if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) { + if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) { restoreInventory(); } if (Settings.forceOnlyAfterLogin) { diff --git a/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java b/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java index d1f890ad..0d4e4002 100644 --- a/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java +++ b/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java @@ -1,91 +1,81 @@ -package fr.xephi.authme.process.logout; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitScheduler; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.Utils; -import fr.xephi.authme.Utils.GroupType; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.cache.backup.DataFileCache; -import fr.xephi.authme.cache.backup.JsonCache; -import fr.xephi.authme.cache.limbo.LimboCache; -import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.events.AuthMeTeleportEvent; -import fr.xephi.authme.settings.Messages; -import fr.xephi.authme.settings.Settings; - -public class AsyncronousLogout { - - protected Player player; - protected String name; - protected AuthMe plugin; - protected DataSource database; - protected boolean canLogout = true; - private Messages m = Messages.getInstance(); - private JsonCache playerBackup; - - public AsyncronousLogout(Player player, AuthMe plugin, - DataSource database) { - this.player = player; - this.plugin = plugin; - this.database = database; - this.name = player.getName().toLowerCase(); - this.playerBackup = new JsonCache(plugin); - } - - private void preLogout() { - if (!PlayerCache.getInstance().isAuthenticated(name)) { - m.send(player, "not_logged_in"); - canLogout = false; - } - } - - public void process() { - preLogout(); - if (!canLogout) - return; - final Player p = player; - BukkitScheduler sched = p.getServer().getScheduler(); - PlayerAuth auth = PlayerCache.getInstance().getAuth(name); - database.updateSession(auth); - auth.setQuitLocX(p.getLocation().getX()); - auth.setQuitLocY(p.getLocation().getY()); - auth.setQuitLocZ(p.getLocation().getZ()); - auth.setWorld(p.getWorld().getName()); - database.updateQuitLoc(auth); - - PlayerCache.getInstance().removePlayer(name); - database.setUnlogged(name); - if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { - Location spawnLoc = plugin.getSpawnLocation(p); - final AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(p, spawnLoc); - sched.scheduleSyncDelayedTask(plugin, new Runnable() { - - @Override - public void run() { - plugin.getServer().getPluginManager().callEvent(tpEvent); - if (!tpEvent.isCancelled()) { - if (tpEvent.getTo() != null) - p.teleport(tpEvent.getTo()); - } - } - }); - } - - if (LimboCache.getInstance().hasLimboPlayer(name)) - LimboCache.getInstance().deleteLimboPlayer(name); - LimboCache.getInstance().addLimboPlayer(player); - Utils.setGroup(player, GroupType.NOTLOGGEDIN); - if (Settings.protectInventoryBeforeLogInEnabled) { - player.getInventory().clear(); - // create cache file for handling lost of inventories on unlogged in - // status - DataFileCache playerData = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour()); - playerBackup.createCache(player, playerData); - } - sched.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin)); - } -} +package fr.xephi.authme.process.logout; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitScheduler; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.Utils.GroupType; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.events.AuthMeTeleportEvent; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class AsyncronousLogout { + + protected Player player; + protected String name; + protected AuthMe plugin; + protected DataSource database; + protected boolean canLogout = true; + private Messages m = Messages.getInstance(); + + public AsyncronousLogout(Player player, AuthMe plugin, + DataSource database) { + this.player = player; + this.plugin = plugin; + this.database = database; + this.name = player.getName().toLowerCase(); + } + + private void preLogout() { + if (!PlayerCache.getInstance().isAuthenticated(name)) { + m.send(player, "not_logged_in"); + canLogout = false; + } + } + + public void process() { + preLogout(); + if (!canLogout) + return; + final Player p = player; + BukkitScheduler sched = p.getServer().getScheduler(); + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + database.updateSession(auth); + auth.setQuitLocX(p.getLocation().getX()); + auth.setQuitLocY(p.getLocation().getY()); + auth.setQuitLocZ(p.getLocation().getZ()); + auth.setWorld(p.getWorld().getName()); + database.updateQuitLoc(auth); + + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { + Location spawnLoc = plugin.getSpawnLocation(p); + final AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(p, spawnLoc); + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (tpEvent.getTo() != null) + p.teleport(tpEvent.getTo()); + } + } + }); + } + + if (LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().deleteLimboPlayer(name); + LimboCache.getInstance().addLimboPlayer(player); + Utils.setGroup(player, GroupType.NOTLOGGEDIN); + + sched.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin)); + } +} diff --git a/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java b/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java index da594606..26917e63 100644 --- a/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java +++ b/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java @@ -1,110 +1,93 @@ -package fr.xephi.authme.process.quit; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitTask; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.Utils; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.cache.limbo.LimboCache; -import fr.xephi.authme.cache.limbo.LimboPlayer; -import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.events.RestoreInventoryEvent; -import fr.xephi.authme.listener.AuthMePlayerListener; -import fr.xephi.authme.settings.Settings; - -public class AsyncronousQuit { - - protected AuthMe plugin; - protected DataSource database; - protected Player player; - private String name; - private ItemStack[] armor = null; - private ItemStack[] inv = null; - private boolean isOp = false; - private boolean isFlying = false; - private boolean needToChange = false; - private boolean isKick = false; - - public AsyncronousQuit(Player p, AuthMe plugin, DataSource database, - boolean isKick) { - this.player = p; - this.plugin = plugin; - this.database = database; - this.name = p.getName().toLowerCase(); - this.isKick = isKick; - } - - public void process() { - if (player == null) - return; - if (Utils.isNPC(player) || Utils.isUnrestricted(player)) { - return; - } - - String ip = plugin.getIP(player); - - if (PlayerCache.getInstance().isAuthenticated(name)) { - if (Settings.isSaveQuitLocationEnabled && database.isAuthAvailable(name)) { - Location loc = player.getLocation(); - PlayerAuth auth = new PlayerAuth(name, loc.getX(), loc.getY(), loc.getZ(), loc.getWorld().getName(), player.getName()); - database.updateQuitLoc(auth); - } - PlayerAuth auth = new PlayerAuth(name, ip, System.currentTimeMillis(), player.getName()); - database.updateSession(auth); - } - - if (LimboCache.getInstance().hasLimboPlayer(name)) { - LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); - if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) { - inv = limbo.getInventory(); - armor = limbo.getArmour(); - } - if (limbo.getGroup() != null && !limbo.getGroup().equals("")) - Utils.addNormal(player, limbo.getGroup()); - needToChange = true; - isOp = limbo.getOperator(); - isFlying = limbo.isFlying(); - if (limbo.getTimeoutTaskId() != null) - limbo.getTimeoutTaskId().cancel(); - if (limbo.getMessageTaskId() != null) - limbo.getMessageTaskId().cancel(); - LimboCache.getInstance().deleteLimboPlayer(name); - } - if (Settings.isSessionsEnabled && !isKick) { - if (Settings.getSessionTimeout != 0) { - BukkitTask task = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() { - - @Override - public void run() { - PlayerCache.getInstance().removePlayer(name); - if (database.isLogged(name)) - database.setUnlogged(name); - plugin.sessions.remove(name); - } - - }, Settings.getSessionTimeout * 20 * 60); - plugin.sessions.put(name, task); - } - } else { - PlayerCache.getInstance().removePlayer(name); - database.setUnlogged(name); - } - AuthMePlayerListener.gameMode.remove(name); - final Player p = player; - RestoreInventoryEvent ev = new RestoreInventoryEvent(player, inv, armor, true); - Bukkit.getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - inv = null; - armor = null; - } else { - inv = ev.getInventory(); - armor = ev.getArmor(); - } - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerQuit(plugin, p, inv, armor, isOp, isFlying, needToChange)); - } -} +package fr.xephi.authme.process.quit; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.listener.AuthMePlayerListener; +import fr.xephi.authme.settings.Settings; + +public class AsyncronousQuit { + + protected AuthMe plugin; + protected DataSource database; + protected Player player; + private String name; + private boolean isOp = false; + private boolean isFlying = false; + private boolean needToChange = false; + private boolean isKick = false; + + public AsyncronousQuit(Player p, AuthMe plugin, DataSource database, + boolean isKick) { + this.player = p; + this.plugin = plugin; + this.database = database; + this.name = p.getName().toLowerCase(); + this.isKick = isKick; + } + + public void process() { + if (player == null) + return; + if (Utils.isNPC(player) || Utils.isUnrestricted(player)) { + return; + } + + String ip = plugin.getIP(player); + + if (PlayerCache.getInstance().isAuthenticated(name)) { + if (Settings.isSaveQuitLocationEnabled && database.isAuthAvailable(name)) { + Location loc = player.getLocation(); + PlayerAuth auth = new PlayerAuth(name, loc.getX(), loc.getY(), loc.getZ(), loc.getWorld().getName(), player.getName()); + database.updateQuitLoc(auth); + } + PlayerAuth auth = new PlayerAuth(name, ip, System.currentTimeMillis(), player.getName()); + database.updateSession(auth); + } + + if (LimboCache.getInstance().hasLimboPlayer(name)) { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (limbo.getGroup() != null && !limbo.getGroup().equals("")) + Utils.addNormal(player, limbo.getGroup()); + needToChange = true; + isOp = limbo.getOperator(); + isFlying = limbo.isFlying(); + if (limbo.getTimeoutTaskId() != null) + limbo.getTimeoutTaskId().cancel(); + if (limbo.getMessageTaskId() != null) + limbo.getMessageTaskId().cancel(); + LimboCache.getInstance().deleteLimboPlayer(name); + } + if (Settings.isSessionsEnabled && !isKick) { + if (Settings.getSessionTimeout != 0) { + BukkitTask task = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + PlayerCache.getInstance().removePlayer(name); + if (database.isLogged(name)) + database.setUnlogged(name); + plugin.sessions.remove(name); + } + + }, Settings.getSessionTimeout * 20 * 60); + plugin.sessions.put(name, task); + } + } else { + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + } + + AuthMePlayerListener.gameMode.remove(name); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerQuit(plugin, player, isOp, isFlying, needToChange)); + } +} diff --git a/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java b/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java index 48813409..ea644270 100644 --- a/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java +++ b/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java @@ -1,48 +1,49 @@ -package fr.xephi.authme.process.quit; - -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.settings.Settings; - -public class ProcessSyncronousPlayerQuit implements Runnable { - - protected AuthMe plugin; - protected Player player; - protected boolean isOp; - protected boolean isFlying; - protected ItemStack[] inv; - protected ItemStack[] armor; - protected boolean needToChange; - - public ProcessSyncronousPlayerQuit(AuthMe plugin, Player player, - ItemStack[] inv, ItemStack[] armor, boolean isOp, boolean isFlying, - boolean needToChange) { - this.plugin = plugin; - this.player = player; - this.isOp = isOp; - this.isFlying = isFlying; - this.armor = armor; - this.inv = inv; - this.needToChange = needToChange; - } - - @Override - public void run() { - if (inv != null && armor != null) - plugin.api.setPlayerInventory(player, inv, armor); - if (needToChange) { - player.setOp(isOp); - if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { - player.setAllowFlight(isFlying); - player.setFlying(isFlying); - } - } - try { - player.getVehicle().eject(); - } catch (Exception e) { - } - } -} +package fr.xephi.authme.process.quit; + +import org.bukkit.GameMode; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.events.RestoreInventoryEvent; +import fr.xephi.authme.settings.Settings; +import org.bukkit.Bukkit; + +public class ProcessSyncronousPlayerQuit implements Runnable { + + protected AuthMe plugin; + protected Player player; + protected boolean isOp; + protected boolean isFlying; + protected boolean needToChange; + + public ProcessSyncronousPlayerQuit(AuthMe plugin, Player player + , boolean isOp, boolean isFlying + , boolean needToChange) { + this.plugin = plugin; + this.player = player; + this.isOp = isOp; + this.isFlying = isFlying; + this.needToChange = needToChange; + } + + @Override + public void run() { + RestoreInventoryEvent ev = new RestoreInventoryEvent(player); + Bukkit.getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + plugin.api.setPlayerInventory(player, ev.getInventory(), ev.getArmor()); + } + + if (needToChange) { + player.setOp(isOp); + if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { + player.setAllowFlight(isFlying); + player.setFlying(isFlying); + } + } + try { + player.getVehicle().eject(); + } catch (Exception e) { + } + } +} diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java index 5a7a1353..ab0612d5 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java @@ -91,14 +91,17 @@ public class ProcessSyncronousPasswordRegister implements Runnable { player.teleport(tpEvent.getTo()); } } - if (Settings.protectInventoryBeforeLogInEnabled && limbo.getInventory() != null && limbo.getArmour() != null) { - RestoreInventoryEvent event = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); + + if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) { + RestoreInventoryEvent event = new RestoreInventoryEvent(player); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled() && event.getArmor() != null && event.getInventory() != null) { player.getInventory().setContents(event.getInventory()); player.getInventory().setArmorContents(event.getArmor()); + plugin.inventoryProtector.sendInventoryPacket(player); } } + limbo.getTimeoutTaskId().cancel(); limbo.getMessageTaskId().cancel(); LimboCache.getInstance().deleteLimboPlayer(name); @@ -153,6 +156,5 @@ public class ProcessSyncronousPasswordRegister implements Runnable { // Register is now finish , we can force all commands forceCommands(); - } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 6b2e6174..276773ca 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -4,7 +4,7 @@ website: http://dev.bukkit.org/bukkit-plugins/authme-reloaded/ description: AuthMe prevents people, which aren't logged in, from doing stuff like placing blocks, moving, typing commands or seeing the inventory of the player. main: fr.xephi.authme.AuthMe version: ${project.version} -softdepend: [Vault, ChestShop, Multiverse-Core, Citizens, CombatTag, Essentials, EssentialsSpawn, PerWorldInventories] +softdepend: [Vault, ChestShop, Multiverse-Core, Citizens, CombatTag, Essentials, EssentialsSpawn, PerWorldInventories, ProtocolLib] commands: register: description: Register an account @@ -22,7 +22,7 @@ commands: usage: /logout unregister: description: unregister your account - usage: /unregister password + usage: /unregister password authme: description: AuthMe op commands usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version' From 63abcc03a9b3e875a3defe38c20349355ccdd5af Mon Sep 17 00:00:00 2001 From: "Gabriele C." Date: Sat, 3 Oct 2015 10:57:47 +0200 Subject: [PATCH 19/27] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index bed52462..3a8a92d1 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ McStats: http://mcstats.org/plugin/AuthMe #####Running Requirements: >- Java 1.7 (should work also with Java 1.8) >- Spigot or CraftBukkit (1.7.10 or 1.8.X) +>- Vault +>- Protocollib
###Plugin Description: From aed42670f66db529f5302a9c0fb6017877a10253 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sat, 3 Oct 2015 11:42:29 +0200 Subject: [PATCH 20/27] Added exclusions --- pom.xml | 60 ++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 9 deletions(-) diff --git a/pom.xml b/pom.xml index f797a2c6..605e94fe 100644 --- a/pom.xml +++ b/pom.xml @@ -200,6 +200,15 @@ true
+ + + org.apache.logging.log4j + log4j-core + 2.0-beta9 + provided + true + + org.xerial @@ -209,15 +218,6 @@ true - - - com.google.code.gson - gson - 2.3.1 - compile - true - - javax.mail @@ -273,6 +273,20 @@ ${bukkitVersion} provided true + + + junit + junit + + + json-simple + com.googlecode.json-simple + + + persistence-api + javax.persistence + + @@ -349,6 +363,26 @@ CommandHandler com.pneumaticraft.commandhandler + + SerializationConfig + me.main__.util + + + Logging + com.dumptruckman.minecraft + + + metrics + org.mcstats.bukkit + + + buscript + com.dumptruckman.minecraft + + + junit + junit + true @@ -478,6 +512,10 @@ AccountsClient com.mojang + + log4j-core + org.apache.logging.log4j + true @@ -573,6 +611,10 @@ lockette org.yi.acru.bukkit.lockette + + log4j-core + org.apache.logging.log4j + true From 4c2348e6e3eaa4e20eca2b8a7c1220f18d9cc0d6 Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sat, 3 Oct 2015 12:19:49 +0200 Subject: [PATCH 21/27] CleanUp (removed setinventory api method --- pom.xml | 30 ++++++++++++------- src/main/java/fr/xephi/authme/Utils.java | 1 - src/main/java/fr/xephi/authme/api/NewAPI.java | 12 -------- .../authme/events/RestoreInventoryEvent.java | 23 -------------- .../login/ProcessSyncronousPlayerLogin.java | 1 - .../quit/ProcessSyncronousPlayerQuit.java | 7 ----- .../ProcessSyncronousPasswordRegister.java | 4 +-- 7 files changed, 21 insertions(+), 57 deletions(-) diff --git a/pom.xml b/pom.xml index 605e94fe..26ecd2ac 100644 --- a/pom.xml +++ b/pom.xml @@ -6,6 +6,7 @@ fr.xephi authme 5.1-SNAPSHOT + jar AuthMeReloaded Authentication plugin for CraftBukkit/Spigot! @@ -88,9 +89,8 @@ com.zaxxer:HikariCP - org.slf4j:slf4j-simple + org.slf4j:slf4j-jdk14 org.slf4j:slf4j-api - com.google.code.gson:gson com.maxmind.geoip:geoip-api com.sun.mail:javax.mail com.comphenix.attribute:AttributeStorage @@ -194,7 +194,7 @@ org.slf4j - slf4j-simple + slf4j-jdk14 1.7.12 compile true @@ -308,13 +308,23 @@ true - - - com.comphenix.protocol - ProtocolLib - 3.4.0 - true - + + + com.comphenix.protocol + ProtocolLib + 3.4.0 + true + + + cglib-nodep + cglib + + + BukkitExecutors + com.comphenix.executors + + + diff --git a/src/main/java/fr/xephi/authme/Utils.java b/src/main/java/fr/xephi/authme/Utils.java index 4abde79f..70171dc0 100644 --- a/src/main/java/fr/xephi/authme/Utils.java +++ b/src/main/java/fr/xephi/authme/Utils.java @@ -160,7 +160,6 @@ public class Utils { } // TODO: remove if not needed - @SuppressWarnings("unused") public static void hasPermOnJoin(Player player) { if (plugin.permission == null) return; diff --git a/src/main/java/fr/xephi/authme/api/NewAPI.java b/src/main/java/fr/xephi/authme/api/NewAPI.java index 937a8abe..ab7d7cb4 100644 --- a/src/main/java/fr/xephi/authme/api/NewAPI.java +++ b/src/main/java/fr/xephi/authme/api/NewAPI.java @@ -6,11 +6,9 @@ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import fr.xephi.authme.AuthMe; -import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.Utils; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; @@ -94,16 +92,6 @@ public class NewAPI { } } - public void setPlayerInventory(Player player, ItemStack[] content, - ItemStack[] armor) { - try { - player.getInventory().setContents(content); - player.getInventory().setArmorContents(armor); - } catch (Exception npe) { - ConsoleLogger.showError("Some error appear while trying to set inventory for " + player.getName()); - } - } - /** * * @param playerName diff --git a/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java b/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java index c3069788..b73c123b 100644 --- a/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java +++ b/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java @@ -1,7 +1,6 @@ package fr.xephi.authme.events; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; /** * This event restore the inventory. @@ -10,37 +9,15 @@ import org.bukkit.inventory.ItemStack; */ public class RestoreInventoryEvent extends CustomEvent { - private ItemStack[] inventory; - private ItemStack[] armor; private Player player; public RestoreInventoryEvent(Player player) { this.player = player; - this.inventory = player.getInventory().getContents(); - this.armor = player.getInventory().getArmorContents(); } public RestoreInventoryEvent(Player player, boolean async) { super(async); this.player = player; - this.inventory = inventory; - this.armor = armor; - } - - public ItemStack[] getInventory() { - return this.inventory; - } - - public void setInventory(ItemStack[] inventory) { - this.inventory = inventory; - } - - public ItemStack[] getArmor() { - return this.armor; - } - - public void setArmor(ItemStack[] armor) { - this.armor = armor; } public Player getPlayer() { diff --git a/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java index da0a42b2..20eacdf2 100644 --- a/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java @@ -95,7 +95,6 @@ public class ProcessSyncronousPlayerLogin implements Runnable { RestoreInventoryEvent event = new RestoreInventoryEvent(player); Bukkit.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { - plugin.api.setPlayerInventory(player, event.getInventory(), event.getArmor()); plugin.inventoryProtector.sendInventoryPacket(player); } } diff --git a/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java b/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java index ea644270..1b661b6f 100644 --- a/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java +++ b/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java @@ -4,9 +4,7 @@ import org.bukkit.GameMode; import org.bukkit.entity.Player; import fr.xephi.authme.AuthMe; -import fr.xephi.authme.events.RestoreInventoryEvent; import fr.xephi.authme.settings.Settings; -import org.bukkit.Bukkit; public class ProcessSyncronousPlayerQuit implements Runnable { @@ -28,11 +26,6 @@ public class ProcessSyncronousPlayerQuit implements Runnable { @Override public void run() { - RestoreInventoryEvent ev = new RestoreInventoryEvent(player); - Bukkit.getPluginManager().callEvent(ev); - if (!ev.isCancelled()) { - plugin.api.setPlayerInventory(player, ev.getInventory(), ev.getArmor()); - } if (needToChange) { player.setOp(isOp); diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java index ab0612d5..1e20f2ba 100644 --- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java @@ -95,9 +95,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable { if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) { RestoreInventoryEvent event = new RestoreInventoryEvent(player); Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled() && event.getArmor() != null && event.getInventory() != null) { - player.getInventory().setContents(event.getInventory()); - player.getInventory().setArmorContents(event.getArmor()); + if (!event.isCancelled()) { plugin.inventoryProtector.sendInventoryPacket(player); } } From e9f299fca8885dd3d6dea5059029a3a846fd7cc2 Mon Sep 17 00:00:00 2001 From: games647 Date: Sat, 3 Oct 2015 18:22:13 +0200 Subject: [PATCH 22/27] Fix PlayerAuth constructor calls --- src/main/java/fr/xephi/authme/api/API.java | 366 ++-- src/main/java/fr/xephi/authme/api/NewAPI.java | 306 ++-- .../xephi/authme/commands/AdminCommand.java | 2 +- .../xephi/authme/commands/EmailCommand.java | 5 +- .../authme/converter/CrazyLoginConverter.java | 4 +- .../authme/converter/RakamakConverter.java | 12 +- .../authme/converter/RoyalAuthConverter.java | 2 +- .../authme/converter/vAuthFileReader.java | 4 +- .../xephi/authme/converter/xAuthToFlat.java | 2 +- .../fr/xephi/authme/datasource/FlatFile.java | 1501 ++++++++--------- .../xephi/authme/plugin/manager/EssSpawn.java | 4 +- .../authme/security/crypts/PHPFUSION.java | 6 +- .../fr/xephi/authme/security/crypts/XF.java | 2 +- .../authme/security/pbkdf2/MacBasedPRF.java | 10 +- .../xephi/authme/settings/OtherAccounts.java | 9 +- .../java/fr/xephi/authme/settings/Spawn.java | 8 +- 16 files changed, 1115 insertions(+), 1128 deletions(-) diff --git a/src/main/java/fr/xephi/authme/api/API.java b/src/main/java/fr/xephi/authme/api/API.java index 11eba861..79eaeaff 100644 --- a/src/main/java/fr/xephi/authme/api/API.java +++ b/src/main/java/fr/xephi/authme/api/API.java @@ -1,183 +1,183 @@ -package fr.xephi.authme.api; - -import java.security.NoSuchAlgorithmException; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.Utils; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.security.PasswordSecurity; -import fr.xephi.authme.settings.Settings; - -public class API { - - public static final String newline = System.getProperty("line.separator"); - public static AuthMe instance; - - @Deprecated - public API(AuthMe instance) { - API.instance = instance; - } - - /** - * Hook into AuthMe - * - * @return AuthMe instance - */ - @Deprecated - public static AuthMe hookAuthMe() { - if (instance != null) - return instance; - Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); - if (plugin == null || !(plugin instanceof AuthMe)) { - return null; - } - instance = (AuthMe) plugin; - return instance; - } - - @Deprecated - public AuthMe getPlugin() { - return instance; - } - - /** - * - * @param player - * @return true if player is authenticate - */ - @Deprecated - public static boolean isAuthenticated(Player player) { - return PlayerCache.getInstance().isAuthenticated(player.getName()); - } - - /** - * - * @param player - * @return true if player is a npc - */ - @Deprecated - public boolean isaNPC(Player player) { - return Utils.isNPC(player); - } - - /** - * - * @param player - * @return true if player is a npc - */ - @Deprecated - public boolean isNPC(Player player) { - return Utils.isNPC(player); - } - - /** - * - * @param player - * @return true if the player is unrestricted - */ - @Deprecated - public static boolean isUnrestricted(Player player) { - return Utils.isUnrestricted(player); - } - - @Deprecated - public static Location getLastLocation(Player player) { - try { - PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); - - if (auth != null) { - Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); - return loc; - } else { - return null; - } - - } catch (NullPointerException ex) { - return null; - } - } - - @Deprecated - public static void setPlayerInventory(Player player, ItemStack[] content, - ItemStack[] armor) { - try { - player.getInventory().setContents(content); - player.getInventory().setArmorContents(armor); - } catch (NullPointerException npe) { - } - } - - /** - * - * @param playerName - * @return true if player is registered - */ - @Deprecated - public static boolean isRegistered(String playerName) { - String player = playerName.toLowerCase(); - return instance.database.isAuthAvailable(player); - } - - /** - * @param String - * playerName, String passwordToCheck - * @return true if the password is correct , false else - */ - @Deprecated - public static boolean checkPassword(String playerName, - String passwordToCheck) { - if (!isRegistered(playerName)) - return false; - String player = playerName.toLowerCase(); - PlayerAuth auth = instance.database.getAuth(player); - try { - return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName); - } catch (NoSuchAlgorithmException e) { - return false; - } - } - - /** - * Register a player - * - * @param String - * playerName, String password - * @return true if the player is register correctly - */ - @Deprecated - public static boolean registerPlayer(String playerName, String password) { - try { - String name = playerName.toLowerCase(); - String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); - if (isRegistered(name)) { - return false; - } - PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com"); - if (!instance.database.saveAuth(auth)) { - return false; - } - return true; - } catch (NoSuchAlgorithmException ex) { - return false; - } - } - - /** - * Force a player to login - * - * @param Player - * player - */ - @Deprecated - public static void forceLogin(Player player) { - instance.management.performLogin(player, "dontneed", true); - } - -} +package fr.xephi.authme.api; + +import java.security.NoSuchAlgorithmException; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Settings; + +public class API { + + public static final String newline = System.getProperty("line.separator"); + public static AuthMe instance; + + @Deprecated + public API(AuthMe instance) { + API.instance = instance; + } + + /** + * Hook into AuthMe + * + * @return AuthMe instance + */ + @Deprecated + public static AuthMe hookAuthMe() { + if (instance != null) + return instance; + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); + if (plugin == null || !(plugin instanceof AuthMe)) { + return null; + } + instance = (AuthMe) plugin; + return instance; + } + + @Deprecated + public AuthMe getPlugin() { + return instance; + } + + /** + * + * @param player + * @return true if player is authenticate + */ + @Deprecated + public static boolean isAuthenticated(Player player) { + return PlayerCache.getInstance().isAuthenticated(player.getName()); + } + + /** + * + * @param player + * @return true if player is a npc + */ + @Deprecated + public boolean isaNPC(Player player) { + return Utils.isNPC(player); + } + + /** + * + * @param player + * @return true if player is a npc + */ + @Deprecated + public boolean isNPC(Player player) { + return Utils.isNPC(player); + } + + /** + * + * @param player + * @return true if the player is unrestricted + */ + @Deprecated + public static boolean isUnrestricted(Player player) { + return Utils.isUnrestricted(player); + } + + @Deprecated + public static Location getLastLocation(Player player) { + try { + PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); + + if (auth != null) { + Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); + return loc; + } else { + return null; + } + + } catch (NullPointerException ex) { + return null; + } + } + + @Deprecated + public static void setPlayerInventory(Player player, ItemStack[] content, + ItemStack[] armor) { + try { + player.getInventory().setContents(content); + player.getInventory().setArmorContents(armor); + } catch (NullPointerException npe) { + } + } + + /** + * + * @param playerName + * @return true if player is registered + */ + @Deprecated + public static boolean isRegistered(String playerName) { + String player = playerName.toLowerCase(); + return instance.database.isAuthAvailable(player); + } + + /** + * @param String + * playerName, String passwordToCheck + * @return true if the password is correct , false else + */ + @Deprecated + public static boolean checkPassword(String playerName, + String passwordToCheck) { + if (!isRegistered(playerName)) + return false; + String player = playerName.toLowerCase(); + PlayerAuth auth = instance.database.getAuth(player); + try { + return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName); + } catch (NoSuchAlgorithmException e) { + return false; + } + } + + /** + * Register a player + * + * @param String + * playerName, String password + * @return true if the player is register correctly + */ + @Deprecated + public static boolean registerPlayer(String playerName, String password) { + try { + String name = playerName.toLowerCase(); + String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); + if (isRegistered(name)) { + return false; + } + PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com", playerName); + if (!instance.database.saveAuth(auth)) { + return false; + } + return true; + } catch (NoSuchAlgorithmException ex) { + return false; + } + } + + /** + * Force a player to login + * + * @param Player + * player + */ + @Deprecated + public static void forceLogin(Player player) { + instance.management.performLogin(player, "dontneed", true); + } + +} diff --git a/src/main/java/fr/xephi/authme/api/NewAPI.java b/src/main/java/fr/xephi/authme/api/NewAPI.java index ab7d7cb4..4a6eb301 100644 --- a/src/main/java/fr/xephi/authme/api/NewAPI.java +++ b/src/main/java/fr/xephi/authme/api/NewAPI.java @@ -1,153 +1,153 @@ -package fr.xephi.authme.api; - -import java.security.NoSuchAlgorithmException; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.Utils; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.security.PasswordSecurity; -import fr.xephi.authme.settings.Settings; - -public class NewAPI { - - public static final String newline = System.getProperty("line.separator"); - public static NewAPI singleton; - public AuthMe plugin; - - public NewAPI(AuthMe plugin) { - this.plugin = plugin; - } - - public NewAPI(Server serv) { - this.plugin = (AuthMe) serv.getPluginManager().getPlugin("AuthMe"); - } - - /** - * Hook into AuthMe - * - * @return AuthMe plugin - */ - public static NewAPI getInstance() { - if (singleton != null) - return singleton; - Plugin p = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); - if (p == null || !(p instanceof AuthMe)) { - return null; - } - AuthMe authme = (AuthMe) p; - singleton = (new NewAPI(authme)); - return singleton; - } - - public AuthMe getPlugin() { - return plugin; - } - - /** - * - * @param player - * @return true if player is authenticate - */ - public boolean isAuthenticated(Player player) { - return PlayerCache.getInstance().isAuthenticated(player.getName()); - } - - /** - * - * @param player - * @return true if player is a npc - */ - public boolean isNPC(Player player) { - return Utils.isNPC(player); - } - - /** - * - * @param player - * @return true if the player is unrestricted - */ - public boolean isUnrestricted(Player player) { - return Utils.isUnrestricted(player); - } - - public Location getLastLocation(Player player) { - try { - PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); - - if (auth != null) { - return new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); - } else { - return null; - } - - } catch (NullPointerException ex) { - return null; - } - } - - /** - * - * @param playerName - * @return true if player is registered - */ - public boolean isRegistered(String playerName) { - String player = playerName.toLowerCase(); - return plugin.database.isAuthAvailable(player); - } - - /** - * @param String - * playerName, String passwordToCheck - * @return true if the password is correct , false else - */ - public boolean checkPassword(String playerName, String passwordToCheck) { - if (!isRegistered(playerName)) - return false; - String player = playerName.toLowerCase(); - PlayerAuth auth = plugin.database.getAuth(player); - try { - return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName); - } catch (NoSuchAlgorithmException e) { - return false; - } - } - - /** - * Register a player - * - * @param String - * playerName, String password - * @return true if the player is register correctly - */ - public boolean registerPlayer(String playerName, String password) { - try { - String name = playerName.toLowerCase(); - String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); - if (isRegistered(name)) { - return false; - } - PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0, "your@email.com"); - return plugin.database.saveAuth(auth); - } catch (NoSuchAlgorithmException ex) { - return false; - } - } - - /** - * Force a player to login - * - * @param Player - * player - */ - public void forceLogin(Player player) { - plugin.management.performLogin(player, "dontneed", true); - } - -} +package fr.xephi.authme.api; + +import java.security.NoSuchAlgorithmException; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Settings; + +public class NewAPI { + + public static final String newline = System.getProperty("line.separator"); + public static NewAPI singleton; + public AuthMe plugin; + + public NewAPI(AuthMe plugin) { + this.plugin = plugin; + } + + public NewAPI(Server serv) { + this.plugin = (AuthMe) serv.getPluginManager().getPlugin("AuthMe"); + } + + /** + * Hook into AuthMe + * + * @return AuthMe plugin + */ + public static NewAPI getInstance() { + if (singleton != null) + return singleton; + Plugin p = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); + if (p == null || !(p instanceof AuthMe)) { + return null; + } + AuthMe authme = (AuthMe) p; + singleton = (new NewAPI(authme)); + return singleton; + } + + public AuthMe getPlugin() { + return plugin; + } + + /** + * + * @param player + * @return true if player is authenticate + */ + public boolean isAuthenticated(Player player) { + return PlayerCache.getInstance().isAuthenticated(player.getName()); + } + + /** + * + * @param player + * @return true if player is a npc + */ + public boolean isNPC(Player player) { + return Utils.isNPC(player); + } + + /** + * + * @param player + * @return true if the player is unrestricted + */ + public boolean isUnrestricted(Player player) { + return Utils.isUnrestricted(player); + } + + public Location getLastLocation(Player player) { + try { + PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); + + if (auth != null) { + return new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); + } else { + return null; + } + + } catch (NullPointerException ex) { + return null; + } + } + + /** + * + * @param playerName + * @return true if player is registered + */ + public boolean isRegistered(String playerName) { + String player = playerName.toLowerCase(); + return plugin.database.isAuthAvailable(player); + } + + /** + * @param String + * playerName, String passwordToCheck + * @return true if the password is correct , false else + */ + public boolean checkPassword(String playerName, String passwordToCheck) { + if (!isRegistered(playerName)) + return false; + String player = playerName.toLowerCase(); + PlayerAuth auth = plugin.database.getAuth(player); + try { + return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName); + } catch (NoSuchAlgorithmException e) { + return false; + } + } + + /** + * Register a player + * + * @param String + * playerName, String password + * @return true if the player is register correctly + */ + public boolean registerPlayer(String playerName, String password) { + try { + String name = playerName.toLowerCase(); + String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); + if (isRegistered(name)) { + return false; + } + PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0, "your@email.com", playerName); + return plugin.database.saveAuth(auth); + } catch (NoSuchAlgorithmException ex) { + return false; + } + } + + /** + * Force a player to login + * + * @param Player + * player + */ + public void forceLogin(Player player) { + plugin.management.performLogin(player, "dontneed", true); + } + +} diff --git a/src/main/java/fr/xephi/authme/commands/AdminCommand.java b/src/main/java/fr/xephi/authme/commands/AdminCommand.java index eab60353..573d956f 100644 --- a/src/main/java/fr/xephi/authme/commands/AdminCommand.java +++ b/src/main/java/fr/xephi/authme/commands/AdminCommand.java @@ -260,7 +260,7 @@ public class AdminCommand implements CommandExecutor { return; } String hash = PasswordSecurity.getHash(Settings.getPasswordHash, lowpass, name); - PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com"); + PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com", name); if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) auth.setSalt(PasswordSecurity.userSalt.get(name)); else auth.setSalt(""); diff --git a/src/main/java/fr/xephi/authme/commands/EmailCommand.java b/src/main/java/fr/xephi/authme/commands/EmailCommand.java index b81627ed..241d543d 100644 --- a/src/main/java/fr/xephi/authme/commands/EmailCommand.java +++ b/src/main/java/fr/xephi/authme/commands/EmailCommand.java @@ -173,12 +173,9 @@ public class EmailCommand implements CommandExecutor { plugin.database.updatePassword(auth); plugin.mail.main(auth, thePass); m.send(player, "email_send"); - } catch (NoSuchAlgorithmException ex) { + } catch (NoSuchAlgorithmException | NoClassDefFoundError ex) { ConsoleLogger.showError(ex.getMessage()); m.send(sender, "error"); - } catch (NoClassDefFoundError ncdfe) { - ConsoleLogger.showError(ncdfe.getMessage()); - m.send(sender, "error"); } } else { m.send(player, "reg_email_msg"); diff --git a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java index 7ba5742a..c598f518 100644 --- a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java +++ b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java @@ -49,10 +49,10 @@ public class CrazyLoginConverter implements Converter { continue; if (args[0].equalsIgnoreCase("name")) continue; - String player = args[0].toLowerCase(); + String playerName = args[0].toLowerCase(); String psw = args[1]; if (psw != null) { - PlayerAuth auth = new PlayerAuth(player, psw, "127.0.0.1", System.currentTimeMillis(), player); + PlayerAuth auth = new PlayerAuth(playerName, psw, "127.0.0.1", System.currentTimeMillis(), playerName); database.saveAuth(auth); } } diff --git a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java index 3f8cc0c0..b2ddf704 100644 --- a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java +++ b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java @@ -74,17 +74,17 @@ public class RakamakConverter implements Converter { } users.close(); for (Entry m : playerPSW.entrySet()) { - String player = m.getKey(); - String psw = playerPSW.get(player); + String playerName = m.getKey(); + String psw = playerPSW.get(playerName); String ip; if (useIP) { - ip = playerIP.get(player); + ip = playerIP.get(playerName); } else { ip = "127.0.0.1"; } - PlayerAuth auth = new PlayerAuth(player, psw, ip, System.currentTimeMillis(), player); - if (PasswordSecurity.userSalt.containsKey(player)) - auth.setSalt(PasswordSecurity.userSalt.get(player)); + PlayerAuth auth = new PlayerAuth(playerName, psw, ip, System.currentTimeMillis(), playerName); + if (PasswordSecurity.userSalt.containsKey(playerName)) + auth.setSalt(PasswordSecurity.userSalt.get(playerName)); database.saveAuth(auth); } ConsoleLogger.info("Rakamak database has been imported correctly"); diff --git a/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java index 78a32aee..4af9f1bd 100644 --- a/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java +++ b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java @@ -30,7 +30,7 @@ public class RoyalAuthConverter implements Converter { if (!file.exists()) continue; RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file); - PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com"); + PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com", o.getName()); data.saveAuth(auth); } catch (Exception e) { ConsoleLogger.writeStackTrace(e); diff --git a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java index 0fb2c73e..4a193e15 100644 --- a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java +++ b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java @@ -44,9 +44,9 @@ public class vAuthFileReader { } if (pname == null) continue; - auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com"); + auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname); } else { - auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com"); + auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", name); } database.saveAuth(auth); } diff --git a/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java b/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java index 0c6d62fd..d9823562 100644 --- a/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java +++ b/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java @@ -47,7 +47,7 @@ public class xAuthToFlat { String pl = getIdPlayer(id); String psw = getPassword(id); if (psw != null && !psw.isEmpty() && pl != null) { - PlayerAuth auth = new PlayerAuth(pl, psw, "192.168.0.1", 0, "your@email.com"); + PlayerAuth auth = new PlayerAuth(pl, psw, "192.168.0.1", 0, "your@email.com", pl); database.saveAuth(auth); } } diff --git a/src/main/java/fr/xephi/authme/datasource/FlatFile.java b/src/main/java/fr/xephi/authme/datasource/FlatFile.java index 22fee78c..0f3872b4 100644 --- a/src/main/java/fr/xephi/authme/datasource/FlatFile.java +++ b/src/main/java/fr/xephi/authme/datasource/FlatFile.java @@ -1,751 +1,750 @@ -package fr.xephi.authme.datasource; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.cache.auth.PlayerCache; -import fr.xephi.authme.settings.Settings; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -public class FlatFile implements DataSource { - - /* - * file layout: - * - * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ: - * LASTPOSWORLD:EMAIL - * - * Old but compatible: - * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY - * :LASTPOSZ:LASTPOSWORLD PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS - * PLAYERNAME:HASHSUM:IP PLAYERNAME:HASHSUM - */ - private File source; - - public FlatFile() { - source = Settings.AUTH_FILE; - try { - source.createNewFile(); - } catch (IOException e) { - ConsoleLogger.showError(e.getMessage()); - if (Settings.isStopEnabled) { - ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN..."); - AuthMe.getInstance().getServer().shutdown(); - } - if (!Settings.isStopEnabled) { - AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); - } - e.printStackTrace(); - } - } - - @Override - public synchronized boolean isAuthAvailable(String user) { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length > 1 && args[0].equalsIgnoreCase(user)) { - return true; - } - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - return false; - } - - @Override - public synchronized boolean saveAuth(PlayerAuth auth) { - if (isAuthAvailable(auth.getNickname())) { - return false; - } - BufferedWriter bw = null; - try { - bw = new BufferedWriter(new FileWriter(source, true)); - bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":" + auth.getWorld() + ":" + auth.getEmail() + "\n"); - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - if (bw != null) { - try { - bw.close(); - } catch (IOException ex) { - } - } - } - return true; - } - - @Override - public synchronized boolean updatePassword(PlayerAuth auth) { - if (!isAuthAvailable(auth.getNickname())) { - return false; - } - PlayerAuth newAuth = null; - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args[0].equals(auth.getNickname())) { - switch (args.length) { - case 4: { - newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", args[0]); - break; - } - case 7: { - newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", args[0]); - break; - } - case 8: { - newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0]); - break; - } - case 9: { - newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0]); - break; - } - default: { - newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", args[0]); - break; - } - } - break; - } - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - if (newAuth != null) { - removeAuth(auth.getNickname()); - saveAuth(newAuth); - } - return true; - } - - @Override - public boolean updateSession(PlayerAuth auth) { - if (!isAuthAvailable(auth.getNickname())) { - return false; - } - PlayerAuth newAuth = null; - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args[0].equalsIgnoreCase(auth.getNickname())) { - switch (args.length) { - case 4: { - newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]); - break; - } - case 7: { - newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", args[0]); - break; - } - case 8: { - newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0]); - break; - } - case 9: { - newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0]); - break; - } - default: { - newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]); - break; - } - } - break; - } - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - if (newAuth != null) { - removeAuth(auth.getNickname()); - saveAuth(newAuth); - } - return true; - } - - @Override - public boolean updateQuitLoc(PlayerAuth auth) { - if (!isAuthAvailable(auth.getNickname())) { - return false; - } - PlayerAuth newAuth = null; - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args[0].equalsIgnoreCase(auth.getNickname())) { - newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), auth.getEmail(), args[0]); - break; - } - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - if (newAuth != null) { - removeAuth(auth.getNickname()); - saveAuth(newAuth); - } - return true; - } - - @Override - public int getIps(String ip) { - BufferedReader br = null; - int countIp = 0; - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length > 3 && args[2].equals(ip)) { - countIp++; - } - } - return countIp; - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return 0; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return 0; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - } - - @Override - public int purgeDatabase(long until) { - BufferedReader br = null; - BufferedWriter bw = null; - ArrayList lines = new ArrayList(); - int cleared = 0; - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length >= 4) { - if (Long.parseLong(args[3]) >= until) { - lines.add(line); - continue; - } - } - cleared++; - } - bw = new BufferedWriter(new FileWriter(source)); - for (String l : lines) { - bw.write(l + "\n"); - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return cleared; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return cleared; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - if (bw != null) { - try { - bw.close(); - } catch (IOException ex) { - } - } - } - return cleared; - } - - @Override - public List autoPurgeDatabase(long until) { - BufferedReader br = null; - BufferedWriter bw = null; - ArrayList lines = new ArrayList(); - List cleared = new ArrayList(); - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length >= 4) { - if (Long.parseLong(args[3]) >= until) { - lines.add(line); - continue; - } - } - cleared.add(args[0]); - } - bw = new BufferedWriter(new FileWriter(source)); - for (String l : lines) { - bw.write(l + "\n"); - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return cleared; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return cleared; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - if (bw != null) { - try { - bw.close(); - } catch (IOException ex) { - } - } - } - return cleared; - } - - @Override - public synchronized boolean removeAuth(String user) { - if (!isAuthAvailable(user)) { - return false; - } - BufferedReader br = null; - BufferedWriter bw = null; - ArrayList lines = new ArrayList(); - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length > 1 && !args[0].equals(user)) { - lines.add(line); - } - } - bw = new BufferedWriter(new FileWriter(source)); - for (String l : lines) { - bw.write(l + "\n"); - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - if (bw != null) { - try { - bw.close(); - } catch (IOException ex) { - } - } - } - return true; - } - - @Override - public synchronized PlayerAuth getAuth(String user) { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args[0].equalsIgnoreCase(user)) { - switch (args.length) { - case 2: - return new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0]); - case 3: - return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0]); - case 4: - return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0]); - case 7: - return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "unavailableworld", "your@email.com", args[0]); - case 8: - return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0]); - case 9: - return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0]); - } - } - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return null; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return null; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - return null; - } - - @Override - public synchronized void close() { - } - - @Override - public void reload() { - } - - @Override - public boolean updateEmail(PlayerAuth auth) { - if (!isAuthAvailable(auth.getNickname())) { - return false; - } - PlayerAuth newAuth = null; - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(source)); - String line = ""; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args[0].equals(auth.getNickname())) { - newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], auth.getEmail(), args[0]); - break; - } - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return false; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - if (newAuth != null) { - removeAuth(auth.getNickname()); - saveAuth(newAuth); - } - return true; - } - - @Override - public boolean updateSalt(PlayerAuth auth) { - return false; - } - - @Override - public List getAllAuthsByName(PlayerAuth auth) { - BufferedReader br = null; - List countIp = new ArrayList(); - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length > 3 && args[2].equals(auth.getIp())) { - countIp.add(args[0]); - } - } - return countIp; - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return new ArrayList(); - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return new ArrayList(); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - } - - @Override - public List getAllAuthsByIp(String ip) { - BufferedReader br = null; - List countIp = new ArrayList(); - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length > 3 && args[2].equals(ip)) { - countIp.add(args[0]); - } - } - return countIp; - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return new ArrayList(); - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return new ArrayList(); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - } - - @Override - public List getAllAuthsByEmail(String email) { - BufferedReader br = null; - List countEmail = new ArrayList(); - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - if (args.length > 8 && args[8].equals(email)) { - countEmail.add(args[0]); - } - } - return countEmail; - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return new ArrayList(); - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return new ArrayList(); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - } - - @Override - public void purgeBanned(List banned) { - BufferedReader br = null; - BufferedWriter bw = null; - ArrayList lines = new ArrayList(); - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - try { - if (banned.contains(args[0])) { - lines.add(line); - } - } catch (NullPointerException npe) { - } catch (ArrayIndexOutOfBoundsException aioobe) { - } - } - bw = new BufferedWriter(new FileWriter(source)); - for (String l : lines) { - bw.write(l + "\n"); - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - if (bw != null) { - try { - bw.close(); - } catch (IOException ex) { - } - } - } - return; - } - - @Override - public DataSourceType getType() { - return DataSourceType.FILE; - } - - @Override - public boolean isLogged(String user) { - return PlayerCache.getInstance().isAuthenticated(user); - } - - @Override - public void setLogged(String user) { - } - - @Override - public void setUnlogged(String user) { - } - - @Override - public void purgeLogged() { - } - - @Override - public int getAccountsRegistered() { - BufferedReader br = null; - int result = 0; - try { - br = new BufferedReader(new FileReader(source)); - while ((br.readLine()) != null) { - result++; - } - } catch (Exception ex) { - ConsoleLogger.showError(ex.getMessage()); - return result; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - return result; - } - - @Override - public void updateName(String oldone, String newone) { - PlayerAuth auth = this.getAuth(oldone); - auth.setName(newone); - this.saveAuth(auth); - this.removeAuth(oldone); - } - - @Override - public List getAllAuths() { - BufferedReader br = null; - List auths = new ArrayList(); - try { - br = new BufferedReader(new FileReader(source)); - String line; - while ((line = br.readLine()) != null) { - String[] args = line.split(":"); - switch (args.length) { - case 2: - auths.add(new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0])); - break; - case 3: - auths.add(new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0])); - break; - case 4: - auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0])); - break; - case 7: - auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "unavailableworld", "your@email.com", args[0])); - break; - case 8: - auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0])); - break; - case 9: - auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0])); - break; - } - } - } catch (FileNotFoundException ex) { - ConsoleLogger.showError(ex.getMessage()); - return auths; - } catch (IOException ex) { - ConsoleLogger.showError(ex.getMessage()); - return auths; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - } - } - } - return auths; - } - - @Override - public List getLoggedPlayers() { - return new ArrayList(); - } -} +package fr.xephi.authme.datasource; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.settings.Settings; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +public class FlatFile implements DataSource { + + /* + * file layout: + * + * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ: + * LASTPOSWORLD:EMAIL + * + * Old but compatible: + * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY + * :LASTPOSZ:LASTPOSWORLD PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS + * PLAYERNAME:HASHSUM:IP PLAYERNAME:HASHSUM + */ + private File source; + + public FlatFile() { + source = Settings.AUTH_FILE; + try { + source.createNewFile(); + } catch (IOException e) { + ConsoleLogger.showError(e.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN..."); + AuthMe.getInstance().getServer().shutdown(); + } + if (!Settings.isStopEnabled) { + AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); + } + e.printStackTrace(); + } + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 1 && args[0].equalsIgnoreCase(user)) { + return true; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return false; + } + + @Override + public synchronized boolean saveAuth(PlayerAuth auth) { + if (isAuthAvailable(auth.getNickname())) { + return false; + } + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter(source, true)); + bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":" + auth.getWorld() + ":" + auth.getEmail() + "\n"); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return true; + } + + @Override + public synchronized boolean updatePassword(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equals(auth.getNickname())) { + switch (args.length) { + case 4: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + case 7: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", args[0]); + break; + } + case 8: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0]); + break; + } + case 9: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0]); + break; + } + default: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + } + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } + + @Override + public boolean updateSession(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equalsIgnoreCase(auth.getNickname())) { + switch (args.length) { + case 4: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + case 7: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", args[0]); + break; + } + case 8: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0]); + break; + } + case 9: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0]); + break; + } + default: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + } + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } + + @Override + public boolean updateQuitLoc(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equalsIgnoreCase(auth.getNickname())) { + newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), auth.getEmail(), args[0]); + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } + + @Override + public int getIps(String ip) { + BufferedReader br = null; + int countIp = 0; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 3 && args[2].equals(ip)) { + countIp++; + } + } + return countIp; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return 0; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return 0; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public int purgeDatabase(long until) { + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + int cleared = 0; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length >= 4) { + if (Long.parseLong(args[3]) >= until) { + lines.add(line); + continue; + } + } + cleared++; + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return cleared; + } + + @Override + public List autoPurgeDatabase(long until) { + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + List cleared = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length >= 4) { + if (Long.parseLong(args[3]) >= until) { + lines.add(line); + continue; + } + } + cleared.add(args[0]); + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return cleared; + } + + @Override + public synchronized boolean removeAuth(String user) { + if (!isAuthAvailable(user)) { + return false; + } + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 1 && !args[0].equals(user)) { + lines.add(line); + } + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return true; + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equalsIgnoreCase(user)) { + switch (args.length) { + case 2: + return new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0]); + case 3: + return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0]); + case 4: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0]); + case 7: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "unavailableworld", "your@email.com", args[0]); + case 8: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0]); + case 9: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0]); + } + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return null; + } + + @Override + public synchronized void close() { + } + + @Override + public void reload() { + } + + @Override + public boolean updateEmail(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line = ""; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equals(auth.getNickname())) { + newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], auth.getEmail(), args[0]); + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } + + @Override + public boolean updateSalt(PlayerAuth auth) { + return false; + } + + @Override + public List getAllAuthsByName(PlayerAuth auth) { + BufferedReader br = null; + List countIp = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 3 && args[2].equals(auth.getIp())) { + countIp.add(args[0]); + } + } + return countIp; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public List getAllAuthsByIp(String ip) { + BufferedReader br = null; + List countIp = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 3 && args[2].equals(ip)) { + countIp.add(args[0]); + } + } + return countIp; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public List getAllAuthsByEmail(String email) { + BufferedReader br = null; + List countEmail = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 8 && args[8].equals(email)) { + countEmail.add(args[0]); + } + } + return countEmail; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public void purgeBanned(List banned) { + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + try { + if (banned.contains(args[0])) { + lines.add(line); + } + } catch (NullPointerException | ArrayIndexOutOfBoundsException exc) { + } + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return; + } + + @Override + public DataSourceType getType() { + return DataSourceType.FILE; + } + + @Override + public boolean isLogged(String user) { + return PlayerCache.getInstance().isAuthenticated(user); + } + + @Override + public void setLogged(String user) { + } + + @Override + public void setUnlogged(String user) { + } + + @Override + public void purgeLogged() { + } + + @Override + public int getAccountsRegistered() { + BufferedReader br = null; + int result = 0; + try { + br = new BufferedReader(new FileReader(source)); + while ((br.readLine()) != null) { + result++; + } + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return result; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return result; + } + + @Override + public void updateName(String oldone, String newone) { + PlayerAuth auth = this.getAuth(oldone); + auth.setName(newone); + this.saveAuth(auth); + this.removeAuth(oldone); + } + + @Override + public List getAllAuths() { + BufferedReader br = null; + List auths = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + switch (args.length) { + case 2: + auths.add(new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0])); + break; + case 3: + auths.add(new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0])); + break; + case 4: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0])); + break; + case 7: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "unavailableworld", "your@email.com", args[0])); + break; + case 8: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", args[0])); + break; + case 9: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], args[0])); + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return auths; + } + + @Override + public List getLoggedPlayers() { + return new ArrayList<>(); + } +} diff --git a/src/main/java/fr/xephi/authme/plugin/manager/EssSpawn.java b/src/main/java/fr/xephi/authme/plugin/manager/EssSpawn.java index 673d7450..cd422b48 100644 --- a/src/main/java/fr/xephi/authme/plugin/manager/EssSpawn.java +++ b/src/main/java/fr/xephi/authme/plugin/manager/EssSpawn.java @@ -32,9 +32,7 @@ public class EssSpawn extends CustomConfiguration { return null; Location location = new Location(Bukkit.getWorld(this.getString("spawns.default.world")), this.getDouble("spawns.default.x"), this.getDouble("spawns.default.y"), this.getDouble("spawns.default.z"), Float.parseFloat(this.getString("spawns.default.yaw")), Float.parseFloat(this.getString("spawns.default.pitch"))); return location; - } catch (NullPointerException npe) { - return null; - } catch (NumberFormatException nfe) { + } catch (NullPointerException | NumberFormatException npe) { return null; } } diff --git a/src/main/java/fr/xephi/authme/security/crypts/PHPFUSION.java b/src/main/java/fr/xephi/authme/security/crypts/PHPFUSION.java index d9f50084..25d9897b 100644 --- a/src/main/java/fr/xephi/authme/security/crypts/PHPFUSION.java +++ b/src/main/java/fr/xephi/authme/security/crypts/PHPFUSION.java @@ -33,10 +33,10 @@ public class PHPFUSION implements EncryptionMethod { hash.append(hex); } digest = hash.toString(); - } catch (UnsupportedEncodingException e) { - } catch (InvalidKeyException e) { - } catch (NoSuchAlgorithmException e) { + } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) { + //ingore } + return digest; } diff --git a/src/main/java/fr/xephi/authme/security/crypts/XF.java b/src/main/java/fr/xephi/authme/security/crypts/XF.java index 54ba7035..b6ad9bde 100644 --- a/src/main/java/fr/xephi/authme/security/crypts/XF.java +++ b/src/main/java/fr/xephi/authme/security/crypts/XF.java @@ -44,7 +44,7 @@ public class XF implements EncryptionMethod { } public String regmatch(String pattern, String line) { - List allMatches = new ArrayList(); + List allMatches = new ArrayList<>(); Matcher m = Pattern.compile(pattern).matcher(line); while (m.find()) { allMatches.add(m.group(1)); diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/MacBasedPRF.java b/src/main/java/fr/xephi/authme/security/pbkdf2/MacBasedPRF.java index 27f8bc0c..b7d80382 100644 --- a/src/main/java/fr/xephi/authme/security/pbkdf2/MacBasedPRF.java +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/MacBasedPRF.java @@ -9,7 +9,7 @@ import javax.crypto.spec.SecretKeySpec; /** * Default PRF implementation based on standard javax.crypt.Mac mechanisms. - * + * *
*

* A free Java implementation of Password Based Key Derivation Function 2 as @@ -37,7 +37,7 @@ import javax.crypto.spec.SecretKeySpec; * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html" * >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. *

- * + * * @author Matthias Gärtner * @version 1.0 */ @@ -51,7 +51,7 @@ public class MacBasedPRF implements PRF { /** * Create Mac-based Pseudo Random Function. - * + * * @param macAlgorithm * Mac algorithm to use, i.e. HMacSHA1 or HMacMD5. */ @@ -70,9 +70,7 @@ public class MacBasedPRF implements PRF { try { mac = Mac.getInstance(macAlgorithm, provider); hLen = mac.getMacLength(); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } catch (NoSuchProviderException e) { + } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException(e); } } diff --git a/src/main/java/fr/xephi/authme/settings/OtherAccounts.java b/src/main/java/fr/xephi/authme/settings/OtherAccounts.java index 4da7b677..697104d4 100644 --- a/src/main/java/fr/xephi/authme/settings/OtherAccounts.java +++ b/src/main/java/fr/xephi/authme/settings/OtherAccounts.java @@ -44,8 +44,8 @@ public class OtherAccounts extends CustomConfiguration { this.getStringList(uuid.toString()).add(player.getName()); save(); } - } catch (NoSuchMethodError e) { - } catch (Exception e) { + } catch (NoSuchMethodError | Exception e) { + //ingore } } @@ -58,10 +58,9 @@ public class OtherAccounts extends CustomConfiguration { this.getStringList(uuid.toString()).remove(player.getName()); save(); } - } catch (NoSuchMethodError e) { - } catch (Exception e) { + } catch (NoSuchMethodError | Exception e) { + //ignore } - } public List getAllPlayersByUUID(UUID uuid) { diff --git a/src/main/java/fr/xephi/authme/settings/Spawn.java b/src/main/java/fr/xephi/authme/settings/Spawn.java index 6827387a..81b0891e 100644 --- a/src/main/java/fr/xephi/authme/settings/Spawn.java +++ b/src/main/java/fr/xephi/authme/settings/Spawn.java @@ -90,9 +90,7 @@ public class Spawn extends CustomConfiguration { return null; Location location = new Location(Bukkit.getWorld(this.getString("spawn.world")), this.getDouble("spawn.x"), this.getDouble("spawn.y"), this.getDouble("spawn.z"), Float.parseFloat(this.getString("spawn.yaw")), Float.parseFloat(this.getString("spawn.pitch"))); return location; - } catch (NullPointerException npe) { - return null; - } catch (NumberFormatException nfe) { + } catch (NullPointerException | NumberFormatException npe) { return null; } } @@ -103,9 +101,7 @@ public class Spawn extends CustomConfiguration { return null; Location location = new Location(Bukkit.getWorld(this.getString("firstspawn.world")), this.getDouble("firstspawn.x"), this.getDouble("firstspawn.y"), this.getDouble("firstspawn.z"), Float.parseFloat(this.getString("firstspawn.yaw")), Float.parseFloat(this.getString("firstspawn.pitch"))); return location; - } catch (NullPointerException npe) { - return null; - } catch (NumberFormatException nfe) { + } catch (NullPointerException | NumberFormatException npe) { return null; } } From c8b13184491a01c25a3a60d65f93c70bd05ea9a5 Mon Sep 17 00:00:00 2001 From: "Gabriele C." Date: Sat, 3 Oct 2015 23:00:00 +0200 Subject: [PATCH 23/27] Update AuthMePlayerListener.java --- src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java index 6da8fb9d..5c213820 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java @@ -271,6 +271,7 @@ public class AuthMePlayerListener implements Listener { } } + // TODO: Add message to the messages file!!! if (Settings.antiBotInAction) { if (!isAuthAvailable) { event.setKickMessage("AntiBot service in action! You actually need to be registered!"); From 33d897ea376609b72bcf2fd3f10a91204892c9aa Mon Sep 17 00:00:00 2001 From: "Gabriele C." Date: Sat, 3 Oct 2015 23:08:11 +0200 Subject: [PATCH 24/27] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a8a92d1..056700d3 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,6 @@ GameHosting.it is leader in Italy as Game Server Provider. With its own DataCent [![GameHosting](http://www.gamehosting.it/images/bn3.png)](http://www.gamehosting.it) #####Credits -

Team members: Xephi(Main Developer, Author), Maxetto(Contributor) and sgdc3(Contributor) +

Team members: look at the team.txt file

Credit for old version of the plugin to: d4rkwarriors, fabe1337 , Whoami2 and pomo4ka

Thanks also to: AS1LV3RN1NJA, Hoeze and eprimex

From 06e098ab392d496e400ab946300bb90b983d350d Mon Sep 17 00:00:00 2001 From: "Gabriele C." Date: Sun, 4 Oct 2015 02:02:45 +0200 Subject: [PATCH 25/27] cleanup --- src/main/java/fr/xephi/authme/AuthMe.java | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index efabc5de..5611fec6 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -192,9 +192,6 @@ public class AuthMe extends JavaPlugin { // Check Multiverse checkMultiverse(); - // Check PerWorldInventories Version - checkPerWorldInventories(); - // Check ChestShop checkChestShop(); @@ -456,25 +453,6 @@ public class AuthMe extends JavaPlugin { } } - // Check PerWorldInventories version - public void checkPerWorldInventories() { - if (server.getPluginManager().isPluginEnabled("PerWorldInventories")) { - double version = 0; - String ver = server.getPluginManager().getPlugin("PerWorldInventories").getDescription().getVersion(); - try { - version = Double.valueOf(ver.split(" ")[0]); - } catch (NumberFormatException nfe) { - try { - version = Double.valueOf(ver.split("t")[0]); - } catch (NumberFormatException ignore) { - } - } - if (version < 1.57) { - ConsoleLogger.showError("Please Update your PerWorldInventories version! INVENTORY WIPE may occur!"); - } - } - } - // Get the Multiverse plugin public void checkMultiverse() { if (Settings.multiverse && server.getPluginManager().isPluginEnabled("Multiverse-Core")) { From 8bda788a783475d3133e6932e0da9080fad71fc2 Mon Sep 17 00:00:00 2001 From: games647 Date: Sun, 4 Oct 2015 10:49:17 +0200 Subject: [PATCH 26/27] Improve performance by correct order of some checks. (i.e. check if the minor things before making a blocking call instead of reverse order) --- src/main/java/fr/xephi/authme/Utils.java | 7 ++- .../authme/listener/AuthMePlayerListener.java | 47 ++++++------------- 2 files changed, 20 insertions(+), 34 deletions(-) diff --git a/src/main/java/fr/xephi/authme/Utils.java b/src/main/java/fr/xephi/authme/Utils.java index 70171dc0..2a9e8c6e 100644 --- a/src/main/java/fr/xephi/authme/Utils.java +++ b/src/main/java/fr/xephi/authme/Utils.java @@ -175,15 +175,18 @@ public class Utils { if (player == null || Utils.isUnrestricted(player)) { return true; } + String name = player.getName().toLowerCase(); if (PlayerCache.getInstance().isAuthenticated(name)) { return true; } - if (!plugin.database.isAuthAvailable(name)) { - if (!Settings.isForcedRegistrationEnabled) { + + if (!Settings.isForcedRegistrationEnabled) { + if (!plugin.database.isAuthAvailable(name)) { return true; } } + return false; } diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java index 5c213820..900a01cf 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java @@ -9,7 +9,6 @@ import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; -import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Settings; import org.bukkit.Bukkit; @@ -66,9 +65,6 @@ public class AuthMePlayerListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { - if (Utils.checkAuth(event.getPlayer())) - return; - String msg = event.getMessage(); if (msg.equalsIgnoreCase("/worldedit cui")) return; @@ -81,8 +77,10 @@ public class AuthMePlayerListener implements Listener { if (Settings.allowCommands.contains(cmd)) return; - event.setMessage("/notloggedin"); - event.setCancelled(true); + if (!Utils.checkAuth(event.getPlayer())) { + event.setMessage("/notloggedin"); + event.setCancelled(true); + } } @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) @@ -246,48 +244,34 @@ public class AuthMePlayerListener implements Listener { if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) return; - if (!Settings.countriesBlacklist.isEmpty()) { + if (!Settings.countriesBlacklist.isEmpty() && !isAuthAvailable + && !plugin.authmePermissible(player, "authme.bypassantibot")) { String code = Utils.getCountryCode(event.getAddress().getHostAddress()); - if (((code == null) || (Settings.countriesBlacklist.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) { + if (((code == null) || Settings.countriesBlacklist.contains(code))) { event.setKickMessage(m.send("country_banned")[0]); event.setResult(PlayerLoginEvent.Result.KICK_OTHER); return; } } - if (Settings.enableProtection && !Settings.countries.isEmpty()) { + if (Settings.enableProtection && !Settings.countries.isEmpty() && !isAuthAvailable + && !plugin.authmePermissible(player, "authme.bypassantibot")) { String code = Utils.getCountryCode(event.getAddress().getHostAddress()); - if (((code == null) || (!Settings.countries.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) { + if (((code == null) || !Settings.countries.contains(code))) { event.setKickMessage(m.send("country_banned")[0]); event.setResult(PlayerLoginEvent.Result.KICK_OTHER); return; } } - if (Settings.isKickNonRegisteredEnabled && !Settings.antiBotInAction) { - if (!isAuthAvailable) { - event.setKickMessage(m.send("reg_only")[0]); - event.setResult(PlayerLoginEvent.Result.KICK_OTHER); - return; - } - } - // TODO: Add message to the messages file!!! - if (Settings.antiBotInAction) { - if (!isAuthAvailable) { + if (Settings.isKickNonRegisteredEnabled && !isAuthAvailable) { + if (Settings.antiBotInAction) { event.setKickMessage("AntiBot service in action! You actually need to be registered!"); event.setResult(PlayerLoginEvent.Result.KICK_OTHER); return; - } - } - - if (isAuthAvailable && plugin.database.getType() != DataSource.DataSourceType.FILE) { - PlayerAuth auth = plugin.database.getAuth(name); - if (auth.getRealName() != null && !auth.getRealName().isEmpty() - && !auth.getRealName().equalsIgnoreCase("Player") && !auth.getRealName().equalsIgnoreCase(name)) { - event.setKickMessage(m.send("same_nick")[0]); + } else { + event.setKickMessage(m.send("reg_only")[0]); event.setResult(PlayerLoginEvent.Result.KICK_OTHER); - if (Settings.banUnsafeIp) - plugin.getServer().banIP(player.getAddress().getAddress().getHostAddress()); return; } } @@ -372,7 +356,7 @@ public class AuthMePlayerListener implements Listener { plugin.management.performQuit(player, false); - if (plugin.database.isAuthAvailable(name) && !PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection) + if (!PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection) event.setQuitMessage(null); } @@ -430,7 +414,6 @@ public class AuthMePlayerListener implements Listener { public void run() { player.closeInventory(); } - }, 1); } From 5576b117c98c7bd697b1a42ae0ee6691ec49e74d Mon Sep 17 00:00:00 2001 From: Gabriele C Date: Sun, 4 Oct 2015 14:33:21 +0200 Subject: [PATCH 27/27] cleanup + moved legacy chestshop support --- .../NewConfiguration/actions.yml | 33 ----- .../NewConfiguration/advanced.yml | 113 ------------------ .../NewConfiguration/database.yml | 68 ----------- .../NewConfiguration/email.yml | 40 ------- .../NewConfiguration/general.yml | 100 ---------------- .../converters.txt | 21 ---- pom.xml | 102 +--------------- src/main/java/fr/xephi/authme/AuthMe.java | 50 ++------ .../listener/AuthMeChestShopListener.java | 25 ---- .../authme/listener/AuthMeServerListener.java | 6 - .../fr/xephi/authme/settings/Settings.java | 10 +- src/main/resources/config.yml | 2 - 12 files changed, 16 insertions(+), 554 deletions(-) delete mode 100644 PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/actions.yml delete mode 100644 PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/advanced.yml delete mode 100644 PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/database.yml delete mode 100644 PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/email.yml delete mode 100644 PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/general.yml delete mode 100644 PROTOTYPE AREA (future stuff and etc...)/converters.txt delete mode 100644 src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/actions.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/actions.yml deleted file mode 100644 index 86a03270..00000000 --- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/actions.yml +++ /dev/null @@ -1,33 +0,0 @@ -# ForcedActions AuthMeReloaded configuration file - -forcedActions: - -# example1: -# at: firstlogin -# executedBy: console -# commands: -# - 'msg %p Welcome!' -# - pex user set group Player - -# example2: -# at: connection -# executedBy: console -# commands: -# - 'msg %p You need to register yourself to play this server!' - -# -# Avariable events: -# connection -# firstconnection -# login -# firstlogin -# wrongpassword -# disconnection -# logout -# serverstop -# serverstart -# pluginreload -# mysqlerror -# antiboton -# antibotoff -# \ No newline at end of file diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/advanced.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/advanced.yml deleted file mode 100644 index a432ec9c..00000000 --- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/advanced.yml +++ /dev/null @@ -1,113 +0,0 @@ -# Advanced AuthMeReloaded configuration file - -sessionLogin: - # Do you want to enable session? When enabled - # the ip of a player will be bound to the nickname - # of the player on login. As long as neither of those - # two change players don't have to login on a reconnect - enabled: false - # After how many minutes a session should timeout? - # 0 for unlimitted sessions, use 0 at your own risk! - # consider that session will end only after timeout, and - # if player's ip is changed but the timeout treshould isent - # ended, player will kick out of sever for invalidSession! - timeout: 10 - # Do we need to timeout the session if the player is offline - # And try to login with an another IP Address? - sessionExpireOnIpChange: true - -security: - # Online players aren't kicked out for "Logged in from another location!", this option should always be set to true! - forceSingleSession: true - # Should we display all other accounts from a player when he joins? - # permission: /authme.admin.accounts - displayOtherAccounts: true - - # Should the purge command can be performed only from the console? - purgeOnlyFromConsole: true - - # Minimum value for the purge ingame command (if enabled), prevent the destruction of the entire database. - minIngamePurgeDays: 30 - - captcha: - # Do players need to write a captcha code if they use too many times a wrong password - useCaptcha: false - # Max allowed tries before request a captcha - maxLoginTry: 5 - # Captcha length - captchaLength: 5 - - # Restricted users will be kicked if their IP aren't the same specified below. - # Usage: - username;ip - RestrictedUsers: - - playername;127.0.0.1 - - # User listed below will bypass every login/registration system. CASE SENSITIVE!!! - # Use this at your own risk!!! USE ONLY WITH ONLINE MODE SERVERS!!! - # This option can add compatibility with BuildCraft and some other mods. - UnrestrictedName: [] - - passwordEncryption: - # possible values: MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, - # PLAINTEXT ( unhashed password), - # MYBB, IPB3, PHPFUSION, SMF, XENFORO, SALTED2MD5, JOOMLA, BCRYPT, WBB3, SHA512, - # DOUBLEMD5, PBKDF2, WORDPRESS, ROYALAUTH, CUSTOM(for developpers only) - passwordHash: SHA256 - # salt length for the SALTED2MD5 MD5(MD5(password)+salt) - doubleMD5SaltLength: 8 - # If password checking return false , do we need to check with all - # other password algorithm to check an old password ? - # AuthMe will update the password to the new passwordHash ! - supportOldPasswordHash: false - - SQLProblem: - # Stop the server if we can't contact the sql database - # Take care with this, if you set that to false, - # AuthMe automatically disable and the server is not protected! - stopServer: true - ReloadCommand: - # /reload support - useReloadCommandSupport: true - console: - # Remove spam console - noConsoleSpam: false - # Replace passwords in the console when player type a command like /login - removePassword: true - -externalBoard: - # MySQL column for the salt , needed for some forum/cms support - mySQLColumnSalt: '' - # MySQL column for the group, needed for some forum/cms support - mySQLColumnGroup: '' - # -1 mean disabled. If u want that only - # activated player can login in your server - # u can put in this options the group number - # of unactivated user, needed for some forum/cms support - nonActivedUserGroup: -1 - # Other MySQL columns where we need to put the Username (case sensitive) - mySQLOtherUsernameColumns: [] - # How much Log to Round needed in BCrypt(do not change it if you do not know what's your doing) - bCryptLog2Round: 10 - # phpBB prefix defined during phpbb installation process - phpbbTablePrefix: 'phpbb_' - # phpBB activated group id , 2 is default registered group defined by phpbb - phpbbActivatedGroupId: 2 - # WordPress prefix defined during WordPress installation process - wordpressTablePrefix: 'wp_' - -hooks: - # Do we need to hook with multiverse for spawn checking? - multiverse: true - # Do we need to hook with ChestShop for prevent buy or selling ? - chestshop: true - # Do we need to hook with BungeeCord for get the real Player ip ? - bungeecord: false - # Do we need to disable Essentials SocialSpy on join ? - disableSocialSpy: true - # Do we need to cache custom Attributes ? - customAttributes: false - -# Spawn Priority, Values : authme, essentials, multiverse, default -spawnPriority: authme,essentials,multiverse,default -# AuthMe will NEVER teleport players ! -noTeleport: false diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/database.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/database.yml deleted file mode 100644 index 6c26091b..00000000 --- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/database.yml +++ /dev/null @@ -1,68 +0,0 @@ -# Database AuthMeReloaded configuration file - -# What type of database do you want to use? Avariable options: sqlite, mysql, redis -backend: sqlite -# Do you like to cache all the queries? (Performance Boost) -caching: true - -# Database Name -databaseName: authme -# Table of the database -tableName: authme - -# MySql Database connection settings -# Avariable only if the AuthMeReloaded-Mysql module is installed! -mysql: - port: '3306' - host: 127.0.0.1 - username: authme - password: '12345' - -# Redis Database connection settings -# Avariable only if the AuthMeReloaded-Redis module is installed! -redis: - # Get Redis from http://redis.io/ - host: 127.0.0.1 - port: 6379 - # If your Redis server uses AUTH, set here the password. - password: "" - -# Database column names -columnNames: - idColumn: id - nameColumn: username - realNameColumn: realname - passwordColumn: password - ipColumn: ip - emailColumn: email - loginStatusColumn: loginstatus - lastLoginColumn: lastlogin - lastlLocationXColumn: x - lastLocationYColumn: y - lastLocationZColumn: z - lastLocationWorldColumn: world - -backup: - # Enable or disable Automatic Backup of the SQLite database, destination path: "/AuthMe/backups/%date%/%timestamp%.sql" - ActivateBackup: false - # Interval time (in minutes), set to 0 to disable periodic backup - Interval: 300 - # Do you want to perform a Backup when the server starts? - OnServerStart: false - # Do you want to perform a Backup when the server stops? - OnServerStop: true - -purge: - # Does AuthMe need to purge automatically old unused accounts? - useAutoPurge: false - # Number of Days required to mark an account as Unused - daysBeforeRemovePlayer: 60 - # What to remove - remove: - playerInventoryFile: true - essentialsFiles: true - permissions: true - limitedCreativesInventories: true - antiXRayFiles: true - # World where players.dat are stored (necessary to remove inventory files) - defaultWorld: 'world' diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/email.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/email.yml deleted file mode 100644 index 48c9b59a..00000000 --- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/email.yml +++ /dev/null @@ -1,40 +0,0 @@ -emailSystem: - # Do you want to replace the Password registration with an Email registration method? - enableEmailRegistration: false - # Do you want to enable the double check of the email address during a player registration? - # When it's true, registration require that kind of command: - # /register - doubleEmailCheck: true - # Like maxRegPerIp but with emails - maxRegPerEmail: 1 - # Do you want to recall players to add an email to their accounts? - recallPlayers: true - # Delay in minute for the recall scheduler - delayRecall: 5 - - passwordRecovery: - # Recovery password length - RecoveryPasswordLength: 8 - # Recovery Email subject - mailSubject: 'Your new AuthMe Password' - # Recovery Email text - mailText: 'Dear ,

This is your new AuthMe password for the server

:



Do not forget to change password after login!
/changepassword newPassword' - - smtpOptions: - # SMTP server host - mailSMTP: smtp.gmail.com - # SMTP server port - mailPort: 465 - # Email account that sends the mails - mailAccount: '' - # Email account's password - mailPassword: '' - # Custom SenderName, that replace the mailAccount name in the emails - mailSenderName: '' - - emailSecurity: - # Blacklisted domains for emails - emailBlacklist: - - 10minutemail.com - # Do you like a Whitelist instead of a Blacklist? - blacklistAsWhitelist: false diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/general.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/general.yml deleted file mode 100644 index 48931ea4..00000000 --- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/general.yml +++ /dev/null @@ -1,100 +0,0 @@ -# █████╗ ██╗ ██╗████████╗██╗ ██╗ ███╗ ███╗███████╗ ██████╗ ███████╗██╗ ██████╗ ██████╗ ███████╗██████╗ -# ██╔══██╗██║ ██║╚══██╔══╝██║ ██║ ████╗ ████║██╔════╝ ██╔══██╗██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝██╔══██╗ -# ███████║██║ ██║ ██║ ███████║ ██╔████╔██║█████╗ ██████╔╝█████╗ ██║ ██║ ██║██║ ██║█████╗ ██║ ██║ -# ██╔══██║██║ ██║ ██║ ██╔══██║ ██║╚██╔╝██║██╔══╝ ██╔══██╗██╔══╝ ██║ ██║ ██║██║ ██║██╔══╝ ██║ ██║ -# ██║ ██║╚██████╔╝ ██║ ██║ ██║ ██║ ╚═╝ ██║███████╗ ██║ ██║███████╗███████╗╚██████╔╝██████╔╝███████╗██████╔╝ -# ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═════╝ - -# Welcome to the AuthMeReloaded main configuration file! - -# Available languages: en, de, br, cz, pl, fr, ru, hu, sk, es, zhtw, fi, zhcn, lt, it, ko, pt -language: en - -registration: - # Do you want to enable the registration on the server? - enabled: true - # Do you want to force players to register before playing? - force: true - # Maximum Registration per IP - maxRegPerIp: 1 - # Maximum allowed username length - maxUsernameLength: 30 - # Minimum required username length - minUsernameLength: 4 - # Regex syntax allowed in player's username - allowedNicknameCharacters: '[a-zA-Z0-9_]*' - # Do you want to kick players after a successful registration? - # Do not use this option with the loginAfterRegister feature below! - kickAfterRegistration: false - # Do you want to force the player to login after a successful registration? - loginAfterRegister: false - -login: - # How many players per IP can join the server concurrently? - maxInstanceForIP: 1 - # Should not registered players be kicked immediately? - kickNonRegistered: false - # Should the players be kicked immediately on wrong password? - kickOnWrongPassword: false - # Send every X seconds a message to a player to remind him that he has to login/register - messageInterval: 5 - # How many second a player can login or register before being kicked? Set this to 0 to disable. - timeout: 30 - # Teleport the player to the world's Spawn after login - teleportToSpawnAfterLogin: true - # Teleport provisionally not logged player to world's Spawn. - # After the login, if teleportToSpawnAfterLogin is set to false the player will be teleported to his last location. - teleportToSpawnBeforeLogin: true - - # ForceSurvivalMode to player when join? - forceSurvivalMode: false - # Do we need to force the survival mode ONLY after /login process? - forceSurvivalOnlyAfterLogin: false - - # Reset every time the player's inventory? - resetInventory: false - # If player join with CreativeMode and ForceSurvivalMode: true inventory will be wiped. - resetInventoryIfCreative: false - # Should we protect the player inventory before logging in? - protectInventoryBeforeLogIn: true - -password: - # minimum Length of password - minPasswordLength: 5 - # Regex sintax for allowed Chars in passwords. - allowedPasswordCharacters: '[\x21-\x7E]*' - # Enable double check of password when you register or change password. - # When it's true, registration require that kind of command: - # /register - doublePasswordCheck: true - # Deny unsafe passwords for being used, put them on lowercase! - unsafePasswords: - - '123456' - - '12345' - - 'qwerty' - - 'password' - -protection: - # Enable some server protection systems (country based login, antibot) - enableProtection: false - # Countries allowed to join the server and register, see http://dev.bukkit.org/bukkit-plugins/authme-reloaded/pages/countries-codes/ for countries' codes - countries: - - US - - GB - # Countries blacklisted automatically (It works also with enableProtection set to false) - countriesBlacklist: - - A1 - - antiBot: - # Do you like to enable the automatic antibot system? - enableAntiBot: false - # Do you want to show AntiBot messages to every player or only to person with the "authme.antibotmessages" permission node? - broadcastMessages: true - # Max number of player allowed to join in 5 secs before the AntiBot activates - antiBotSensibility: 5 - # Duration in minutes of the antibot protection - antiBotDuration: 10 - -# These features are only available on the VeryGames Server Provider -veryGames: - enableIpCheck: false diff --git a/PROTOTYPE AREA (future stuff and etc...)/converters.txt b/PROTOTYPE AREA (future stuff and etc...)/converters.txt deleted file mode 100644 index 0290f672..00000000 --- a/PROTOTYPE AREA (future stuff and etc...)/converters.txt +++ /dev/null @@ -1,21 +0,0 @@ -_________________________________________________________________________________ -> < -> WARNING: Conversions can't be undone! DO ALWAYS A BACKUP BEFORE!!! < -> < -_________________________________________________________________________________ -> AuthMe Reloaded converters description file < -_________________________________________________________________________________ - -Built-in converters (Into the Plugin's core module): - Old File Backend ("file") >>> SQLite ("/authme converter flatfiletosqlite") THIS CONVERTER WILL BE REMOVED FROM THE CORE IN FUTURE VERSIONS!!! - -Converters in the Converters module (Into the Converters module avariable at: NEED LINK): - SQlite >>> MySql ("/authme converter sqlitetomysql") - MySql >>> Redis ("/authme converter mysqltoredis") - Rakamak >>> SQlite ("/authme converter rakamaktosqlite [databasefile.rak] [(ip-mode) (ipdatabasefle.rak)]") - CrazyLogin >>> SQlite ("/authme converter crazylogintosqlite [databasefile.db]") - xAuth (Min version 2.6) >>> SQlite ("/authme converter xauthtosqlite") NOTE: xAUTH MUST BE INSTALLED AND CONFIGURED IN THE SERVER, it works with all the xAuth backends! - -Discontinued Converters (use an old AuthMe version like 3.4): - RoyalAuth >>> SQlite - vAuth >>> SQlite diff --git a/pom.xml b/pom.xml index 26ecd2ac..86fe315e 100644 --- a/pom.xml +++ b/pom.xml @@ -160,11 +160,12 @@ http://repo.luricos.de/content/repositories/releases - + @@ -530,104 +531,5 @@ true
- - - com.acrobot.chestshop - chestshop - 3.8.12 - provided - - - org.bukkit - bukkit - - - org.bukkit - craftbukkit - - - Vault - net.milkbowl.vault - - - odditem - info.somethingodd - - - scrollingmenusign - me.desht - - - truezip - de.schlichtherle - - - residence - net.t00thpick1 - - - Heroes - com.herocraftonline.heroes - - - HeroChat - com.dthielke.herochat - - - worldguard - com.sk89q - - - worldedit - com.sk89q - - - lwc - com.griefcraft.lwc - - - js - rhino - - - jchronic - com.sk89q - - - deadbolt - com.daemitus.deadbolt - - - bukkit-classloader-check - com.sk89q.spigot - - - jsr305 - com.google.code.findbugs - - - opencsv - net.sf.opencsv - - - simplechestlock - com.webkonsept.bukkit.simplechestlock - - - commandbook - com.sk89q - - - lockette - org.yi.acru.bukkit.lockette - - - log4j-core - org.apache.logging.log4j - - - true - - diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 5611fec6..8ea2a79d 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -65,7 +65,6 @@ public class AuthMe extends JavaPlugin { private JsonCache playerBackup; public OtherAccounts otherAccounts; public Location essentialsSpawn; - public boolean legacyChestShop = false; public boolean antibotMod = false; public boolean delayedAntiBot = true; @@ -192,9 +191,6 @@ public class AuthMe extends JavaPlugin { // Check Multiverse checkMultiverse(); - // Check ChestShop - checkChestShop(); - // Check Essentials checkEssentials(); @@ -242,12 +238,6 @@ public class AuthMe extends JavaPlugin { Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); } - // Legacy chestshop hook - if (legacyChestShop) { - pm.registerEvents(new AuthMeChestShopListener(this), this); - ConsoleLogger.info("Hooked successfully with ChestShop!"); - } - // Reload support hook if (Settings.reloadSupport) { if (database != null) { @@ -425,34 +415,6 @@ public class AuthMe extends JavaPlugin { } } - // Check the version of the ChestShop plugin - public void checkChestShop() { - if (Settings.legacyChestShop && server.getPluginManager().isPluginEnabled("ChestShop")) { - String rawver = com.Acrobot.ChestShop.ChestShop.getVersion(); - double version; - try { - version = Double.valueOf(rawver.split(" ")[0]); - } catch (NumberFormatException nfe) { - try { - version = Double.valueOf(rawver.split("t")[0]); - } catch (NumberFormatException nfee) { - legacyChestShop = false; - return; - } - } - if (version >= 3.813) { - return; - } - if (version < 3.50) { - ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!"); - return; - } - legacyChestShop = true; - } else { - legacyChestShop = false; - } - } - // Get the Multiverse plugin public void checkMultiverse() { if (Settings.multiverse && server.getPluginManager().isPluginEnabled("Multiverse-Core")) { @@ -506,10 +468,16 @@ public class AuthMe extends JavaPlugin { } } + // Check the presence of the ProtocolLib plugin public void checkProtocolLib() { - if (server.getPluginManager().isPluginEnabled("ProtocolLib")) { - inventoryProtector = new AuthMeInventoryListener(this); - ProtocolLibrary.getProtocolManager().addPacketListener(inventoryProtector); + if (Settings.protectInventoryBeforeLogInEnabled) { + if (server.getPluginManager().isPluginEnabled("ProtocolLib")) { + inventoryProtector = new AuthMeInventoryListener(this); + ProtocolLibrary.getProtocolManager().addPacketListener(inventoryProtector); + } else { + ConsoleLogger.showError("WARNING!!! The protectInventory feature requires ProtocolLib! Disabling it..."); + Settings.protectInventoryBeforeLogInEnabled = false; + } } } diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java deleted file mode 100644 index 476f2586..00000000 --- a/src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java +++ /dev/null @@ -1,25 +0,0 @@ -package fr.xephi.authme.listener; - -import com.Acrobot.ChestShop.Events.PreTransactionEvent; -import com.Acrobot.ChestShop.Events.PreTransactionEvent.TransactionOutcome; -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.Utils; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; - -public class AuthMeChestShopListener implements Listener { - - public AuthMe plugin; - - public AuthMeChestShopListener(AuthMe plugin) { - this.plugin = plugin; - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) - public void onPreTransaction(PreTransactionEvent event) { - if (Utils.checkAuth(event.getClient())) - return; - event.setCancelled(TransactionOutcome.OTHER); - } -} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java index 22f71493..6581f510 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java @@ -56,10 +56,6 @@ public class AuthMeServerListener implements Listener { ConsoleLogger.info("Multiverse-Core has been disabled, unhook!"); return; } - if (pluginName.equalsIgnoreCase("ChestShop")) { - plugin.legacyChestShop = false; - ConsoleLogger.info("ChestShop has been disabled, unhook!"); - } if (pluginName.equalsIgnoreCase("CombatTagPlus")) { plugin.combatTagPlus = null; ConsoleLogger.info("CombatTagPlus has been disabled, unhook!"); @@ -81,8 +77,6 @@ public class AuthMeServerListener implements Listener { plugin.checkEssentials(); if (pluginName.equalsIgnoreCase("Multiverse-Core")) plugin.checkMultiverse(); - if (pluginName.equalsIgnoreCase("ChestShop")) - plugin.checkChestShop(); if (pluginName.equalsIgnoreCase("CombatTagPlus")) plugin.checkCombatTagPlus(); if (pluginName.equalsIgnoreCase("Vault")) diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java index b43cf29b..9264ae54 100644 --- a/src/main/java/fr/xephi/authme/settings/Settings.java +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -60,7 +60,7 @@ public final class Settings extends YamlConfiguration { protectInventoryBeforeLogInEnabled, isBackupActivated, isBackupOnStart, isBackupOnStop, isStopEnabled, reloadSupport, rakamakUseIp, noConsoleSpam, removePassword, displayOtherAccounts, - useCaptcha, emailRegistration, multiverse, legacyChestShop, bungee, + useCaptcha, emailRegistration, multiverse, bungee, banUnsafeIp, doubleEmailCheck, sessionExpireOnIpChange, disableSocialSpy, forceOnlyAfterLogin, useEssentialsMotd, usePurge, purgePlayerDat, purgeEssentialsFile, supportOldPassword, @@ -222,7 +222,6 @@ public final class Settings extends YamlConfiguration { saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8); getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); multiverse = configFile.getBoolean("Hooks.multiverse", true); - legacyChestShop = configFile.getBoolean("Hooks.legacyChestshop", false); bungee = configFile.getBoolean("Hooks.bungeecord", false); getForcedWorlds = configFile.getStringList("settings.restrictions.ForceSpawnOnTheseWorlds"); banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false); @@ -462,12 +461,13 @@ public final class Settings extends YamlConfiguration { changes = true; } if (contains("Hooks.chestshop")) { - if (getBoolean("Hooks.chestshop")) { - set("Hooks.legacyChestshop", true); - } set("Hooks.chestshop", null); changes = true; } + if (contains("Hooks.legacyChestshop")) { + set("Hooks.legacyChestshop", null); + changes = true; + } if (!contains("Email.generateImage")) { set("Email.generateImage", true); changes = true; diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 19753d80..c10c977e 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -353,8 +353,6 @@ Email: Hooks: # Do we need to hook with multiverse for spawn checking? multiverse: true - # Do we need to hook with legacy ChestShop < 3.8.13 for prevent buy or selling ? - legacyChestshop: false # Do we need to hook with BungeeCord for get the real Player ip ? bungeecord: false # Do we need to disable Essentials SocialSpy on join ?