diff --git a/lib/ChestShop.jar b/lib/ChestShop.jar new file mode 100644 index 00000000..d4dcdabe Binary files /dev/null and b/lib/ChestShop.jar differ diff --git a/lib/Citizens.jar b/lib/Citizens.jar new file mode 100644 index 00000000..ee6f92e6 Binary files /dev/null and b/lib/Citizens.jar differ diff --git a/lib/CombatTag-5.4.jar b/lib/CombatTag-5.4.jar new file mode 100644 index 00000000..8dd68c9f Binary files /dev/null and b/lib/CombatTag-5.4.jar differ diff --git a/lib/Multiverse-Core-2.5.jar b/lib/Multiverse-Core-2.5.jar new file mode 100644 index 00000000..69e8faf2 Binary files /dev/null and b/lib/Multiverse-Core-2.5.jar differ diff --git a/lib/Notifications.jar b/lib/Notifications.jar new file mode 100644 index 00000000..e7393927 Binary files /dev/null and b/lib/Notifications.jar differ diff --git a/lib/SpoutPlugin.jar b/lib/SpoutPlugin.jar new file mode 100644 index 00000000..6b378964 Binary files /dev/null and b/lib/SpoutPlugin.jar differ diff --git a/lib/Vault.jar b/lib/Vault.jar new file mode 100644 index 00000000..5a8fb223 Binary files /dev/null and b/lib/Vault.jar differ diff --git a/lib/bukkit-1.4.7-R1.0.jar b/lib/bukkit-1.4.7-R1.0.jar new file mode 100644 index 00000000..1f9725a9 Binary files /dev/null and b/lib/bukkit-1.4.7-R1.0.jar differ diff --git a/lib/bungeecord-api-1.4.7-20130228.060400-44.jar b/lib/bungeecord-api-1.4.7-20130228.060400-44.jar new file mode 100644 index 00000000..5e49cf3e Binary files /dev/null and b/lib/bungeecord-api-1.4.7-20130228.060400-44.jar differ diff --git a/lib/citizensapi-2.0.6-SNAPSHOT.jar b/lib/citizensapi-2.0.6-SNAPSHOT.jar new file mode 100644 index 00000000..b2cfa7dc Binary files /dev/null and b/lib/citizensapi-2.0.6-SNAPSHOT.jar differ diff --git a/lib/h2-1.3.164.jar b/lib/h2-1.3.164.jar new file mode 100644 index 00000000..f5519a6b Binary files /dev/null and b/lib/h2-1.3.164.jar differ diff --git a/lib/mail.jar b/lib/mail.jar new file mode 100644 index 00000000..300f436a Binary files /dev/null and b/lib/mail.jar differ diff --git a/lib/mysql-connector-java.jar b/lib/mysql-connector-java.jar new file mode 100644 index 00000000..0539039f Binary files /dev/null and b/lib/mysql-connector-java.jar differ diff --git a/lib/sqlite-jdbc.jar b/lib/sqlite-jdbc.jar new file mode 100644 index 00000000..b0bec7b0 Binary files /dev/null and b/lib/sqlite-jdbc.jar differ diff --git a/lib/xAuth.jar b/lib/xAuth.jar new file mode 100644 index 00000000..0b943212 Binary files /dev/null and b/lib/xAuth.jar differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..2b677843 --- /dev/null +++ b/pom.xml @@ -0,0 +1,137 @@ + + 4.0.0 + uk.org.whoami.authme.AuthMe + AuthMe + jar + AuthMe + + UTF-8 + src/main/resources/META-INF/MANIFEST.MF + + + + Bukkit + Bukkit + http://repo.bukkit.org/content/groups/public/ + + + + + + maven-jar-plugin + 2.2 + + + ${manifest.file} + + + + + + 2.7.10b2 + + + org.bukkit + bukkit + 1.4.7-R1.0 + + + net.milkbowl.vault + Vault + 1.2.23-SNAPSHOT + system + ${project.basedir}/lib/Vault.jar + + + net.citizensnpcs + citizensapi + 2.0.6-SNAPSHOT + system + ${project.basedir}/lib/citizensapi-2.0.6-SNAPSHOT.jar + + + net.citizensnpcs + Citizens + 1.2.1 + system + ${project.basedir}/lib/Citizens.jar + + + org.getSpout + SpoutPlugin + 1.4.7-R1.0-SNAPSHOT + system + ${project.basedir}/lib/SpoutPlugin.jar + + + com.trc202 + CombatTag + 5.4 + system + ${project.basedir}/lib/CombatTag-5.4.jar + + + mysql + mysql-connector-java + 5.1.6 + system + ${project.basedir}/lib/mysql-connector-java.jar + + + org.xerial + sqlite-jdbc + 3.7.2 + system + ${project.basedir}/lib/sqlite-jdbc.jar + + + me.muizers + Notifications + 1.1 + system + ${project.basedir}/lib/Notifications.jar + + + com.Acrobot + ChestShop + 3.50 t0047 + system + ${project.basedir}/lib/ChestShop.jar + + + com.h2 + h2 + 1.3.164 + system + ${project.basedir}/lib/h2-1.3.164.jar + + + com.cypherx + xauth + 2.0.26 + system + ${project.basedir}/lib/xAuth.jar + + + com.onarandombox + MultiverseCore + 2.5-b654 + system + ${project.basedir}/lib/Multiverse-Core-2.5.jar + + + net.md-5 + bungeecord-api + 1.4.7-SNAPSHOT + system + ${project.basedir}/lib/bungeecord-api-1.4.7-20130228.060400-44.jar + + + com.sun.mail + javax.mail + 1.4.5 + system + ${project.basedir}/lib/mail.jar + + + \ No newline at end of file diff --git a/scripts/auth_db_to_mysql.pl b/scripts/auth_db_to_mysql.pl new file mode 100644 index 00000000..11565e86 --- /dev/null +++ b/scripts/auth_db_to_mysql.pl @@ -0,0 +1,59 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use DBI; + +############################## +# EDIT THESE CONFIG SETTINGS # +############################## + +my $host = "localhost"; +my $database = "authme"; +my $username = "authme"; +my $password = "password"; +my $auth_file = "/opt/craftbukkit/plugins/auths.db"; + +############################### +# DO NOT EDIT BELOW THIS LINE # +############################### + +open FILE, "$auth_file" or die $!; +my $dbh = DBI->connect("DBI:mysql:$database;host=$host", "$username", "$password") or die "Could not connect to database: $DBI::errstr"; + +$dbh->do('CREATE TABLE `authme` ( + `id` INTEGER AUTO_INCREMENT, + `username` VARCHAR(255) NOT NULL, + `password` VARCHAR(255) NOT NULL, + `ip` VARCHAR(40) NOT NULL, + `lastlogin` BIGINT, + CONSTRAINT `table_const_prim` PRIMARY KEY (`id`));'); + +my $st = 'INSERT INTO `authme` (`username`, `password`, `ip`, `lastlogin`) VALUES '; +my $i = 0; + +while() { + if($i == 1000) { + $i = 0; + $dbh->do($st); + $st = 'INSERT INTO `authme` (`username`, `password`, `ip`, `lastlogin`) VALUES '; + } + my @auth = split(':'); + + if($i != 0) { + $st .= ", "; + } + + $st .= "(\"$auth[0]\", \"$auth[1]\", "; + $st .= "\"" . ($auth[2] || '198.18.0.1') . "\", "; + $st .= ($auth[3] || '0') . ")"; + $i++; +} + +if($i > 0) { + $dbh->do($st); +} + +$dbh->disconnect(); +close FILE; + diff --git a/src/main/java/uk/org/whoami/authme/AuthMe.java b/src/main/java/uk/org/whoami/authme/AuthMe.java new file mode 100644 index 00000000..8fa9ad91 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/AuthMe.java @@ -0,0 +1,501 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme; + +import java.io.File; +import java.io.IOException; +import java.sql.SQLException; +import java.util.Date; +import java.util.HashMap; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; + +import uk.org.whoami.authme.api.API; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.backup.FileCache; +import uk.org.whoami.authme.cache.limbo.LimboCache; +import uk.org.whoami.authme.cache.limbo.LimboPlayer; +import uk.org.whoami.authme.commands.AdminCommand; +import uk.org.whoami.authme.commands.CaptchaCommand; +import uk.org.whoami.authme.commands.ChangePasswordCommand; +import uk.org.whoami.authme.commands.EmailCommand; +import uk.org.whoami.authme.commands.LoginCommand; +import uk.org.whoami.authme.commands.LogoutCommand; +import uk.org.whoami.authme.commands.RegisterCommand; +import uk.org.whoami.authme.commands.UnregisterCommand; +import uk.org.whoami.authme.datasource.CacheDataSource; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.datasource.FileDataSource; +import uk.org.whoami.authme.datasource.MiniConnectionPoolManager.TimeoutException; +import uk.org.whoami.authme.datasource.MySQLDataSource; +import uk.org.whoami.authme.listener.AuthMeBlockListener; +import uk.org.whoami.authme.listener.AuthMeChestShopListener; +import uk.org.whoami.authme.listener.AuthMeEntityListener; +import uk.org.whoami.authme.listener.AuthMePlayerListener; +import uk.org.whoami.authme.listener.AuthMeSpoutListener; +import uk.org.whoami.authme.plugin.manager.CitizensCommunicator; +import uk.org.whoami.authme.plugin.manager.CombatTagComunicator; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.PlayersLogs; +import uk.org.whoami.authme.settings.Settings; + +import me.muizers.Notifications.Notifications; +import net.citizensnpcs.Citizens; +import net.milkbowl.vault.permission.Permission; + +import org.bukkit.Bukkit; +import org.bukkit.Server; + +import com.onarandombox.MultiverseCore.MultiverseCore; + +import uk.org.whoami.authme.commands.PasspartuCommand; +import uk.org.whoami.authme.datasource.SqliteDataSource; +import uk.org.whoami.authme.filter.ConsoleFilter; + +public class AuthMe extends JavaPlugin { + + public DataSource database = null; + private Settings settings; + private Messages m; + private PlayersLogs pllog; + public Management management; + public static Server server; + public static Plugin authme; + public static Permission permission; + private static AuthMe instance; + private Utils utils = Utils.getInstance(); + private JavaPlugin plugin; + private FileCache playerBackup = new FileCache(); + public CitizensCommunicator citizens; + public SendMailSSL mail = null; + public int CitizensVersion = 0; + public int CombatTag = 0; + public double ChestShop = 0; + public boolean BungeeCord = false; + public Notifications notifications; + public API api; + public HashMap captcha = new HashMap(); + public HashMap cap = new HashMap(); + public MultiverseCore mv = null; + + @Override + public void onEnable() { + instance = this; + authme = instance; + + citizens = new CitizensCommunicator(this); + + settings = new Settings(this); + settings.loadConfigOptions(); + + setMessages(Messages.getInstance()); + pllog = PlayersLogs.getInstance(); + + server = getServer(); + + + //Set Console Filter + if (Settings.removePassword) + Bukkit.getLogger().setFilter(new ConsoleFilter()); + + + //Load MailApi + File mailFile = new File("lib", "mail.jar"); + if (mailFile.exists()) { + //Set SMTP + mail = new SendMailSSL(this); + } else { + mail = null; + } + + //Check Citizens Version + citizensVersion(); + + //Check Combat Tag Version + combatTag(); + + //Check Notifications + checkNotifications(); + + //Check Multiverse + checkMultiverse(); + + //Check ChestShop + checkChestShop(); + + /* + * Back style on start if avaible + */ + if(Settings.isBackupActivated && Settings.isBackupOnStart) { + Boolean Backup = new PerformBackup(this).DoBackup(); + if(Backup) ConsoleLogger.info("Backup Complete"); + else ConsoleLogger.showError("Error while making Backup"); + } + + /* + * Backend MYSQL - FILE - SQLITE + */ + switch (Settings.getDataSource) { + case FILE: + try { + database = new FileDataSource(); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN..."); + server.shutdown(); + } + if (!Settings.isStopEnabled) + this.getServer().getPluginManager().disablePlugin(this); + return; + } + break; + case MYSQL: + try { + database = new MySQLDataSource(); + } catch (ClassNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); + server.shutdown(); + } + if (!Settings.isStopEnabled) + this.getServer().getPluginManager().disablePlugin(this); + return; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); + server.shutdown(); + } + if (!Settings.isStopEnabled) + this.getServer().getPluginManager().disablePlugin(this); + return; + } catch(TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); + server.shutdown(); + } + if (!Settings.isStopEnabled) + this.getServer().getPluginManager().disablePlugin(this); + return; + } + break; + case SQLITE: + try { + database = new SqliteDataSource(); + } catch (ClassNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN..."); + server.shutdown(); + } + if (!Settings.isStopEnabled) + this.getServer().getPluginManager().disablePlugin(this); + return; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN..."); + server.shutdown(); + } + if (!Settings.isStopEnabled) + this.getServer().getPluginManager().disablePlugin(this); + return; + } + break; + } + + if (Settings.isCachingEnabled) { + database = new CacheDataSource(this, database); + } + + api = new API(this, database); + + management = new Management(database, this); + + PluginManager pm = getServer().getPluginManager(); + if (pm.isPluginEnabled("Spout")) { + pm.registerEvents(new AuthMeSpoutListener(database), this); + ConsoleLogger.info("Successfully hook with Spout!"); + } + pm.registerEvents(new AuthMePlayerListener(this,database),this); + pm.registerEvents(new AuthMeBlockListener(database, this),this); + pm.registerEvents(new AuthMeEntityListener(database, this),this); + if (ChestShop != 0) { + pm.registerEvents(new AuthMeChestShopListener(database, this), this); + ConsoleLogger.info("Successfully hook with ChestShop!"); + } + + + //Find Permissions + if(Settings.isPermissionCheckEnabled) { + RegisteredServiceProvider permissionProvider = + getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); + if (permissionProvider != null) + permission = permissionProvider.getProvider(); + else { + + ConsoleLogger.showError("Vault and Permissions plugins is needed for enable AuthMe Reloaded!"); + this.getServer().getPluginManager().disablePlugin(this); + } + } + + this.getCommand("authme").setExecutor(new AdminCommand(this, database)); + this.getCommand("register").setExecutor(new RegisterCommand(database, this)); + this.getCommand("login").setExecutor(new LoginCommand(this)); + this.getCommand("changepassword").setExecutor(new ChangePasswordCommand(database, this)); + this.getCommand("logout").setExecutor(new LogoutCommand(this,database)); + this.getCommand("unregister").setExecutor(new UnregisterCommand(this, database)); + this.getCommand("passpartu").setExecutor(new PasspartuCommand(database, this)); + this.getCommand("email").setExecutor(new EmailCommand(this, database)); + this.getCommand("captcha").setExecutor(new CaptchaCommand(this)); + + if(!Settings.isForceSingleSessionEnabled) { + ConsoleLogger.showError("ATTENTION by disabling ForceSingleSession, your server protection is set to low"); + } + + if (Settings.reloadSupport) + try { + if (!new File(getDataFolder() + File.separator + "players.yml").exists()) { + pllog = new PlayersLogs(); + } + onReload(); + if (server.getOnlinePlayers().length < 1) { + try { + PlayersLogs.players.clear(); + pllog.save(); + } catch (NullPointerException npe) { + } + } + } catch (NullPointerException ex) { + + } + + ConsoleLogger.info("Authme " + this.getDescription().getVersion() + " enabled"); + } + + + private void checkChestShop() { + if (!Settings.chestshop) { + this.ChestShop = 0; + return; + } + if (this.getServer().getPluginManager().isPluginEnabled("ChestShop")) { + try { + String ver = com.Acrobot.ChestShop.ChestShop.getVersion(); + try { + double version = Double.valueOf(ver.split(" ")[0]); + if (version >= 3.50) { + this.ChestShop = version; + } else { + ConsoleLogger.showError("Please Update your ChestShop version!"); + } + } catch (NumberFormatException nfe) { + try { + double version = Double.valueOf(ver.split("t")[0]); + if (version >= 3.50) { + this.ChestShop = version; + } else { + ConsoleLogger.showError("Please Update your ChestShop version!"); + } + } catch (NumberFormatException nfee) { + + } + + } + + } catch (NullPointerException npe) {} + catch (NoClassDefFoundError ncdfe) {} + catch (ClassCastException cce) {} + } + + } + + private void checkMultiverse() { + if(!Settings.multiverse) { + mv = null; + return; + } + if (this.getServer().getPluginManager().getPlugin("Multiverse-Core") != null && this.getServer().getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + try { + mv = (MultiverseCore) this.getServer().getPluginManager().getPlugin("Multiverse-Core"); + ConsoleLogger.info("Hook with Multiverse-Core for SpawnLocations"); + } catch (NullPointerException npe) { + mv = null; + } catch (ClassCastException cce) { + mv = null; + } catch (NoClassDefFoundError ncdfe) { + mv = null; + } + } + } + + private void checkNotifications() { + if (!Settings.notifications) { + this.notifications = null; + return; + } + if (this.getServer().getPluginManager().getPlugin("Notifications") != null && this.getServer().getPluginManager().getPlugin("Notifications").isEnabled()) { + this.notifications = (Notifications) this.getServer().getPluginManager().getPlugin("Notifications"); + ConsoleLogger.info("Successfully hook with Notifications"); + } else { + this.notifications = null; + } + + } + + private void combatTag() { + if (this.getServer().getPluginManager().getPlugin("CombatTag") != null && this.getServer().getPluginManager().getPlugin("CombatTag").isEnabled()) { + this.CombatTag = 1; + } else { + this.CombatTag = 0; + } + } + + private void citizensVersion() { + if (this.getServer().getPluginManager().getPlugin("Citizens") != null && this.getServer().getPluginManager().getPlugin("Citizens").isEnabled()) { + Citizens cit = (Citizens) this.getServer().getPluginManager().getPlugin("Citizens"); + String ver = cit.getDescription().getVersion(); + String[] args = ver.split("\\."); + if (args[0].contains("1")) { + this.CitizensVersion = 1; + } else { + this.CitizensVersion = 2; + } + } else { + this.CitizensVersion = 0; + } + } + + @Override + public void onDisable() { + if (Bukkit.getOnlinePlayers() != null) + for(Player player : Bukkit.getOnlinePlayers()) { + this.savePlayer(player); + } + pllog.save(); + + if (database != null) { + database.close(); + } + //utils = Utils.getInstance(); + + /* + * Back style on start if avaible + */ + if(Settings.isBackupActivated && Settings.isBackupOnStop) { + Boolean Backup = new PerformBackup(this).DoBackup(); + if(Backup) ConsoleLogger.info("Backup Complete"); + else ConsoleLogger.showError("Error while making Backup"); + } + ConsoleLogger.info("Authme " + this.getDescription().getVersion() + " disabled"); + + + } + + private void onReload() { + try { + if (Bukkit.getServer().getOnlinePlayers() != null && !PlayersLogs.players.isEmpty()) { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (PlayersLogs.players.contains(player.getName())) { + String name = player.getName().toLowerCase(); + PlayerAuth pAuth = database.getAuth(name); + // if Mysql is unavaible + if(pAuth == null) + break; + PlayerAuth auth = new PlayerAuth(name, pAuth.getHash(), pAuth.getIp(), new Date().getTime()); + database.updateSession(auth); + PlayerCache.getInstance().addPlayer(auth); + } + } + } + return; + } catch (NullPointerException ex) { + return; + } + } + + public static AuthMe getInstance() { + return instance; + } + + public void savePlayer(Player player) throws IllegalStateException, NullPointerException { + try { + if ((citizens.isNPC(player, this)) || (Utils.getInstance().isUnrestricted(player)) || (CombatTagComunicator.isNPC(player))) { + return; + } + } catch (Exception e) { } + + try { + String name = player.getName().toLowerCase(); + if ((PlayerCache.getInstance().isAuthenticated(name)) && (!player.isDead()) && + (Settings.isSaveQuitLocationEnabled.booleanValue())) { + PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), (int)player.getLocation().getX(), (int)player.getLocation().getY(), (int)player.getLocation().getZ()); + this.database.updateQuitLoc(auth); + } + + if (LimboCache.getInstance().hasLimboPlayer(name)) + { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) { + player.getInventory().setArmorContents(limbo.getArmour()); + player.getInventory().setContents(limbo.getInventory()); + } + if (!limbo.getLoc().getChunk().isLoaded()) { + limbo.getLoc().getChunk().load(); + } + player.teleport(limbo.getLoc()); + this.utils.addNormal(player, limbo.getGroup()); + player.setOp(limbo.getOperator()); + + this.plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); + LimboCache.getInstance().deleteLimboPlayer(name); + if (this.playerBackup.doesCacheExist(name)) { + this.playerBackup.removeCache(name); + } + } + + PlayerCache.getInstance().removePlayer(name); + player.saveData(); + } catch (Exception ex) { + } + } + + public void setCitizensCommunicator(CitizensCommunicator citizens) { + this.citizens = citizens; + } + + public CitizensCommunicator getCitizensCommunicator() { + return citizens; + } + + public void setMessages(Messages m) { + this.m = m; + } + + public Messages getMessages() { + return m; + } + +} diff --git a/src/main/java/uk/org/whoami/authme/ConsoleLogger.java b/src/main/java/uk/org/whoami/authme/ConsoleLogger.java new file mode 100644 index 00000000..99bfb763 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/ConsoleLogger.java @@ -0,0 +1,32 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme; + +import java.util.logging.Logger; + +public class ConsoleLogger { + + private static final Logger log = Logger.getLogger("Minecraft"); + + public static void info(String message) { + log.info("[AuthMe] " + message); + } + + public static void showError(String message) { + log.severe("[AuthMe] ERROR: " + message); + } +} diff --git a/src/main/java/uk/org/whoami/authme/LogActions.java b/src/main/java/uk/org/whoami/authme/LogActions.java new file mode 100644 index 00000000..79b65482 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/LogActions.java @@ -0,0 +1,75 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +/** + * + * @author stefano + */ +public class LogActions { + + private boolean logData; + private File dataLog; + private boolean logMessages; + private File messageLog; + private String dataFolder; + private String dLog,mLog; + + public LogActions() { + try { + if (logData) + this.dataLog = new File(dataFolder, dLog); + if (logMessages) + this.messageLog = new File(dataFolder, mLog); + } catch (Exception e){ + + ConsoleLogger.showError("[AuthMe] Error opening logfiles; bad filename?"); + if (logData) + this.dataLog = new File(dataFolder, "death_data.log"); + if (logMessages) + this.messageLog = new File(dataFolder, "death_messages.log"); + } + } + + + @SuppressWarnings("unused") + private void initFiles() { + if (logData && !this.dataLog.exists()) { + try { + this.dataLog.createNewFile(); + BufferedWriter writer = new BufferedWriter(new FileWriter(this.dataLog,true)); + writer.write("#AuthMe Registration Log - This file stores serialized data on player regitration, changepassword and unregistration:"); + writer.newLine(); + writer.write("#Date | Time | Player | ip | Action [Register|ChangePassword|Unregister]"); + writer.newLine(); + writer.write("#Dont remove this file if you want to store all Registration Action"); + writer.newLine(); + writer.write("#If This file will become too big, rename it and let plugin create new one"); + writer.newLine(); + writer.close(); + } catch (IOException e) { + ConsoleLogger.showError("[AuthMe] Error writing data log: "); + e.printStackTrace(); + } + } + if (logMessages && !this.messageLog.exists()) { + try { + this.messageLog.createNewFile(); + BufferedWriter writer = new BufferedWriter(new FileWriter(this.messageLog,true)); + writer.write("#AuthMe Multiple Access Log - This file stores player Login, Wrong Password and Error"); + writer.newLine(); + writer.close(); + } catch (IOException e) { + ConsoleLogger.showError("[AuthMe] Error writing message log: "); + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/uk/org/whoami/authme/Management.java b/src/main/java/uk/org/whoami/authme/Management.java new file mode 100644 index 00000000..31f851af --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/Management.java @@ -0,0 +1,427 @@ +package uk.org.whoami.authme; + +import java.security.NoSuchAlgorithmException; +import java.util.Date; +import java.util.List; + +import me.muizers.Notifications.Notification; +import net.md_5.bungee.api.connection.ConnectedPlayer; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; + +import uk.org.whoami.authme.api.API; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.backup.FileCache; +import uk.org.whoami.authme.cache.limbo.LimboCache; +import uk.org.whoami.authme.cache.limbo.LimboPlayer; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.events.AuthMeTeleportEvent; +import uk.org.whoami.authme.events.LoginEvent; +import uk.org.whoami.authme.events.RestoreInventoryEvent; +import uk.org.whoami.authme.events.SpawnTeleportEvent; +import uk.org.whoami.authme.listener.AuthMePlayerListener; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.security.RandomString; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.PlayersLogs; +import uk.org.whoami.authme.settings.Settings; + +public class Management { + + private Messages m = Messages.getInstance(); + private PlayersLogs pllog = PlayersLogs.getInstance(); + private Utils utils = Utils.getInstance(); + private FileCache playerCache = new FileCache(); + private DataSource database; + public AuthMe plugin; + private boolean passpartu = false; + public static RandomString rdm = new RandomString(Settings.captchaLength); + public PluginManager pm; + + public Management(DataSource database, AuthMe plugin) { + this.database = database; + this.plugin = plugin; + this.pm = plugin.getServer().getPluginManager(); + } + + public Management(DataSource database, boolean passpartu, AuthMe plugin) { + this.database = database; + this.passpartu = passpartu; + this.plugin = plugin; + this.pm = plugin.getServer().getPluginManager(); + } + + public String performLogin(Player player, String password) { + + String name = player.getName().toLowerCase(); + String ip = player.getAddress().getAddress().getHostAddress(); + if (Settings.bungee && player instanceof ProxiedPlayer) { + ProxiedPlayer pPlayer = (ProxiedPlayer) player; + ip = pPlayer.getAddress().getAddress().getHostAddress(); + } else if (Settings.bungee && player instanceof ConnectedPlayer) { + ConnectedPlayer cPlayer = (ConnectedPlayer) player; + ip = cPlayer.getAddress().getAddress().getHostAddress(); + } + World world = player.getWorld(); + Location spawnLoc = world.getSpawnLocation(); + if (plugin.mv != null) { + try { + spawnLoc = plugin.mv.getMVWorldManager().getMVWorld(world).getSpawnLocation(); + } catch (NullPointerException npe) { + } catch (ClassCastException cce) { + } catch (NoClassDefFoundError ncdfe) { + } + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return m._("logged_in"); + + } + + if (!database.isAuthAvailable(player.getName().toLowerCase())) { + return m._("user_unknown"); + } + + PlayerAuth pAuth = database.getAuth(name); + // if Mysql is unavaible + if(pAuth == null) + return m._("user_unknown"); + + //if columnGroup is set + if(!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) { + return m._("vb_nonActiv"); + } + + String hash = pAuth.getHash(); + String email = pAuth.getEmail(); + + + try { + if(!passpartu) { + if (Settings.useCaptcha) { + if(!plugin.captcha.containsKey(name)) { + plugin.captcha.put(name, 1); + } else { + int i = plugin.captcha.get(name) + 1; + plugin.captcha.remove(name); + plugin.captcha.put(name, i); + } + + if(plugin.captcha.containsKey(name) && plugin.captcha.get(name) > Settings.maxLoginTry) { + player.sendMessage(m._("need_captcha")); + plugin.cap.put(name, rdm.nextString()); + return "Type : /captcha " + plugin.cap.get(name); + } else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) > Settings.maxLoginTry) { + try { + plugin.captcha.remove(name); + plugin.cap.remove(name); + } catch (NullPointerException npe) { + } + + } + } + if (PasswordSecurity.comparePasswordWithHash(password, hash, name)) { + PlayerAuth auth = new PlayerAuth(name, hash, ip, new Date().getTime(), email); + + database.updateSession(auth); + PlayerCache.getInstance().addPlayer(auth); + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (limbo != null) { + + + player.setOp(limbo.getOperator()); + + this.utils.addNormal(player, limbo.getGroup()); + + + if ((Settings.isTeleportToSpawnEnabled.booleanValue()) && (!Settings.isForceSpawnLocOnJoinEnabled.booleanValue() && Settings.getForcedWorlds.contains(player.getWorld().getName()))) + { + if ((Settings.isSaveQuitLocationEnabled.booleanValue()) && (this.database.getAuth(name).getQuitLocY() != 0)) + { + this.utils.packCoords(this.database.getAuth(name).getQuitLocX(), this.database.getAuth(name).getQuitLocY(), this.database.getAuth(name).getQuitLocZ(), player); + } + else { + + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + + } + + } + else if (Settings.isForceSpawnLocOnJoinEnabled.booleanValue() && Settings.getForcedWorlds.contains(player.getWorld().getName())) { + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, true); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + else if ((Settings.isSaveQuitLocationEnabled.booleanValue()) && (this.database.getAuth(name).getQuitLocY() != 0)) + { + this.utils.packCoords(this.database.getAuth(name).getQuitLocX(), this.database.getAuth(name).getQuitLocY(), this.database.getAuth(name).getQuitLocZ(), player); + } + else { + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + + + player.setGameMode(GameMode.getByValue(limbo.getGameMode())); + + if (Settings.protectInventoryBeforeLogInEnabled.booleanValue() && player.hasPlayedBefore()) { + RestoreInventoryEvent event = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + API.setPlayerInventory(player, limbo.getInventory(), limbo.getArmour()); + } + } + + + player.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); + player.getServer().getScheduler().cancelTask(limbo.getMessageTaskId()); + LimboCache.getInstance().deleteLimboPlayer(name); + if (this.playerCache.doesCacheExist(name)) { + this.playerCache.removeCache(name); + } + + } + + /* + * Little Work Around under Registration Group Switching for admins that + * add Registration thru a web Scripts. + */ + if ( Settings.isPermissionCheckEnabled && AuthMe.permission.playerInGroup(player, Settings.unRegisteredGroup) && !Settings.unRegisteredGroup.isEmpty() ) { + AuthMe.permission.playerRemoveGroup(player.getWorld(), player.getName(), Settings.unRegisteredGroup); + AuthMe.permission.playerAddGroup(player.getWorld(), player.getName(), Settings.getRegisteredGroup); + } + + try { + if (!PlayersLogs.players.contains(player.getName())) + PlayersLogs.players.add(player.getName()); + pllog.save(); + } catch (NullPointerException ex) { + + } + + Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); + if (Settings.useCaptcha) { + if(plugin.captcha.containsKey(name)) { + plugin.captcha.remove(name); + } + if(plugin.cap.containsKey(name)) { + plugin.cap.containsKey(name); + } + } + player.sendMessage(m._("login")); + displayOtherAccounts(auth); + if(!Settings.noConsoleSpam) + ConsoleLogger.info(player.getDisplayName() + " logged in!"); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged in!")); + } + player.saveData(); + + } else { + if (!Settings.noConsoleSpam) + ConsoleLogger.info(player.getDisplayName() + " used the wrong password"); + if (Settings.isKickOnWrongPasswordEnabled) { + int gm = AuthMePlayerListener.gameMode.get(name); + player.setGameMode(GameMode.getByValue(gm)); + player.kickPlayer(m._("wrong_pwd")); + } else { + return (m._("wrong_pwd")); + } + } + } else { + // need for bypass password check if passpartu command is enabled + PlayerAuth auth = new PlayerAuth(name, hash, ip, new Date().getTime(), email); + database.updateSession(auth); + PlayerCache.getInstance().addPlayer(auth); + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (limbo != null) { + + + player.setOp(limbo.getOperator()); + + this.utils.addNormal(player, limbo.getGroup()); + + + if ((Settings.isTeleportToSpawnEnabled.booleanValue()) && (!Settings.isForceSpawnLocOnJoinEnabled.booleanValue() && Settings.getForcedWorlds.contains(player.getWorld().getName()))) + { + if ((Settings.isSaveQuitLocationEnabled.booleanValue()) && (this.database.getAuth(name).getQuitLocY() != 0)) { + Location quitLoc = new Location(player.getWorld(), this.database.getAuth(name).getQuitLocX() + 0.5D, this.database.getAuth(name).getQuitLocY() + 0.5D, this.database.getAuth(name).getQuitLocZ() + 0.5D); + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, quitLoc); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + else + { + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + + } + else if (Settings.isForceSpawnLocOnJoinEnabled.booleanValue() && Settings.getForcedWorlds.contains(player.getWorld().getName())) { + + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, true); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + else if ((Settings.isSaveQuitLocationEnabled.booleanValue()) && (this.database.getAuth(name).getQuitLocY() != 0)) { + Location quitLoc = new Location(player.getWorld(), this.database.getAuth(name).getQuitLocX() + 0.5D, this.database.getAuth(name).getQuitLocY() + 0.5D, this.database.getAuth(name).getQuitLocZ() + 0.5D); + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, quitLoc); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + else + { + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); + pm.callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + + + player.setGameMode(GameMode.getByValue(limbo.getGameMode())); + + if (Settings.protectInventoryBeforeLogInEnabled.booleanValue() && player.hasPlayedBefore()) { + RestoreInventoryEvent event = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + API.setPlayerInventory(player, limbo.getInventory(), limbo.getArmour()); + } + } + + + player.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); + player.getServer().getScheduler().cancelTask(limbo.getMessageTaskId()); + LimboCache.getInstance().deleteLimboPlayer(name); + if (this.playerCache.doesCacheExist(name)) { + this.playerCache.removeCache(name); + } + } + + /* + * Little Work Around under Registration Group Switching for admins that + * add Registration thru a web Scripts. + */ + if ( Settings.isPermissionCheckEnabled && AuthMe.permission.playerInGroup(player, Settings.unRegisteredGroup) && !Settings.unRegisteredGroup.isEmpty() ) { + AuthMe.permission.playerRemoveGroup(player.getWorld(), player.getName(), Settings.unRegisteredGroup); + AuthMe.permission.playerAddGroup(player.getWorld(), player.getName(), Settings.getRegisteredGroup); + } + + try { + if (!PlayersLogs.players.contains(player.getName())) + PlayersLogs.players.add(player.getName()); + pllog.save(); + } catch (NullPointerException ex) { } + + Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); + if (Settings.useCaptcha) { + if(plugin.captcha.containsKey(name)) { + plugin.captcha.remove(name); + } + if(plugin.cap.containsKey(name)) { + plugin.cap.containsKey(name); + } + } + player.sendMessage(m._("login")); + displayOtherAccounts(auth); + if(!Settings.noConsoleSpam) + ConsoleLogger.info(player.getDisplayName() + " logged in!"); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged in!")); + } + player.saveData(); + this.passpartu = false; + } + + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + return (m._("error")); + } + return ""; + } + + private void displayOtherAccounts(PlayerAuth auth) { + if (!Settings.displayOtherAccounts) { + return; + } + if (auth == null) { + return; + } + if (this.database.getAllAuthsByName(auth).isEmpty() || this.database.getAllAuthsByName(auth) == null) { + return; + } + if(this.database.getAllAuthsByName(auth).size() == 1) { + return; + } + List accountList = this.database.getAllAuthsByName(auth); + String message = "[AuthMe] "; + int i = 0; + for (String account : accountList) { + i++; + message = message + account; + if (i != accountList.size()) { + message = message + ", "; + } else { + message = message + "."; + } + + } + for (Player player : AuthMe.getInstance().getServer().getOnlinePlayers()) { + if (player.hasPermission("authme.seeOtherAccounts")) { + player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + String.valueOf(accountList.size()) + " accounts"); + player.sendMessage(message); + } + } + } + + +} diff --git a/src/main/java/uk/org/whoami/authme/PerformBackup.java b/src/main/java/uk/org/whoami/authme/PerformBackup.java new file mode 100644 index 00000000..5d995f1e --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/PerformBackup.java @@ -0,0 +1,160 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import uk.org.whoami.authme.settings.Settings; + +/** + * + * @author stefano + */ +public class PerformBackup { + + private String dbName = Settings.getMySQLDatabase; + private String dbUserName = Settings.getMySQLUsername; + private String dbPassword = Settings.getMySQLPassword; + private String tblname = Settings.getMySQLTablename; + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm"); + String dateString = format.format( new Date() ); + private String path = AuthMe.getInstance().getDataFolder()+"/backups/backup"+dateString; + private AuthMe instance; + + public PerformBackup(AuthMe instance) { + this.setInstance(instance); + + } + + public boolean DoBackup() { + + switch(Settings.getDataSource) { + case FILE: return FileBackup("auths.db"); + + case MYSQL: return MySqlBackup(); + + case SQLITE: return FileBackup(Settings.getMySQLDatabase+".db"); + + } + + return false; + } + + private boolean MySqlBackup() { + File dirBackup = new File(AuthMe.getInstance().getDataFolder()+"/backups"); + + if(!dirBackup.exists()) + dirBackup.mkdir(); + if(checkWindows(Settings.backupWindowsPath)) { + String executeCmd = Settings.backupWindowsPath+"\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path+".sql"; + //ConsoleLogger.info(executeCmd); + Process runtimeProcess; + try { + //System.out.println("path "+path+" cmd "+executeCmd); + runtimeProcess = Runtime.getRuntime().exec(executeCmd); + int processComplete = runtimeProcess.waitFor(); + + if (processComplete == 0) { + ConsoleLogger.info("Backup created successfully"); + return true; + } else { + ConsoleLogger.info("Could not create the backup"); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } else { + String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path+".sql"; + Process runtimeProcess; + try { + //System.out.println("path "+path+" cmd "+executeCmd); + runtimeProcess = Runtime.getRuntime().exec(executeCmd); + int processComplete = runtimeProcess.waitFor(); + + if (processComplete == 0) { + ConsoleLogger.info("Backup created successfully"); + return true; + } else { + ConsoleLogger.info("Could not create the backup"); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + return false; + } + + private boolean FileBackup(String backend) { + File dirBackup = new File(AuthMe.getInstance().getDataFolder()+"/backups"); + + if(!dirBackup.exists()) + dirBackup.mkdir(); + + try { + + copy(new File("plugins/AuthMe/"+backend),new File(path+".db")); + return true; + + } catch (Exception ex) { + ex.printStackTrace(); + } + + + return false; + } + + /* + * Check if we are under Windows and correct location + * of mysqldump.exe otherwise return error. + */ + private boolean checkWindows(String windowsPath) { + String isWin = System.getProperty("os.name").toLowerCase(); + + if(isWin.indexOf("win") >= 0) { + //ConsoleLogger.info(windowsPath+"\\bin\\mysqldump.exe"); + if(new File(windowsPath+"\\bin\\mysqldump.exe").exists()) { + return true; + } else { + ConsoleLogger.showError("Mysql Windows Path is incorrect please check it"); + return true; + } + } else return false; + + + } + + /* + * Copyr src bytefile into dst file + */ + void copy(File src, File dst) throws IOException { + InputStream in = new FileInputStream(src); + OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); + } + +public void setInstance(AuthMe instance) { + this.instance = instance; +} + +public AuthMe getInstance() { + return instance; +} + +} diff --git a/src/main/java/uk/org/whoami/authme/SendMailSSL.java b/src/main/java/uk/org/whoami/authme/SendMailSSL.java new file mode 100644 index 00000000..f15a906f --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/SendMailSSL.java @@ -0,0 +1,88 @@ +package uk.org.whoami.authme; + +import java.io.UnsupportedEncodingException; +import java.util.Properties; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.PasswordAuthentication; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.bukkit.Bukkit; + +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.settings.Settings; + +public class SendMailSSL { + + public AuthMe instance; + + public SendMailSSL(AuthMe instance) { + this.instance = instance; + } + public void main(final PlayerAuth auth, final String newPass) { + + String sendername; + + if (Settings.getmailSenderName.isEmpty() || Settings.getmailSenderName == null) { + sendername = Settings.getmailAccount; + } else { + sendername = Settings.getmailSenderName; + } + + Properties props = new Properties(); + props.put("mail.smtp.host", Settings.getmailSMTP); + props.put("mail.smtp.socketFactory.port", String.valueOf(Settings.getMailPort)); + props.put("mail.smtp.socketFactory.class", + "javax.net.ssl.SSLSocketFactory"); + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.port", String.valueOf(Settings.getMailPort)); + + Session session = Session.getInstance(props, + new javax.mail.Authenticator() { + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(Settings.getmailAccount,Settings.getmailPassword); + } + }); + + try { + + final Message message = new MimeMessage(session); + try { + message.setFrom(new InternetAddress(Settings.getmailAccount, sendername)); + } catch (UnsupportedEncodingException uee) { + message.setFrom(new InternetAddress(Settings.getmailAccount)); + } + message.setRecipients(Message.RecipientType.TO, + InternetAddress.parse(auth.getEmail())); + message.setSubject(Settings.getMailSubject); + String text = Settings.getMailText; + text = text.replaceAll("", auth.getNickname()); + text = text.replaceAll("", instance.getServer().getServerName()); + text = text.replaceAll("", newPass); + message.setText(text); + + Bukkit.getScheduler().runTaskAsynchronously(instance, new Runnable() { + + @Override + public void run() { + try { + Transport.send(message); + } catch (MessagingException e) { + e.printStackTrace(); + } + + } + + }); + + if(!Settings.noConsoleSpam) + ConsoleLogger.info("Email sent to : " + auth.getNickname()); + + } catch (MessagingException e) { + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/src/main/java/uk/org/whoami/authme/Utils.java b/src/main/java/uk/org/whoami/authme/Utils.java new file mode 100644 index 00000000..346bc6bf --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/Utils.java @@ -0,0 +1,270 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme; + +import java.io.File; +import java.io.FileWriter; +import java.util.Iterator; +import java.util.Random; +import java.util.Scanner; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import uk.org.whoami.authme.events.AuthMeTeleportEvent; +import uk.org.whoami.authme.settings.Settings; + +/** + * + * @author stefano + */ +public class Utils { + //private Settings settings = Settings.getInstance(); + private String currentGroup; + private static Utils singleton; + private String unLoggedGroup = Settings.getUnloggedinGroup; + BukkitTask id; + /* + public Utils(Player player) { + this.player = player; + + } + */ + public void setGroup(Player player, groupType group) { + if (!player.isOnline()) + return; + if(!Settings.isPermissionCheckEnabled) + return; + + switch(group) { + case UNREGISTERED: { + currentGroup = AuthMe.permission.getPrimaryGroup(player); + AuthMe.permission.playerRemoveGroup(player, currentGroup); + AuthMe.permission.playerAddGroup(player, Settings.unRegisteredGroup); + break; + } + case REGISTERED: { + currentGroup = AuthMe.permission.getPrimaryGroup(player); + AuthMe.permission.playerRemoveGroup(player, currentGroup); + AuthMe.permission.playerAddGroup(player, Settings.getRegisteredGroup); + break; + } + } + return; + } + + public String removeAll(Player player) { + if(!Utils.getInstance().useGroupSystem()){ + return null; + } + + if( !Settings.getJoinPermissions.isEmpty() ) { + hasPermOnJoin(player); + } + + this.currentGroup = AuthMe.permission.getPrimaryGroup(player.getWorld(),player.getName().toString()); + //System.out.println("current grop" + currentGroup); + if(AuthMe.permission.playerRemoveGroup(player.getWorld(),player.getName().toString(), currentGroup) && AuthMe.permission.playerAddGroup(player.getWorld(),player.getName().toString(),this.unLoggedGroup)) { + + return currentGroup; + } + + return null; + + } + + public boolean addNormal(Player player, String group) { + if(!Utils.getInstance().useGroupSystem()){ + return false; + } + // System.out.println("in add normal"); + /* if (AuthMe.permission.playerRemove(this.player, "-*")) + return true; + */ + if(AuthMe.permission.playerRemoveGroup(player.getWorld(),player.getName().toString(),this.unLoggedGroup) && AuthMe.permission.playerAddGroup(player.getWorld(),player.getName().toString(),group)) { + //System.out.println("vecchio "+this.unLoggedGroup+ "nuovo" + group); + return true; + + } + return false; + } + + private String hasPermOnJoin(Player player) { + /* if(Settings.getJoinPermissions.isEmpty()) + return null; */ + Iterator iter = Settings.getJoinPermissions.iterator(); + while (iter.hasNext()) { + String permission = iter.next(); + // System.out.println("permissions? "+ permission); + + if(AuthMe.permission.playerHas(player, permission)){ + // System.out.println("player has permissions " +permission); + AuthMe.permission.playerAddTransient(player, permission); + } + } + return null; + } + + public boolean isUnrestricted(Player player) { + + + if(Settings.getUnrestrictedName.isEmpty() || Settings.getUnrestrictedName == null) + return false; + + // System.out.println("name to escape "+player.getName()); + if(Settings.getUnrestrictedName.contains(player.getName())) { + // System.out.println("name to escape correctly"+player.getName()); + return true; + } + + return false; + + + } + public static Utils getInstance() { + + singleton = new Utils(); + + return singleton; + } + + private boolean useGroupSystem() { + + if(Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty()) { + return true; + } return false; + + } + + public void packCoords(int x, int y, int z, final Player pl) + { + final World world = pl.getWorld(); + final int fY = y; + final Location loc = new Location(world, x + 0.5D, y + 0.6D, z + 0.5D); + + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, loc); + AuthMe.getInstance().getServer().getPluginManager().callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + pl.teleport(tpEvent.getTo()); + } + + id = Bukkit.getScheduler().runTaskTimerAsynchronously(AuthMe.authme, new Runnable() + { + @Override + public void run() { + int current = (int)pl.getLocation().getY(); + World currentWorld = pl.getWorld(); + + if (current != fY && world.getName() == currentWorld.getName()) { + pl.teleport(loc); + } + } + + }, 1L, 20L); + + + Bukkit.getScheduler().runTaskLaterAsynchronously(AuthMe.authme, new Runnable() + { + + @Override + public void run() { + id.cancel(); + + } + + }, 60L); + } + + /* + * Random Token for passpartu + * + */ + public boolean obtainToken() { + File file = new File("plugins/AuthMe/passpartu.token"); + + if (file.exists()) + file.delete(); + + FileWriter writer = null; + try { + file.createNewFile(); + writer = new FileWriter(file); + String token = generateToken(); + writer.write(token+":"+System.currentTimeMillis()/1000+"\r\n"); + writer.flush(); + System.out.println("[AuthMe] Security passpartu token: "+ token); + writer.close(); + return true; + } catch(Exception e) { + e.printStackTrace(); + } + + + return false; + } + + /* + * Read Toekn + */ + public boolean readToken(String inputToken) { + File file = new File("plugins/AuthMe/passpartu.token"); + + if (!file.exists()) + return false; + + if (inputToken.isEmpty() ) + return false; + + Scanner reader = null; + try { + reader = new Scanner(file); + + while (reader.hasNextLine()) { + final String line = reader.nextLine(); + + if (line.contains(":")) { + String[] tokenInfo = line.split(":"); + //System.err.println("Authme input token "+inputToken+" saved token "+tokenInfo[0]); + //System.err.println("Authme time "+System.currentTimeMillis()/1000+"saved time "+Integer.parseInt(tokenInfo[1])); + if(tokenInfo[0].equals(inputToken) && System.currentTimeMillis()/1000-30 <= Integer.parseInt(tokenInfo[1]) ) { + file.delete(); + reader.close(); + return true; + } + } + } + } catch(Exception e) { + e.printStackTrace(); + } + + reader.close(); + return false; + } + /* + * Generate Random Token + */ + private String generateToken() { + // obtain new random token + Random rnd = new Random (); + char[] arr = new char[5]; + + for (int i=0; i<5; i++) { + int n = rnd.nextInt (36); + arr[i] = (char) (n < 10 ? '0'+n : 'a'+n-10); + } + + return new String(arr); + } + public enum groupType { + UNREGISTERED, REGISTERED, NOTLOGGEDIN, LOGGEDIN + } + +} diff --git a/src/main/java/uk/org/whoami/authme/api/API.java b/src/main/java/uk/org/whoami/authme/api/API.java new file mode 100644 index 00000000..eb0a8e31 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/api/API.java @@ -0,0 +1,191 @@ +package uk.org.whoami.authme.api; + +import java.lang.reflect.Array; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.datasource.DataSource.DataSourceType; +import uk.org.whoami.authme.security.PasswordSecurity.HashAlgorithm; +import uk.org.whoami.authme.settings.Settings; + +public class API { + + public AuthMe instance; + public DataSource database; + + public API(AuthMe instance, DataSource database) { + this.instance = instance; + this.database = database; + } + /** + * Hook into AuthMe + * @return AuthMe instance + */ + public static AuthMe hookAuthMe() { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); + if (plugin == null && !(plugin instanceof AuthMe)) { + return null; + } + return (AuthMe) plugin; + } + + public AuthMe getPlugin() { + return instance; + } + + /** + * + * @param player + * @return true if player is authenticate + */ + public static boolean isAuthenticated(Player player) { + return PlayerCache.getInstance().isAuthenticated(player.getName()); + } + + /** + * + * @param player + * @return true if player is a npc + */ + public boolean isaNPC(Player player) { + return instance.getCitizensCommunicator().isNPC(player, instance); + } + + /** + * + * @param player + * @return true if the player is unrestricted + */ + public static boolean isUnrestricted(Player player) { + return Utils.getInstance().isUnrestricted(player); + } + + public static boolean isChatAllowed() { + return Settings.isChatAllowed; + } + + public static boolean isAllowRestrictedIp() { + return Settings.isAllowRestrictedIp; + } + + public static boolean isBackupActivated() { + return Settings.isBackupActivated; + } + + public static boolean isForceSpawnLocOnJoinEnabled() { + return Settings.isForceSpawnLocOnJoinEnabled; + } + + public static DataSourceType getDataSource() { + return Settings.getDataSource; + } + + public static int getMovementRadius() { + return Settings.getMovementRadius; + } + + public static List getJoinPermissions() { + return Settings.getJoinPermissions; + } + + public static Boolean isPasspartuEnable() { + return Settings.enablePasspartu; + } + + public static String getcUnrestrictedName() { + return Settings.getcUnrestrictedName; + } + + public static Boolean getEnablePasswordVerifier() { + return Settings.getEnablePasswordVerifier; + } + + public static int getMaxNickLength() { + return Settings.getMaxNickLength; + } + + public static int getMinNickLength() { + return Settings.getMinNickLength; + } + + public static Array getLastLocationColumns() { + Array columns = null; + Array.set(columns, 0, Settings.getMySQLlastlocX); + Array.set(columns, 1, Settings.getMySQLlastlocY); + Array.set(columns, 2, Settings.getMySQLlastlocZ); + return columns; + } + + public static Location getLastLocation(Player player) { + try { + PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName()); + + if (auth != null) { + Location loc = new Location(player.getWorld(), auth.getQuitLocX(), auth.getQuitLocY() , auth.getQuitLocZ()); + return loc; + } else { + return null; + } + + } catch (NullPointerException ex) { + return null; + } + + } + + public static String getNickRegex() { + return Settings.getNickRegex; + } + + public static int getPasswordMinLen() { + return Settings.getPasswordMinLen; + } + + public static HashAlgorithm getPasswordHash() { + return Settings.getPasswordHash; + } + + public static int getRegistrationTimeout() { + return Settings.getRegistrationTimeout; + } + + public static int getSessionTimeout() { + return Settings.getSessionTimeout; + } + + public static String getUnloggedinGroup() { + return Settings.getUnloggedinGroup; + } + + public static void setPlayerInventory(Player player, ItemStack[] content, ItemStack[] armor) { + try { + player.getInventory().setContents(content); + player.getInventory().setArmorContents(armor); + } catch (NullPointerException npe) { + } + + + } + + public void saveAuth(final PlayerAuth auth) { + instance.getServer().getScheduler().runTask(instance, new Runnable() { + + @Override + public void run() { + database.saveAuth(auth); + } + + }); + } + +} diff --git a/src/main/java/uk/org/whoami/authme/cache/auth/PlayerAuth.java b/src/main/java/uk/org/whoami/authme/cache/auth/PlayerAuth.java new file mode 100644 index 00000000..37cff4f9 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/cache/auth/PlayerAuth.java @@ -0,0 +1,223 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.cache.auth; + +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.settings.Settings; + + +public class PlayerAuth { + + private String nickname; + private String hash; + private String ip = "198.18.0.1"; + private long lastLogin; + private int x = 0; + private int y = 0; + private int z = 0; + private String salt = ""; + private String vBhash = null; + private int groupId; + private String email = "your@email.com"; + + public PlayerAuth(String nickname, String hash, String ip, long lastLogin) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + } + + public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String email) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.email = email; + } + + public PlayerAuth(String nickname, int x, int y, int z) { + this.nickname = nickname; + this.x = x; + this.y = y; + this.z = z; + } + + public PlayerAuth(String nickname, String hash, String ip, long lastLogin, int x, int y, int z, String email) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.x = x; + this.y = y; + this.z = z; + this.email = email; + } + + // + // This constructor is needed for Vbulletin board Auth! + // + public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, int x, int y, int z, String email) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.x = x; + this.y = y; + this.z = z; + this.salt = salt; + this.groupId = groupId; + this.email = email; + } + + // IPB Constructor with groups + public PlayerAuth(String nickname, String hash, String salt, int groupId , String ip, long lastLogin) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.salt = salt; + this.groupId = groupId; + } + + // IPB Constructor without groups + public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.salt = salt; + } + + public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, int x, int y, int z, String email) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.x = x; + this.y = y; + this.z = z; + this.salt = salt; + this.email = email; + } + + + public PlayerAuth(String nickname, String hash, String ip, long lastLogin, int x, int y, int z) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.x = x; + this.y = y; + this.z = z; + this.email = "your@email.com"; + } + + + public String getIp() { + return ip; + } + + public String getNickname() { + return nickname; + } + + public String getHash() { + if(!salt.isEmpty() && Settings.getPasswordHash == PasswordSecurity.HashAlgorithm.MD5VB) { + vBhash = "$MD5vb$"+salt+"$"+hash; + // Compose Vbullettin Hash System! + return vBhash; + } + else { + return hash; + } + } + + //Get Salt + public String getSalt() { + return this.salt; + } + + // + // GroupId for unactivated User on Vbullettin Board + // + public int getGroupId() { + return groupId; + } + + public int getQuitLocX() { + return x; + } + public int getQuitLocY() { + return y; + } + public int getQuitLocZ() { + return z; + } + public String getEmail() { + return email; + } + public void setQuitLocX(int x) { + this.x = x; + } + public void setQuitLocY(int y) { + this.y = y; + } + public void setQuitLocZ(int z) { + this.z = z; + } + public long getLastLogin() { + return lastLogin; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public void setLastLogin(long lastLogin) { + this.lastLogin = lastLogin; + } + + public void setEmail(String email) { + this.email = email; + } + + public void setSalt(String salt) { + this.salt = salt; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof PlayerAuth)) { + return false; + } + PlayerAuth other = (PlayerAuth) obj; + + return other.getIp().equals(this.ip) && other.getNickname().equals(this.nickname); + } + + @Override + public int hashCode() { + int hashCode = 7; + hashCode = 71 * hashCode + (this.nickname != null ? this.nickname.hashCode() : 0); + hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0); + return hashCode; + } +} diff --git a/src/main/java/uk/org/whoami/authme/cache/auth/PlayerCache.java b/src/main/java/uk/org/whoami/authme/cache/auth/PlayerCache.java new file mode 100644 index 00000000..505fdad4 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/cache/auth/PlayerCache.java @@ -0,0 +1,57 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.cache.auth; + +import java.util.HashMap; + +public class PlayerCache { + + private static PlayerCache singleton = null; + private HashMap cache; + + private PlayerCache() { + cache = new HashMap(); + } + + public void addPlayer(PlayerAuth auth) { + cache.put(auth.getNickname(), auth); + } + + public void updatePlayer(PlayerAuth auth) { + cache.remove(auth.getNickname()); + cache.put(auth.getNickname(), auth); + } + + public void removePlayer(String user) { + cache.remove(user); + } + + public boolean isAuthenticated(String user) { + return cache.containsKey(user); + } + + public PlayerAuth getAuth(String user) { + return cache.get(user); + } + + public static PlayerCache getInstance() { + if (singleton == null) { + singleton = new PlayerCache(); + } + return singleton; + } +} diff --git a/src/main/java/uk/org/whoami/authme/cache/backup/DataFileCache.java b/src/main/java/uk/org/whoami/authme/cache/backup/DataFileCache.java new file mode 100644 index 00000000..1cdf7b2d --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/cache/backup/DataFileCache.java @@ -0,0 +1,49 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme.cache.backup; + +/** + * + * @author stefano + */ +import org.bukkit.inventory.ItemStack; + +public class DataFileCache { + + + private ItemStack[] inventory; + private ItemStack[] armor; + private String group; + private boolean operator; + + public DataFileCache(ItemStack[] inventory, ItemStack[] armor){ + this.inventory = inventory; + this.armor = armor; + + } + + public DataFileCache(ItemStack[] inventory, ItemStack[] armor, String group, boolean operator){ + this.inventory = inventory; + this.armor = armor; + this.group = group; + this.operator = operator; + } + public ItemStack[] getInventory(){ + return inventory; + } + + public ItemStack[] getArmour(){ + return armor; + } + + public String getGroup(){ + return group; + } + + public Boolean getOperator(){ + return operator; + } +} + diff --git a/src/main/java/uk/org/whoami/authme/cache/backup/FileCache.java b/src/main/java/uk/org/whoami/authme/cache/backup/FileCache.java new file mode 100644 index 00000000..9e79808b --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/cache/backup/FileCache.java @@ -0,0 +1,228 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme.cache.backup; + +/** + * + * @author stefano + */ +import java.io.File; +import java.io.FileWriter; + +import java.util.Scanner; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + +import uk.org.whoami.authme.ConsoleLogger; + + +public class FileCache { + //private HashMap ench; + + + public FileCache() { + final File folder = new File("cache"); + if (!folder.exists()) { + folder.mkdirs(); + } + } + + public void createCache(String playername, DataFileCache playerData, String group, boolean operator) { + final File file = new File("cache/" + playername + + ".cache"); + + if (file.exists()) { + return; + } + + FileWriter writer = null; + try { + file.createNewFile(); + + writer = new FileWriter(file); + + // put player group in cache + // put if player is an op or not 1: is op 0: isnet op! + // line format Group|OperatorStatus + + if(operator) + writer.write(group+";1\r\n"); + else writer.write(group+";0\r\n"); + + writer.flush(); + + ItemStack[] invstack = playerData.getInventory(); + + for (int i = 0; i < invstack.length; i++) { + + int itemid = 0; + int amount = 0; + int durability = 0; + String enchList = ""; + //ench = new HashMap(); + + if (invstack[i] != null) { + itemid = invstack[i].getTypeId(); + amount = invstack[i].getAmount(); + durability = invstack[i].getDurability(); + + + for(Enchantment e : invstack[i].getEnchantments().keySet()) + { + try { + enchList = enchList.concat(e.getName()+":"+invstack[i].getEnchantmentLevel(e)+":"); + } catch (NullPointerException npe) { + ConsoleLogger.showError(npe.getMessage()); + ConsoleLogger.showError("The player " + playername + " has an illegaly enchant, Check Him !"); + } + + + + } + } + + writer.write("i" + ":" + itemid + ":" + amount + ":" + + durability + ":"+ enchList + "\r\n"); + writer.flush(); + } + + ItemStack[] armorstack = playerData.getArmour(); + + for (int i = 0; i < armorstack.length; i++) { + int itemid = 0; + int amount = 0; + int durability = 0; + String enchList = ""; + + if (armorstack[i] != null) { + itemid = armorstack[i].getTypeId(); + amount = armorstack[i].getAmount(); + durability = armorstack[i].getDurability(); + + for(Enchantment e : armorstack[i].getEnchantments().keySet()) + { + try { + enchList = enchList.concat(e.getName()+":"+armorstack[i].getEnchantmentLevel(e)+":"); + } catch (NullPointerException npe) { + ConsoleLogger.showError(npe.getMessage()); + ConsoleLogger.showError("The player " + playername + " has an illegaly enchant, Check Him !"); + } + + + } + } + + writer.write("w" + ":" + itemid + ":" + amount + ":" + + durability + ":"+ enchList + "\r\n"); + writer.flush(); + } + + writer.close(); + } catch (final Exception e) { + e.printStackTrace(); + } + } + + public DataFileCache readCache(String playername) { + final File file = new File("cache/" + playername + + ".cache"); + + ItemStack[] stacki = new ItemStack[36]; + ItemStack[] stacka = new ItemStack[4]; + String group = null; + boolean op = false; + + if (!file.exists()) { + return new DataFileCache(stacki, stacka); + } + + Scanner reader = null; + try { + reader = new Scanner(file); + + int i = 0; + int a = 0; + while (reader.hasNextLine()) { + final String line = reader.nextLine(); + + if (!line.contains(":")) { + // the fist line rapresent the player group and operator status + final String[] playerInfo = line.split(";"); + group = playerInfo[0]; + + if (Integer.parseInt(playerInfo[1]) == 1) { + op = true; + } else op = false; + + continue; + } + + final String[] in = line.split(":"); + + /*if (in.length != 4) { + continue; + } */ + + if (!in[0].equals("i") && !in[0].equals("w")) { + continue; + } + // can enchant item? size ofstring in file - 4 all / 2 = number of enchant + if (in[0].equals("i")) { + stacki[i] = new ItemStack(Integer.parseInt(in[1]), + Integer.parseInt(in[2]), Short.parseShort((in[3]))); + // qui c'e' un problema serio! + if(in.length > 4 && !in[4].isEmpty()) { + for(int k=4;k 4 && !in[4].isEmpty()) { + for(int k=4;k. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.cache.limbo; + +import java.util.HashMap; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.cache.backup.FileCache; +import uk.org.whoami.authme.events.ResetInventoryEvent; +import uk.org.whoami.authme.events.StoreInventoryEvent; +import uk.org.whoami.authme.settings.Settings; + +public class LimboCache { + + private static LimboCache singleton = null; + private HashMap cache; + private FileCache playerData = new FileCache(); + public AuthMe plugin; + + private LimboCache(AuthMe plugin) { + this.plugin = plugin; + this.cache = new HashMap(); + } + + public void addLimboPlayer(Player player) { + String name = player.getName().toLowerCase(); + Location loc = player.getLocation(); + int gameMode = player.getGameMode().getValue(); + ItemStack[] arm; + ItemStack[] inv; + boolean operator; + String playerGroup = ""; + + if (playerData.doesCacheExist(name)) { + 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; + } + playerGroup = playerData.readCache(name).getGroup(); + operator = playerData.readCache(name).getOperator(); + } else { + 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; + } + + if(player.isOp() ) { + operator = true; + } else { + operator = false; + } + } + + + + if(Settings.isForceSurvivalModeEnabled) { + if(Settings.isResetInventoryIfCreative && gameMode != 0 ) { + ResetInventoryEvent event = new ResetInventoryEvent(player); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + player.sendMessage("Your inventory has been cleaned!"); + } + } + gameMode = 0; + } + if(player.isDead()) { + loc = player.getWorld().getSpawnLocation(); + if (plugin.mv != null) + { + try { + loc = plugin.mv.getMVWorldManager().getMVWorld(player.getWorld().getName()).getSpawnLocation(); + } catch (NullPointerException npe) {} + } + + } + try { + if(cache.containsKey(name) && playerGroup.isEmpty()) { + LimboPlayer groupLimbo = cache.get(name); + playerGroup = groupLimbo.getGroup(); + } + } catch (NullPointerException ex) { + } + + cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup)); + } + + public void addLimboPlayer(Player player, String group) { + + cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group)); + } + + public void deleteLimboPlayer(String name) { + cache.remove(name); + } + + public LimboPlayer getLimboPlayer(String name) { + return cache.get(name); + } + + public boolean hasLimboPlayer(String name) { + return cache.containsKey(name); + } + + + public static LimboCache getInstance() { + if (singleton == null) { + singleton = new LimboCache(AuthMe.getInstance()); + } + return singleton; + } + + public void updateLimboPlayer(Player player) { + if (this.hasLimboPlayer(player.getName().toLowerCase())) { + this.deleteLimboPlayer(player.getName().toLowerCase()); + } + this.addLimboPlayer(player); + } +} diff --git a/src/main/java/uk/org/whoami/authme/cache/limbo/LimboPlayer.java b/src/main/java/uk/org/whoami/authme/cache/limbo/LimboPlayer.java new file mode 100644 index 00000000..a688f370 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/cache/limbo/LimboPlayer.java @@ -0,0 +1,102 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.cache.limbo; + +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; + +public class LimboPlayer { + + private String name; + private ItemStack[] inventory; + private ItemStack[] armour; + private Location loc = null; + private int timeoutTaskId = -1; + private int messageTaskId = -1; + private int gameMode = 0; + private boolean operator = false; + private String group = null; + + public LimboPlayer(String name, Location loc, ItemStack[] inventory, ItemStack[] armour, int gameMode, boolean operator, String group) { + this.name = name; + this.loc = loc; + this.inventory = inventory; + this.armour = armour; + this.gameMode = gameMode; + this.operator = operator; + this.group = group; + } + + public LimboPlayer(String name, Location loc, int gameMode, boolean operator, String group) { + this.name = name; + this.loc = loc; + this.gameMode = gameMode; + this.operator = operator; + this.group = group; + } + + public LimboPlayer(String name, String group) { + this.name = name; + this.group = group; + } + + + public String getName() { + return name; + } + + public Location getLoc() { + return loc; + } + + public ItemStack[] getArmour() { + return armour; + } + + public ItemStack[] getInventory() { + return inventory; + } + + public int getGameMode() { + return gameMode; + } + + public boolean getOperator() { + return operator; + } + + public String getGroup() { + return group; + } + + public void setTimeoutTaskId(int i) { + this.timeoutTaskId = i; + } + + public int getTimeoutTaskId() { + return timeoutTaskId; + } + + public void setMessageTaskId(int messageTaskId) { + this.messageTaskId = messageTaskId; + } + + public int getMessageTaskId() { + return messageTaskId; + } + +} diff --git a/src/main/java/uk/org/whoami/authme/commands/AdminCommand.java b/src/main/java/uk/org/whoami/authme/commands/AdminCommand.java new file mode 100644 index 00000000..f4807df7 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/AdminCommand.java @@ -0,0 +1,405 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.commands; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.NoSuchAlgorithmException; +import java.util.Date; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.converter.FlatToSql; +import uk.org.whoami.authme.converter.RakamakConverter; +import uk.org.whoami.authme.converter.xAuthToFlat; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.Settings; +import uk.org.whoami.authme.settings.SpoutCfg; + +public class AdminCommand implements CommandExecutor { + + public AuthMe plugin; + + private Messages m = Messages.getInstance(); + private SpoutCfg s = SpoutCfg.getInstance(); + //private Settings settings = Settings.getInstance(); + public DataSource database; + + public AdminCommand(AuthMe plugin, DataSource database) { + this.database = database; + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (args.length == 0) { + sender.sendMessage("Usage: /authme reload - Reload the config"); + sender.sendMessage("/authme register - Register a player"); + sender.sendMessage("/authme changepassword - Change player password"); + sender.sendMessage("/authme unregister - Unregister a player"); + sender.sendMessage("/authme purge - Purge Database"); + sender.sendMessage("/authme version - Get AuthMe version infos"); + sender.sendMessage("/authme lastlogin - Display Date about the Player's LastLogin"); + return true; + } + + if((sender instanceof ConsoleCommandSender) && args[0].equalsIgnoreCase("passpartuToken")) { + if(args.length > 1) { + System.out.println("[AuthMe] command usage: authme passpartuToken"); + return true; + } + + if(Utils.getInstance().obtainToken()) { + System.out.println("[AuthMe] You have 30s for insert this token ingame with /passpartu [token]"); + } else { + System.out.println("[AuthMe] Security error on passpartu token, redo it. "); + } + return true; + } + + + if (!sender.hasPermission("authme.admin." + args[0].toLowerCase())) { + sender.sendMessage(m._("no_perm")); + return true; + } + + + if (args[0].equalsIgnoreCase("version")) { + sender.sendMessage("AuthMe Version: "+AuthMe.getInstance().getDescription().getVersion()); + return true; + } + + + if (args[0].equalsIgnoreCase("purge")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme purge "); + return true; + } + + try { + long days = Long.parseLong(args[1]) * 86400000; + long until = new Date().getTime() - days; + + sender.sendMessage("Deleted " + database.purgeDatabase(until) + " user accounts"); + + } catch (NumberFormatException e) { + sender.sendMessage("Usage: /authme purge "); + return true; + } + } else if (args[0].equalsIgnoreCase("reload")) { + database.reload(); + + //Trying to load config from JAR-Ressources, if config.yml doesn't exist... + File newConfigFile = new File("plugins/AuthMe","config.yml"); + if (!newConfigFile.exists()) { + InputStream fis = getClass().getResourceAsStream("/config.yml"); + FileOutputStream fos = null; + try { + fos = new FileOutputStream(newConfigFile); + byte[] buf = new byte[1024]; + int i = 0; + + while ((i = fis.read(buf)) != -1) { + fos.write(buf, 0, i); + } + } catch (Exception e) { + Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR"); + } finally { + try { + if (fis != null) { + fis.close(); + } + if (fos != null) { + fos.close(); + } + } catch (Exception e) { + } + } + } + YamlConfiguration newConfig = YamlConfiguration.loadConfiguration(newConfigFile); + Settings.reloadConfigOptions(newConfig); + m.reload(); + s.reload(); + sender.sendMessage(m._("reload")); + } else if (args[0].equalsIgnoreCase("lastlogin")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme lastlogin "); + return true; + } + try { + if (database.getAuth(args[1].toLowerCase()) != null) { + PlayerAuth player = database.getAuth(args[1].toLowerCase()); + long lastLogin = player.getLastLogin(); + Date d = new Date(lastLogin); + final long diff = System.currentTimeMillis() - lastLogin; + final String msg = (int)(diff / 86400000) + " days " + (int)(diff / 3600000 % 24) + " hours " + (int)(diff / 60000 % 60) + " mins " + (int)(diff / 1000 % 60) + " secs."; + String lastIP = player.getIp(); + sender.sendMessage("[AuthMe] " + args[1].toLowerCase() + " lastlogin : " + d.toString()); + sender.sendMessage("[AuthMe] The player : " + player.getNickname() + " is unlogged since " + msg); + sender.sendMessage("[AuthMe] LastPlayer IP : " + lastIP); + } + } catch (NullPointerException e) { + sender.sendMessage("This player does not exist"); + } + } else if (args[0].equalsIgnoreCase("accounts")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme accounts "); + sender.sendMessage("Or: /authme accounts "); + return true; + } + if (!args[1].contains(".")) { + final CommandSender fSender = sender; + final String[] arguments = args; + Bukkit.getScheduler().runTask(plugin, new Runnable() { + + @Override + public void run() { + PlayerAuth pAuth = null; + String message = "[AuthMe] "; + try { + pAuth = database.getAuth(arguments[1].toLowerCase()); + } catch (NullPointerException npe){ + fSender.sendMessage("[AuthMe] This player is unknown"); + return; + } + if (pAuth != null) { + List accountList = database.getAllAuthsByName(pAuth); + if (accountList.isEmpty() || accountList == null) { + fSender.sendMessage("[AuthMe] This player is unknown"); + return; + } + if (accountList.size() == 1) { + fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); + return; + } + int i = 0; + for (String account : accountList) { + i++; + message = message + account; + if (i != accountList.size()) { + message = message + ", "; + } else { + message = message + "."; + } + } + fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); + fSender.sendMessage(message); + } else { + fSender.sendMessage("[AuthMe] This player is unknown"); + return; + } + + } + + }); + return true; + } else { + final CommandSender fSender = sender; + final String[] arguments = args; + Bukkit.getScheduler().runTask(plugin, new Runnable() { + + @Override + public void run() { + String message = "[AuthMe] "; + if (arguments[1] != null) { + List accountList = database.getAllAuthsByIp(arguments[1]); + if (accountList.isEmpty() || accountList == null) { + fSender.sendMessage("[AuthMe] Please put a valid IP"); + return; + } + if (accountList.size() == 1) { + fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); + return; + } + int i = 0; + for (String account : accountList) { + i++; + message = message + account; + if (i != accountList.size()) { + message = message + ", "; + } else { + message = message + "."; + } + } + fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); + fSender.sendMessage(message); + } else { + fSender.sendMessage("[AuthMe] Please put a valid IP"); + return; + } + + } + + }); + return true; + } + } else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) { + if (args.length != 3) { + sender.sendMessage("Usage: /authme register playername password"); + return true; + } + + try { + String name = args[1].toLowerCase(); + String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name); + + if (database.isAuthAvailable(name)) { + sender.sendMessage(m._("user_regged")); + return true; + } + + PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0); + if (!database.saveAuth(auth)) { + sender.sendMessage(m._("error")); + return true; + } + sender.sendMessage(m._("registered")); + ConsoleLogger.info(args[1] + " registered"); + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage(m._("error")); + } + } else if (args[0].equalsIgnoreCase("convertflattosql")) { + try { + FlatToSql.FlatToSqlConverter(); + if (sender instanceof Player) + sender.sendMessage("[AuthMe] FlatFile converted to authme.sql file"); + } catch (IOException e) { + e.printStackTrace(); + } catch (NullPointerException ex) { + System.out.println(ex.getMessage()); + } + + } else if (args[0].equalsIgnoreCase("xauthimport")) { + xAuthToFlat converter = new xAuthToFlat(plugin, database); + if (converter.convert(sender)) { + sender.sendMessage("[AuthMe] Successfull convert from xAuth database"); + } else { + sender.sendMessage("[AuthMe] Error while trying to convert from xAuth database"); + } + + } else if (args[0].equalsIgnoreCase("getemail")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme getemail playername"); + return true; + } + String playername = args[1].toLowerCase(); + PlayerAuth getAuth = PlayerCache.getInstance().getAuth(playername); + sender.sendMessage("[AuthMe] " + args[1] + " email : " + getAuth.getEmail()); + return true; + + } else if (args[0].equalsIgnoreCase("chgemail")) { + if (args.length != 3) { + sender.sendMessage("Usage: /authme chgemail playername email"); + return true; + } + String playername = args[1].toLowerCase(); + PlayerAuth getAuth = PlayerCache.getInstance().getAuth(playername); + getAuth.setEmail(args[2]); + if (!database.updateEmail(getAuth)) { + sender.sendMessage(m._("error")); + return true; + } + PlayerCache.getInstance().updatePlayer(getAuth); + return true; + + } else if (args[0].equalsIgnoreCase("convertfromrakamak")) { + try { + RakamakConverter.RakamakConvert(); + if (sender instanceof Player) + sender.sendMessage("[AuthMe] Rakamak database converted to auths.db"); + } catch (IOException e) { + e.printStackTrace(); + } catch (NullPointerException ex) { + System.out.println(ex.getMessage()); + } + + } else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) { + if (args.length != 3) { + sender.sendMessage("Usage: /authme changepassword playername newpassword"); + return true; + } + + try { + String name = args[1].toLowerCase(); + String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name); + + PlayerAuth auth = null; + if (PlayerCache.getInstance().isAuthenticated(name)) { + auth = PlayerCache.getInstance().getAuth(name); + } else if (database.isAuthAvailable(name)) { + auth = database.getAuth(name); + } else { + sender.sendMessage(m._("unknown_user")); + return true; + } + auth.setHash(hash); + + if (!database.updatePassword(auth)) { + sender.sendMessage(m._("error")); + return true; + } + + sender.sendMessage("pwd_changed"); + ConsoleLogger.info(args[1] + "'s password changed"); + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage(m._("error")); + } + } else if (args[0].equalsIgnoreCase("unregister") || args[0].equalsIgnoreCase("unreg") || args[0].equalsIgnoreCase("del") ) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme unregister playername"); + return true; + } + + String name = args[1].toLowerCase(); + + if (!database.removeAuth(name)) { + sender.sendMessage(m._("error")); + return true; + } + + PlayerCache.getInstance().removePlayer(name); + sender.sendMessage("unregistered"); + + ConsoleLogger.info(args[1] + " unregistered"); + } else { + sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername"); + } + return true; + } +} diff --git a/src/main/java/uk/org/whoami/authme/commands/CaptchaCommand.java b/src/main/java/uk/org/whoami/authme/commands/CaptchaCommand.java new file mode 100644 index 00000000..fbb85441 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/CaptchaCommand.java @@ -0,0 +1,81 @@ +package uk.org.whoami.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.security.RandomString; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.Settings; + +public class CaptchaCommand implements CommandExecutor { + + public AuthMe plugin; + private Messages m = Messages.getInstance(); + public static RandomString rdm = new RandomString(Settings.captchaLength); + + public CaptchaCommand(AuthMe plugin) { + this.plugin = plugin; + } + + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, + String label, String[] args) { + + if (!(sender instanceof Player)) { + return true; + } + + Player player = (Player) sender; + String name = player.getName().toLowerCase(); + + + if (args.length == 0) { + player.sendMessage(m._("usage_captcha")); + return true; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + player.sendMessage(m._("logged_in")); + return true; + } + + if (!player.hasPermission("authme." + label.toLowerCase())) { + player.sendMessage(m._("no_perm")); + return true; + } + + if (!Settings.useCaptcha) { + player.sendMessage(m._("usage_log")); + return true; + } + + if(!plugin.cap.containsKey(name)) { + player.sendMessage(m._("usage_log")); + return true; + } + + if(Settings.useCaptcha && !args[0].equals(plugin.cap.get(name))) { + plugin.cap.remove(name); + plugin.cap.put(name, rdm.nextString()); + player.sendMessage(m._("wrong_captcha").replaceAll("THE_CAPTCHA", plugin.cap.get(name))); + return true; + } + try { + plugin.captcha.remove(name); + plugin.cap.remove(name); + } catch (NullPointerException npe) { + } + + player.sendMessage("Your captcha is correct"); + player.sendMessage(m._("login_msg")); + return true; + + + } + +} diff --git a/src/main/java/uk/org/whoami/authme/commands/ChangePasswordCommand.java b/src/main/java/uk/org/whoami/authme/commands/ChangePasswordCommand.java new file mode 100644 index 00000000..1ddf4833 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/ChangePasswordCommand.java @@ -0,0 +1,105 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.commands; + +import java.security.NoSuchAlgorithmException; + +import me.muizers.Notifications.Notification; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.Settings; + +public class ChangePasswordCommand implements CommandExecutor { + + private Messages m = Messages.getInstance(); + //private Settings settings = Settings.getInstance(); + private DataSource database; + public AuthMe plugin; + + public ChangePasswordCommand(DataSource database, AuthMe plugin) { + this.database = database; + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!sender.hasPermission("authme." + label.toLowerCase())) { + sender.sendMessage(m._("no_perm")); + return true; + } + + Player player = (Player) sender; + String name = player.getName().toLowerCase(); + if (!PlayerCache.getInstance().isAuthenticated(name)) { + player.sendMessage(m._("not_logged_in")); + return true; + } + + // + // Check to prevent Changing Password if is active VBullettin system + // + if(!Settings.getMySQLColumnSalt.isEmpty()) { + player.sendMessage(m._("You can Change Your Password on Forum panel!")); + return true; + } + + if (args.length != 2) { + player.sendMessage(m._("usage_changepassword")); + return true; + } + + try { + String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, args[1], name); + + if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), name)) { + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + auth.setHash(hashnew); + if (!database.updatePassword(auth)) { + player.sendMessage(m._("error")); + return true; + } + PlayerCache.getInstance().updatePlayer(auth); + player.sendMessage(m._("pwd_changed")); + ConsoleLogger.info(player.getName() + " changed his password"); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " change his password!")); + } + } else { + player.sendMessage(m._("wrong_pwd")); + } + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage(m._("error")); + } + return true; + } +} diff --git a/src/main/java/uk/org/whoami/authme/commands/EmailCommand.java b/src/main/java/uk/org/whoami/authme/commands/EmailCommand.java new file mode 100644 index 00000000..f686f118 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/EmailCommand.java @@ -0,0 +1,204 @@ +/* + * Copyright 2012 darkwarriors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package uk.org.whoami.authme.commands; + +import java.security.NoSuchAlgorithmException; + +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.security.RandomString; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.Settings; + +/** + * + * @author darkwarriors + */ +public class EmailCommand implements CommandExecutor { + + public AuthMe plugin; + private DataSource data; + private Messages m = Messages.getInstance(); + + public EmailCommand(AuthMe plugin, DataSource data) { + this.plugin = plugin; + this.data = data; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!sender.hasPermission("authme." + label.toLowerCase())) { + sender.sendMessage(m._("no_perm")); + return true; + } + + Player player = (Player) sender; + String name = player.getName().toLowerCase(); + + if (args.length == 0) { + player.sendMessage("usage: /email add "); + player.sendMessage("usage: /email change "); + player.sendMessage("usage: /email recovery "); + return true; + } + + if(args[0].equalsIgnoreCase("add")) { + if (args.length != 3) { + player.sendMessage("[AuthMe] /email add "); + return true; + } + if(args[1].equals(args[2]) && PlayerCache.getInstance().isAuthenticated(name)) { + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + if (auth.getEmail() == null || !auth.getEmail().contains("your@email.com")) { + player.sendMessage("[AuthMe] /email change "); + return true; + } + if (!args[1].contains("@")) { + player.sendMessage("[AuthMe] Invalid Email !"); + return true; + } + auth.setEmail(args[1]); + if (!data.updateEmail(auth)) { + player.sendMessage(m._("error")); + return true; + } + PlayerCache.getInstance().updatePlayer(auth); + player.sendMessage("[AuthMe] Email Added !"); + player.sendMessage(auth.getEmail()); + } else if (PlayerCache.getInstance().isAuthenticated(name)){ + player.sendMessage("[AuthMe] Confirm your Email ! "); + } else { + if (!data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + player.sendMessage(m._("reg_msg")); + } + } + } else if(args[0].equalsIgnoreCase("change") && args.length == 3 ) { + if(PlayerCache.getInstance().isAuthenticated(name)) { + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + if (auth.getEmail() == null || auth.getEmail() == "your@email.com") { + player.sendMessage("[AuthMe] Please use : /email add "); + return true; + } + if (args[1] != auth.getEmail()) { + player.sendMessage("[AuthMe] Invalid Email !"); + return true; + } + if (!args[2].contains("@")) { + player.sendMessage("[AuthMe] New Email is Invalid !"); + return true; + } + auth.setEmail(args[2]); + if (!data.updateEmail(auth)) { + player.sendMessage("[AuthMe] /email command only available with MySQL and SQLite"); + return true; + } + PlayerCache.getInstance().updatePlayer(auth); + player.sendMessage("[AuthMe] Email Change !"); + player.sendMessage("[AuthMe] Your Email : " + auth.getEmail()); + } else if (PlayerCache.getInstance().isAuthenticated(name)){ + player.sendMessage("[AuthMe] Confirm your Email ! "); + } else { + if (!data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + player.sendMessage(m._("reg_msg")); + } + } + } + if(args[0].equalsIgnoreCase("recovery")) { + if (args.length != 2) { + player.sendMessage("usage: /email recovery "); + return true; + } + if (plugin.mail == null) { + player.sendMessage(m._("error")); + ConsoleLogger.info("Missed mail.jar in lib folder"); + return true; + } + if (data.isAuthAvailable(name)) { + if (PlayerCache.getInstance().isAuthenticated(name)) { + player.sendMessage(m._("logged_in")); + return true; + } + + try { + RandomString rand = new RandomString(Settings.getRecoveryPassLength); + String thePass = rand.nextString(); + String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, name); + PlayerAuth auth = null; + if (PlayerCache.getInstance().isAuthenticated(name)) { + auth = PlayerCache.getInstance().getAuth(name); + } else if (data.isAuthAvailable(name)) { + auth = data.getAuth(name); + } else { + sender.sendMessage(m._("unknown_user")); + return true; + } + if (Settings.getmailAccount == "" || Settings.getmailAccount.isEmpty()) { + player.sendMessage(m._("error")); + return true; + } + + if (!args[1].equalsIgnoreCase(auth.getEmail())) { + player.sendMessage("[AuthMe] Invalid Email"); + return true; + } + + final String finalhashnew = hashnew; + final PlayerAuth finalauth = auth; + + Bukkit.getScheduler().runTask(plugin, new Runnable() { + + @Override + public void run() { + finalauth.setHash(finalhashnew); + data.updatePassword(finalauth); + + } + + }); + plugin.mail.main(auth, thePass); + player.sendMessage("[AuthMe] Recovery Email Send !"); + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage(m._("error")); + } catch (NoClassDefFoundError ncdfe) { + ConsoleLogger.showError(ncdfe.getMessage()); + sender.sendMessage(m._("error")); + } + } else { + player.sendMessage(m._("reg_msg")); + } + } + + return true; + } +} diff --git a/src/main/java/uk/org/whoami/authme/commands/LoginCommand.java b/src/main/java/uk/org/whoami/authme/commands/LoginCommand.java new file mode 100644 index 00000000..01018725 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/LoginCommand.java @@ -0,0 +1,65 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.Settings; + +public class LoginCommand implements CommandExecutor { + + private AuthMe plugin; + private Messages m = Messages.getInstance(); + + public LoginCommand(AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, final String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if(!Settings.useCaptcha) { + + } + + final Player player = (Player) sender; + + if (args.length == 0) { + player.sendMessage(m._("usage_log")); + return true; + } + + if (!player.hasPermission("authme." + label.toLowerCase())) { + player.sendMessage(m._("no_perm")); + return true; + } + + String result = plugin.management.performLogin(player, args[0]); + if (result != "") player.sendMessage(result); + + return true; + } +} + diff --git a/src/main/java/uk/org/whoami/authme/commands/LogoutCommand.java b/src/main/java/uk/org/whoami/authme/commands/LogoutCommand.java new file mode 100644 index 00000000..2c09c92c --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/LogoutCommand.java @@ -0,0 +1,133 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.commands; + +import me.muizers.Notifications.Notification; + +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.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.backup.DataFileCache; +import uk.org.whoami.authme.cache.backup.FileCache; +import uk.org.whoami.authme.cache.limbo.LimboCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.events.AuthMeTeleportEvent; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.PlayersLogs; +import uk.org.whoami.authme.settings.Settings; +import uk.org.whoami.authme.task.MessageTask; +import uk.org.whoami.authme.task.TimeoutTask; + +public class LogoutCommand implements CommandExecutor { + + private Messages m = Messages.getInstance(); + private PlayersLogs pllog = PlayersLogs.getInstance(); + //private Settings settings = Settings.getInstance(); + private AuthMe plugin; + private DataSource database; + private Utils utils = Utils.getInstance(); + private FileCache playerBackup = new FileCache(); + + public LogoutCommand(AuthMe plugin, DataSource database) { + this.plugin = plugin; + this.database = database; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!sender.hasPermission("authme." + label.toLowerCase())) { + sender.sendMessage(m._("no_perm")); + return true; + } + + Player player = (Player) sender; + String name = player.getName().toLowerCase(); + + if (!PlayerCache.getInstance().isAuthenticated(name)) { + player.sendMessage(m._("not_logged_in")); + return true; + } + + //clear session + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + auth.setIp("198.18.0.1"); + database.updateSession(auth); + + PlayerCache.getInstance().removePlayer(name); + + LimboCache.getInstance().addLimboPlayer(player , utils.removeAll(player)); + LimboCache.getInstance().addLimboPlayer(player); + if(Settings.protectInventoryBeforeLogInEnabled) { + player.getInventory().setArmorContents(new ItemStack[4]); + player.getInventory().setContents(new ItemStack[36]); + // create cache file for handling lost of inventories on unlogged in status + DataFileCache playerData = new DataFileCache(player.getInventory().getContents(),player.getInventory().getArmorContents()); + playerBackup.createCache(name, playerData, LimboCache.getInstance().getLimboPlayer(name).getGroup(),LimboCache.getInstance().getLimboPlayer(name).getOperator()); + } + if (Settings.isTeleportToSpawnEnabled) { + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, player.getWorld().getSpawnLocation()); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + + int delay = Settings.getRegistrationTimeout * 20; + int interval = Settings.getWarnMessageInterval; + BukkitScheduler sched = sender.getServer().getScheduler(); + if (delay != 0) { + BukkitTask id = sched.runTaskLater(plugin, new TimeoutTask(plugin, name), delay); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id.getTaskId()); + } + BukkitTask msgT = sched.runTask(plugin, new MessageTask(plugin, name, m._("login_msg"), interval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT.getTaskId()); + + try { + if (PlayersLogs.players.contains(player.getName())) { + PlayersLogs.players.remove(player.getName()); + pllog.save(); + } + } catch (NullPointerException npe) { + + } + + player.sendMessage(m._("logout")); + ConsoleLogger.info(player.getDisplayName() + " logged out"); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged out!")); + } + + return true; + } +} diff --git a/src/main/java/uk/org/whoami/authme/commands/PasspartuCommand.java b/src/main/java/uk/org/whoami/authme/commands/PasspartuCommand.java new file mode 100644 index 00000000..537de544 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/PasspartuCommand.java @@ -0,0 +1,54 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.Management; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; + +/** + * + * @author stefano + */ +public class PasspartuCommand implements CommandExecutor { + private Utils utils = new Utils(); + private DataSource database; + public AuthMe plugin; + + public PasspartuCommand(DataSource database, AuthMe plugin) { + this.database = database; + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + + if (PlayerCache.getInstance().isAuthenticated(sender.getName().toLowerCase())) { + return true; + } + + if ((sender instanceof Player) && args.length == 1) { + if(utils.readToken(args[0])) { + //bypass login! + Management bypass = new Management(database,true, plugin); + String result = bypass.performLogin((Player)sender, "dontneed"); + if (result != "") sender.sendMessage(result); + return true; + } + + sender.sendMessage("Time is expired or Token is Wrong!"); + return true; + } + sender.sendMessage("usage: /passpartu token"); + return true; + } +} diff --git a/src/main/java/uk/org/whoami/authme/commands/RecoveryCommand.java b/src/main/java/uk/org/whoami/authme/commands/RecoveryCommand.java new file mode 100644 index 00000000..14bcbb08 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/RecoveryCommand.java @@ -0,0 +1,24 @@ +/* + * Copyright 2012 darkwarriors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package uk.org.whoami.authme.commands; + +/** + * + * @author darkwarriors + */ +public class RecoveryCommand { + +} diff --git a/src/main/java/uk/org/whoami/authme/commands/RegisterCommand.java b/src/main/java/uk/org/whoami/authme/commands/RegisterCommand.java new file mode 100644 index 00000000..ad505a86 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/RegisterCommand.java @@ -0,0 +1,299 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.commands; + +import java.security.NoSuchAlgorithmException; +import java.util.Date; + +import me.muizers.Notifications.Notification; +import net.md_5.bungee.api.connection.ConnectedPlayer; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.limbo.LimboCache; +import uk.org.whoami.authme.cache.limbo.LimboPlayer; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.events.AuthMeTeleportEvent; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.security.RandomString; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.PlayersLogs; +import uk.org.whoami.authme.settings.Settings; +import uk.org.whoami.authme.task.MessageTask; +import uk.org.whoami.authme.task.TimeoutTask; + +public class RegisterCommand implements CommandExecutor { + + private Messages m = Messages.getInstance(); + private PlayersLogs pllog = PlayersLogs.getInstance(); + private DataSource database; + public boolean isFirstTimeJoin; + public PlayerAuth auth; + public AuthMe plugin; + + public RegisterCommand(DataSource database, AuthMe plugin) { + this.database = database; + this.isFirstTimeJoin = false; + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!sender.hasPermission("authme." + label.toLowerCase())) { + sender.sendMessage(m._("no_perm")); + return true; + } + + final Player player = (Player) sender; + final String name = player.getName().toLowerCase(); + String ipA = player.getAddress().getAddress().getHostAddress(); + + if (Settings.bungee && player instanceof ProxiedPlayer) { + ProxiedPlayer pPlayer = (ProxiedPlayer) player; + ipA = pPlayer.getAddress().getAddress().getHostAddress(); + } else if (Settings.bungee && player instanceof ConnectedPlayer) { + ConnectedPlayer cPlayer = (ConnectedPlayer) player; + ipA = cPlayer.getAddress().getAddress().getHostAddress(); + } + + final String ip = ipA; + + if (PlayerCache.getInstance().isAuthenticated(name)) { + player.sendMessage(m._("logged_in")); + return true; + } + + if (!Settings.isRegistrationEnabled) { + player.sendMessage(m._("reg_disabled")); + return true; + } + + if (database.isAuthAvailable(player.getName().toLowerCase())) { + player.sendMessage(m._("user_regged")); + if (pllog.getStringList("players").contains(player.getName())) { + pllog.getStringList("players").remove(player.getName()); + } + return true; + } + // + // Check if player exeded the max number of registration + // + + if(Settings.getmaxRegPerIp > 0 ){ + + if(!sender.hasPermission("authme.allow2accounts") && database.getAllAuthsByIp(ipA).size() >= Settings.getmaxRegPerIp) { + player.sendMessage(m._("max_reg")); + return true; + } + } + + if(Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) { + if(!args[0].contains("@")) { + player.sendMessage(m._("usage_reg")); + return true; + } + if(Settings.doubleEmailCheck) { + if(args.length < 2) { + player.sendMessage(m._("usage_reg")); + return true; + } + if(args[0] != args[1]) { + player.sendMessage(m._("usage_reg")); + return true; + } + } + final String email = args[0]; + if(Settings.getmaxRegPerEmail > 0) { + if (!sender.hasPermission("authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) { + player.sendMessage(m._("max_reg")); + return true; + } + } + RandomString rand = new RandomString(Settings.getRecoveryPassLength); + final String thePass = rand.nextString(); + + if (!thePass.isEmpty()) { + Bukkit.getScheduler().runTask(plugin, new Runnable() { + + @Override + public void run() { + if (PasswordSecurity.userSalt.containsKey(name)) { + try { + final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, name); + final PlayerAuth fAuth = new PlayerAuth(name, hashnew, PasswordSecurity.userSalt.get(name), ip, new Date().getTime(), (int) player.getLocation().getX() , (int) player.getLocation().getY(), (int) player.getLocation().getZ(), email); + database.saveAuth(fAuth); + database.updateEmail(fAuth); + database.updateSession(fAuth); + plugin.mail.main(fAuth, thePass); + } catch (NoSuchAlgorithmException e) { + ConsoleLogger.showError(e.getMessage()); + } + } else { + try { + final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, name); + final PlayerAuth fAuth = new PlayerAuth(name, hashnew, ip, new Date().getTime(), (int) player.getLocation().getX() , (int) player.getLocation().getY(), (int) player.getLocation().getZ(), email); + database.saveAuth(fAuth); + database.updateEmail(fAuth); + database.updateSession(fAuth); + plugin.mail.main(fAuth, thePass); + } catch (NoSuchAlgorithmException e) { + ConsoleLogger.showError(e.getMessage()); + } + } + } + + }); + + + if(!Settings.getRegisteredGroup.isEmpty()){ + Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED); + } + player.sendMessage(m._("vb_nonActiv")); + String msg = m._("login_msg"); + int time = Settings.getRegistrationTimeout * 20; + int msgInterval = Settings.getWarnMessageInterval; + if (time != 0) { + Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getTimeoutTaskId()); + BukkitTask id = Bukkit.getScheduler().runTaskLater(plugin, new TimeoutTask(plugin, name), time); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id.getTaskId()); + } + + Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId()); + BukkitTask nwMsg = Bukkit.getScheduler().runTask(plugin, new MessageTask(plugin, name, msg, msgInterval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(nwMsg.getTaskId()); + + LimboCache.getInstance().deleteLimboPlayer(name); + this.isFirstTimeJoin = true; + player.saveData(); + if (!Settings.noConsoleSpam) + ConsoleLogger.info(player.getName() + " registered "+player.getAddress().getAddress().getHostAddress()); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " has registered!")); + } + return true; + } + } + + if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2) ) { + player.sendMessage(m._("usage_reg")); + return true; + } + //System.out.println("pass legth "+args[0].length()); + //System.out.println("pass length permit"+Settings.passwordMaxLength); + if(args[0].length() < Settings.getPasswordMinLen || args[0].length() > Settings.passwordMaxLength) { + player.sendMessage(m._("pass_len")); + return true; + } + + + + try { + String hash; + if(Settings.getEnablePasswordVerifier) { + if (args[0].equals(args[1])) { + hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[0], name); + } else { + player.sendMessage(m._("password_error")); + return true; + } + } else + hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[0], name); + + if (Settings.getMySQLColumnSalt.isEmpty()) + { + auth = new PlayerAuth(name, hash, ip, new Date().getTime()); + } else { + auth = new PlayerAuth(name, hash, PasswordSecurity.userSalt.get(name), ip, new Date().getTime()); + } + if (!database.saveAuth(auth)) { + player.sendMessage(m._("error")); + return true; + } + PlayerCache.getInstance().addPlayer(auth); + + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (limbo != null) { + player.setGameMode(GameMode.getByValue(limbo.getGameMode())); + if (Settings.isTeleportToSpawnEnabled) { + World world = player.getWorld(); + Location loca = world.getSpawnLocation(); + if (plugin.mv != null) { + try { + loca = plugin.mv.getMVWorldManager().getMVWorld(world).getSpawnLocation(); + } catch (NullPointerException npe) { + + } catch (ClassCastException cce) { + + } catch (NoClassDefFoundError ncdfe) { + + } + } + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, loca); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + + sender.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); + sender.getServer().getScheduler().cancelTask(limbo.getMessageTaskId()); + LimboCache.getInstance().deleteLimboPlayer(name); + } + + + if(!Settings.getRegisteredGroup.isEmpty()){ + Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED); + } + player.sendMessage(m._("registered")); + if (!Settings.getmailAccount.isEmpty()) + player.sendMessage(m._("add_email")); + this.isFirstTimeJoin = true; + player.saveData(); + if (!Settings.noConsoleSpam) + ConsoleLogger.info(player.getName() + " registered "+player.getAddress().getAddress().getHostAddress()); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " has registered!")); + } + + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage(m._("error")); + } + return true; + } +} diff --git a/src/main/java/uk/org/whoami/authme/commands/UnregisterCommand.java b/src/main/java/uk/org/whoami/authme/commands/UnregisterCommand.java new file mode 100644 index 00000000..4f2845d1 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/commands/UnregisterCommand.java @@ -0,0 +1,142 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.commands; + +import java.security.NoSuchAlgorithmException; + +import me.muizers.Notifications.Notification; + +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.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.backup.FileCache; +import uk.org.whoami.authme.cache.limbo.LimboCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.PlayersLogs; +import uk.org.whoami.authme.settings.Settings; +import uk.org.whoami.authme.task.MessageTask; +import uk.org.whoami.authme.task.TimeoutTask; + +public class UnregisterCommand implements CommandExecutor { + + private Messages m = Messages.getInstance(); + private PlayersLogs pllog = PlayersLogs.getInstance(); + //private Settings settings = Settings.getInstance(); + public AuthMe plugin; + private DataSource database; + private FileCache playerCache = new FileCache(); + + public UnregisterCommand(AuthMe plugin, DataSource database) { + this.plugin = plugin; + this.database = database; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!sender.hasPermission("authme." + label.toLowerCase())) { + sender.sendMessage(m._("no_perm")); + return true; + } + + Player player = (Player) sender; + String name = player.getName().toLowerCase(); + + if (!PlayerCache.getInstance().isAuthenticated(name)) { + player.sendMessage(m._("not_logged_in")); + return true; + } + + if (args.length != 1) { + player.sendMessage(m._("usage_unreg")); + return true; + } + try { + if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), name)) { + if (!database.removeAuth(name)) { + player.sendMessage("error"); + return true; + } + if(Settings.isForcedRegistrationEnabled) { + player.getInventory().setArmorContents(new ItemStack[4]); + player.getInventory().setContents(new ItemStack[36]); + player.saveData(); + PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); + LimboCache.getInstance().addLimboPlayer(player); + + + int delay = Settings.getRegistrationTimeout * 20; + int interval = Settings.getWarnMessageInterval; + BukkitScheduler sched = sender.getServer().getScheduler(); + if (delay != 0) { + BukkitTask id = sched.runTaskLater(plugin, new TimeoutTask(plugin, name), delay); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id.getTaskId()); + } + sched.runTask(plugin, new MessageTask(plugin, name, m._("reg_msg"), interval)); + if(!Settings.unRegisteredGroup.isEmpty()){ + Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED); + } + player.sendMessage("unregistered"); + ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " unregistered himself!")); + } + return true; + } + if(!Settings.unRegisteredGroup.isEmpty()){ + Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED); + } + PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); + // check if Player cache File Exist and delete it, preventing duplication of items + if(playerCache.doesCacheExist(name)) { + playerCache.removeCache(name); + } + + if (PlayersLogs.players.contains(player.getName())) { + PlayersLogs.players.remove(player.getName()); + pllog.save(); + } + player.sendMessage("unregistered"); + ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); + if(plugin.notifications != null) { + plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " unregistered himself!")); + } + return true; + } else { + player.sendMessage(m._("wrong_pwd")); + } + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage("Internal Error please read the server log"); + } + return true; + } +} diff --git a/src/main/java/uk/org/whoami/authme/converter/FlatToSql.java b/src/main/java/uk/org/whoami/authme/converter/FlatToSql.java new file mode 100644 index 00000000..eed144b7 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/converter/FlatToSql.java @@ -0,0 +1,98 @@ +package uk.org.whoami.authme.converter; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.settings.Settings; + + +public class FlatToSql { + + public AuthMe instance; + + public FlatToSql (AuthMe instance) { + this.instance = instance; + } + + public FlatToSql getInstance() { + return this; + } + + 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 columnEmail; + + private static File source; + private static File output; + + public static void FlatToSqlConverter() throws IOException { + tableName = Settings.getMySQLTablename; + columnName = Settings.getMySQLColumnName; + columnPassword = Settings.getMySQLColumnPassword; + columnIp = Settings.getMySQLColumnIp; + columnLastLogin = Settings.getMySQLColumnLastLogin; + lastlocX = Settings.getMySQLlastlocX; + lastlocY = Settings.getMySQLlastlocY; + lastlocZ = Settings.getMySQLlastlocZ; + columnEmail = Settings.getMySQLColumnEmail; + + try { + source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); + source.createNewFile(); + output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql"); + BufferedReader br = null; + BufferedWriter sql = null; + br = new BufferedReader(new FileReader(source)); + sql = new BufferedWriter(new FileWriter(output)); + String createDB = " CREATE TABLE IF NOT EXISTS " + tableName + " (" + + "id INTEGER AUTO_INCREMENT," + + columnName + " VARCHAR(255) NOT NULL UNIQUE," + + columnPassword + " VARCHAR(255) NOT NULL," + + columnIp + " VARCHAR(40) NOT NULL," + + columnLastLogin + " BIGINT," + + lastlocX + " smallint(6) DEFAULT '0'," + + lastlocY + " smallint(6) DEFAULT '0'," + + lastlocZ + " smallint(6) DEFAULT '0'," + + columnEmail + " VARCHAR(255) NOT NULL," + + "CONSTRAINT table_const_prim PRIMARY KEY (id));"; + sql.write(createDB); + String line; + int i = 1; + String newline; + while ((line = br.readLine()) != null) { + sql.newLine(); + 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, " + "your@email.com" + ");"; + else if (args.length == 7) + newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", " + "your@email.com" + ");"; + else + newline = ""; + if (newline != "") + sql.write(newline); + i = i + 1; + } + sql.close(); + br.close(); + System.out.println("[AuthMe] The FlatFile has been converted to authme.sql file"); + + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + } + } +} diff --git a/src/main/java/uk/org/whoami/authme/converter/RakamakConverter.java b/src/main/java/uk/org/whoami/authme/converter/RakamakConverter.java new file mode 100644 index 00000000..a1c21c1d --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/converter/RakamakConverter.java @@ -0,0 +1,125 @@ +package uk.org.whoami.authme.converter; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map.Entry; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.security.PasswordSecurity.HashAlgorithm; +import uk.org.whoami.authme.settings.Settings; + + +public class RakamakConverter { + + public AuthMe instance; + + public RakamakConverter (AuthMe instance) { + this.instance = instance; + } + + public RakamakConverter getInstance() { + return this; + } + + private static HashAlgorithm hash; + private static Boolean useIP; + private static String fileName; + private static String ipFileName; + + private static File source; + private static File output; + private static File ipfiles; + private static boolean alreadyExist = false; + + public static void RakamakConvert() throws IOException { + hash = Settings.rakamakHash; + useIP = Settings.rakamakUseIp; + fileName = Settings.rakamakUsers; + ipFileName = Settings.rakamakUsersIp; + 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); + output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); + source.createNewFile(); + ipfiles.createNewFile(); + if (new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db").exists()) { + alreadyExist = true; + } + output.createNewFile(); + BufferedReader users = null; + BufferedWriter outputDB = null; + BufferedReader ipFile = null; + ipFile = new BufferedReader(new FileReader(ipfiles)); + String line; + String newLine = null; + if (useIP) { + String tempLine; + while ((tempLine = ipFile.readLine()) != null) { + if (tempLine.contains("=")) { + String[] args = tempLine.split("="); + playerIP.put(args[0], args[1]); + } + } + } + ipFile.close(); + users = new BufferedReader(new FileReader(source)); + while ((line = users.readLine()) != null) { + if (line.contains("=")) { + String[] arguments = line.split("="); + try { + playerPSW.put(arguments[0],PasswordSecurity.getHash(hash, arguments[1], arguments[0].toLowerCase())); + } catch (NoSuchAlgorithmException e) { + ConsoleLogger.showError(e.getMessage()); + } + } + } + + + users.close(); + outputDB = new BufferedWriter(new FileWriter(output)); + for (Entry m : playerPSW.entrySet()) { + if (useIP) { + String player = m.getKey(); + String psw = playerPSW.get(player); + String ip = playerIP.get(player); + newLine = player + ":" + psw + ":" + ip + ":1325376060:0:0:0"; + + } else { + String player = m.getKey(); + String psw = playerPSW.get(player); + String ip = "127.0.0.1"; + newLine = player + ":" + psw + ":" + ip + ":1325376060:0:0:0"; + } + if (alreadyExist) outputDB.newLine(); + outputDB.write(newLine); + System.out.println("Write line"); + outputDB.newLine(); + } + + + outputDB.close(); + + System.out.println("[AuthMe] Rakamak database has been converted to auths.db"); + + + + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + } + } +} diff --git a/src/main/java/uk/org/whoami/authme/converter/xAuthToFlat.java b/src/main/java/uk/org/whoami/authme/converter/xAuthToFlat.java new file mode 100644 index 00000000..68746e4b --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/converter/xAuthToFlat.java @@ -0,0 +1,129 @@ +package uk.org.whoami.authme.converter; + +import java.io.File; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.command.CommandSender; + +import com.cypherx.xauth.xAuth; +import com.cypherx.xauth.database.Table; +import com.cypherx.xauth.utils.xAuthLog; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.datasource.DataSource; + +public class xAuthToFlat { + + public AuthMe instance; + public DataSource database; + + public xAuthToFlat(AuthMe instance, DataSource database) { + this.instance = instance; + this.database = database; + } + + public boolean convert(CommandSender sender) { + if (instance.getServer().getPluginManager().getPlugin("xAuth") == null) { + sender.sendMessage("[AuthMe] xAuth plugin not found"); + return false; + } + if (!(new File("./plugins/xAuth/xAuth.h2.db").exists())) { + sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data..."); + } + List players = getXAuthPlayers(); + if (players == null || players.isEmpty()) { + sender.sendMessage("[AuthMe] Error while import xAuthPlayers"); + return false; + } + + sender.sendMessage("[AuthMe] Starting import..."); + for (int id : players) { + String pl = getIdPlayer(id); + String psw = getPassword(id); + if (psw != null && !psw.isEmpty() && pl != null) { + PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0); + database.saveAuth(auth); + } + } + sender.sendMessage("[AuthMe] Import done!"); + return true; + } + + public String getIdPlayer(int id) { + String realPass = ""; + Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); + PreparedStatement ps = null; + ResultSet rs = null; + + try { + String sql = String.format("SELECT `playername` FROM `%s` WHERE `id` = ?", + xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); + ps = conn.prepareStatement(sql); + ps.setInt(1, id); + rs = ps.executeQuery(); + if (!rs.next()) + return null; + + realPass = rs.getString("playername").toLowerCase(); + } catch (SQLException e) { + xAuthLog.severe("Failed to retrieve name for account: " + id, e); + return null; + } finally { + xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); + } + return realPass; + } + + public List getXAuthPlayers() { + List xP = new ArrayList(); + Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); + PreparedStatement ps = null; + ResultSet rs = null; + try { + String sql = String.format("SELECT * FROM `%s`", + xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); + ps = conn.prepareStatement(sql); + rs = ps.executeQuery(); + while(rs.next()) { + xP.add(rs.getInt("id")); + } + } catch (SQLException e) { + xAuthLog.severe("Cannot import xAuthPlayers", e); + return new ArrayList(); + } finally { + xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); + } + return xP; + } + + public String getPassword(int accountId) { + String realPass = ""; + Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); + PreparedStatement ps = null; + ResultSet rs = null; + + try { + String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?", + xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); + ps = conn.prepareStatement(sql); + ps.setInt(1, accountId); + rs = ps.executeQuery(); + if (!rs.next()) + return null; + + realPass = rs.getString("password"); + } catch (SQLException e) { + xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e); + return null; + } finally { + xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); + } + return realPass; + } +} diff --git a/src/main/java/uk/org/whoami/authme/datasource/CacheDataSource.java b/src/main/java/uk/org/whoami/authme/datasource/CacheDataSource.java new file mode 100644 index 00000000..1ea0a4e9 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/datasource/CacheDataSource.java @@ -0,0 +1,178 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.datasource; + +import java.util.HashMap; +import java.util.List; + +import org.bukkit.entity.Player; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; + +public class CacheDataSource implements DataSource { + + private DataSource source; + public AuthMe plugin; + private final HashMap cache = new HashMap(); + + public CacheDataSource(AuthMe plugin, DataSource source) { + this.plugin = plugin; + this.source = source; + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + return cache.containsKey(user) ? true : source.isAuthAvailable(user); + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + if(cache.containsKey(user)) { + return cache.get(user); + } else { + PlayerAuth auth = source.getAuth(user); + cache.put(user, auth); + return auth; + } + } + + @Override + public synchronized boolean saveAuth(PlayerAuth auth) { + if (source.saveAuth(auth)) { + cache.put(auth.getNickname(), auth); + return true; + } + return false; + } + + @Override + public synchronized boolean updatePassword(PlayerAuth auth) { + if (source.updatePassword(auth)) { + cache.get(auth.getNickname()).setHash(auth.getHash()); + return true; + } + return false; + } + + @Override + public boolean updateSession(PlayerAuth auth) { + if (source.updateSession(auth)) { + cache.get(auth.getNickname()).setIp(auth.getIp()); + cache.get(auth.getNickname()).setLastLogin(auth.getLastLogin()); + return true; + } + return false; + } + + @Override + public boolean updateQuitLoc(PlayerAuth auth) { + //System.out.println("[debug name chace non work]"+auth.getNickname()+"[debug loc]"+auth.getQuitLocX()); + if (source.updateQuitLoc(auth)) { + //System.out.println("[debug name chace]"+auth.getNickname()+"[debug loc]"+auth.getQuitLocX()); + cache.get(auth.getNickname()).setQuitLocX(auth.getQuitLocX()); + cache.get(auth.getNickname()).setQuitLocY(auth.getQuitLocY()); + cache.get(auth.getNickname()).setQuitLocZ(auth.getQuitLocZ()); + return true; + + } + return false; + } + + @Override + public int getIps(String ip) { + return source.getIps(ip); + } + + @Override + public int purgeDatabase(long until) { + int cleared = source.purgeDatabase(until); + + if (cleared > 0) { + for (PlayerAuth auth : cache.values()) { + if(auth.getLastLogin() < until) { + cache.remove(auth.getNickname()); + } + } + } + return cleared; + } + + @Override + public synchronized boolean removeAuth(String user) { + if (source.removeAuth(user)) { + cache.remove(user); + return true; + } + return false; + } + + @Override + public synchronized void close() { + source.close(); + } + + @Override + public void reload() { + cache.clear(); + for (Player player : plugin.getServer().getOnlinePlayers()) { + String user = player.getName().toLowerCase(); + if (PlayerCache.getInstance().isAuthenticated(user)) { + try { + PlayerAuth auth = source.getAuth(user); + cache.put(user, auth); + } catch (NullPointerException npe) { + } + + } + } + } + + @Override + public boolean updateEmail(PlayerAuth auth) { + if(source.updateEmail(auth)) { + cache.get(auth.getNickname()).setEmail(auth.getEmail()); + return true; + } + return false; + } + + @Override + public boolean updateSalt(PlayerAuth auth) { + if(source.updateSalt(auth)) { + cache.get(auth.getNickname()).setSalt(auth.getSalt()); + return true; + } + return false; + } + + @Override + public List getAllAuthsByName(PlayerAuth auth) { + return source.getAllAuthsByName(auth); + } + + @Override + public List getAllAuthsByIp(String ip) { + return source.getAllAuthsByIp(ip); + } + + @Override + public List getAllAuthsByEmail(String email) { + return source.getAllAuthsByEmail(email); + } +} diff --git a/src/main/java/uk/org/whoami/authme/datasource/DataSource.java b/src/main/java/uk/org/whoami/authme/datasource/DataSource.java new file mode 100644 index 00000000..21fc0568 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/datasource/DataSource.java @@ -0,0 +1,62 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.datasource; + +import java.util.List; + +import uk.org.whoami.authme.cache.auth.PlayerAuth; + +public interface DataSource { + + public enum DataSourceType { + + MYSQL, FILE, SQLITE + } + + boolean isAuthAvailable(String user); + + PlayerAuth getAuth(String user); + + boolean saveAuth(PlayerAuth auth); + + boolean updateSession(PlayerAuth auth); + + boolean updatePassword(PlayerAuth auth); + + int purgeDatabase(long until); + + boolean removeAuth(String user); + + boolean updateQuitLoc(PlayerAuth auth); + + int getIps(String ip); + + List getAllAuthsByName(PlayerAuth auth); + + List getAllAuthsByIp(String ip); + + List getAllAuthsByEmail(String email); + + boolean updateEmail(PlayerAuth auth); + + boolean updateSalt(PlayerAuth auth); + + void close(); + + void reload(); + +} diff --git a/src/main/java/uk/org/whoami/authme/datasource/FileDataSource.java b/src/main/java/uk/org/whoami/authme/datasource/FileDataSource.java new file mode 100644 index 00000000..436163f8 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/datasource/FileDataSource.java @@ -0,0 +1,474 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.datasource; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.settings.Settings; + +public class FileDataSource implements DataSource { + + + /* file layout: + * + * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:COORDS + * + * Old but compatible: + * PLAYERNAME:HASHSUM:IP + * PLAYERNAME:HASHSUM + * + */ + private File source; + + public FileDataSource() throws IOException { + source = new File(Settings.AUTH_FILE); + source.createNewFile(); + } + + @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].equals(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 { + if( auth.getQuitLocY() == 0 ) { + bw = new BufferedWriter(new FileWriter(source, true)); + bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + "\n"); + //System.out.println("[Debug save1] "+auth.getQuitLocY()); + } else { + bw = new BufferedWriter(new FileWriter(source, true)); + bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + "\n"); + //System.out.println("[Debug save2] "+auth.getQuitLocY()); + } + } 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())) { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3])); + 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) { + } + } + } + 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].equals(auth.getNickname())) { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin()); + 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) { + } + } + } + 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].equals(auth.getNickname())) { + //System.out.println("[Debug update] "+auth.getQuitLocX()); + newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); + 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) { + } + } + } + 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(":"); + //System.out.println(ip+" match? "+args[2]); + 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 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].equals(user)) { + switch (args.length) { + case 2: + return new PlayerAuth(args[0], args[1], "198.18.0.1", 0); + case 3: + return new PlayerAuth(args[0], args[1], args[2], 0); + case 4: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3])); + case 7: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Integer.parseInt(args[4]), Integer.parseInt(args[5]), Integer.parseInt(args[6])); + } + } + } + } 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) { + return false; + } + + @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(":"); + //System.out.println(ip+" match? "+args[2]); + 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) { + return new ArrayList(); + } +} diff --git a/src/main/java/uk/org/whoami/authme/datasource/MiniConnectionPoolManager.java b/src/main/java/uk/org/whoami/authme/datasource/MiniConnectionPoolManager.java new file mode 100644 index 00000000..7d3fb5ea --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/datasource/MiniConnectionPoolManager.java @@ -0,0 +1,319 @@ +// Copyright 2007-2011 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland +// www.source-code.biz, www.inventec.ch/chdh +// +// This module is multi-licensed and may be used under the terms +// of any of the following licenses: +// +// EPL, Eclipse Public License, http://www.eclipse.org/legal +// LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html +// MPL, Mozilla Public License 1.1, http://www.mozilla.org/MPL +// +// Please contact the author if you need another license. +// This module is provided "as is", without warranties of any kind. + +package uk.org.whoami.authme.datasource; + +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.LinkedList; +import javax.sql.ConnectionEvent; +import javax.sql.ConnectionEventListener; +import javax.sql.ConnectionPoolDataSource; +import javax.sql.PooledConnection; + +/** +* A lightweight standalone JDBC connection pool manager. +* +*

The public methods of this class are thread-safe. +* +*

Home page: www.source-code.biz/miniconnectionpoolmanager
+* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
+* Multi-licensed: EPL / LGPL / MPL. +*/ +public class MiniConnectionPoolManager { + +private ConnectionPoolDataSource dataSource; +private int maxConnections; +private long timeoutMs = 70 * 1000L; +private PrintWriter logWriter; +private Semaphore semaphore; +private LinkedList recycledConnections; +private int activeConnections; +private PoolConnectionEventListener poolConnectionEventListener; +private boolean isDisposed; +private boolean doPurgeConnection; + +/** +* Thrown in {@link #getConnection()} or {@link #getValidConnection()} when no free connection becomes +* available within timeout seconds. +*/ +public static class TimeoutException extends RuntimeException { + private static final long serialVersionUID = 1; + public TimeoutException () { + super("Timeout while waiting for a free database connection."); } + public TimeoutException (String msg) { + super(msg); }} + +/** +* Constructs a MiniConnectionPoolManager object with a timeout of 60 seconds. +* +* @param dataSource +* the data source for the connections. +* @param maxConnections +* the maximum number of connections. +*/ +public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections) { + this(dataSource, maxConnections, 70); } + +/** +* Constructs a MiniConnectionPoolManager object. +* +* @param dataSource +* the data source for the connections. +* @param maxConnections +* the maximum number of connections. +* @param timeout +* the maximum time in seconds to wait for a free connection. +*/ +public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections, int timeout) { + this.dataSource = dataSource; + this.maxConnections = maxConnections; + this.timeoutMs = timeout * 1000L; + try { + logWriter = dataSource.getLogWriter(); } + catch (SQLException e) {} + if (maxConnections < 1) { + throw new IllegalArgumentException("Invalid maxConnections value."); } + semaphore = new Semaphore(maxConnections,true); + recycledConnections = new LinkedList(); + poolConnectionEventListener = new PoolConnectionEventListener(); } + +/** +* Closes all unused pooled connections. +*/ +public synchronized void dispose() throws SQLException { + if (isDisposed) { + return; } + isDisposed = true; + SQLException e = null; + while (!recycledConnections.isEmpty()) { + PooledConnection pconn = recycledConnections.remove(); + try { + pconn.close(); } + catch (SQLException e2) { + if (e == null) { + e = e2; }}} + if (e != null) { + throw e; }} + +/** +* Retrieves a connection from the connection pool. +* +*

If maxConnections connections are already in use, the method +* waits until a connection becomes available or timeout seconds elapsed. +* When the application is finished using the connection, it must close it +* in order to return it to the pool. +* +* @return +* a new Connection object. +* @throws TimeoutException +* when no connection becomes available within timeout seconds. +*/ +public Connection getConnection() throws SQLException { + return getConnection2(timeoutMs); } + +private Connection getConnection2 (long timeoutMs) throws SQLException { + // This routine is unsynchronized, because semaphore.tryAcquire() may block. + synchronized (this) { + if (isDisposed) { + throw new IllegalStateException("Connection pool has been disposed."); }} + try { + if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) { + throw new TimeoutException(); }} + catch (InterruptedException e) { + throw new RuntimeException("Interrupted while waiting for a database connection.",e); } + boolean ok = false; + try { + Connection conn = getConnection3(); + ok = true; + return conn; } + finally { + if (!ok) { + semaphore.release(); }}} + +private synchronized Connection getConnection3() throws SQLException { + if (isDisposed) { + throw new IllegalStateException("Connection pool has been disposed."); } // test again with lock + PooledConnection pconn; + if (!recycledConnections.isEmpty()) { + pconn = recycledConnections.remove(); } + else { + pconn = dataSource.getPooledConnection(); + pconn.addConnectionEventListener(poolConnectionEventListener); } + Connection conn = pconn.getConnection(); + activeConnections++; + assertInnerState(); + return conn; } + +/** +* Retrieves a connection from the connection pool and ensures that it is valid +* by calling {@link Connection#isValid(int)}. +* +*

If a connection is not valid, the method tries to get another connection +* until one is valid (or a timeout occurs). +* +*

Pooled connections may become invalid when e.g. the database server is +* restarted. +* +*

This method is slower than {@link #getConnection()} because the JDBC +* driver has to send an extra command to the database server to test the connection. +* +* +*

This method requires Java 1.6 or newer. +* +* @throws TimeoutException +* when no valid connection becomes available within timeout seconds. +*/ +public Connection getValidConnection() { + long time = System.currentTimeMillis(); + long timeoutTime = time + timeoutMs; + int triesWithoutDelay = getInactiveConnections() + 1; + while (true) { + Connection conn = getValidConnection2(time, timeoutTime); + if (conn != null) { + return conn; } + triesWithoutDelay--; + if (triesWithoutDelay <= 0) { + triesWithoutDelay = 0; + try { + Thread.sleep(250); + } catch (InterruptedException e) { + throw new RuntimeException("Interrupted while waiting for a valid database connection.", e); + } + } + time = System.currentTimeMillis(); + if (time >= timeoutTime) { + throw new TimeoutException("Timeout while waiting for a valid database connection."); + } + } +} + +private Connection getValidConnection2 (long time, long timeoutTime) { + long rtime = Math.max(1, timeoutTime - time); + Connection conn; + try { + conn = getConnection2(rtime); } + catch (SQLException e) { + return null; } + rtime = timeoutTime - System.currentTimeMillis(); + int rtimeSecs = Math.max(1, (int)((rtime+999)/1000)); + try { + if (conn.isValid(rtimeSecs)) { + return conn; }} + catch (SQLException e) {} + // This Exception should never occur. If it nevertheless occurs, it's because of an error in the + // JDBC driver which we ignore and assume that the connection is not valid. + // When isValid() returns false, the JDBC driver should have already called connectionErrorOccurred() + // and the PooledConnection has been removed from the pool, i.e. the PooledConnection will + // not be added to recycledConnections when Connection.close() is called. + // But to be sure that this works even with a faulty JDBC driver, we call purgeConnection(). + purgeConnection(conn); + return null; } + +// Purges the PooledConnection associated with the passed Connection from the connection pool. +private synchronized void purgeConnection (Connection conn) { + try { + doPurgeConnection = true; + // (A potential problem of this program logic is that setting the doPurgeConnection flag + // has an effect only if the JDBC driver calls connectionClosed() synchronously within + // Connection.close().) + conn.close(); } + catch (SQLException e) {} + // ignore exception from close() + finally { + doPurgeConnection = false; }} + +private synchronized void recycleConnection (PooledConnection pconn) { + if (isDisposed || doPurgeConnection) { + disposeConnection(pconn); + return; } + if (activeConnections <= 0) { + throw new AssertionError(); } + activeConnections--; + semaphore.release(); + recycledConnections.add(pconn); + assertInnerState(); } + +private synchronized void disposeConnection (PooledConnection pconn) { + pconn.removeConnectionEventListener(poolConnectionEventListener); + if (!recycledConnections.remove(pconn)) { + // If the PooledConnection is not in the recycledConnections list, + // we assume that the connection was active. + if (activeConnections <= 0) { + throw new AssertionError(); } + activeConnections--; + semaphore.release(); } + closeConnectionAndIgnoreException(pconn); + assertInnerState(); } + +private void closeConnectionAndIgnoreException (PooledConnection pconn) { + try { + pconn.close(); } + catch (SQLException e) { + log("Error while closing database connection: "+e.toString()); }} + +private void log (String msg) { + String s = "MiniConnectionPoolManager: "+msg; + try { + if (logWriter == null) { + System.err.println(s); } + else { + logWriter.println(s); }} + catch (Exception e) {}} + +private void assertInnerState() { + if (activeConnections < 0) { + throw new AssertionError(); } + if (activeConnections + recycledConnections.size() > maxConnections) { + throw new AssertionError(); } + if (activeConnections + semaphore.availablePermits() > maxConnections) { + throw new AssertionError(); }} + +private class PoolConnectionEventListener implements ConnectionEventListener { + public void connectionClosed (ConnectionEvent event) { + PooledConnection pconn = (PooledConnection)event.getSource(); + recycleConnection(pconn); } + public void connectionErrorOccurred (ConnectionEvent event) { + PooledConnection pconn = (PooledConnection)event.getSource(); + disposeConnection(pconn); }} + +/** +* Returns the number of active (open) connections of this pool. +* +*

This is the number of Connection objects that have been +* issued by {@link #getConnection()}, for which Connection.close() +* has not yet been called. +* +* @return +* the number of active connections. +**/ +public synchronized int getActiveConnections() { + return activeConnections; } + +/** +* Returns the number of inactive (unused) connections in this pool. +* +*

This is the number of internally kept recycled connections, +* for which Connection.close() has been called and which +* have not yet been reused. +* +* @return +* the number of inactive connections. +**/ +public synchronized int getInactiveConnections() { + return recycledConnections.size(); } + +} // end class MiniConnectionPoolManager \ No newline at end of file diff --git a/src/main/java/uk/org/whoami/authme/datasource/MySQLDataSource.java b/src/main/java/uk/org/whoami/authme/datasource/MySQLDataSource.java new file mode 100644 index 00000000..6a64034d --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/datasource/MySQLDataSource.java @@ -0,0 +1,579 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.datasource; + +import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.datasource.MiniConnectionPoolManager.TimeoutException; +import uk.org.whoami.authme.settings.Settings; + +public class MySQLDataSource implements DataSource { + + private String host; + private String port; + private String username; + private String password; + private String database; + private String tableName; + private String columnName; + private String columnPassword; + private String columnIp; + private String columnLastLogin; + private String columnSalt; + private String columnGroup; + private String lastlocX; + private String lastlocY; + private String lastlocZ; + private String columnEmail; + private String columnID; + private List columnOthers; + private MiniConnectionPoolManager conPool; + + public MySQLDataSource() throws ClassNotFoundException, SQLException { + this.host = Settings.getMySQLHost; + this.port = Settings.getMySQLPort; + this.username = Settings.getMySQLUsername; + this.password = Settings.getMySQLPassword; + + this.database = Settings.getMySQLDatabase; + this.tableName = Settings.getMySQLTablename; + this.columnName = Settings.getMySQLColumnName; + this.columnPassword = Settings.getMySQLColumnPassword; + this.columnIp = Settings.getMySQLColumnIp; + this.columnLastLogin = Settings.getMySQLColumnLastLogin; + this.lastlocX = Settings.getMySQLlastlocX; + this.lastlocY = Settings.getMySQLlastlocY; + this.lastlocZ = Settings.getMySQLlastlocZ; + this.columnSalt = Settings.getMySQLColumnSalt; + this.columnGroup = Settings.getMySQLColumnGroup; + this.columnEmail = Settings.getMySQLColumnEmail; + this.columnOthers = Settings.getMySQLOtherUsernameColumn; + this.columnID = Settings.getMySQLColumnId; + + connect(); + setup(); + } + + private synchronized void connect() throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.jdbc.Driver"); + ConsoleLogger.info("MySQL driver loaded"); + MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource(); + dataSource.setDatabaseName(database); + dataSource.setServerName(host); + dataSource.setPort(Integer.parseInt(port)); + dataSource.setUser(username); + dataSource.setPassword(password); + + conPool = new MiniConnectionPoolManager(dataSource, 10); + ConsoleLogger.info("Connection pool ready"); + } + + private synchronized void setup() throws SQLException { + Connection con = null; + Statement st = null; + ResultSet rs = null; + try { + con = conPool.getValidConnection(); + st = con.createStatement(); + st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + + columnID + " INTEGER AUTO_INCREMENT," + + columnName + " VARCHAR(255) NOT NULL UNIQUE," + + columnPassword + " VARCHAR(255) NOT NULL," + + columnIp + " VARCHAR(40) NOT NULL," + + columnLastLogin + " BIGINT," + + lastlocX + " smallint(6) DEFAULT '0'," + + lastlocY + " smallint(6) DEFAULT '0'," + + lastlocZ + " smallint(6) DEFAULT '0'," + + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); + + rs = con.getMetaData().getColumns(null, null, tableName, columnIp); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + columnIp + " VARCHAR(40) NOT NULL;"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + columnLastLogin + " BIGINT;"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " smallint(6) NOT NULL DEFAULT '0' AFTER " + + columnLastLogin +" , ADD " + lastlocY + " smallint(6) NOT NULL DEFAULT '0' AFTER " + lastlocX + " , ADD " + lastlocZ + " smallint(6) NOT NULL DEFAULT '0' AFTER " + lastlocY + ";"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, columnEmail); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com' AFTER " + lastlocZ +";"); + } + } finally { + close(rs); + close(st); + close(con); + } + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnName + "=?;"); + + pst.setString(1, user); + rs = pst.executeQuery(); + return rs.next(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnName + "=?;"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) { + if (rs.getString(columnIp).isEmpty() ) { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "198.18.0.1", rs.getLong(columnLastLogin), rs.getInt(lastlocX), rs.getInt(lastlocY), rs.getInt(lastlocZ), rs.getString(columnEmail)); + } else { + if(!columnSalt.isEmpty()){ + if(!columnGroup.isEmpty()) + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword),rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getInt(lastlocX), rs.getInt(lastlocY), rs.getInt(lastlocZ), rs.getString(columnEmail)); + else return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword),rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getInt(lastlocX), rs.getInt(lastlocY), rs.getInt(lastlocZ), rs.getString(columnEmail)); + } else { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getInt(lastlocX), rs.getInt(lastlocY), rs.getInt(lastlocZ), rs.getString(columnEmail)); + } + } + } else { + return null; + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized boolean saveAuth(PlayerAuth auth) { + Connection con = null; + PreparedStatement pst = null; + try { + con = conPool.getValidConnection(); + if ((columnSalt.isEmpty() || columnSalt == null) && (auth.getSalt().isEmpty() || auth.getSalt() == null)) { + pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + ") VALUES (?,?,?,?);"); + pst.setString(1, auth.getNickname()); + pst.setString(2, auth.getHash()); + pst.setString(3, auth.getIp()); + pst.setLong(4, auth.getLastLogin()); + pst.executeUpdate(); + } else { + pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);"); + pst.setString(1, auth.getNickname()); + pst.setString(2, auth.getHash()); + pst.setString(3, auth.getIp()); + pst.setLong(4, auth.getLastLogin()); + pst.setString(5, auth.getSalt()); + pst.executeUpdate(); + } + if (!columnOthers.isEmpty()) { + for(String column : columnOthers) { + pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + "." + column + "=? WHERE " + columnName + "=?;"); + pst.setString(1, auth.getNickname()); + pst.setString(2, auth.getNickname()); + pst.executeUpdate(); + } + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(pst); + close(con); + } + return true; + } + + @Override + public synchronized boolean updatePassword(PlayerAuth auth) { + Connection con = null; + PreparedStatement pst = null; + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;"); + pst.setString(1, auth.getHash()); + pst.setString(2, auth.getNickname()); + pst.executeUpdate(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(pst); + close(con); + } + return true; + } + + @Override + public boolean updateSession(PlayerAuth auth) { + Connection con = null; + PreparedStatement pst = null; + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;"); + pst.setString(1, auth.getIp()); + pst.setLong(2, auth.getLastLogin()); + pst.setString(3, auth.getNickname()); + pst.executeUpdate(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(pst); + close(con); + } + return true; + } + + @Override + public int purgeDatabase(long until) { + Connection con = null; + PreparedStatement pst = null; + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + " getAllAuthsByName(PlayerAuth auth) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList(); + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnIp + "=?;"); + pst.setString(1, auth.getIp()); + rs = pst.executeQuery(); + while(rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public List getAllAuthsByIp(String ip) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList(); + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while(rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public List getAllAuthsByEmail(String email) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countEmail = new ArrayList(); + try { + con = conPool.getValidConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnEmail + "=?;"); + pst.setString(1, email); + rs = pst.executeQuery(); + while(rs.next()) { + countEmail.add(rs.getString(columnName)); + } + return countEmail; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + +} diff --git a/src/main/java/uk/org/whoami/authme/datasource/SqliteDataSource.java b/src/main/java/uk/org/whoami/authme/datasource/SqliteDataSource.java new file mode 100644 index 00000000..c7ced642 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/datasource/SqliteDataSource.java @@ -0,0 +1,514 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme.datasource; + + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + +import org.sqlite.*; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.datasource.MiniConnectionPoolManager.TimeoutException; +import uk.org.whoami.authme.settings.Settings; + +/** + * + * @author stefano + */ +@SuppressWarnings("unused") +public class SqliteDataSource implements DataSource { + + private String host; + private String port; + private String username; + private String password; + private String database; + private String tableName; + private String columnName; + private String columnPassword; + private String columnIp; + private String columnLastLogin; + private String columnSalt; + private String columnGroup; + private int nonActivatedGroup; + private String lastlocX; + private String lastlocY; + private String lastlocZ; + private String columnEmail; + private String columnID; + private Connection con; + + public SqliteDataSource() throws ClassNotFoundException, SQLException { + //Settings s = Settings.getInstance(); + this.host = Settings.getMySQLHost; + this.port = Settings.getMySQLPort; + this.username = Settings.getMySQLUsername; + this.password = Settings.getMySQLPassword; + + this.database = Settings.getMySQLDatabase; + this.tableName = Settings.getMySQLTablename; + this.columnName = Settings.getMySQLColumnName; + this.columnPassword = Settings.getMySQLColumnPassword; + this.columnIp = Settings.getMySQLColumnIp; + this.columnLastLogin = Settings.getMySQLColumnLastLogin; + this.columnSalt = Settings.getMySQLColumnSalt; + this.columnGroup = Settings.getMySQLColumnGroup; + this.lastlocX = Settings.getMySQLlastlocX; + this.lastlocY = Settings.getMySQLlastlocY; + this.lastlocZ = Settings.getMySQLlastlocZ; + this.nonActivatedGroup = Settings.getNonActivatedGroup; + this.columnEmail = Settings.getMySQLColumnEmail; + this.columnID = Settings.getMySQLColumnId; + + connect(); + setup(); + } + + private synchronized void connect() throws ClassNotFoundException, SQLException { + Class.forName("org.sqlite.JDBC"); + ConsoleLogger.info("SQLite driver loaded"); + + this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"+database+".db"); + + } + + private synchronized void setup() throws SQLException { + //Connection con = null; + Statement st = null; + ResultSet rs = null; + try { + st = con.createStatement(); + st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + + columnID + " INTEGER AUTO_INCREMENT," + + columnName + " VARCHAR(255) NOT NULL UNIQUE," + + columnPassword + " VARCHAR(255) NOT NULL," + + columnIp + " VARCHAR(40) NOT NULL," + + columnLastLogin + " BIGINT," + + lastlocX + " smallint(6) DEFAULT '0'," + + lastlocY + " smallint(6) DEFAULT '0'," + + lastlocZ + " smallint(6) DEFAULT '0'," + + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); + + rs = con.getMetaData().getColumns(null, null, tableName, columnIp); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + columnIp + " VARCHAR(40) NOT NULL;"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + + columnLastLogin + " BIGINT;"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " smallint(6) NOT NULL DEFAULT '0'; " + + "ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " smallint(6) NOT NULL DEFAULT '0'; " + + "ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " smallint(6) NOT NULL DEFAULT '0';"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, columnEmail); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';"); + } + } finally { + close(rs); + close(st); + //close(con); + } + ConsoleLogger.info("SQLite Setup finished"); + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + PreparedStatement pst = null; + ResultSet rs = null; + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?"); + pst.setString(1, user); + rs = pst.executeQuery(); + return rs.next(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + //close(con); + } + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + //Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnName + "=?;"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) { + if (rs.getString(columnIp).isEmpty() ) { + //System.out.println("[Authme Debug] ColumnIp is empty"); + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "198.18.0.1", rs.getLong(columnLastLogin), rs.getInt(lastlocX), rs.getInt(lastlocY), rs.getInt(lastlocZ), rs.getString(columnEmail)); + } else { + if(!columnSalt.isEmpty()){ + //System.out.println("[Authme Debug] column Salt is" + rs.getString(columnSalt)); + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword),rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getInt(lastlocX), rs.getInt(lastlocY), rs.getInt(lastlocZ), rs.getString(columnEmail)); + } else { + //System.out.println("[Authme Debug] column Salt is empty"); + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getInt(lastlocX), rs.getInt(lastlocY), rs.getInt(lastlocZ), rs.getString(columnEmail)); + + } + } + } else { + return null; + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } finally { + close(rs); + close(pst); + //close(con); + } + } + + @Override + public synchronized boolean saveAuth(PlayerAuth auth) { + //Connection con = null; + PreparedStatement pst = null; + try { + if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) { + pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + ") VALUES (?,?,?,?);"); + pst.setString(1, auth.getNickname()); + pst.setString(2, auth.getHash()); + pst.setString(3, auth.getIp()); + pst.setLong(4, auth.getLastLogin()); + pst.executeUpdate(); + } else { + pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);"); + pst.setString(1, auth.getNickname()); + pst.setString(2, auth.getHash()); + pst.setString(3, auth.getIp()); + pst.setLong(4, auth.getLastLogin()); + pst.setString(5, auth.getSalt()); + pst.executeUpdate(); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(pst); + //close(con); + } + return true; + } + + @Override + public synchronized boolean updatePassword(PlayerAuth auth) { + //Connection con = null; + PreparedStatement pst = null; + try { + pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;"); + pst.setString(1, auth.getHash()); + pst.setString(2, auth.getNickname()); + pst.executeUpdate(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(pst); + //close(con); + } + return true; + } + + @Override + public boolean updateSession(PlayerAuth auth) { + //Connection con = null; + PreparedStatement pst = null; + try { + pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;"); + pst.setString(1, auth.getIp()); + pst.setLong(2, auth.getLastLogin()); + pst.setString(3, auth.getNickname()); + pst.executeUpdate(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(pst); + //close(con); + } + return true; + } + + @Override + public int purgeDatabase(long until) { + //Connection con = null; + PreparedStatement pst = null; + try { + + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + " getAllAuthsByName(PlayerAuth auth) { + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList(); + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnIp + "=?;"); + pst.setString(1, auth.getIp()); + rs = pst.executeQuery(); + while(rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (NullPointerException npe) { + return new ArrayList(); + } finally { + close(rs); + close(pst); + //close(con); + } + } + + @Override + public List getAllAuthsByIp(String ip) { + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList(); + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while(rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (NullPointerException npe) { + return new ArrayList(); + } finally { + close(rs); + close(pst); + //close(con); + } + } + + @Override + public List getAllAuthsByEmail(String email) { + PreparedStatement pst = null; + ResultSet rs = null; + List countEmail = new ArrayList(); + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + + columnEmail + "=?;"); + pst.setString(1, email); + rs = pst.executeQuery(); + while(rs.next()) { + countEmail.add(rs.getString(columnName)); + } + return countEmail; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (TimeoutException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList(); + } catch (NullPointerException npe) { + return new ArrayList(); + } finally { + close(rs); + close(pst); + } + } + +} diff --git a/src/main/java/uk/org/whoami/authme/debug/CardboardBox.java b/src/main/java/uk/org/whoami/authme/debug/CardboardBox.java new file mode 100644 index 00000000..161d8d24 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/debug/CardboardBox.java @@ -0,0 +1,53 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + * + * http://forums.bukkit.org/threads/cardboard-serializable-itemstack-with-enchantments.75768/ + */ +package uk.org.whoami.authme.debug; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + +public class CardboardBox implements Serializable { + private static final long serialVersionUID = 729890133797629668L; + + private final int type, amount; + private final short damage; + + private final HashMap enchants; + + public CardboardBox(ItemStack item) { + this.type = item.getTypeId(); + this.amount = item.getAmount(); + this.damage = item.getDurability(); + + HashMap map = new HashMap(); + + Map enchantments = item.getEnchantments(); + + for(Enchantment enchantment : enchantments.keySet()) { + map.put(new CardboardEnchantment(enchantment), enchantments.get(enchantment)); + } + + this.enchants = map; + } + + public ItemStack unbox() { + ItemStack item = new ItemStack(type, amount, damage); + + HashMap map = new HashMap(); + + for(CardboardEnchantment cEnchantment : enchants.keySet()) { + map.put(cEnchantment.unbox(), enchants.get(cEnchantment)); + } + + item.addUnsafeEnchantments(map); + + return item; + } +} \ No newline at end of file diff --git a/src/main/java/uk/org/whoami/authme/debug/CardboardEnchantment.java b/src/main/java/uk/org/whoami/authme/debug/CardboardEnchantment.java new file mode 100644 index 00000000..c056ac2d --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/debug/CardboardEnchantment.java @@ -0,0 +1,25 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme.debug; + +import java.io.Serializable; +import org.bukkit.enchantments.Enchantment; + +/** + * A serializable Enchantment + */ +public class CardboardEnchantment implements Serializable { + private static final long serialVersionUID = 8973856768102665381L; + + private final int id; + + public CardboardEnchantment(Enchantment enchantment) { + this.id = enchantment.getId(); + } + + public Enchantment unbox() { + return Enchantment.getById(this.id); + } +} \ No newline at end of file diff --git a/src/main/java/uk/org/whoami/authme/events/AuthMeTeleportEvent.java b/src/main/java/uk/org/whoami/authme/events/AuthMeTeleportEvent.java new file mode 100644 index 00000000..be6ea5b0 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/AuthMeTeleportEvent.java @@ -0,0 +1,30 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public class AuthMeTeleportEvent extends CustomEvent { + + private Player player; + private Location to; + private Location from; + + public AuthMeTeleportEvent(Player player, Location to) { + this.player = player; + this.from = player.getLocation(); + this.to = to; + } + public Player getPlayer() { + return player; + } + public void setTo(Location to) { + this.to = to; + } + public Location getTo() { + return to; + } + public Location getFrom() { + return from; + } + +} diff --git a/src/main/java/uk/org/whoami/authme/events/CustomEvent.java b/src/main/java/uk/org/whoami/authme/events/CustomEvent.java new file mode 100644 index 00000000..b5f610e0 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/CustomEvent.java @@ -0,0 +1,36 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.Server; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class CustomEvent extends Event { + + + private boolean isCancelled; + private static final HandlerList handlers = new HandlerList(); + private static Server s; + + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public boolean isCancelled() { + return this.isCancelled; + } + + public void setCancelled(boolean cancelled) { + this.isCancelled = cancelled; + } + + + public static Server getServer() { + return s; + } + +} diff --git a/src/main/java/uk/org/whoami/authme/events/LoginEvent.java b/src/main/java/uk/org/whoami/authme/events/LoginEvent.java new file mode 100644 index 00000000..4c6cca34 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/LoginEvent.java @@ -0,0 +1,31 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.entity.Player; + +public class LoginEvent extends UncancellableEvent { + + + private Player player; + private boolean isLogin; + + public LoginEvent(Player player, boolean isLogin) { + this.player = player; + this.isLogin = isLogin; + } + + public Player getPlayer() { + return this.player; + } + + public void setPlayer(Player player) { + this.player = player; + } + + public void setLogin(boolean isLogin) { + this.isLogin = isLogin; + } + + public boolean isLogin() { + return isLogin; + } +} diff --git a/src/main/java/uk/org/whoami/authme/events/ProtectInventoryEvent.java b/src/main/java/uk/org/whoami/authme/events/ProtectInventoryEvent.java new file mode 100644 index 00000000..b6fd1551 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/ProtectInventoryEvent.java @@ -0,0 +1,58 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import uk.org.whoami.authme.api.API; + +public class ProtectInventoryEvent extends CustomEvent { + + private ItemStack[] storedinventory; + private ItemStack[] storedarmor; + private ItemStack[] emptyInventory = null; + private ItemStack[] emptyArmor = null; + private Player player; + + public ProtectInventoryEvent(Player player, ItemStack[] storedinventory, ItemStack[] storedarmor) { + this.player = player; + this.storedinventory = storedinventory; + this.storedarmor = storedarmor; + } + + public ProtectInventoryEvent(Player player, ItemStack[] storedinventory, ItemStack[] storedarmor, int newInventory, int newArmor) { + this.player = player; + this.storedinventory = storedinventory; + this.storedarmor = storedarmor; + this.setNewInventory(new ItemStack[newInventory]); + this.setNewArmor(new ItemStack[newArmor]); + API.setPlayerInventory(player, new ItemStack[newInventory], new ItemStack[newArmor]); + } + + public ItemStack[] getStoredInventory() { + return this.storedinventory; + } + + public ItemStack[] getStoredArmor() { + return this.storedarmor; + } + + public Player getPlayer() { + return this.player; + } + + public void setNewInventory(ItemStack[] emptyInventory) { + this.emptyInventory = emptyInventory; + } + + public ItemStack[] getEmptyInventory() { + return this.emptyInventory; + } + + public void setNewArmor(ItemStack[] emptyArmor) { + this.emptyArmor = emptyArmor; + } + + public ItemStack[] getEmptyArmor() { + return this.emptyArmor; + } +} diff --git a/src/main/java/uk/org/whoami/authme/events/ResetInventoryEvent.java b/src/main/java/uk/org/whoami/authme/events/ResetInventoryEvent.java new file mode 100644 index 00000000..e2eff209 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/ResetInventoryEvent.java @@ -0,0 +1,24 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import uk.org.whoami.authme.api.API; + +public class ResetInventoryEvent extends CustomEvent { + + private Player player; + + public ResetInventoryEvent(Player player) { + this.player = player; + API.setPlayerInventory(player, new ItemStack[36], new ItemStack[4]); + } + + public Player getPlayer() { + return this.player; + } + + public void setPlayer(Player player) { + this.player = player; + } +} diff --git a/src/main/java/uk/org/whoami/authme/events/RestoreInventoryEvent.java b/src/main/java/uk/org/whoami/authme/events/RestoreInventoryEvent.java new file mode 100644 index 00000000..b2232195 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/RestoreInventoryEvent.java @@ -0,0 +1,41 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class RestoreInventoryEvent extends CustomEvent { + + private ItemStack[] inventory; + private ItemStack[] armor; + private Player player; + + public RestoreInventoryEvent(Player player, ItemStack[] inventory, ItemStack[] armor) { + 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() { + return this.player; + } + + public void setPlayer(Player player) { + this.player = player; + } +} diff --git a/src/main/java/uk/org/whoami/authme/events/SessionEvent.java b/src/main/java/uk/org/whoami/authme/events/SessionEvent.java new file mode 100644 index 00000000..9b88cd3a --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/SessionEvent.java @@ -0,0 +1,27 @@ +package uk.org.whoami.authme.events; + +import uk.org.whoami.authme.cache.auth.PlayerAuth; + +public class SessionEvent extends CustomEvent { + + + private PlayerAuth player; + private boolean isLogin; + + public SessionEvent(PlayerAuth auth, boolean isLogin) { + this.player = auth; + this.isLogin = isLogin; + } + + public PlayerAuth getPlayerAuth() { + return this.player; + } + + public void setPlayer(PlayerAuth player) { + this.player = player; + } + + public boolean isLogin() { + return isLogin; + } +} diff --git a/src/main/java/uk/org/whoami/authme/events/SpawnTeleportEvent.java b/src/main/java/uk/org/whoami/authme/events/SpawnTeleportEvent.java new file mode 100644 index 00000000..7bbfc628 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/SpawnTeleportEvent.java @@ -0,0 +1,35 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public class SpawnTeleportEvent extends CustomEvent { + + private Player player; + private Location to; + private Location from; + private boolean isAuthenticated; + + public SpawnTeleportEvent(Player player, Location from, Location to, boolean isAuthenticated) { + this.player = player; + this.from = from; + this.to = to; + this.isAuthenticated = isAuthenticated; + } + public Player getPlayer() { + return player; + } + public void setTo(Location to) { + this.to = to; + } + public Location getTo() { + return to; + } + public Location getFrom() { + return from; + } + public boolean isAuthenticated() { + return isAuthenticated; + } + +} diff --git a/src/main/java/uk/org/whoami/authme/events/StoreInventoryEvent.java b/src/main/java/uk/org/whoami/authme/events/StoreInventoryEvent.java new file mode 100644 index 00000000..1d5a11a8 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/StoreInventoryEvent.java @@ -0,0 +1,50 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import uk.org.whoami.authme.cache.backup.FileCache; + +public class StoreInventoryEvent extends CustomEvent { + + + private ItemStack[] inventory; + private ItemStack[] armor; + private Player player; + + public StoreInventoryEvent(Player player) { + this.player = player; + this.inventory = player.getInventory().getContents(); + this.armor = player.getInventory().getArmorContents(); + } + + public StoreInventoryEvent(Player player, FileCache fileCache) { + this.player = player; + this.inventory = fileCache.readCache(player.getName().toLowerCase()).getInventory(); + this.armor = fileCache.readCache(player.getName().toLowerCase()).getArmour(); + } + + 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() { + return this.player; + } + + public void setPlayer(Player player) { + this.player = player; + } +} diff --git a/src/main/java/uk/org/whoami/authme/events/UncancellableEvent.java b/src/main/java/uk/org/whoami/authme/events/UncancellableEvent.java new file mode 100644 index 00000000..1c6f17e4 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/events/UncancellableEvent.java @@ -0,0 +1,26 @@ +package uk.org.whoami.authme.events; + +import org.bukkit.Server; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class UncancellableEvent extends Event { + + + private static final HandlerList handlers = new HandlerList(); + private static Server s; + + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public static Server getServer() { + return s; + } + +} diff --git a/src/main/java/uk/org/whoami/authme/filter/ConsoleFilter.java b/src/main/java/uk/org/whoami/authme/filter/ConsoleFilter.java new file mode 100644 index 00000000..656d1733 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/filter/ConsoleFilter.java @@ -0,0 +1,23 @@ +package uk.org.whoami.authme.filter; + +import java.util.logging.Filter; +import java.util.logging.LogRecord; + +public class ConsoleFilter implements Filter { + + public ConsoleFilter() {} + + @Override + public boolean isLoggable(LogRecord record) { + String logM = record.getMessage().toLowerCase(); + if (!logM.contains("issued server command:")) return true; + if (!logM.contains("/login") && !logM.contains("/l") && !logM.contains("/reg") && !logM.contains("/changepassword") && !logM.contains("/unregister") + && !logM.contains("/authme register") && !logM.contains("/authme changepassword")&& !logM.contains("/authme reg")&& !logM.contains("/authme cp")) return true; + String playername = record.getMessage().split(" ")[0]; + record.setMessage(playername + " issued an AuthMe command!"); + return true; + } + + + +} diff --git a/src/main/java/uk/org/whoami/authme/gui/Clickable.java b/src/main/java/uk/org/whoami/authme/gui/Clickable.java new file mode 100644 index 00000000..7787c9a5 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/gui/Clickable.java @@ -0,0 +1,7 @@ +package uk.org.whoami.authme.gui; + +import org.getspout.spoutapi.event.screen.ButtonClickEvent; + +public interface Clickable { + public void handleClick(ButtonClickEvent event); +} diff --git a/src/main/java/uk/org/whoami/authme/gui/CustomButton.java b/src/main/java/uk/org/whoami/authme/gui/CustomButton.java new file mode 100644 index 00000000..67ad0695 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/gui/CustomButton.java @@ -0,0 +1,27 @@ +package uk.org.whoami.authme.gui; + +import org.getspout.spoutapi.event.screen.ButtonClickEvent; +import org.getspout.spoutapi.gui.GenericButton; + +public class CustomButton extends GenericButton +{ + public Clickable handleRef = null; + + public CustomButton(Clickable c) { + handleRef = c; + } + + @Override + public void onButtonClick(ButtonClickEvent event) { + handleRef.handleClick(event); + } + + public CustomButton setMidPos(int x, int y) + { + this.setX(x) + .setY(y) + .shiftXPos(-(width / 2)) + .shiftYPos(-(height / 2)); + return this; + } +} diff --git a/src/main/java/uk/org/whoami/authme/gui/screens/LoginScreen.java b/src/main/java/uk/org/whoami/authme/gui/screens/LoginScreen.java new file mode 100644 index 00000000..91e9b13f --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/gui/screens/LoginScreen.java @@ -0,0 +1,153 @@ +package uk.org.whoami.authme.gui.screens; + +/** + * @Author Hoezef + */ +import java.util.List; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.getspout.spoutapi.event.screen.ButtonClickEvent; +import org.getspout.spoutapi.gui.Button; +import org.getspout.spoutapi.gui.Color; +import org.getspout.spoutapi.gui.GenericLabel; +import org.getspout.spoutapi.gui.GenericPopup; +import org.getspout.spoutapi.gui.GenericTextField; +import org.getspout.spoutapi.gui.RenderPriority; +import org.getspout.spoutapi.gui.Widget; +import org.getspout.spoutapi.gui.WidgetAnchor; +import org.getspout.spoutapi.player.SpoutPlayer; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.gui.Clickable; +import uk.org.whoami.authme.gui.CustomButton; +import uk.org.whoami.authme.settings.SpoutCfg; + +public class LoginScreen extends GenericPopup implements Clickable{ + + public AuthMe plugin = AuthMe.getInstance(); + private SpoutCfg spoutCfg = SpoutCfg.getInstance(); + + private CustomButton exitBtn; + private CustomButton loginBtn; + private GenericTextField passBox; + private GenericLabel titleLbl; + private GenericLabel textLbl; + private GenericLabel errorLbl; + + String exitTxt = spoutCfg.getString("LoginScreen.exit button"); //"Quit"; + String loginTxt = spoutCfg.getString("LoginScreen.login button"); //"Login"; + String exitMsg = spoutCfg.getString("LoginScreen.exit message"); //"Good Bye"; + String title = spoutCfg.getString("LoginScreen.title"); //"LOGIN" + @SuppressWarnings("unchecked") + List textlines = (List) spoutCfg.getList("LoginScreen.text"); + public SpoutPlayer splayer; + + public LoginScreen(SpoutPlayer player) { + this.splayer = player; + + createScreen(); + } + + private void createScreen() { + int objects = textlines.size() + 4; + int part = !(textlines.size() <= 5) ? 195 / objects : 20; + int h = 3*part/4, w = 8*part; + + titleLbl = new GenericLabel(); + titleLbl + .setText(title) + .setTextColor(new Color(1.0F, 0, 0, 1.0F)) + .setAlign(WidgetAnchor.TOP_CENTER) + .setHeight(h) + .setWidth(w) + .setX(maxWidth / 2 ) + .setY(25); + this.attachWidget(plugin, titleLbl); + + int ystart = 25 + h + part/2; + for (int x=0; x. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.listener; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.plugin.manager.CombatTagComunicator; +import uk.org.whoami.authme.settings.Settings; + +public class AuthMeBlockListener implements Listener { + + private DataSource data; + public AuthMe instance; + //private Settings settings = Settings.getInstance(); + + public AuthMeBlockListener(DataSource data, AuthMe instance) { + this.data = data; + this.instance = instance; + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if(instance.getCitizensCommunicator().isNPC(player, instance) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + event.setCancelled(true); + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if(instance.getCitizensCommunicator().isNPC(player, instance) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + event.setCancelled(true); + } + +} diff --git a/src/main/java/uk/org/whoami/authme/listener/AuthMeChestShopListener.java b/src/main/java/uk/org/whoami/authme/listener/AuthMeChestShopListener.java new file mode 100644 index 00000000..ea093df7 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/listener/AuthMeChestShopListener.java @@ -0,0 +1,54 @@ +package uk.org.whoami.authme.listener; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import com.Acrobot.ChestShop.Events.PreTransactionEvent; +import com.Acrobot.ChestShop.Events.PreTransactionEvent.TransactionOutcome; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.plugin.manager.CombatTagComunicator; +import uk.org.whoami.authme.settings.Settings; + +public class AuthMeChestShopListener implements Listener { + + public DataSource database; + public AuthMe plugin; + + public AuthMeChestShopListener(DataSource database, AuthMe plugin) { + this.database = database; + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPreTransaction(PreTransactionEvent event) { + if (event.isCancelled() || event.getClient() == null || event == null) { + return; + } + + Player player = event.getClient(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!database.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + event.setCancelled(TransactionOutcome.OTHER); + + } + +} diff --git a/src/main/java/uk/org/whoami/authme/listener/AuthMeEntityListener.java b/src/main/java/uk/org/whoami/authme/listener/AuthMeEntityListener.java new file mode 100644 index 00000000..dea3cb04 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/listener/AuthMeEntityListener.java @@ -0,0 +1,229 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.listener; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityInteractEvent; +import org.bukkit.event.entity.EntityRegainHealthEvent; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.plugin.manager.CombatTagComunicator; +import uk.org.whoami.authme.settings.Settings; + +public class AuthMeEntityListener implements Listener{ + + private DataSource data; + public AuthMe instance; + //private Settings settings = Settings.getInstance(); + + public AuthMeEntityListener(DataSource data, AuthMe instance) { + this.data = data; + this.instance = instance; + } + + @EventHandler + public void onEntityDamage(EntityDamageEvent event) { + if (event.isCancelled()) { + return; + } + Entity entity = event.getEntity(); + + if (!(entity instanceof Player)) { + return; + } + /* + System.out.println("[ Entity Damage ] "+event.getEntity().toString()); + @Future implementation till CombatTag dont release any apis + if(event.getEntity().toString().indexOf("PvPLogger") != -1 ) { + System.out.println("la stringa contiene PvPLogger 2"); + return; + } + */ + if(instance.getCitizensCommunicator().isNPC(entity, instance) || Utils.getInstance().isUnrestricted((Player)entity) || CombatTagComunicator.isNPC(entity)) { + return; + } + + Player player = (Player) entity; + String name = player.getName().toLowerCase(); + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + player.setFireTicks(0); + event.setCancelled(true); + } + + @EventHandler + public void onEntityTarget(EntityTargetEvent event) { + if (event.isCancelled()) { + return; + } + + Entity entity = event.getEntity(); + if (!(entity instanceof Player)) { + return; + } + + Player player = (Player) entity; + String name = player.getName().toLowerCase(); + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + event.setCancelled(true); + } + + @EventHandler + public void onFoodLevelChange(FoodLevelChangeEvent event) { + if (event.isCancelled()) { + return; + } + + Entity entity = event.getEntity(); + if (!(entity instanceof Player)) { + return; + } + + Player player = (Player) entity; + String name = player.getName().toLowerCase(); + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + event.setCancelled(true); + + } + + @EventHandler(priority = EventPriority.LOWEST) + public void EntityRegainHealthEvent(EntityRegainHealthEvent event) { + if (event.isCancelled()) { + return; + } + + Entity entity = event.getEntity(); + if (!(entity instanceof Player)) { + return; + } + + Player player = (Player) entity; + String name = player.getName().toLowerCase(); + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + event.setCancelled(true); + } + + @EventHandler (priority = EventPriority.MONITOR) + public void onEntityInteract(EntityInteractEvent event) { + if (event.isCancelled() || event == null) { + return; + } + + if (!(event.getEntity() instanceof Player)) { + return; + } + + Player player = (Player) event.getEntity(); + String name = player.getName().toLowerCase(); + + if (instance.getCitizensCommunicator().isNPC(player, instance) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + event.setCancelled(true); + + } + + @EventHandler (priority = EventPriority.LOWEST) + public void onLowestEntityInteract(EntityInteractEvent event) { + if (event.isCancelled() || event == null) { + return; + } + + if (!(event.getEntity() instanceof Player)) { + return; + } + + Player player = (Player) event.getEntity(); + String name = player.getName().toLowerCase(); + + if (instance.getCitizensCommunicator().isNPC(player, instance) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + event.setCancelled(true); + + } +} diff --git a/src/main/java/uk/org/whoami/authme/listener/AuthMePlayerListener.java b/src/main/java/uk/org/whoami/authme/listener/AuthMePlayerListener.java new file mode 100644 index 00000000..b0ebc5a8 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/listener/AuthMePlayerListener.java @@ -0,0 +1,1085 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.listener; + +import java.util.Date; +import java.util.HashMap; + +import net.md_5.bungee.api.connection.ConnectedPlayer; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerLoginEvent.Result; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; + +import uk.org.whoami.authme.api.API; +import uk.org.whoami.authme.cache.backup.DataFileCache; +import uk.org.whoami.authme.cache.backup.FileCache; +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.Utils; +import uk.org.whoami.authme.cache.auth.PlayerAuth; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.limbo.LimboPlayer; +import uk.org.whoami.authme.cache.limbo.LimboCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.events.AuthMeTeleportEvent; +import uk.org.whoami.authme.events.ProtectInventoryEvent; +import uk.org.whoami.authme.events.RestoreInventoryEvent; +import uk.org.whoami.authme.events.SessionEvent; +import uk.org.whoami.authme.events.SpawnTeleportEvent; +import uk.org.whoami.authme.plugin.manager.CombatTagComunicator; +import uk.org.whoami.authme.settings.Messages; +import uk.org.whoami.authme.settings.PlayersLogs; +import uk.org.whoami.authme.settings.Settings; +import uk.org.whoami.authme.task.MessageTask; +import uk.org.whoami.authme.task.TimeoutTask; + + +public class AuthMePlayerListener implements Listener { + + + public static int gm = 0; + public static HashMap gameMode = new HashMap(); + private Utils utils = Utils.getInstance(); + private Messages m = Messages.getInstance(); + public AuthMe plugin; + private DataSource data; + private FileCache playerBackup = new FileCache(); + + public AuthMePlayerListener(AuthMe plugin, DataSource data) { + this.plugin = plugin; + this.data = data; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player) ) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + String msg = event.getMessage(); + //WorldEdit GUI Shit + if (msg.equalsIgnoreCase("/worldedit cui")) { + return; + } + + String cmd = msg.split(" ")[0]; + if (cmd.equalsIgnoreCase("/login") || cmd.equalsIgnoreCase("/register") || cmd.equalsIgnoreCase("/passpartu") || cmd.equalsIgnoreCase("/l") || cmd.equalsIgnoreCase("/reg") || cmd.equalsIgnoreCase("/email") || cmd.equalsIgnoreCase("/captcha")) { + return; + } + + if (Settings.allowCommands.contains(cmd)) { + return; + } + + event.setMessage("/notloggedin"); + event.setCancelled(true); + } + + @EventHandler( priority = EventPriority.NORMAL) + public void onPlayerNormalChat(AsyncPlayerChatEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + if(plugin.CitizensVersion != 0) { + if (plugin.getCitizensCommunicator().isNPC(player, plugin)) { + return; + } + } + + if(plugin.CombatTag != 0) { + if (CombatTagComunicator.isNPC(player)) { + return; + } + } + + if (Utils.getInstance().isUnrestricted(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + String cmd = event.getMessage().split(" ")[0]; + + if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) { + //System.out.println("debug chat: chat isnt allowed"); + event.setCancelled(true); + return; + } + + if (!event.isAsynchronous()) { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + player.sendMessage(m._("reg_msg")); + } + } else { + + Bukkit.getScheduler().runTask(plugin, new Runnable() + { + @Override + public void run() { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (Settings.isForcedRegistrationEnabled) { + player.sendMessage(m._("reg_msg")); + } + } + }}); + } + } + + @EventHandler( priority = EventPriority.HIGH) + public void onPlayerHighChat(AsyncPlayerChatEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + if(plugin.CitizensVersion != 0) { + if (plugin.getCitizensCommunicator().isNPC(player, plugin)) { + return; + } + } + + if(plugin.CombatTag != 0) { + if (CombatTagComunicator.isNPC(player)) { + return; + } + } + + if (Utils.getInstance().isUnrestricted(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + String cmd = event.getMessage().split(" ")[0]; + + if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) { + //System.out.println("debug chat: chat isnt allowed"); + event.setCancelled(true); + return; + } + + if (!event.isAsynchronous()) { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + player.sendMessage(m._("reg_msg")); + } + } else { + + Bukkit.getScheduler().runTask(plugin, new Runnable() + { + @Override + public void run() { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (Settings.isForcedRegistrationEnabled) { + player.sendMessage(m._("reg_msg")); + } + } + }}); + } + } + + @EventHandler( priority = EventPriority.MONITOR) + public void onPlayerChat(AsyncPlayerChatEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + if(plugin.CitizensVersion != 0) { + if (plugin.getCitizensCommunicator().isNPC(player, plugin)) { + return; + } + } + + if(plugin.CombatTag != 0) { + if (CombatTagComunicator.isNPC(player)) { + return; + } + } + + if (Utils.getInstance().isUnrestricted(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + String cmd = event.getMessage().split(" ")[0]; + + if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) { + //System.out.println("debug chat: chat isnt allowed"); + event.setCancelled(true); + return; + } + + if (!event.isAsynchronous()) { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + player.sendMessage(m._("reg_msg")); + } + } else { + + Bukkit.getScheduler().runTask(plugin, new Runnable() + { + @Override + public void run() { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (Settings.isForcedRegistrationEnabled) { + player.sendMessage(m._("reg_msg")); + } + } + }}); + } + } + + @EventHandler( priority = EventPriority.HIGHEST) + public void onPlayerHighestChat(AsyncPlayerChatEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + if(plugin.CitizensVersion != 0) { + if (plugin.getCitizensCommunicator().isNPC(player, plugin)) { + return; + } + } + + if(plugin.CombatTag != 0) { + if (CombatTagComunicator.isNPC(player)) { + return; + } + } + + if (Utils.getInstance().isUnrestricted(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + String cmd = event.getMessage().split(" ")[0]; + + if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) { + //System.out.println("debug chat: chat isnt allowed"); + event.setCancelled(true); + return; + } + + if (!event.isAsynchronous()) { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + player.sendMessage(m._("reg_msg")); + } + } else { + + Bukkit.getScheduler().runTask(plugin, new Runnable() + { + @Override + public void run() { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (Settings.isForcedRegistrationEnabled) { + player.sendMessage(m._("reg_msg")); + } + } + }}); + } + } + + + @EventHandler( priority = EventPriority.LOWEST) + public void onPlayerEarlyChat(AsyncPlayerChatEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + if(plugin.CitizensVersion != 0) { + if (plugin.getCitizensCommunicator().isNPC(player, plugin)) { + return; + } + } + + if(plugin.CombatTag != 0) { + if (CombatTagComunicator.isNPC(player)) { + return; + } + } + + if (Utils.getInstance().isUnrestricted(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + String cmd = event.getMessage().split(" ")[0]; + + if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) { + //System.out.println("debug chat: chat isnt allowed"); + event.setCancelled(true); + return; + } + + if (!event.isAsynchronous()) { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + player.sendMessage(m._("reg_msg")); + } + } else { + + Bukkit.getScheduler().runTask(plugin, new Runnable() + { + @Override + public void run() { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (Settings.isForcedRegistrationEnabled) { + player.sendMessage(m._("reg_msg")); + } + } + }}); + } + } + + @EventHandler( priority = EventPriority.LOW) + public void onPlayerLowChat(AsyncPlayerChatEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + if(plugin.CitizensVersion != 0) { + if (plugin.getCitizensCommunicator().isNPC(player, plugin)) { + return; + } + } + + if(plugin.CombatTag != 0) { + if (CombatTagComunicator.isNPC(player)) { + return; + } + } + + if (Utils.getInstance().isUnrestricted(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + String cmd = event.getMessage().split(" ")[0]; + + if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) { + //System.out.println("debug chat: chat isnt allowed"); + event.setCancelled(true); + return; + } + + if (!event.isAsynchronous()) { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + player.sendMessage(m._("reg_msg")); + } + } else { + + Bukkit.getScheduler().runTask(plugin, new Runnable() + { + @Override + public void run() { + if (data.isAuthAvailable(name)) { + player.sendMessage(m._("login_msg")); + } else { + if (Settings.isForcedRegistrationEnabled) { + player.sendMessage(m._("reg_msg")); + } + } + }}); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerMove(PlayerMoveEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!Settings.isForcedRegistrationEnabled) { + return; + } + + if (!Settings.isMovementAllowed) { + event.setTo(event.getFrom()); + return; + } + + if (Settings.getMovementRadius == 0) { + return; + } + + + int radius = Settings.getMovementRadius; + Location spawn = player.getWorld().getSpawnLocation(); + if (plugin.mv != null) { + try { + spawn = plugin.mv.getMVWorldManager().getMVWorld(player.getWorld()).getSpawnLocation(); + } catch (NullPointerException npe) { + } catch (ClassCastException cce) { + } catch (NoClassDefFoundError ncdfe) { + } + } + + if ((spawn.distance(player.getLocation()) > radius) ) { + event.getPlayer().teleport(spawn); + } + + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerLogin(PlayerLoginEvent event) { + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (player.isOnline() && Settings.isForceSingleSessionEnabled) { + event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("same_nick")); + return; + } + + if(!event.isAsynchronous()) { + if(data.isAuthAvailable(name) && !LimboCache.getInstance().hasLimboPlayer(name)) { + if(!Settings.isSessionsEnabled) { + LimboCache.getInstance().addLimboPlayer(player , utils.removeAll(player)); + } else if(PlayerCache.getInstance().isAuthenticated(name)) { + if(LimboCache.getInstance().hasLimboPlayer(player.getName().toLowerCase())) { + LimboCache.getInstance().deleteLimboPlayer(name); + } + LimboCache.getInstance().addLimboPlayer(player , utils.removeAll(player)); + } + } + } else { + Bukkit.getScheduler().runTask(plugin, new Runnable() { + + @Override + public void run() { + if(data.isAuthAvailable(name) && !LimboCache.getInstance().hasLimboPlayer(name)) { + if(!Settings.isSessionsEnabled) { + LimboCache.getInstance().addLimboPlayer(player , utils.removeAll(player)); + } else if(PlayerCache.getInstance().isAuthenticated(name)) { + if(LimboCache.getInstance().hasLimboPlayer(player.getName().toLowerCase())) { + LimboCache.getInstance().deleteLimboPlayer(name); + } + LimboCache.getInstance().addLimboPlayer(player , utils.removeAll(player)); + } + } + + } + + }); + } + + //Check if forceSingleSession is set to true, so kick player that has joined with same nick of online player + if(player.isOnline() && Settings.isForceSingleSessionEnabled ) { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); + //System.out.println(" limbo ? "+limbo.getGroup()); + event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("same_nick")); + if(PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + utils.addNormal(player, limbo.getGroup()); + LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase()); + } + return; + + } + + int min = Settings.getMinNickLength; + int max = Settings.getMaxNickLength; + String regex = Settings.getNickRegex; + + if (name.length() > max || name.length() < min) { + + event.disallow(Result.KICK_OTHER, m._("name_len")); + return; + } + if (!player.getName().matches(regex) || name.equals("Player")) { + try { + event.disallow(Result.KICK_OTHER, m._("regex").replaceAll("REG_EX", regex)); + } catch (StringIndexOutOfBoundsException exc) { + event.disallow(Result.KICK_OTHER, "allowed char : " + regex); + } + return; + } + + if (Settings.isKickNonRegisteredEnabled) { + if (!data.isAuthAvailable(name)) { + event.disallow(Result.KICK_OTHER, m._("reg_only")); + return; + } + } + } + + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerJoin(PlayerJoinEvent event) { + if (event.getPlayer() == null) { + return; + } + + Player player = event.getPlayer(); + World world = player.getWorld(); + Location spawnLoc = world.getSpawnLocation(); + gm = player.getGameMode().getValue(); + final String name = player.getName().toLowerCase(); + gameMode.put(name, gm); + BukkitScheduler sched = plugin.getServer().getScheduler(); + final PlayerJoinEvent e = event; + + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + String ip = player.getAddress().getAddress().getHostAddress(); + if (Settings.bungee && player instanceof ProxiedPlayer) { + ProxiedPlayer pPlayer = (ProxiedPlayer) player; + ip = pPlayer.getAddress().getAddress().getHostAddress(); + } else if (Settings.bungee && player instanceof ConnectedPlayer) { + ConnectedPlayer cPlayer = (ConnectedPlayer) player; + ip = cPlayer.getAddress().getAddress().getHostAddress(); + } + if(Settings.isAllowRestrictedIp && !Settings.getRestrictedIp(name, ip)) { + int gM = gameMode.get(name); + player.setGameMode(GameMode.getByValue(gM)); + player.kickPlayer("You are not the Owner of this account, please try another name!"); + if (Settings.banUnsafeIp) + plugin.getServer().banIP(ip); + return; + } + + if (data.isAuthAvailable(name)) { + + + if (Settings.isSessionsEnabled) { + PlayerAuth auth = data.getAuth(name); + long timeout = Settings.getSessionTimeout * 60000; + long lastLogin = auth.getLastLogin(); + long cur = new Date().getTime(); + + + if((cur - lastLogin < timeout || timeout == 0) && !auth.getIp().equals("198.18.0.1") ) { + if (auth.getNickname().equalsIgnoreCase(name) && auth.getIp().equals(ip) ) { + Bukkit.getServer().getPluginManager().callEvent(new SessionEvent(auth, true)); + if(PlayerCache.getInstance().getAuth(name) != null) { + PlayerCache.getInstance().updatePlayer(auth); + } else { + PlayerCache.getInstance().addPlayer(auth); + } + player.sendMessage(m._("valid_session")); + return; + } else { + int gM = gameMode.get(name); + player.setGameMode(GameMode.getByValue(gM)); + player.kickPlayer(m._("unvalid_session")); + return; + } + } else { + + PlayerCache.getInstance().removePlayer(name); + LimboCache.getInstance().addLimboPlayer(player , utils.removeAll(player)); + } + } + // isent in session or session was ended correctly + LimboCache.getInstance().addLimboPlayer(player); + + try { + playerBackup.createCache(name, new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(),LimboCache.getInstance().getLimboPlayer(name).getArmour()), LimboCache.getInstance().getLimboPlayer(name).getGroup(),LimboCache.getInstance().getLimboPlayer(name).getOperator()); + } catch (NullPointerException npe) { + ConsoleLogger.showError("Problem while trying to create player cache for : " + name); + } + + } else { + if(!Settings.unRegisteredGroup.isEmpty()){ + utils.setGroup(player, Utils.groupType.UNREGISTERED); + } + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + + + if(Settings.protectInventoryBeforeLogInEnabled) { + try { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); + ProtectInventoryEvent ev = new ProtectInventoryEvent(player, limbo.getInventory(), limbo.getArmour(), 36, 4); + Bukkit.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + if (!Settings.noConsoleSpam) + ConsoleLogger.info("ProtectInventoryEvent has been cancelled for " + player.getName() + " ..."); + } + } catch (NullPointerException ex) { + } + } + + if(player.isOp()) + player.setOp(false); + + if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + + + String msg = data.isAuthAvailable(name) ? m._("login_msg") : m._("reg_msg"); + int time = Settings.getRegistrationTimeout * 20; + int msgInterval = Settings.getWarnMessageInterval; + if (time != 0) { + + BukkitTask id = sched.runTaskLater(plugin, new TimeoutTask(plugin, name), time); + if(!LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().addLimboPlayer(player); + + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id.getTaskId()); + } + + if(!LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().addLimboPlayer(player); + BukkitTask msgT = sched.runTask(plugin, new MessageTask(plugin, name, msg, msgInterval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT.getTaskId()); + + if (Settings.isForceSurvivalModeEnabled) + sched.runTask(plugin, new Runnable() { + public void run() { + e.getPlayer().setGameMode(GameMode.SURVIVAL); + } + }); + } + + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerQuit(PlayerQuitEvent event) { + if (event.getPlayer() == null) { + return; + } + + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead()) { + if(Settings.isSaveQuitLocationEnabled && data.isAuthAvailable(name)) { + PlayerAuth auth = new PlayerAuth(event.getPlayer().getName().toLowerCase(),(int)player.getLocation().getX(),(int)player.getLocation().getY(),(int)player.getLocation().getZ()); + try { + data.updateQuitLoc(auth); + } catch (NullPointerException npe) { } + + } + } + + if (LimboCache.getInstance().hasLimboPlayer(name)) { + //System.out.println("e' nel quit"); + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if(Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) { + RestoreInventoryEvent ev = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); + Bukkit.getServer().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + API.setPlayerInventory(player, limbo.getInventory(), limbo.getArmour()); + } + } + utils.addNormal(player, limbo.getGroup()); + player.setOp(limbo.getOperator()); + //System.out.println("debug quit group reset "+limbo.getGroup()); + this.plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); + LimboCache.getInstance().deleteLimboPlayer(name); + if(playerBackup.doesCacheExist(name)) { + playerBackup.removeCache(name); + } + } + try { + PlayerCache.getInstance().removePlayer(name); + } catch (NullPointerException npe) { + + } + try { + PlayersLogs.players.remove(player.getName()); + PlayersLogs.getInstance().save(); + } catch (NullPointerException ex) { + + } + if (gameMode.containsKey(name)) gameMode.remove(name); + player.saveData(); + } + + @EventHandler(priority=EventPriority.MONITOR) + public void onPlayerKick(PlayerKickEvent event) { + if (event.getPlayer() == null) { + return; + } + if (event.isCancelled()) { + return; + } + + Player player = event.getPlayer(); + + if ((plugin.getCitizensCommunicator().isNPC(player, plugin)) || (Utils.getInstance().isUnrestricted(player)) || (CombatTagComunicator.isNPC(player))) { + return; + } + + if ((Settings.isForceSingleSessionEnabled) && + (event.getReason().contains("You logged in from another location"))) { + event.setCancelled(true); + return; + } + + String name = player.getName().toLowerCase(); + if ((PlayerCache.getInstance().isAuthenticated(name)) && (!player.isDead()) && + (Settings.isSaveQuitLocationEnabled.booleanValue()) && data.isAuthAvailable(name)) { + PlayerAuth auth = new PlayerAuth(event.getPlayer().getName().toLowerCase(), (int)player.getLocation().getX(), (int)player.getLocation().getY(), (int)player.getLocation().getZ()); + this.data.updateQuitLoc(auth); + } + + if (LimboCache.getInstance().hasLimboPlayer(name)) + { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) { + try { + RestoreInventoryEvent ev = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); + Bukkit.getServer().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + API.setPlayerInventory(player, ev.getInventory(), ev.getArmor()); + } + } catch (NullPointerException npe){ + ConsoleLogger.showError("Problem while restore " + name + "inventory after a kick"); + } + } + try { + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if(!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } catch (NullPointerException npe) { + + } + this.utils.addNormal(player, limbo.getGroup()); + player.setOp(limbo.getOperator()); + + this.plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); + LimboCache.getInstance().deleteLimboPlayer(name); + if (this.playerBackup.doesCacheExist(name)) { + this.playerBackup.removeCache(name); + } + } + try { + PlayerCache.getInstance().removePlayer(name); + PlayersLogs.players.remove(player.getName()); + PlayersLogs.getInstance().save(); + if (gameMode.containsKey(name)) gameMode.remove(name); + player.saveData(); + } catch (NullPointerException ex) {} + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerPickupItem(PlayerPickupItemEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerInteract(PlayerInteractEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + + final int sign = event.getClickedBlock().getTypeId(); + if (sign == Material.SIGN_POST.getId() || sign == Material.WALL_SIGN.getId()) { + event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY); + } + + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerDropItem(PlayerDropItemEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + //System.out.println("player try to drop item"); + + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerBedEnter(PlayerBedEnterEvent event) { + if (event.isCancelled() || event.getPlayer() == null) { + return; + } + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onSignChange(SignChangeEvent event) { + if (event.isCancelled() || event.getPlayer() == null || event == null) { + return; + } + Player player = event.getPlayer(); + String name = player.getName().toLowerCase(); + + if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { + return; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + if (!data.isAuthAvailable(name)) { + if (!Settings.isForcedRegistrationEnabled) { + return; + } + } + event.setCancelled(true); + + } + + +} \ No newline at end of file diff --git a/src/main/java/uk/org/whoami/authme/listener/AuthMeSpoutListener.java b/src/main/java/uk/org/whoami/authme/listener/AuthMeSpoutListener.java new file mode 100644 index 00000000..1357ce6c --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/listener/AuthMeSpoutListener.java @@ -0,0 +1,35 @@ +package uk.org.whoami.authme.listener; + +/** + * @Author Hoezef + */ + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.getspout.spoutapi.event.spout.SpoutCraftEnableEvent; + + +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.gui.screens.LoginScreen; +import uk.org.whoami.authme.settings.SpoutCfg; + +public class AuthMeSpoutListener implements Listener { + private DataSource data; + + + public AuthMeSpoutListener(DataSource data) { + + this.data = data; + } + + @EventHandler + public void onSpoutCraftEnable(final SpoutCraftEnableEvent event) + { + if(SpoutCfg.getInstance().getBoolean("LoginScreen.enabled")) { + if (data.isAuthAvailable(event.getPlayer().getName().toLowerCase()) && !PlayerCache.getInstance().isAuthenticated(event.getPlayer().getName().toLowerCase()) ) { + event.getPlayer().getMainScreen().attachPopupScreen(new LoginScreen(event.getPlayer())); + } + } + } +} diff --git a/src/main/java/uk/org/whoami/authme/plugin/manager/CitizensCommunicator.java b/src/main/java/uk/org/whoami/authme/plugin/manager/CitizensCommunicator.java new file mode 100644 index 00000000..81fe7a60 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/plugin/manager/CitizensCommunicator.java @@ -0,0 +1,27 @@ +package uk.org.whoami.authme.plugin.manager; + +import net.citizensnpcs.api.CitizensAPI; +import net.citizensnpcs.api.CitizensManager; + +import org.bukkit.entity.Entity; + +import uk.org.whoami.authme.AuthMe; + +public class CitizensCommunicator { + + public AuthMe instance; + + public CitizensCommunicator(AuthMe instance) { + this.instance = instance; + } + + public boolean isNPC(final Entity player, AuthMe instance) { + if (instance.CitizensVersion == 1) { + return CitizensManager.isNPC(player); + } else if (instance.CitizensVersion == 2) { + return CitizensAPI.getNPCRegistry().isNPC(player); + } else { + return false; + } + } +} diff --git a/src/main/java/uk/org/whoami/authme/plugin/manager/CombatTagComunicator.java b/src/main/java/uk/org/whoami/authme/plugin/manager/CombatTagComunicator.java new file mode 100644 index 00000000..dafa9b3a --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/plugin/manager/CombatTagComunicator.java @@ -0,0 +1,72 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme.plugin.manager; + +import com.trc202.CombatTag.CombatTag; +import com.trc202.CombatTagApi.CombatTagApi; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +/** + * + * @author stefano + */ +public abstract class CombatTagComunicator { + static CombatTagApi combatApi; + + public CombatTagComunicator() { + if(Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null){ + combatApi = new CombatTagApi((CombatTag)Bukkit.getServer().getPluginManager().getPlugin("CombatTag")); + } + } + /** + * Checks to see if the player is in combat. The combat time can be configured by the server owner + * If the player has died while in combat the player is no longer considered in combat and as such will return false + * @param playerName + * @return true if player is in combat + */ + public abstract boolean isInCombat(String player); + + /** + * Checks to see if the player is in combat. The combat time can be configured by the server owner + * If the player has died while in combat the player is no longer considered in combat and as such will return false + * @param player + * @return true if player is in combat + */ + public abstract boolean isInCombat(Player player); + + /** + * Returns the time before the tag is over + * -1 if the tag has expired + * -2 if the player is not in combat + * @param player + * @return + */ + public abstract long getRemainingTagTime(String player); + + //(Implemented in 3.8) + /** + * Returns if the entity is an NPC + * @param player + * @return true if the player is an NPC + */ + public static boolean isNPC(Entity player) { + try { + if(Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null){ + combatApi = new CombatTagApi((CombatTag) Bukkit.getServer().getPluginManager().getPlugin("CombatTag")); + return combatApi.isNPC(player); + } + } catch (ClassCastException ex) { + return false; + } catch (NullPointerException npe) { + return false; + } catch (NoClassDefFoundError ncdfe) { + return false; + } + return false; + } +} diff --git a/src/main/java/uk/org/whoami/authme/security/PasswordSecurity.java b/src/main/java/uk/org/whoami/authme/security/PasswordSecurity.java new file mode 100644 index 00000000..efea449a --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/security/PasswordSecurity.java @@ -0,0 +1,318 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.security; + +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.HashMap; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.settings.Settings; + +public class PasswordSecurity { + + private static SecureRandom rnd = new SecureRandom(); + public static HashMap userSalt = new HashMap(); + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, + digest)); + } + + private static String getSHA1(String message) throws NoSuchAlgorithmException { + MessageDigest sha1 = MessageDigest.getInstance("SHA1"); + sha1.reset(); + sha1.update(message.getBytes()); + byte[] digest = sha1.digest(); + + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, + digest)); + } + + private static String getSHA256(String message) throws NoSuchAlgorithmException { + MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); + + sha256.reset(); + sha256.update(message.getBytes()); + byte[] digest = sha256.digest(); + + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, + digest)); + } + + public static String getWhirlpool(String message) { + Whirlpool w = new Whirlpool(); + byte[] digest = new byte[Whirlpool.DIGESTBYTES]; + w.NESSIEinit(); + w.NESSIEadd(message); + w.NESSIEfinalize(digest); + return Whirlpool.display(digest); + } + + private static String getSaltedHash(String message, String salt) throws NoSuchAlgorithmException { + return "$SHA$" + salt + "$" + getSHA256(getSHA256(message) + salt); + } + + // + // VBULLETIN 3.X 4.X METHOD + // + + private static String getSaltedMd5(String message, String salt) throws NoSuchAlgorithmException { + return "$MD5vb$" + salt + "$" + getMD5(getMD5(message) + salt); + } + + private static String getSaltedMyBB(String message, String salt) throws NoSuchAlgorithmException { + return getMD5(getMD5(salt)+ getMD5(message)); + } + + private static String getXAuth(String message, String salt) { + String hash = getWhirlpool(salt + message).toLowerCase(); + int saltPos = (message.length() >= hash.length() ? hash.length() - 1 : message.length()); + return hash.substring(0, saltPos) + salt + hash.substring(saltPos); + } + + private static String getSaltedIPB3(String message, String salt) throws NoSuchAlgorithmException { + + return getMD5(getMD5(salt) + getMD5(message)); + + } + + private static String createSalt(int length) throws NoSuchAlgorithmException { + byte[] msg = new byte[40]; + rnd.nextBytes(msg); + + MessageDigest sha1 = MessageDigest.getInstance("SHA1"); + sha1.reset(); + byte[] digest = sha1.digest(msg); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)).substring(0, length); + } + + public static String getHash(HashAlgorithm alg, String password, String name) throws NoSuchAlgorithmException { + switch (alg) { + case MD5: + return getMD5(password); + case SHA1: + return getSHA1(password); + case SHA256: + String salt = createSalt(16); + return getSaltedHash(password, salt); + case MD5VB: + String salt2 = createSalt(16); + return getSaltedMd5(password, salt2); + case WHIRLPOOL: + return getWhirlpool(password); + case XAUTH: + String xsalt = createSalt(12); + return getXAuth(password, xsalt); + case PHPBB: + return getPhpBB(password); + case PLAINTEXT: + return getPlainText(password); + case MYBB: + String salt3 = ""; + try { + salt3 = AuthMe.getInstance().database.getAuth(name).getSalt(); + } catch (NullPointerException npe) { + } + if (salt3.isEmpty() || salt3 == null) { + salt3 = createSalt(8); + userSalt.put(name, salt3); + } + return getSaltedMyBB(password, salt3); + case IPB3: + String salt4 = ""; + try { + salt4 = AuthMe.getInstance().database.getAuth(name).getSalt(); + } catch (NullPointerException npe) { + } + if (salt4.isEmpty() || salt4 == null) { + salt4 = createSalt(5); + userSalt.put(name, salt4); + } + return getSaltedIPB3(password, salt4); + case PHPFUSION: + String salt5 = ""; + try { + salt5 = AuthMe.getInstance().database.getAuth(name).getSalt(); + } catch (NullPointerException npe) { + } + if (salt5.isEmpty() || salt5 == null) { + salt5 = createSalt(12); + userSalt.put(name, getSHA1(salt5)); + } + return getPhPFusion(password, getSHA1(salt5)); + case SMF: + return getSHA1(name.toLowerCase() + password); + case XFSHA1: + return getSHA1(getSHA1(password) + Settings.getPredefinedSalt); + case XFSHA256: + return getSHA256(getSHA256(password) + Settings.getPredefinedSalt); + case SALTED2MD5: + String salt6 = ""; + try { + salt6 = AuthMe.getInstance().database.getAuth(name).getSalt(); + } catch (NullPointerException npe) { + } + if (salt6.isEmpty() || salt6 == null) { + salt6 = createSalt(Settings.saltLength); + userSalt.put(name, salt6); + } + return getMD5(getMD5(password) + salt6); + case JOOMLA: + String saltj = ""; + try { + saltj = AuthMe.getInstance().database.getAuth(name).getHash().split(":")[1]; + } catch (NullPointerException npe) { + } catch (ArrayIndexOutOfBoundsException aioobe) { + } + if (saltj.isEmpty() || saltj == null) { + saltj = createSalt(32); + userSalt.put(name, saltj); + } + return getMD5(password + saltj) + ":" + saltj; + default: + throw new NoSuchAlgorithmException("Unknown hash algorithm"); + } + } + + public static boolean comparePasswordWithHash(String password, String hash, String playername) throws NoSuchAlgorithmException { + //System.out.println("[Authme Debug] debug hashString"+hash); + if(hash.contains("$H$")) { + PhpBB checkHash = new PhpBB(); + return checkHash.phpbb_check_hash(password, hash); + } + if(!Settings.getMySQLColumnSalt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.IPB3) { + String saltipb = AuthMe.getInstance().database.getAuth(playername).getSalt(); + return hash.equals(getSaltedIPB3(password, saltipb)); + } + if(!Settings.getMySQLColumnSalt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.PHPFUSION) { + String saltfusion = AuthMe.getInstance().database.getAuth(playername).getSalt(); + return hash.equals(getPhPFusion(password, saltfusion)); + } + if(!Settings.getMySQLColumnSalt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.MYBB) { + String saltmybb = AuthMe.getInstance().database.getAuth(playername).getSalt(); + return hash.equals(getSaltedMyBB(password, saltmybb)); + } + if(Settings.getPasswordHash == HashAlgorithm.SMF) { + return hash.equals(getSHA1(playername.toLowerCase() + password)); + } + if(Settings.getPasswordHash == HashAlgorithm.XFSHA1) { + return hash.equals(getSHA1(getSHA1(password) + Settings.getPredefinedSalt)); + } + if(Settings.getPasswordHash == HashAlgorithm.XFSHA256) { + return hash.equals(getSHA256(getSHA256(password)+ Settings.getPredefinedSalt)); + } + if(!Settings.getMySQLColumnSalt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.SALTED2MD5) { + String salt2md5 = AuthMe.getInstance().database.getAuth(playername).getSalt(); + return hash.equals(getMD5(getMD5(password) + salt2md5)); + } + if(Settings.getPasswordHash == HashAlgorithm.JOOMLA) { + String saltj = hash.split(":")[1]; + return hash.equals(getMD5(password + saltj) + ":" + saltj); + } + // PlainText Password + if(hash.length() < 32 ) { + return hash.equals(password); + } + + if (hash.length() == 32) { + return hash.equals(getMD5(password)); + } + + if (hash.length() == 40) { + return hash.equals(getSHA1(password)); + } + + if (hash.length() == 140) { + int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length()); + String salt = hash.substring(saltPos, saltPos + 12); + return hash.equals(getXAuth(password, salt)); + } + + if (hash.contains("$")) { + //System.out.println("[Authme Debug] debug hashString"+hash); + String[] line = hash.split("\\$"); + if (line.length > 3 && line[1].equals("SHA")) { + return hash.equals(getSaltedHash(password, line[2])); + } else { + if(line[1].equals("MD5vb")) { + //System.out.println("[Authme Debug] password hashed from Authme"+getSaltedMd5(password, line[2])); + //System.out.println("[Authme Debug] salt from Authme"+line[2]); + //System.out.println("[Authme Debug] equals? Authme: "+hash); + //hash = "$MD5vb$" + salt + "$" + hash; + return hash.equals(getSaltedMd5(password, line[2])); + } + } + } + return false; + } + + private static String getPhpBB(String password) { + PhpBB hash = new PhpBB(); + String phpBBhash = hash.phpbb_hash(password); + return phpBBhash; + } + + + private static String getPlainText(String password) { + return password; + } + + public static String getPhPFusion(String msg, String keyString) { + String digest = null; + String algo = "HmacSHA256"; + try { + SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo); + Mac mac = Mac.getInstance(algo); + mac.init(key); + + byte[] bytes = mac.doFinal(msg.getBytes("ASCII")); + + StringBuffer hash = new StringBuffer(); + for (int i = 0; i < bytes.length; i++) { + String hex = Integer.toHexString(0xFF & bytes[i]); + if (hex.length() == 1) { + hash.append('0'); + } + hash.append(hex); + } + digest = hash.toString(); + } catch (UnsupportedEncodingException e) { + } catch (InvalidKeyException e) { + } catch (NoSuchAlgorithmException e) { + } + return digest; + } + + public enum HashAlgorithm { + + MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, PLAINTEXT, MYBB, IPB3, PHPFUSION, SMF, XFSHA1, XFSHA256, SALTED2MD5, JOOMLA + } +} diff --git a/src/main/java/uk/org/whoami/authme/security/PhpBB.java b/src/main/java/uk/org/whoami/authme/security/PhpBB.java new file mode 100644 index 00000000..82f975e6 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/security/PhpBB.java @@ -0,0 +1,191 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package uk.org.whoami.authme.security; + +import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; + +/** + * + * @author stefano + */ +public class PhpBB { + private static final int PHP_VERSION = 4; + private String itoa64 = +"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + + public String phpbb_hash(String password) { + String random_state = unique_id(); + String random = ""; + int count = 6; + + if (random.length() < count) { + random = ""; + + for (int i = 0; i < count; i += 16) { + random_state = md5(unique_id() + random_state); + random += pack(md5(random_state)); + } + random = random.substring(0, count); + } + + String hash = _hash_crypt_private( + password, _hash_gensalt_private(random, itoa64)); + if (hash.length() == 34) + return hash; + + return md5(password); + } + + private String unique_id() { + return unique_id("c"); + } + + // global $config; + // private boolean dss_seeded = false; + + private String unique_id(String extra) { + // TODO Generate something random here. + return "1234567890abcdef"; + } + + + private String _hash_gensalt_private(String input, String itoa64) { + return _hash_gensalt_private(input, itoa64, 6); + } + + @SuppressWarnings("unused") +private String _hash_gensalt_private( + String input, String itoa64, int iteration_count_log2) { + if (iteration_count_log2 < 4 || iteration_count_log2 > 31) { + iteration_count_log2 = 8; + } + + String output = "$H$"; + output += itoa64.charAt( + Math.min(iteration_count_log2 + + ((PHP_VERSION >= 5) ? 5 : 3), 30)); + output += _hash_encode64(input, 6); + + return output; + } + + /** + * Encode hash + */ + private String _hash_encode64(String input, int count) { + String output = ""; + int i = 0; + + do { + int value = input.charAt(i++); + output += itoa64.charAt(value & 0x3f); + + if (i < count) + value |= input.charAt(i) << 8; + + output += itoa64.charAt((value >> 6) & 0x3f); + + if (i++ >= count) + break; + + if (i < count) + value |= input.charAt(i) << 16; + + output += itoa64.charAt((value >> 12) & 0x3f); + + if (i++ >= count) + break; + + output += itoa64.charAt((value >> 18) & 0x3f); + } while (i < count); + + return output; + } + + String _hash_crypt_private(String password, String setting) { + String output = "*"; + + // Check for correct hash + if (!setting.substring(0, 3).equals("$H$")) + return output; + + int count_log2 = itoa64.indexOf(setting.charAt(3)); + if (count_log2 < 7 || count_log2 > 30) + return output; + + int count = 1 << count_log2; + String salt = setting.substring(4, 12); + if (salt.length() != 8) + return output; + + String m1 = md5(salt + password); + String hash = pack(m1); + do { + hash = pack(md5(hash + password)); + } while (--count > 0); + + output = setting.substring(0, 12); + output += _hash_encode64(hash, 16); + + return output; + } + + public boolean phpbb_check_hash( String password, String hash) { + if (hash.length() == 34) + return _hash_crypt_private(password, hash).equals(hash); + else + return md5(password).equals(hash); + } + + public static String md5(String data) { + try { + byte[] bytes = data.getBytes("ISO-8859-1"); + MessageDigest md5er = MessageDigest.getInstance("MD5"); + byte[] hash = md5er.digest(bytes); + return bytes2hex(hash); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + static int hexToInt(char ch) { + if(ch >= '0' && ch <= '9') + return ch - '0'; + + ch = Character.toUpperCase(ch); + if(ch >= 'A' && ch <= 'F') + return ch - 'A' + 0xA; + + throw new IllegalArgumentException("Not a hex character: " + ch); + } + + private static String bytes2hex(byte[] bytes) { + StringBuffer r = new StringBuffer(32); + for (int i = 0; i < bytes.length; i++) { + String x = Integer.toHexString(bytes[i] & 0xff); + if (x.length() < 2) + r.append("0"); + r.append(x); + } + return r.toString(); + } + + static String pack(String hex) { + StringBuffer buf = new StringBuffer(); + for(int i = 0; i < hex.length(); i += 2) { + char c1 = hex.charAt(i); + char c2 = hex.charAt(i+1); + char packed = (char) (hexToInt(c1) * 16 + hexToInt(c2)); + buf.append(packed); + } + return buf.toString(); + } +} + diff --git a/src/main/java/uk/org/whoami/authme/security/RandomString.java b/src/main/java/uk/org/whoami/authme/security/RandomString.java new file mode 100644 index 00000000..e599d8e6 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/security/RandomString.java @@ -0,0 +1,35 @@ +package uk.org.whoami.authme.security; + +import java.util.Random; + +public class RandomString +{ + + private static final char[] symbols = new char[36]; + + static { + for (int idx = 0; idx < 10; ++idx) + symbols[idx] = (char) ('0' + idx); + for (int idx = 10; idx < 36; ++idx) + symbols[idx] = (char) ('a' + idx - 10); + } + + private final Random random = new Random(); + + private final char[] buf; + + public RandomString(int length) + { + if (length < 1) + throw new IllegalArgumentException("length < 1: " + length); + buf = new char[length]; + } + + public String nextString() + { + for (int idx = 0; idx < buf.length; ++idx) + buf[idx] = symbols[random.nextInt(symbols.length)]; + return new String(buf); + } + +} \ No newline at end of file diff --git a/src/main/java/uk/org/whoami/authme/security/Whirlpool.java b/src/main/java/uk/org/whoami/authme/security/Whirlpool.java new file mode 100644 index 00000000..01201c5b --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/security/Whirlpool.java @@ -0,0 +1,440 @@ +package uk.org.whoami.authme.security; + +/** + * The Whirlpool hashing function. + * + *

+ * References + * + *

+ * The Whirlpool algorithm was developed by + * Paulo S. L. M. Barreto and + * Vincent Rijmen. + * + * See + * P.S.L.M. Barreto, V. Rijmen, + * ``The Whirlpool hashing function,'' + * First NESSIE workshop, 2000 (tweaked version, 2003), + * + * + * @author Paulo S.L.M. Barreto + * @author Vincent Rijmen. + * + * @version 3.0 (2003.03.12) + * + * ============================================================================= + * + * Differences from version 2.1: + * + * - Suboptimal diffusion matrix replaced by cir(1, 1, 4, 1, 8, 5, 2, 9). + * + * ============================================================================= + * + * Differences from version 2.0: + * + * - Generation of ISO/IEC 10118-3 test vectors. + * - Bug fix: nonzero carry was ignored when tallying the data length + * (this bug apparently only manifested itself when feeding data + * in pieces rather than in a single chunk at once). + * + * Differences from version 1.0: + * + * - Original S-box replaced by the tweaked, hardware-efficient version. + * + * ============================================================================= + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +import java.util.Arrays; + +class Whirlpool { + + /** + * The message digest size (in bits) + */ + public static final int DIGESTBITS = 512; + + /** + * The message digest size (in bytes) + */ + public static final int DIGESTBYTES = DIGESTBITS >>> 3; + + /** + * The number of rounds of the internal dedicated block cipher. + */ + protected static final int R = 10; + + /** + * The substitution box. + */ + private static final String sbox = + "\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152" + + "\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57" + + "\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85" + + "\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8" + + "\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333" + + "\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0" + + "\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE" + + "\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d" + + "\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF" + + "\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A" + + "\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c" + + "\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04" + + "\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB" + + "\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9" + + "\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1" + + "\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886"; + + private static long[][] C = new long[8][256]; + private static long[] rc = new long[R + 1]; + + static { + for (int x = 0; x < 256; x++) { + char c = sbox.charAt(x/2); + long v1 = ((x & 1) == 0) ? c >>> 8 : c & 0xff; + long v2 = v1 << 1; + if (v2 >= 0x100L) { + v2 ^= 0x11dL; + } + long v4 = v2 << 1; + if (v4 >= 0x100L) { + v4 ^= 0x11dL; + } + long v5 = v4 ^ v1; + long v8 = v4 << 1; + if (v8 >= 0x100L) { + v8 ^= 0x11dL; + } + long v9 = v8 ^ v1; + /* + * build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2, 9]: + */ + C[0][x] = + (v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32) | + (v8 << 24) | (v5 << 16) | (v2 << 8) | (v9 ); + /* + * build the remaining circulant tables C[t][x] = C[0][x] rotr t + */ + for (int t = 1; t < 8; t++) { + C[t][x] = (C[t - 1][x] >>> 8) | ((C[t - 1][x] << 56)); + } + } + /* + for (int t = 0; t < 8; t++) { + System.out.println("static const u64 C" + t + "[256] = {"); + for (int i = 0; i < 64; i++) { + System.out.print(" "); + for (int j = 0; j < 4; j++) { + String v = Long.toHexString(C[t][4*i + j]); + while (v.length() < 16) { + v = "0" + v; + } + System.out.print(" LL(0x" + v + "),"); + } + System.out.println(); + } + System.out.println("};"); + System.out.println(); + } + System.out.println(); + //*/ + + /* + * build the round constants: + */ + rc[0] = 0L; /* not used (assigment kept only to properly initialize all variables) */ + for (int r = 1; r <= R; r++) { + int i = 8*(r - 1); + rc[r] = + (C[0][i ] & 0xff00000000000000L) ^ + (C[1][i + 1] & 0x00ff000000000000L) ^ + (C[2][i + 2] & 0x0000ff0000000000L) ^ + (C[3][i + 3] & 0x000000ff00000000L) ^ + (C[4][i + 4] & 0x00000000ff000000L) ^ + (C[5][i + 5] & 0x0000000000ff0000L) ^ + (C[6][i + 6] & 0x000000000000ff00L) ^ + (C[7][i + 7] & 0x00000000000000ffL); + } + /* + System.out.println("static const u64 rc[R + 1] = {"); + for (int r = 0; r <= R; r++) { + String v = Long.toHexString(rc[r]); + while (v.length() < 16) { + v = "0" + v; + } + System.out.println(" LL(0x" + v + "),"); + } + System.out.println("};"); + System.out.println(); + //*/ + } + + /** + * Global number of hashed bits (256-bit counter). + */ + protected byte[] bitLength = new byte[32]; + + /** + * Buffer of data to hash. + */ + protected byte[] buffer = new byte[64]; + + /** + * Current number of bits on the buffer. + */ + protected int bufferBits = 0; + + /** + * Current (possibly incomplete) byte slot on the buffer. + */ + protected int bufferPos = 0; + + /** + * The hashing state. + */ + protected long[] hash = new long[8]; + protected long[] K = new long[8]; // the round key + protected long[] L = new long[8]; + protected long[] block = new long[8]; // mu(buffer) + protected long[] state = new long[8]; // the cipher state + + public Whirlpool() { + } + + /** + * The core Whirlpool transform. + */ + protected void processBuffer() { + /* + * map the buffer to a block: + */ + for (int i = 0, j = 0; i < 8; i++, j += 8) { + block[i] = + (((long)buffer[j ] ) << 56) ^ + (((long)buffer[j + 1] & 0xffL) << 48) ^ + (((long)buffer[j + 2] & 0xffL) << 40) ^ + (((long)buffer[j + 3] & 0xffL) << 32) ^ + (((long)buffer[j + 4] & 0xffL) << 24) ^ + (((long)buffer[j + 5] & 0xffL) << 16) ^ + (((long)buffer[j + 6] & 0xffL) << 8) ^ + (((long)buffer[j + 7] & 0xffL) ); + } + /* + * compute and apply K^0 to the cipher state: + */ + for (int i = 0; i < 8; i++) { + state[i] = block[i] ^ (K[i] = hash[i]); + } + /* + * iterate over all rounds: + */ + for (int r = 1; r <= R; r++) { + /* + * compute K^r from K^{r-1}: + */ + for (int i = 0; i < 8; i++) { + L[i] = 0L; + for (int t = 0, s = 56; t < 8; t++, s -= 8) { + L[i] ^= C[t][(int)(K[(i - t) & 7] >>> s) & 0xff]; + } + } + for (int i = 0; i < 8; i++) { + K[i] = L[i]; + } + K[0] ^= rc[r]; + /* + * apply the r-th round transformation: + */ + for (int i = 0; i < 8; i++) { + L[i] = K[i]; + for (int t = 0, s = 56; t < 8; t++, s -= 8) { + L[i] ^= C[t][(int)(state[(i - t) & 7] >>> s) & 0xff]; + } + } + for (int i = 0; i < 8; i++) { + state[i] = L[i]; + } + } + /* + * apply the Miyaguchi-Preneel compression function: + */ + for (int i = 0; i < 8; i++) { + hash[i] ^= state[i] ^ block[i]; + } + } + + /** + * Initialize the hashing state. + */ + public void NESSIEinit() { + Arrays.fill(bitLength, (byte)0); + bufferBits = bufferPos = 0; + buffer[0] = 0; // it's only necessary to cleanup buffer[bufferPos]. + Arrays.fill(hash, 0L); // initial value + } + + /** + * Delivers input data to the hashing algorithm. + * + * @param source plaintext data to hash. + * @param sourceBits how many bits of plaintext to process. + * + * This method maintains the invariant: bufferBits < 512 + */ + public void NESSIEadd(byte[] source, long sourceBits) { + /* + sourcePos + | + +-------+-------+------- + ||||||||||||||||||||| source + +-------+-------+------- + +-------+-------+-------+-------+-------+------- + |||||||||||||||||||||| buffer + +-------+-------+-------+-------+-------+------- + | + bufferPos + */ + int sourcePos = 0; // index of leftmost source byte containing data (1 to 8 bits). + int sourceGap = (8 - ((int)sourceBits & 7)) & 7; // space on source[sourcePos]. + int bufferRem = bufferBits & 7; // occupied bits on buffer[bufferPos]. + int b; + // tally the length of the added data: + long value = sourceBits; + for (int i = 31, carry = 0; i >= 0; i--) { + carry += (bitLength[i] & 0xff) + ((int)value & 0xff); + bitLength[i] = (byte)carry; + carry >>>= 8; + value >>>= 8; + } + // process data in chunks of 8 bits: + while (sourceBits > 8) { // at least source[sourcePos] and source[sourcePos+1] contain data. + // take a byte from the source: + b = ((source[sourcePos] << sourceGap) & 0xff) | + ((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap)); + if (b < 0 || b >= 256) { + throw new RuntimeException("LOGIC ERROR"); + } + // process this byte: + buffer[bufferPos++] |= b >>> bufferRem; + bufferBits += 8 - bufferRem; // bufferBits = 8*bufferPos; + if (bufferBits == 512) { + // process data block: + processBuffer(); + // reset buffer: + bufferBits = bufferPos = 0; + } + buffer[bufferPos] = (byte)((b << (8 - bufferRem)) & 0xff); + bufferBits += bufferRem; + // proceed to remaining data: + sourceBits -= 8; + sourcePos++; + } + // now 0 <= sourceBits <= 8; + // furthermore, all data (if any is left) is in source[sourcePos]. + if (sourceBits > 0) { + b = (source[sourcePos] << sourceGap) & 0xff; // bits are left-justified on b. + // process the remaining bits: + buffer[bufferPos] |= b >>> bufferRem; + } else { + b = 0; + } + if (bufferRem + sourceBits < 8) { + // all remaining data fits on buffer[bufferPos], and there still remains some space. + bufferBits += sourceBits; + } else { + // buffer[bufferPos] is full: + bufferPos++; + bufferBits += 8 - bufferRem; // bufferBits = 8*bufferPos; + sourceBits -= 8 - bufferRem; + // now 0 <= sourceBits < 8; furthermore, all data is in source[sourcePos]. + if (bufferBits == 512) { + // process data block: + processBuffer(); + // reset buffer: + bufferBits = bufferPos = 0; + } + buffer[bufferPos] = (byte)((b << (8 - bufferRem)) & 0xff); + bufferBits += (int)sourceBits; + } + } + + /** + * Get the hash value from the hashing state. + * + * This method uses the invariant: bufferBits < 512 + */ + public void NESSIEfinalize(byte[] digest) { + // append a '1'-bit: + buffer[bufferPos] |= 0x80 >>> (bufferBits & 7); + bufferPos++; // all remaining bits on the current byte are set to zero. + // pad with zero bits to complete 512N + 256 bits: + if (bufferPos > 32) { + while (bufferPos < 64) { + buffer[bufferPos++] = 0; + } + // process data block: + processBuffer(); + // reset buffer: + bufferPos = 0; + } + while (bufferPos < 32) { + buffer[bufferPos++] = 0; + } + // append bit length of hashed data: + System.arraycopy(bitLength, 0, buffer, 32, 32); + // process data block: + processBuffer(); + // return the completed message digest: + for (int i = 0, j = 0; i < 8; i++, j += 8) { + long h = hash[i]; + digest[j ] = (byte)(h >>> 56); + digest[j + 1] = (byte)(h >>> 48); + digest[j + 2] = (byte)(h >>> 40); + digest[j + 3] = (byte)(h >>> 32); + digest[j + 4] = (byte)(h >>> 24); + digest[j + 5] = (byte)(h >>> 16); + digest[j + 6] = (byte)(h >>> 8); + digest[j + 7] = (byte)(h ); + } + } + + /** + * Delivers string input data to the hashing algorithm. + * + * @param source plaintext data to hash (ASCII text string). + * + * This method maintains the invariant: bufferBits < 512 + */ + public void NESSIEadd(String source) { + if (source.length() > 0) { + byte[] data = new byte[source.length()]; + for (int i = 0; i < source.length(); i++) { + data[i] = (byte)source.charAt(i); + } + NESSIEadd(data, 8*data.length); + } + } + + protected static String display(byte[] array) { + char[] val = new char[2*array.length]; + String hex = "0123456789ABCDEF"; + for (int i = 0; i < array.length; i++) { + int b = array[i] & 0xff; + val[2*i] = hex.charAt(b >>> 4); + val[2*i + 1] = hex.charAt(b & 15); + } + return String.valueOf(val); + } +} diff --git a/src/main/java/uk/org/whoami/authme/settings/CustomConfiguration.java b/src/main/java/uk/org/whoami/authme/settings/CustomConfiguration.java new file mode 100644 index 00000000..66523665 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/settings/CustomConfiguration.java @@ -0,0 +1,88 @@ +package uk.org.whoami.authme.settings; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +public class CustomConfiguration extends YamlConfiguration{ + + private File configFile; + + public CustomConfiguration(File file) + { + this.configFile = file; + + load(); + } + + public void load() + { + try { + super.load(configFile); + } catch (FileNotFoundException e) { + Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not find " + configFile.getName() + ", creating new one..."); + reload(); + } catch (IOException e) { + Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not load " + configFile.getName(), e); + } catch (InvalidConfigurationException e) { + Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, configFile.getName() + " is no valid configuration file", e); + } + } + + public boolean reload() { + boolean out = true; + if (!configFile.exists()) + { + out = loadRessource(configFile); + } + if (out) load(); + return out; + } + + public void save() { + try { + super.save(configFile); + } catch (IOException ex) { + Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save config to " + configFile.getName(), ex); + } + } + + public boolean loadRessource(File file) { + boolean out = true; + if (!file.exists()) { + InputStream fis = getClass().getResourceAsStream("/" + file.getName()); + FileOutputStream fos = null; + try { + fos = new FileOutputStream(file); + byte[] buf = new byte[1024]; + int i = 0; + + while ((i = fis.read(buf)) != -1) { + fos.write(buf, 0, i); + } + } catch (Exception e) { + Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR"); + out = false; + } finally { + try { + if (fis != null) { + fis.close(); + } + if (fos != null) { + fos.close(); + } + } catch (Exception e) { + } + } + } + return out; + } +} diff --git a/src/main/java/uk/org/whoami/authme/settings/Messages.java b/src/main/java/uk/org/whoami/authme/settings/Messages.java new file mode 100644 index 00000000..7ae9cbb4 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/settings/Messages.java @@ -0,0 +1,100 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.settings; + +import java.io.File; + +public class Messages extends CustomConfiguration { + + private static Messages singleton = null; + + + public Messages() { + + super(new File(Settings.MESSAGE_FILE+"_"+Settings.messagesLanguage+".yml")); + loadDefaults(); + loadFile(); + singleton = this; + + } + + private void loadDefaults() { + this.set("logged_in", "&cAlready logged in!"); + this.set("not_logged_in", "&cNot logged in!"); + this.set("reg_disabled", "&cRegistration is disabled"); + this.set("user_regged", "&cUsername already registered"); + this.set("usage_reg", "&cUsage: /register password ConfirmPassword"); + this.set("usage_log", "&cUsage: /login password"); + this.set("user_unknown", "&cUsername not registered"); + this.set("pwd_changed", "&cPassword changed!"); + this.set("reg_only", "&fRegistered players only! Please visit http://example.com to register"); + this.set("valid_session", "&cSession login"); + this.set("login_msg", "&cPlease login with \"/login password\""); + this.set("reg_msg", "&cPlease register with \"/register password ConfirmPassword\""); + this.set("timeout", "&fLogin Timeout"); + this.set("wrong_pwd", "&cWrong password"); + this.set("logout", "&cSuccessful logout"); + this.set("usage_unreg", "&cUsage: /unregister password"); + this.set("registered", "&cSuccessfully registered!"); + this.set("unregistered", "&cSuccessfully unregistered!"); + this.set("login", "&cSuccessful login!"); + this.set("no_perm", "&cNo Permission"); + this.set("same_nick", "&fSame nick is already playing"); + this.set("reg_voluntarily", "&fYou can register your nickname with the server with the command \"/register password ConfirmPassword\""); + this.set("reload", "&fConfiguration and database has been reloaded"); + this.set("error", "&fAn error ocurred; Please contact the admin"); + this.set("unknown_user", "&fUser is not in database"); + this.set("unsafe_spawn","&fYour Quit location was unsafe, teleporting you to World Spawn"); + this.set("unvalid_session","&fSession Dataes doesnt corrispond Plaese wait the end of session"); + this.set("max_reg","&fYou have Exceded the max number of Registration for your Account"); + this.set("password_error","&fPassword doesnt match"); + this.set("pass_len","&fYour password dind''t reach the minimum length or exeded the max length"); + this.set("vb_nonActiv","&fYour Account isent Activated yet check your Emails!"); + this.set("usage_changepassword", "&fUsage: /changepassword oldPassword newPassword"); + this.set("name_len", "&cYour nickname is too Short or too long"); + this.set("regex", "&cYour nickname contains illegal characters. Allowed chars: REG_EX"); + this.set("add_email","&cPlease add your email with : /email add yourEmail confirmEmail"); + this.set("bad_database_email", "[AuthMe] This /email command only available with MySQL and SQLite, contact an Admin"); + this.set("recovery_email", "&cForgot your password? Please use /email recovery "); + this.set("usage_captcha", "&cUsage: /captcha "); + this.set("wrong_captcha", "&cWrong Captcha, please use : /captcha THE_CAPTCHA"); + this.set("valid_captcha", "&cYour captcha is valid !"); + } + + private void loadFile() { + this.load(); + this.save(); + + } + + public String _(String msg) { + String loc = (String) this.get(msg); + if (loc != null) { + return loc.replace("&", "\u00a7"); + } + return msg; + } + + + public static Messages getInstance() { + if (singleton == null) { + singleton = new Messages(); + } + return singleton; + } + +} diff --git a/src/main/java/uk/org/whoami/authme/settings/PlayersLogs.java b/src/main/java/uk/org/whoami/authme/settings/PlayersLogs.java new file mode 100644 index 00000000..c84e7f97 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/settings/PlayersLogs.java @@ -0,0 +1,30 @@ +package uk.org.whoami.authme.settings; + +import java.io.File; +import java.util.List; + +public class PlayersLogs extends CustomConfiguration { + + private static PlayersLogs pllog = null; + public static List players; + + @SuppressWarnings("unchecked") + public PlayersLogs() { + super(new File("./plugins/AuthMe/players.yml")); + pllog = this; + load(); + save(); + players = (List) this.getList("players"); + + } + + public static PlayersLogs getInstance() { + if (pllog == null) { + pllog = new PlayersLogs(); + } + return pllog; + } + + + +} diff --git a/src/main/java/uk/org/whoami/authme/settings/Settings.java b/src/main/java/uk/org/whoami/authme/settings/Settings.java new file mode 100644 index 00000000..e2b36151 --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/settings/Settings.java @@ -0,0 +1,666 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.settings; + +import java.io.File; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.bukkit.configuration.MemoryConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; + +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.datasource.DataSource; +import uk.org.whoami.authme.datasource.DataSource.DataSourceType; +import uk.org.whoami.authme.security.PasswordSecurity; +import uk.org.whoami.authme.security.PasswordSecurity.HashAlgorithm; + +public final class Settings extends YamlConfiguration { + + public static final String PLUGIN_FOLDER = "./plugins/AuthMe"; + public static final String CACHE_FOLDER = Settings.PLUGIN_FOLDER + "/cache"; + public static final String AUTH_FILE = Settings.PLUGIN_FOLDER + "/auths.db"; + public static final String MESSAGE_FILE = Settings.PLUGIN_FOLDER + "/messages"; + public static final String SETTINGS_FILE = Settings.PLUGIN_FOLDER + "/config.yml"; + public static List allowCommands = null; + public static List getJoinPermissions = null; + public static List getUnrestrictedName = null; + private static List getRestrictedIp; + public static List getMySQLOtherUsernameColumn = null; + public static List getForcedWorlds = null; + + public final Plugin plugin; + private final File file; + + public static DataSourceType getDataSource; + public static HashAlgorithm getPasswordHash; + public static HashAlgorithm rakamakHash; + + public static Boolean isPermissionCheckEnabled, isRegistrationEnabled, isForcedRegistrationEnabled, + isTeleportToSpawnEnabled, isSessionsEnabled, isChatAllowed, isAllowRestrictedIp, + isMovementAllowed, isKickNonRegisteredEnabled, isForceSingleSessionEnabled, + isForceSpawnLocOnJoinEnabled, isForceExactSpawnEnabled, isSaveQuitLocationEnabled, + isForceSurvivalModeEnabled, isResetInventoryIfCreative, isCachingEnabled, isKickOnWrongPasswordEnabled, + getEnablePasswordVerifier, protectInventoryBeforeLogInEnabled, isBackupActivated, isBackupOnStart, + isBackupOnStop, enablePasspartu, isStopEnabled, reloadSupport, rakamakUseIp, noConsoleSpam, removePassword, displayOtherAccounts, + useCaptcha, emailRegistration, multiverse, notifications, chestshop, bungee, banUnsafeIp, doubleEmailCheck; + + + public static String getNickRegex, getUnloggedinGroup, getMySQLHost, getMySQLPort, + getMySQLUsername, getMySQLPassword, getMySQLDatabase, getMySQLTablename, + getMySQLColumnName, getMySQLColumnPassword, getMySQLColumnIp, getMySQLColumnLastLogin, + getMySQLColumnSalt, getMySQLColumnGroup, getMySQLColumnEmail, unRegisteredGroup, backupWindowsPath, + getcUnrestrictedName, getRegisteredGroup, messagesLanguage, getMySQLlastlocX, getMySQLlastlocY, getMySQLlastlocZ, + rakamakUsers, rakamakUsersIp, getmailAccount, getmailPassword, getmailSMTP, getMySQLColumnId, getmailSenderName, + getPredefinedSalt, getMailSubject, getMailText; + + + public static int getWarnMessageInterval, getSessionTimeout, getRegistrationTimeout, getMaxNickLength, + getMinNickLength, getPasswordMinLen, getMovementRadius, getmaxRegPerIp, getNonActivatedGroup, + passwordMaxLength, getRecoveryPassLength, getMailPort, maxLoginTry, captchaLength, saltLength, getmaxRegPerEmail; + + protected static YamlConfiguration configFile; + + public Settings(Plugin plugin) { + //super(new File(Settings.PLUGIN_FOLDER + "/config.yml"), this.plugin); + this.file = new File(plugin.getDataFolder(),"config.yml"); + + this.plugin = plugin; + + + + //options().indent(4); + // Override to always indent 4 spaces + if(exists()) { + load(); + } + else { + loadDefaults(file.getName()); + load(); + } + + configFile = (YamlConfiguration) plugin.getConfig(); + + //saveDefaults(); + + } + + +@SuppressWarnings("unchecked") +public void loadConfigOptions() { + + plugin.getLogger().info("Loading Configuration File..."); + + mergeConfig(); + + messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage","en")); + isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false); + isForcedRegistrationEnabled = configFile.getBoolean("settings.registration.force", true); + isRegistrationEnabled = configFile.getBoolean("settings.registration.enabled", true); + isTeleportToSpawnEnabled = configFile.getBoolean("settings.restrictions.teleportUnAuthedToSpawn",false); + getWarnMessageInterval = configFile.getInt("settings.registration.messageInterval",5); + isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled",false); + getSessionTimeout = configFile.getInt("settings.sessions.timeout",10); + getRegistrationTimeout = configFile.getInt("settings.restrictions.timeout",30); + isChatAllowed = configFile.getBoolean("settings.restrictions.allowChat",false); + getMaxNickLength = configFile.getInt("settings.restrictions.maxNicknameLength",20); + getMinNickLength = configFile.getInt("settings.restrictions.minNicknameLength",3); + getPasswordMinLen = configFile.getInt("settings.security.minPasswordLength",4); + getNickRegex = configFile.getString("settings.restrictions.allowedNicknameCharacters","[a-zA-Z0-9_?]*"); + isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser",false); + getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser"); + isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement",false); + getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius",100); + getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin"); + isKickOnWrongPasswordEnabled = configFile.getBoolean("settings.restrictions.kickOnWrongPassword",false); + isKickNonRegisteredEnabled = configFile.getBoolean("settings.restrictions.kickNonRegistered",false); + isForceSingleSessionEnabled = configFile.getBoolean("settings.restrictions.ForceSingleSession",true); + isForceSpawnLocOnJoinEnabled = configFile.getBoolean("settings.restrictions.ForceSpawnLocOnJoinEnabled",false); + isSaveQuitLocationEnabled = configFile.getBoolean("settings.restrictions.SaveQuitLocation", false); + isForceSurvivalModeEnabled = configFile.getBoolean("settings.GameMode.ForceSurvivalMode", false); + isResetInventoryIfCreative = configFile.getBoolean("settings.GameMode.ResetInventoryIfCreative",false); + getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp",1); + getPasswordHash = getPasswordHash(); + getUnloggedinGroup = configFile.getString("settings.security.unLoggedinGroup","unLoggedInGroup"); + getDataSource = getDataSource(); + isCachingEnabled = configFile.getBoolean("DataSource.caching",true); + getMySQLHost = configFile.getString("DataSource.mySQLHost","127.0.0.1"); + getMySQLPort = configFile.getString("DataSource.mySQLPort","3306"); + getMySQLUsername = configFile.getString("DataSource.mySQLUsername","authme"); + getMySQLPassword = configFile.getString("DataSource.mySQLPassword","12345"); + getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase","authme"); + getMySQLTablename = configFile.getString("DataSource.mySQLTablename","authme"); + getMySQLColumnEmail = configFile.getString("DataSource.mySQLColumnEmail","email"); + getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName","username"); + getMySQLColumnPassword = configFile.getString("DataSource.mySQLColumnPassword","password"); + getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp","ip"); + getMySQLColumnLastLogin = configFile.getString("DataSource.mySQLColumnLastLogin","lastlogin"); + getMySQLColumnSalt = configFile.getString("ExternalBoardOptions.mySQLColumnSalt"); + getMySQLColumnGroup = configFile.getString("ExternalBoardOptions.mySQLColumnGroup",""); + getMySQLlastlocX = configFile.getString("DataSource.mySQLlastlocX","x"); + getMySQLlastlocY = configFile.getString("DataSource.mySQLlastlocY","y"); + getMySQLlastlocZ = configFile.getString("DataSource.mySQLlastlocZ","z"); + getNonActivatedGroup = configFile.getInt("ExternalBoardOptions.nonActivedUserGroup", -1); + unRegisteredGroup = configFile.getString("GroupOptions.UnregisteredPlayerGroup",""); + getUnrestrictedName = configFile.getStringList("settings.unrestrictions.UnrestrictedName"); + getRegisteredGroup = configFile.getString("GroupOptions.RegisteredPlayerGroup",""); + getEnablePasswordVerifier = configFile.getBoolean("settings.restrictions.enablePasswordVerifier" , true); + protectInventoryBeforeLogInEnabled = configFile.getBoolean("settings.restrictions.ProtectInventoryBeforeLogIn", true); + passwordMaxLength = configFile.getInt("settings.security.passwordMaxLength", 20); + isBackupActivated = configFile.getBoolean("BackupSystem.ActivateBackup",false); + isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart",false); + isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop",false); + backupWindowsPath = configFile.getString("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\"); + enablePasspartu = configFile.getBoolean("Passpartu.enablePasspartu",false); + isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer", true); + reloadSupport = configFile.getBoolean("Security.ReloadCommand.useReloadCommandSupport", true); + allowCommands = (List) configFile.getList("settings.restrictions.allowCommands"); + if (configFile.contains("allowCommands")) { + if (!allowCommands.contains("/login")) + allowCommands.add("/login"); + if (!allowCommands.contains("/register")) + allowCommands.add("/register"); + if (!allowCommands.contains("/l")) + allowCommands.add("/l"); + if (!allowCommands.contains("/reg")) + allowCommands.add("/reg"); + if (!allowCommands.contains("/passpartu")) + allowCommands.add("/passpartu"); + if (!allowCommands.contains("/email")) + allowCommands.add("/email"); + if(!allowCommands.contains("/captcha")) + allowCommands.add("/captcha"); + } + rakamakUsers = configFile.getString("Converter.Rakamak.fileName", "users.rak"); + rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName", "UsersIp.rak"); + rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false); + rakamakHash = getRakamakHash(); + noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", false); + removePassword = configFile.getBoolean("Security.console.removePassword", true); + getmailAccount = configFile.getString("Email.mailAccount", ""); + getmailPassword = configFile.getString("Email.mailPassword", ""); + 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()); + displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true); + getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id"); + getmailSenderName = configFile.getString("Email.mailSenderName", ""); + getPredefinedSalt = configFile.getString("Xenoforo.predefinedSalt", ""); + useCaptcha = configFile.getBoolean("Security.captcha.useCaptcha", false); + maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5); + captchaLength = configFile.getInt("Security.captcha.captchaLength", 5); + getMailSubject = configFile.getString("Email.mailSubject", "Your new AuthMe Password"); + getMailText = configFile.getString("Email.mailText", "Dear , \n\n This is your new AuthMe password for the server : \n\n \n\n \n\n Do not forget to change password after login! \n /changepassword newPassword"); + emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false); + saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8); + getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); + multiverse = configFile.getBoolean("Hooks.multiverse", true); + chestshop = configFile.getBoolean("Hooks.chestshop", true); + notifications = configFile.getBoolean("Hooks.notifications", true); + bungee = configFile.getBoolean("Hooks.bungeecord", false); + getForcedWorlds = (List) configFile.getList("settings.restrictions.ForceSpawnOnTheseWorlds"); + banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false); + doubleEmailCheck = configFile.getBoolean("settings.registration.doubleEmailCheck", false); + + saveDefaults(); + } + + +@SuppressWarnings("unchecked") +public static void reloadConfigOptions(YamlConfiguration newConfig) { + configFile = newConfig; + + //plugin.getLogger().info("RELoading Configuration File..."); + messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage","en")); + isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false); + isForcedRegistrationEnabled = configFile.getBoolean("settings.registration.force", true); + isRegistrationEnabled = configFile.getBoolean("settings.registration.enabled", true); + isTeleportToSpawnEnabled = configFile.getBoolean("settings.restrictions.teleportUnAuthedToSpawn",false); + getWarnMessageInterval = configFile.getInt("settings.registration.messageInterval",5); + isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled",false); + getSessionTimeout = configFile.getInt("settings.sessions.timeout",10); + getRegistrationTimeout = configFile.getInt("settings.restrictions.timeout",30); + isChatAllowed = configFile.getBoolean("settings.restrictions.allowChat",false); + getMaxNickLength = configFile.getInt("settings.restrictions.maxNicknameLength",20); + getMinNickLength = configFile.getInt("settings.restrictions.minNicknameLength",3); + getPasswordMinLen = configFile.getInt("settings.security.minPasswordLength",4); + getNickRegex = configFile.getString("settings.restrictions.allowedNicknameCharacters","[a-zA-Z0-9_?]*"); + isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser",false); + getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser"); + isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement",false); + getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius",100); + getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin"); + isKickOnWrongPasswordEnabled = configFile.getBoolean("settings.restrictions.kickOnWrongPassword",false); + isKickNonRegisteredEnabled = configFile.getBoolean("settings.restrictions.kickNonRegistered",false); + isForceSingleSessionEnabled = configFile.getBoolean("settings.restrictions.ForceSingleSession",true); + isForceSpawnLocOnJoinEnabled = configFile.getBoolean("settings.restrictions.ForceSpawnLocOnJoinEnabled",false); + isSaveQuitLocationEnabled = configFile.getBoolean("settings.restrictions.SaveQuitLocation",false); + isForceSurvivalModeEnabled = configFile.getBoolean("settings.GameMode.ForceSurvivalMode",false); + isResetInventoryIfCreative = configFile.getBoolean("settings.GameMode.ResetInventoryIfCreative",false); + getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp",1); + getPasswordHash = getPasswordHash(); + getUnloggedinGroup = configFile.getString("settings.security.unLoggedinGroup","unLoggedInGroup"); + getDataSource = getDataSource(); + isCachingEnabled = configFile.getBoolean("DataSource.caching",true); + getMySQLHost = configFile.getString("DataSource.mySQLHost","127.0.0.1"); + getMySQLPort = configFile.getString("DataSource.mySQLPort","3306"); + getMySQLUsername = configFile.getString("DataSource.mySQLUsername","authme"); + getMySQLPassword = configFile.getString("DataSource.mySQLPassword","12345"); + getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase","authme"); + getMySQLTablename = configFile.getString("DataSource.mySQLTablename","authme"); + getMySQLColumnEmail = configFile.getString("DataSource.mySQLColumnEmail","email"); + getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName","username"); + getMySQLColumnPassword = configFile.getString("DataSource.mySQLColumnPassword","password"); + getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp","ip"); + getMySQLColumnLastLogin = configFile.getString("DataSource.mySQLColumnLastLogin","lastlogin"); + getMySQLlastlocX = configFile.getString("DataSource.mySQLlastlocX","x"); + getMySQLlastlocY = configFile.getString("DataSource.mySQLlastlocY","y"); + getMySQLlastlocZ = configFile.getString("DataSource.mySQLlastlocZ","z"); + getMySQLColumnSalt = configFile.getString("ExternalBoardOptions.mySQLColumnSalt",""); + getMySQLColumnGroup = configFile.getString("ExternalBoardOptions.mySQLColumnGroup",""); + getNonActivatedGroup = configFile.getInt("ExternalBoardOptions.nonActivedUserGroup", -1); + unRegisteredGroup = configFile.getString("GroupOptions.UnregisteredPlayerGroup",""); + getUnrestrictedName = configFile.getStringList("settings.unrestrictions.UnrestrictedName"); + getRegisteredGroup = configFile.getString("GroupOptions.RegisteredPlayerGroup",""); + getEnablePasswordVerifier = configFile.getBoolean("settings.restrictions.enablePasswordVerifier" , true); + protectInventoryBeforeLogInEnabled = configFile.getBoolean("settings.restrictions.ProtectInventoryBeforeLogIn", true); + passwordMaxLength = configFile.getInt("settings.security.passwordMaxLength", 20); + isBackupActivated = configFile.getBoolean("BackupSystem.ActivateBackup",false); + isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart",false); + isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop",false); + backupWindowsPath = configFile.getString("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\"); + enablePasspartu = configFile.getBoolean("Passpartu.enablePasspartu",false); + isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer", true); + reloadSupport = configFile.getBoolean("Security.ReloadCommand.useReloadCommandSupport", true); + allowCommands = (List) configFile.getList("settings.restrictions.allowCommands"); + if (configFile.contains("allowCommands")) { + if (!allowCommands.contains("/login")) + allowCommands.add("/login"); + if (!allowCommands.contains("/register")) + allowCommands.add("/register"); + if (!allowCommands.contains("/l")) + allowCommands.add("/l"); + if (!allowCommands.contains("/reg")) + allowCommands.add("/reg"); + if (!allowCommands.contains("/passpartu")) + allowCommands.add("/passpartu"); + if (!allowCommands.contains("/email")) + allowCommands.add("/email"); + if(!allowCommands.contains("/captcha")) + allowCommands.add("/captcha"); + } + rakamakUsers = configFile.getString("Converter.Rakamak.fileName", "users.rak"); + rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName", "UsersIp.rak"); + rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false); + rakamakHash = getRakamakHash(); + noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", false); + removePassword = configFile.getBoolean("Security.console.removePassword", true); + getmailAccount = configFile.getString("Email.mailAccount", ""); + getmailPassword = configFile.getString("Email.mailPassword", ""); + 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()); + displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true); + getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id"); + getmailSenderName = configFile.getString("Email.mailSenderName", ""); + getPredefinedSalt = configFile.getString("Xenoforo.predefinedSalt", ""); + useCaptcha = configFile.getBoolean("Security.captcha.useCaptcha", false); + maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5); + captchaLength = configFile.getInt("Security.captcha.captchaLength", 5); + getMailSubject = configFile.getString("Email.mailSubject", "Your new AuthMe Password"); + getMailText = configFile.getString("Email.mailText", "Dear , \n\n This is your new AuthMe password for the server : \n\n \n\n \n\n Do not forget to change password after login! \n /changepassword newPassword"); + emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false); + saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8); + getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); + multiverse = configFile.getBoolean("Hooks.multiverse", true); + chestshop = configFile.getBoolean("Hooks.chestshop", true); + notifications = configFile.getBoolean("Hooks.notifications", true); + bungee = configFile.getBoolean("Hooks.bungeecord", false); + getForcedWorlds = (List) configFile.getList("settings.restrictions.ForceSpawnOnTheseWorlds"); + banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false); + doubleEmailCheck = configFile.getBoolean("settings.registration.doubleEmailCheck", false); + + } + + +public void mergeConfig() { + + if (contains("settings.restrictions.allowedPluginTeleportHandler")) { + set("settings.restrictions.allowedPluginTeleportHandler", null); + } + + if(!contains("DataSource.mySQLColumnEmail")) { + set("DataSource.mySQLColumnEmail","email"); + } + + if(contains("Email.GmailAccount")) { + set("Email.mailAccount", getString("Email.GmailAccount")); + set("Email.GmailAccount", null); + } + + if(contains("Email.GmailPassword")) { + set("Email.mailPassword", getString("Email.GmailPassword")); + set("Email.GmailPassword", null); + } + + if(!contains("Email.RecoveryPasswordLength")) { + set("Email.RecoveryPasswordLength", 8); + } + + if(!contains("Email.mailPort")) { + set("Email.mailPort", 465); + } + + if(!contains("Email.mailSMTP")) { + set("Email.mailSMTP", "smtp.gmail.com"); + } + + if(!contains("Email.mailAccount")) { + set("Email.mailAccount", ""); + } + + if(!contains("Email.mailPassword")) { + set("Email.mailPassword", ""); + } + + if(!contains("ExternalBoardOptions.mySQLOtherUsernameColumns")) { + set("ExternalBoardOptions.mySQLOtherUsernameColumns", new ArrayList()); + } + + if(!contains("settings.restrictions.displayOtherAccounts")) { + set("settings.restrictions.displayOtherAccounts", true); + } + + if(!contains("DataSource.mySQLColumnId")) { + set("DataSource.mySQLColumnId", "id"); + } + + if(!contains("Email.mailSenderName")) { + set("Email.mailSenderName", ""); + } + + if(!contains("Xenoforo.predefinedSalt")) { + set("Xenoforo.predefinedSalt", ""); + } + + if(!contains("Security.captcha.useCaptcha")) { + set("Security.captcha.useCaptcha", false); + } + + if(!contains("Security.captcha.maxLoginTry")) { + set("Security.captcha.maxLoginTry", 5); + } + + if(!contains("Security.captcha.captchaLength")) { + set("Security.captcha.captchaLength", 5); + } + + if(!contains("Email.mailSubject")) { + set("Email.mailSubject", ""); + } + + if(!contains("Email.mailText")) { + set("Email.mailText", "Dear , \n\n This is your new AuthMe password for the server : \n\n \n\n \n\n Do not forget to change password after login! \n /changepassword newPassword"); + } + + if(!contains("settings.registration.enableEmailRegistrationSystem")) { + set("settings.registration.enableEmailRegistrationSystem", false); + } + + if(!contains("settings.security.doubleMD5SaltLength")) { + set("settings.security.doubleMD5SaltLength", 8); + } + + if(!contains("Email.maxRegPerEmail")) { + set("Email.maxRegPerEmail", 1); + } + + if(!contains("Hooks.multiverse")) { + set("Hooks.multiverse", true); + set("Hooks.chestshop", true); + set("Hooks.notifications", true); + set("Hooks.bungeecord", false); + } + + if(!contains("settings.restrictions.ForceSpawnOnTheseWorlds")) { + set("settings.restrictions.ForceSpawnOnTheseWorlds", new ArrayList()); + } + + if(!contains("settings.restrictions.banUnsafedIP")) { + set("settings.restrictions.banUnsafedIP", false); + } + + if(!contains("settings.registration.doubleEmailCheck")) { + set("settings.registration.doubleEmailCheck", false); + } + + plugin.getLogger().info("Merge new Config Options if needed.."); + plugin.saveConfig(); + + return; + } + /** + * + * + * + */ + private static HashAlgorithm getPasswordHash() { + String key = "settings.security.passwordHash"; + + try { + return PasswordSecurity.HashAlgorithm.valueOf(configFile.getString(key,"SHA256").toUpperCase()); + } catch (IllegalArgumentException ex) { + ConsoleLogger.showError("Unknown Hash Algorithm; defaulting to SHA256"); + return PasswordSecurity.HashAlgorithm.SHA256; + } + } + + + private static HashAlgorithm getRakamakHash() { + String key = "Converter.Rakamak.newPasswordHash"; + + try { + return PasswordSecurity.HashAlgorithm.valueOf(configFile.getString(key,"SHA256").toUpperCase()); + } catch (IllegalArgumentException ex) { + ConsoleLogger.showError("Unknown Hash Algorithm; defaulting to SHA256"); + return PasswordSecurity.HashAlgorithm.SHA256; + } + } + + /** + * + * + * + */ + private static DataSourceType getDataSource() { + String key = "DataSource.backend"; + + try { + return DataSource.DataSourceType.valueOf(configFile.getString(key).toUpperCase()); + } catch (IllegalArgumentException ex) { + ConsoleLogger.showError("Unknown database backend; defaulting to file database"); + return DataSource.DataSourceType.FILE; + } + } + + /** + * Config option for setting and check restricted user by + * username;ip , 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) { + + Iterator iter = getRestrictedIp.iterator(); + + /* setup a few boolean variables to test the parameters */ + Boolean trueonce = false; + Boolean namefound = false; + + while (iter.hasNext()) { + String[] args = iter.next().split(";"); + + String testname = args[0]; + String testip = args[1]; + + /** Changing this logic to be more customized + * test each case against the entire + * list not just the first one in the list.*/ + + /* Fist Check the name */ + if(testname.equalsIgnoreCase(name) ) { + namefound = true; + /* Check to see if the IP is the same */ + if(testip.equalsIgnoreCase(ip)) { + trueonce = true; + }; + } + } + // if the name is not found in the list let the user pass they are not being monitored + if ( namefound == false){ + return true; + } + else { + // if the name and IP was found once in the list let the user pass they are in the config + if ( trueonce == true ){ + return true; + // otherwise nip them in the bud and THEY SHALL NOT PASS! + } else { + return false; + } + } +} + + + /** + * Loads the configuration from disk + * + * @return True if loaded successfully + */ + public final boolean load() { + try { + load(file); + return true; + } catch (Exception ex) { + return false; + } + } + + public final void reload() { + load(); + loadDefaults(file.getName()); + } + + /** + * Saves the configuration to disk + * + * @return True if saved successfully + */ + public final boolean save() { + try { + save(file); + return true; + } catch (Exception ex) { + return false; + } + } + + /** + * Simple function for if the Configuration file exists + * + * @return True if configuration exists on disk + */ + public final boolean exists() { + return file.exists(); + } + + /** + * Loads a file from the plugin jar and sets as default + * + * @param filename The filename to open + */ + public final void loadDefaults(String filename) { + InputStream stream = plugin.getResource(filename); + if(stream == null) return; + + setDefaults(YamlConfiguration.loadConfiguration(stream)); + } + + /** + * Saves current configuration (plus defaults) to disk. + * + * If defaults and configuration are empty, saves blank file. + * + * @return True if saved successfully + */ + public final boolean saveDefaults() { + options().copyDefaults(true); + options().copyHeader(true); + boolean success = save(); + options().copyDefaults(false); + options().copyHeader(false); + + return success; + } + + + /** + * Clears current configuration defaults + */ + public final void clearDefaults() { + setDefaults(new MemoryConfiguration()); + } + + /** +* Check loaded defaults against current configuration +* +* @return false When all defaults aren't present in config +*/ + public boolean checkDefaults() { + if (getDefaults() == null) { + return true; + } + return getKeys(true).containsAll(getDefaults().getKeys(true)); + } + /* + public static Settings getInstance() { + if (singleton == null) { + singleton = new Settings(); + } + return singleton; + } +*/ + public static String checkLang(String lang) { + for(messagesLang language: messagesLang.values()) { + //System.out.println(language.toString()); + if(lang.toLowerCase().contains(language.toString())) { + ConsoleLogger.info("Set Language: "+lang); + return lang; + } + } + ConsoleLogger.info("Set Default Language: En "); + return "en"; + } + + public enum messagesLang { + en, de, br, cz, pl, fr, ru, hu, sk, es + } +} diff --git a/src/main/java/uk/org/whoami/authme/settings/SpoutCfg.java b/src/main/java/uk/org/whoami/authme/settings/SpoutCfg.java new file mode 100644 index 00000000..93efed4f --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/settings/SpoutCfg.java @@ -0,0 +1,45 @@ +package uk.org.whoami.authme.settings; + +/** + * @Author Hoezef + */ +import java.io.File; +import java.util.ArrayList; + +public class SpoutCfg extends CustomConfiguration{ + + private static SpoutCfg instance = null; + + public SpoutCfg(File file) + { + super(file); + loadDefaults(); + load(); + save(); + } + + @SuppressWarnings("serial") + private void loadDefaults() { + this.set("Spout GUI enabled", true); + //Login: + this.set("LoginScreen.enabled", true); + this.set("LoginScreen.exit button", "Quit"); + this.set("LoginScreen.exit message", "Good Bye"); + this.set("LoginScreen.login button", "Login"); + this.set("LoginScreen.title", "LOGIN"); + this.set("LoginScreen.text", new ArrayList() {{ + add("Sample text"); + add("Change this at spout.yml"); + add("------------------"); + add("AuthMe Reloaded by d4rkwarriors"); + }}); + //Registration: + //this.set("RegistrationScreen.enabled",true); + + } + + public static SpoutCfg getInstance() { + if (instance == null) instance = new SpoutCfg(new File("plugins/AuthMe", "spout.yml")); + return instance; + } +} \ No newline at end of file diff --git a/src/main/java/uk/org/whoami/authme/task/MessageTask.java b/src/main/java/uk/org/whoami/authme/task/MessageTask.java new file mode 100644 index 00000000..2bb0613b --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/task/MessageTask.java @@ -0,0 +1,60 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.task; + +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import uk.org.whoami.authme.AuthMe; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.limbo.LimboCache; + +public class MessageTask implements Runnable { + + private AuthMe plugin; + private String name; + private String msg; + private int interval; + + public MessageTask(AuthMe plugin, String name, String msg, int interval) { + this.plugin = plugin; + this.name = name; + this.msg = msg; + this.interval = interval; + } + + @Override + public void run() { + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + for (Player player : plugin.getServer().getOnlinePlayers()) { + if (player.getName().toLowerCase().equals(name)) { + player.sendMessage(msg); + + BukkitScheduler sched = plugin.getServer().getScheduler(); + BukkitTask late = sched.runTaskLater(plugin, this, interval * 20); + if(LimboCache.getInstance().hasLimboPlayer(name)) { + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(late.getTaskId()); + } + + } + } + } +} diff --git a/src/main/java/uk/org/whoami/authme/task/TimeoutTask.java b/src/main/java/uk/org/whoami/authme/task/TimeoutTask.java new file mode 100644 index 00000000..4b3e013a --- /dev/null +++ b/src/main/java/uk/org/whoami/authme/task/TimeoutTask.java @@ -0,0 +1,72 @@ +/* + * Copyright 2011 Sebastian Köhler . + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.org.whoami.authme.task; + +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import uk.org.whoami.authme.ConsoleLogger; +import uk.org.whoami.authme.cache.backup.FileCache; +import uk.org.whoami.authme.cache.auth.PlayerCache; +import uk.org.whoami.authme.cache.limbo.LimboPlayer; +import uk.org.whoami.authme.cache.limbo.LimboCache; +import uk.org.whoami.authme.listener.AuthMePlayerListener; +import uk.org.whoami.authme.settings.Messages; + + +public class TimeoutTask implements Runnable { + + private JavaPlugin plugin; + private String name; + private Messages m = Messages.getInstance(); + private FileCache playerCache = new FileCache(); + + public TimeoutTask(JavaPlugin plugin, String name) { + this.plugin = plugin; + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public void run() { + if (PlayerCache.getInstance().isAuthenticated(name)) { + return; + } + + for (Player player : plugin.getServer().getOnlinePlayers()) { + if (player.getName().toLowerCase().equals(name)) { + if (LimboCache.getInstance().hasLimboPlayer(name)) { + LimboPlayer inv = LimboCache.getInstance().getLimboPlayer(name); + player.getServer().getScheduler().cancelTask(inv.getTimeoutTaskId()); + + if(playerCache.doesCacheExist(name)) { + playerCache.removeCache(name); + } + } + int gm = AuthMePlayerListener.gameMode.get(name); + player.setGameMode(GameMode.getByValue(gm)); + ConsoleLogger.info("Set " + player.getName() + " to gamemode: " + GameMode.getByValue(gm).name()); + player.kickPlayer(m._("timeout")); + break; + } + } + } +} diff --git a/src/main/resources/META-INF/MANIFEST.MF b/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 00000000..54a8422c --- /dev/null +++ b/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: ../lib/mail.jar + diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 00000000..459d7e1d --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1,126 @@ +DataSource: + mySQLColumnName: username + mySQLTablename: authme + mySQLUsername: authme + backend: file + mySQLColumnLastLogin: lastlogin + mySQLDatabase: authme + mySQLPort: '3306' + mySQLColumnIp: ip + mySQLHost: 127.0.0.1 + mySQLColumnPassword: password + mySQLPassword: '12345' + caching: true + mySQLlastlocX: x + mySQLlastlocY : y + mySQLlastlocZ : z + mySQLColumnEmail: email + mySQLColumnId: id +GroupOptions: + UnregisteredPlayerGroup: '' + RegisteredPlayerGroup: '' + Permissions: + PermissionsOnJoin: [] +settings: + sessions: + enabled: false + timeout: 10 + restrictions: + allowChat: false + allowCommands: + - /login + - /register + - /l + - /reg + - /passpartu + - /email + - /captcha + maxRegPerIp: 1 + maxNicknameLength: 20 + ForceSingleSession: true + ForceSpawnLocOnJoinEnabled: false + SaveQuitLocation: false + AllowRestrictedUser: false + AllowedRestrictedUser: [] + kickNonRegistered: false + kickOnWrongPassword: false + teleportUnAuthedToSpawn: false + minNicknameLength: 3 + allowMovement: false + timeout: 30 + allowedNicknameCharacters: '[a-zA-Z0-9_?]*' + allowedMovementRadius: 100 + enablePasswordVerifier: true + ProtectInventoryBeforeLogIn: true + displayOtherAccounts: true + ForceSpawnOnTheseWorlds: + - world + - world_nether + - world_the_end + banUnsafedIP: false + GameMode: + ForceSurvivalMode: false + ResetInventoryIfCreative: false + security: + minPasswordLength: 4 + unLoggedinGroup: unLoggedinGroup + passwordHash: SHA256 + doubleMD5SaltLength: 8 + registration: + enabled: true + messageInterval: 5 + force: true + enableEmailRegistrationSystem: false + doubleEmailCheck: false + unrestrictions: + UnrestrictedName: [] + messagesLanguage: en +ExternalBoardOptions: + mySQLColumnSalt: '' + mySQLColumnGroup: '' + nonActivedUserGroup: -1 + mySQLOtherUsernameColumns: [] +Xenoforo: + predefinedSalt: '' +permission: + EnablePermissionCheck: false +BackupSystem: + ActivateBackup: false + OnServerStart: false + OnServerStop: true + MysqlWindowsPath: 'C:\\Program Files\\MySQL\\MySQL Server 5.1\\' +Passpartu: + enablePasspartu: false +Security: + SQLProblem: + stopServer: true + ReloadCommand: + useReloadCommandSupport: true + console: + noConsoleSpam: false + removePassword: true + captcha: + useCaptcha: false + maxLoginTry: 5 + captchaLength: 5 +Converter: + Rakamak: + fileName: users.rak + useIP: false + ipFileName: UsersIp.rak + newPasswordHash: SHA256 +Email: + mailSMTP: smtp.gmail.com + mailPort: 465 + mailAccount: '' + mailPassword: '' + mailSenderName: '' + RecoveryPasswordLength: 8 + mailSubject: 'Your new AuthMe Password' + mailText: 'Dear , \n\n This is your new AuthMe password for the server \n\n : \n\n \n\nDo not forget to change password after login! \n /changepassword newPassword' + maxRegPerEmail: 1 +Hooks: + multiverse: true + chestshop: true + bungeecord: false + notifications: true \ No newline at end of file diff --git a/src/main/resources/messages_br.yml b/src/main/resources/messages_br.yml new file mode 100644 index 00000000..10c8fe51 --- /dev/null +++ b/src/main/resources/messages_br.yml @@ -0,0 +1,38 @@ +unknown_user: '&fUsuario inexistente' +not_logged_in: '&cNao conectado!' +reg_voluntarily: '&fPara registrar um nickname, digite: "/register senha senha"' +usage_log: '&cPara entrar digite: "/login senha"' +wrong_pwd: '&cErro. Senha Incorreta.' +unregistered: '&cDesregistrado com sucesso!' +reg_disabled: '&cNovos registros estao desativados.' +valid_session: '&cSessao de login' +login: '&cLogado com sucesso!' +vb_nonActiv: '&fSua conta nao esta ativada, verifique os seus e-mails!' +user_regged: '&cEste nome ja foi registrado antes.' +usage_reg: '&cPara registrar digite: "/register senha senha"' +max_reg: '&fNumero maximo de registros excedido.' +no_perm: '&cSem permissao!' +error: '&fOcorreu um erro de sistema, por favor reporte ao ADM.' +login_msg: '&cPara entrar digite: "/login password"' +reg_msg: '&cPara registrar um nick digite: "/register senha senha"' +usage_unreg: '&cPara desregistrar digite: /unregister senha' +pwd_changed: '&cSenha modificada!' +user_unknown: '&cNome de usuario nao existe. Verifique.' +password_error: '&fErro! Senha incorreta!' +unvalid_session: '&fSessao invalida! Desconecte e reconecte-se novamente.' +reg_only: '&fRegistro permitido somente para nomes na Whitelist!' +logged_in: '&cJa esta logado!' +logout: '&cSaida realizada com sucesso.' +same_nick: '&fEste nick ja esta online...' +registered: '&cRegistrado com sucesso!' +pass_len: '&fSenha muito curta.' +reload: '&fAuthMe Recarregado.' +timeout: '&fDemorou....' +name_len: '&cYour nickname is too Short or too long' +regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' +add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' +bad_database_email: '[AuthMe] This /email command only available with MySQL and SQLite, contact an Admin' +recovery_email: '&cForgot your password? Please use /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' \ No newline at end of file diff --git a/src/main/resources/messages_cz.yml b/src/main/resources/messages_cz.yml new file mode 100644 index 00000000..1546bffc --- /dev/null +++ b/src/main/resources/messages_cz.yml @@ -0,0 +1,40 @@ +unknown_user: '&cHrac neni registrovan.' +not_logged_in: '&cNeprihlasen!' +reg_voluntarily: '&cRegistruj se prikazem "/register heslo heslo".' +usage_log: '&cPouziti: "/login vaseheslo".' +wrong_pwd: '&cSpatne heslo.' +unregistered: '&cUspesna unregistrace!' +reg_disabled: '&cRegistrace je zakazana!' +valid_session: '&cAutomaticke znovuprihlaseni.' +login: '&cUspesne prihlaseni!' +user_regged: '&cUzivatelske jmeno je jiz registrovano.' +usage_reg: '&cPouziti: "/register heslo heslo".' +no_perm: '&cNemas opravneni.' +error: '&cVyskytla se chyba kontaktujte admina ...' +login_msg: '&cProsim prihlaste se "/login vaseheslo".' +reg_msg: '&cProsim zaregistrujte se "/register heslo heslo".' +usage_unreg: '&cPouziti: "/unregister vaseheslo".' +pwd_changed: '&cHeslo zmeneno!' +user_unknown: '&cUzivatelske jmeno neni registrovano.' +reg_only: '&cServer je pouze pro registrovane! Navstivte http://bit.ly/zyEzzS.' +logged_in: '&cJste jiz prihlasen!' +logout: '&cOdhlaseni bylo uspesne.' +same_nick: '&cNekdo jiz hraje se stejnym nickem.' +registered: '&cRegistrace byla uspesna!' +reload: '&cPrenacteni AuthMe probehlo uspesne.' +timeout: '&cCas na prihlaseni vyprsel!' +unsafe_spawn: '&cVase pozice pri odpojeni byla nebezpecna, teleportuji na spawn!' +unvalid_session: '&cChybna data pri cteni pockejte do vyprseni.' +max_reg: '&cJiz jste prekrocil(a) limit pro pocet uctu z vasi IP.' +password_error: '&cHesla se neshoduji!' +pass_len: '&cVase heslo nedosahuje minimalni delky (4).' +vb_nonActiv: '&cVas ucet neni aktivaovany, zkontrolujte si vas E-mail.' +usage_changepassword: '&cPouziti: "/changepassword stareHeslo noveHeslo".' +name_len: '&cYour nickname is too Short or too long' +regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' +add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' +bad_database_email: '[AuthMe] This /email command only available with MySQL and SQLite, contact an Admin' +recovery_email: '&cForgot your password? Please use /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' \ No newline at end of file diff --git a/src/main/resources/messages_de.yml b/src/main/resources/messages_de.yml new file mode 100644 index 00000000..14261073 --- /dev/null +++ b/src/main/resources/messages_de.yml @@ -0,0 +1,41 @@ +unknown_user: '&fBenutzer ist nicht in der Datenbank' +unsafe_spawn: '&fDeine Logoutposition war unsicher, du wurdest zum Spawn teleportiert' +not_logged_in: '&cNicht eingelogt!' +reg_voluntarily: '&fDu kannst dich mit folgendem Befehl registrieren + "/register passwort"' +usage_log: '&cBenutze: /login passwort' +wrong_pwd: '&cFalsches Passwort' +unregistered: '&cErfolgreich unregistriert!' +reg_disabled: '&cRegistrierungen sind deaktiviert' +valid_session: '&cErfolgreich eingelogt' +login: '&cErfolgreich eingelogt!' +vb_nonActiv: '&fDein Account ist noch nicht aktiviert, bitte pruefe deine E-Mails!' +user_regged: '&cBenutzername wurde schon registriert' +usage_reg: '&cBenutze: /register passwort' +max_reg: '&fDu hast die maximale Anzahl an Accounts erreicht' +no_perm: '&cKeine Rechte' +error: '&fEin Fehler ist unterlaufen, bitte kontaktiere einen Admin' +login_msg: '&cBitte logge dich ein mit "/login passwort"' +reg_msg: '&cBitte registriere dich mit "/register passwort"' +usage_unreg: '&cBenutze: /unregister passwort' +pwd_changed: '&cPasswort geaendert!' +user_unknown: '&cBenutzername nicht registriert' +password_error: '&fPasswort falsch' +unvalid_session: '&fPerioden login Fehler, bitte warte...' +reg_only: '&fNur registrierte Spieler! Bitte besuche http://example.com zum registrieren' +logged_in: '&cSchon eingelogt!' +logout: '&cErfolgreich ausgelogt' +same_nick: '&fSelber Name spielt bereits' +registered: '&cErfolgreich registriert!' +pass_len: '&fIhr Passwort erreicht nicht die minimale Laenge oder überschreitet die maximale Laenge' +reload: '&fKonfiguration und Datenbank neu geladen' +timeout: '&fLogin dauerte zu lange' +usage_changepassword: '&fBenutze: /changepassword altesPasswort neuesPasswort' +name_len: '&cYour nickname is too Short or too long' +regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' +add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' +bad_database_email: '[AuthMe] This /email command only available with MySQL and SQLite, contact an Admin' +recovery_email: '&cForgot your password? Please use /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' \ No newline at end of file diff --git a/src/main/resources/messages_en.yml b/src/main/resources/messages_en.yml new file mode 100644 index 00000000..846cb60f --- /dev/null +++ b/src/main/resources/messages_en.yml @@ -0,0 +1,42 @@ +unknown_user: '&fUser is not in database' +unsafe_spawn: '&fYour Quit location was unsafe, teleporting you to World Spawn' +not_logged_in: '&cNot logged in!' +reg_voluntarily: '&fYou can register your nickname with the server with the command "/register password ConfirmPassword"' +usage_log: '&cUsage: /login password' +wrong_pwd: '&cWrong password' +unregistered: '&cSuccessfully unregistered!' +reg_disabled: '&cRegistration is disabled' +valid_session: '&cSession login' +login: '&cSuccessful login!' +vb_nonActiv: '&fYour Account isent Activated yet check your Emails!' +user_regged: '&cUsername already registered' +usage_reg: '&cUsage: /register password ConfirmPassword' +max_reg: '&fYou have Exeded the max number of Registration for your Account' +no_perm: '&cNo Permission' +error: '&fAn error ocurred; Please contact the admin' +login_msg: '&cPlease login with "/login password"' +reg_msg: '&cPlease register with "/register password ConfirmPassword"' +usage_unreg: '&cUsage: /unregister password' +pwd_changed: '&cPassword changed!' +user_unknown: '&cUsername not registered' +password_error: '&fPassword doesnt match' +unvalid_session: '&fSession Dataes doesnt corrispond Plaese wait the end of session' +reg_only: '&fRegistered players only! Please visit http://example.com to register' +logged_in: '&cAlready logged in!' +logout: '&cSuccessful logout' +same_nick: '&fSame nick is already playing' +registered: '&cSuccessfully registered!' +pass_len: '&fYour password dind''t reach the minimum length or exeded the max length' +reload: '&fConfiguration and database has been reloaded' +timeout: '&fLogin Timeout' +usage_changepassword: '&fUsage: /changepassword oldPassword newPassword' +name_len: '&cYour nickname is too Short or too long' +regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' +add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' +bad_database_email: '[AuthMe] This /email command only available with MySQL and SQLite, contact an Admin' +recovery_email: '&cForgot your password? Please use /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' + + diff --git a/src/main/resources/messages_es.yml b/src/main/resources/messages_es.yml new file mode 100644 index 00000000..da2682b7 --- /dev/null +++ b/src/main/resources/messages_es.yml @@ -0,0 +1,41 @@ +# This file must be in ANSI if win, or UTF-8 if linux. +unknown_user: '&fEl usuario no está en la base de datos' +unsafe_spawn: '&fTu lugar de desconexión es inseguro, teletransportándote al punto inicial del mundo' +not_logged_in: '&c¡No has iniciado sesión!' +reg_voluntarily: '&fRegístrate con: "/register Contraseña ConfirmarContraseña"' +usage_log: '&cUso: /login contraseña' +wrong_pwd: '&cContraseña incorrecta' +unregistered: '&c¡Cuenta eliminada del registro!' +reg_disabled: '&cEl registro está desactivado' +valid_session: '&cInicio de sesión' +login: '&c¡Sesión iniciada!' +vb_nonActiv: '&fTu cuenta no está activada aún, ¡revisa tu correo!' +user_regged: '&cUsuario ya registrado' +usage_reg: '&cUso: /register Contraseña ConfirmarContraseña' +max_reg: '&fHas excedido la cantidad máxima de registros para tu cuenta' +no_perm: '&cNo tienes permiso' +error: '&fHa ocurrido un error. Por favor contacta al administrador.' +login_msg: '&cInicia sesión con "/login contraseña"' +reg_msg: '&cPor favor, regístrate con "/register Contraseña ConfirmarContraseña"' +usage_unreg: '&cUso: /unregister contraseña' +pwd_changed: '&c¡Contraseña cambiada!' +user_unknown: '&cUsuario no registrado' +password_error: '&fLas contraseñas no son iguales' +unvalid_session: '&fLos datos de sesión no corresponden. Por favor espera a terminar la sesión.' +reg_only: '&f¡Sólo para jugadores registrados! Por favor visita http://www.example.com/ para registrarte' +logged_in: '&c¡Ya has iniciado sesión!' +logout: '&cDesconectado correctamente.' +same_nick: '&fYa hay un usuario con ese nick conectado (posible error)' +registered: '&c¡Registrado correctamente!' +pass_len: '&fTu contraseña es muy larga o muy corta' +reload: '&fLa configuración y la base de datos han sido recargados' +timeout: '&fTiempo de espera para inicio de sesión excedido' +usage_changepassword: '&fUso: /changepw contraseñaaActual contraseñaNueva' +name_len: '&cTu nombre de usuario es muy largo o muy corto' +regex: '&cTu usuario tiene carácteres no admitidos, los cuales son: REG_EX' +add_email: '&cPor favor agrega tu e-mail con: /email add tuEmail confirmarEmail' +bad_database_email: '[AuthMe] El comando /email sólo está disponible con MySQL y SQLite, contacta a un administrador' +recovery_email: '&c¿Olvidaste tu contraseña? Por favor usa /email recovery ' +usage_captcha: '&cUso: /captcha ' +wrong_captcha: '&cCaptcha incorrecto, please use : /captcha EL_CAPTCHA' +valid_captcha: '&c¡ Captcha ingresado correctamente !' diff --git a/src/main/resources/messages_fr.yml b/src/main/resources/messages_fr.yml new file mode 100644 index 00000000..60b4982f --- /dev/null +++ b/src/main/resources/messages_fr.yml @@ -0,0 +1,40 @@ +unknown_user: '&fUtilisateur non enregistrer' +unsafe_spawn: '&fTeleportation dans un endroit sur' +not_logged_in: '&cNon connecter!' +reg_voluntarily: '&fVous venez d arriver? faites un "/register motdepasse confirmermotdepasse"' +usage_log: '&cUtilisez: /login motdepasse' +wrong_pwd: '&cMauvais MotDePasse' +unregistered: '&cVous avez ete desenregistrer!' +reg_disabled: '&cL''enregistrement est desactiver' +valid_session: '&cVous etes authentifier' +login: '&cLogin effectuer!' +vb_nonActiv: '&fCe compte n''est pas activer, consultez vos emails!' +user_regged: '&cCe nom est deja utiliser' +usage_reg: '&cUtilisez la commande /register motdepasse confirmermotdepasse' +max_reg: '&fLimite d''enregistrement atteinte pour cet account' +no_perm: '&cVous n''avez pas la permission' +error: '&fUne erreur est apparue, veuillez contacter un administrateur' +login_msg: '&cConnectez-vous via un /login motdepasse' +reg_msg: '&cUtilisez /register motdepasse confirmermotdepasse' +usage_unreg: '&cUtilisez: /unregister password' +pwd_changed: '&cMotdePasse changer avec succes!' +user_unknown: '&c Ce pseudo n est pas enregistrer' +password_error: '&fCe mot de passe est incorrect' +unvalid_session: '&fSession invalide, relancez le jeu ou attendez la fin de la session' +reg_only: '&fSeul les joueurs enregistrer sont admis!' +logged_in: '&cVous etes deja connecter!' +logout: '&cVous avez ete deconnecter' +same_nick: '&fUne personne ayant ce pseudo joue deja !' +registered: '&cEnregistrement reussi!' +pass_len: '&fVotre mot de passe ne respecte pas les normes de longueurs' +reload: '&fConfig et BDD ont ete relancer' +timeout: '&fVous avez ete expulser, trop lent pour vous enregistrer !' +usage_changepassword: '&fCommande /changepassword ancienmdp nouveaumdp' +name_len: '&cVotre pseudo est trop long ou trop court' +regex: '&cVotre pseudo contient des caracteres interdits! Caracteres Autorises: REG_EX' +add_email: '&cMerci d''ajouter votre email : /email add yourEmail confirmEmail' +bad_database_email: '[AuthMe] La commande /email est disponible uniquement pour MySQL et SQLite, contactez un Admin' +recovery_email: '&cOublie de MotDePasse? Utilisez /email recovery ' +usage_captcha: '&cTrop de Mauvais MotDePasse, utilisez: /captcha ' +wrong_captcha: '&cCaptcha Incorrect, entrez de nouveau : /captcha THE_CAPTCHA' +valid_captcha: '&cLe Captcha est valide, Merci!' \ No newline at end of file diff --git a/src/main/resources/messages_hu.yml b/src/main/resources/messages_hu.yml new file mode 100644 index 00000000..0f302655 --- /dev/null +++ b/src/main/resources/messages_hu.yml @@ -0,0 +1,40 @@ +reg_only: Csak regisztrlt jtkosoknak! Jelentkezni a yndicraft@freemail.hu e-mail cmen lehet +usage_unreg: '&cHasznlat: /unregister jelsz' +registered: '&aSikeres regisztrci. dvzllek!' +user_regged: '&cJtkosnv mr regisztrlva' +login_msg: '&cKrlek jelentkezz be: "/login jelsz"' +not_logged_in: '&cNem vagy bejelentkezve!' +logout: '&cSikeresen kijelentkeztl' +usage_log: '&cBejelentkezs: /login jelsz' +unknown_user: User is not in database +reg_voluntarily: Regisztrlhatod beceneved a szerveren a kvetkez parancsal "/register jelsz jelsz" +reg_disabled: '&cRegisztrci letiltva' +no_perm: '&cNincs engedlyed' +usage_reg: '&cHasznlat: /register jelsz jelszjra' +unregistered: '&cRegisztrci sikeresen trlve!' +same_nick: Ezen a jtkosnven mr jtszanak +valid_session: '&cSession login' +pwd_changed: '&cJelsz cserlve!' +reload: Beltsok s adatbzis jratltve! +timeout: Bejelentkezsi idtllps +error: Hiba lpett fel; Lpj kapcsolatba a tulajjal' +logged_in: '&cMr be vagy jelentkezve!' +login: '&aSikeresen Belptl! dvzllek!!!' +wrong_pwd: '&4Hibs jelsz' +user_unknown: '&cJtkosnv nem regisztrlt' +reg_msg: '&cKrlek Regisztrlj: "/register jelsz jelszjra"' +unsafe_spawn: A kilpsi helyzeted nem biztonsgos, teleportls a kezd Spawnra. +max_reg: Csak egy karakterrel Registrlhatsz!!! +password_error: A jelsz nem illik ssze +unvalid_session: Session Dataes doesnt corrispond Plaese wait the end of session +pass_len: A jelszavad nem ri el a minimlis hosszat +vb_nonActiv: Your Account isent Activated yet check your Emails! +usage_changepassword: 'hasznlat: /changepassword rgiJelsz jJelsz' +name_len: '&cYour nickname is too Short or too long' +regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' +add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' +bad_database_email: '[AuthMe] This /email command only available with MySQL and SQLite, contact an Admin' +recovery_email: '&cForgot your password? Please use /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' diff --git a/src/main/resources/messages_pl.yml b/src/main/resources/messages_pl.yml new file mode 100644 index 00000000..e0d12938 --- /dev/null +++ b/src/main/resources/messages_pl.yml @@ -0,0 +1,40 @@ +logged_in: '&fJestes juz zalogowany!' +not_logged_in: '&4Nie jestes zalogowany!' +reg_disabled: '&4Rejestracja jest wylaczona' +user_regged: '&4Gracz juz jest zarejestrowany' +usage_reg: '&4Uzycie: /register haslo ponownie_haslo' +usage_log: '&cUzycie: /login haslo' +user_unknown: '&fGracz nie jest zarejestrowany' +pwd_changed: '&fHaslo zostalo zmienione!' +reg_only: '&fTylko zarejestrowani uzytkownicy maja do tego dostep!' +valid_session: '&cSesja logowania' +login_msg: '&2Prosze sie zalogowac przy uzyciu &6/login ' +reg_msg: '&2Prosze sie zarejestrowac przy uzyciu &6/register ' +timeout: '&fUplynal limit czasu zalogowania' +wrong_pwd: '&cNiepoprawne haslo' +logout: '&cPomyslnie wylogowany' +usage_unreg: '&cUzycie: /unregister haslo' +registered: '&aPomyslnie zarejestrowany!' +unregistered: '&4Pomyslnie odrejestrowany!' +login: '&aHaslo zaakceptowane!' +no_perm: '&4Nie masz uprawnien' +same_nick: '&fTen nick juz gra' +reg_voluntarily: '&fMozesz zarejestrowac swoj nick na serwerze przy uzyciu "/register haslo ponownie_haslo"' +reload: '&fKonfiguracja bazy danych zostala przeladowana' +error: '&fBlad prosimy napisac do aministracji' +unknown_user: '&fUzytkownika nie ma w bazie danych' +unsafe_spawn: '&fTwoje pozycja jest niebezpieczna. Zostaniesz przeniesiony na bezpieczny spawn.' +unvalid_session: '&fSesja zakonczona!' +max_reg: '&fPrzekroczyles limit zarejestrowanych kont na serwerze.' +password_error: '&fHaslo niepoprawne!' +pass_len: '&fTwoje haslo jest za krotkie lub za dlugie! Sprobuj ponownie..' +vb_nonActiv: '&fTwoje konto nie zostalo aktywowane! Sprawdz maila.' +usage_changepassword: '&fUzycie: /changepassword starehaslo nowehaslo' +name_len: '&cYour nickname is too Short or too long' +regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' +add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' +bad_database_email: '[AuthMe] This /email command only available with MySQL and SQLite, contact an Admin' +recovery_email: '&cForgot your password? Please use /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' diff --git a/src/main/resources/messages_ru.yml b/src/main/resources/messages_ru.yml new file mode 100644 index 00000000..488b1716 --- /dev/null +++ b/src/main/resources/messages_ru.yml @@ -0,0 +1,42 @@ +unknown_user: '&cЭтого игрока нет в базе' +unsafe_spawn: '&6Твоё расположение перед выходом из игры было небезопасным - &aты + перенесён на спавн' +not_logged_in: '&cТы не в игре!' +reg_voluntarily: '&eЗарегистрируйся - &d/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ &eили &d/register + ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +usage_log: '&eСинтаксис: &d/l ПАРОЛЬ &eили &d/login ПАРОЛЬ' +wrong_pwd: '&cНеправильный пароль' +unregistered: '&aРегистрация снята' +reg_disabled: '&6Регистрация отключена' +valid_session: '&aСессия открыта' +login: '&aТы в игре' +vb_nonActiv: '&aТвой аккаунт активирован. &5Проверь свою электронную почту.' +user_regged: '&cЭтот игрок уже зарегистрирован' +usage_reg: '&eСинтаксис: &d/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ &eили &d/register ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +max_reg: '&cТы превысил максимальное число регистраций' +no_perm: '&cНет разрешения' +error: '&cЧто-то пошло не так... &5Свяжись с администратором.' +login_msg: '&eВойди в игру - &d/l ПАРОЛЬ &eили &d/login ПАРОЛЬ' +reg_msg: '&eЗарегистрируйся - &d/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ &eили &d/register ПАРОЛЬ + ПОВТОР_ПАРОЛЯ' +usage_unreg: '&eСинтаксис: &d/unregister ПАРОЛЬ' +pwd_changed: '&aПароль изменён' +user_unknown: '&cТакой игрок не зарегистрирован' +password_error: '&cПароль не найден' +unvalid_session: '&cДата сессии некорректна. &5Дождись конца сессии.' +reg_only: '&cРегистрация только для игроков! &5Зайди на &dhttp://example.com &5для + регистрации.' +logged_in: '&cТы уже в матрице!' +logout: '&aТы вышел с сервера' +same_nick: '&cЭтот игрок уже играет' +registered: '&aУспешная регистрация' +pass_len: '&cТвой пароль либо слишком длинный, либо слишком короткий' +reload: '&aКонфигурация и база данных перезагружена' +timeout: '&cТы не успел войти в игру' +usage_changepassword: '&eСинтаксис: &d/changepassword СТАРЫЙ_ПАРОЛЬ НОВЫЙ_ПАРОЛЬ' +name_len: '&cТвой ник либо слишком длинный, либо слишком короткий' +regex: '&cТвой ник содержит недопустимые символы. Разрешено использовать: REG_EX' +add_email: '&eДобавь свой email: &d/email add АДРЕС_ПОЧТЫ ПОВТОР_АДРЕСА_ПОЧТЫ' +bad_database_email: '&c[AuthMe] Команда &d/email&c доступна только при работе с MySQL + или SQLite' +recovery_email: '&cЗабыл пароль? Используй команду &d/email recovery <АДРЕС_ПОЧТЫ>' diff --git a/src/main/resources/messages_sk.yml b/src/main/resources/messages_sk.yml new file mode 100644 index 00000000..38f23846 --- /dev/null +++ b/src/main/resources/messages_sk.yml @@ -0,0 +1,44 @@ +# Slovak translate by Judzi # +# www.judzi.eu | judzi@cs-gaming.eu # +# 02.02.2013 - 4:35 AM - Thanks for use # + +logged_in: '&cAktuálne si uz prihláseny!' +not_logged_in: '&cNie si este prihláseny!' +reg_disabled: '&cRegistrácia nie je povolená' +user_regged: '&cZadané meno je uz zaregistrované' +usage_reg: '&cPríkaz: /register heslo zopakujHeslo' +usage_log: '&cPríkaz: /login heslo' +user_unknown: '&cZadané meno nie je zaregistrované!' +pwd_changed: '&cHeslo zmenené!' +reg_only: '&fVstup iba pre registrovanych! Navstiv http://www.cs-gaming.eu pre registráciu' +valid_session: '&cZapamätané prihlásenie' +login_msg: '&cPrihlás sa príkazom "/login heslo"' +reg_msg: '&cZaregistruj sa príkazom "/register heslo zopakujHeslo"' +timeout: '&fVyprsal cas na prihlásenie' +wrong_pwd: '&cZadal si zlé heslo' +logout: '&cBol si úspesne odhláseny' +usage_unreg: '&cPríkaz: /unregister heslo' +registered: '&cBol si úspesne zaregistrovany' +unregistered: '&cUcet bol vymazany!' +login: '&cBol si úspesne prihláseny!' +no_perm: '&cZiadne' +same_nick: '&fHrác s tymto nickom uz hrá!' +reg_voluntarily: '&fZaregistruj sa pomocou príkazu "/register heslo zopakujHeslo"' +reload: '&fKonfigurácia a databáza bola obnovená' +error: '&fNastala chyba; Kontaktujte administrátora' +unknown_user: '&fHrac nie je v databázi' +unsafe_spawn: '&fTvoj pozícia bol nebezpecná, teleportujem hraca na spawn' +unvalid_session: '&fZapamätane casove data nie su doveryhodne. Cakaj na ukoncenie spojenia' +max_reg: '&fDosiahol si maximum registrovanych uctov.' +password_error: '&fHeslá sa nezhodujú' +pass_len: '&fHeslo je velmi kratke alebo dlhe' +vb_nonActiv: '&fUcet nie je aktivny. Prezri si svoj e-mail!' +usage_changepassword: '&fPríkaz: /changepassword stareHeslo noveHeslo' +name_len: '&cTvoje meno je velmi krátke alebo dlhé' +regex: '&cTvoje meno obsahuje zakázané znaky. Povolené znaky: REG_EX' +add_email: '&cPridaj svoj e-mail príkazom "/email add email zopakujEmail"' +bad_database_email: '[AuthMe] Tento príkaz je dostupny iba pri MySQL SQLite' +recovery_email: '&cZabudol si heslo? Pouzi príkaz /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' \ No newline at end of file diff --git a/src/main/resources/players.yml b/src/main/resources/players.yml new file mode 100644 index 00000000..cf746f52 --- /dev/null +++ b/src/main/resources/players.yml @@ -0,0 +1 @@ +players: [] \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 00000000..1f07e70b --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,128 @@ +name: AuthMe +author: darkwarriros,Xephi +website: http://www.multiplayer-italia.com/ +description: AuthMe prevents people, which aren't logged in, from doing stuff like placing blocks, moving, typing commands or seeing the inventory of the current player. +main: uk.org.whoami.authme.AuthMe +version: 2.7.10b1 +softdepend: [Vault, ChestShop, Spout, Multiverse-Core, Notifications, Citizens, CombatTag] +commands: + register: + description: Register an account + usage: /register password confirmpassword + aliases: reg + login: + description: Login into a account + usage: /login password + aliases: l + changepassword: + description: Change password of a account + usage: /changepassword oldPassword newPassword + logout: + description: Logout + usage: /logout + unregister: + description: unregister your account + usage: /unregister password + passpartu: + description: compare passpartu token + usage: /passpartu token + authme: + description: AuthMe op commands + usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version' + email: + description: Add Email or recover password + usage: '/email add your@email.com your@email.com|change oldEmail newEmail|recovery your@email.com' + captcha: + description: Captcha + usage: /captcha theCaptcha +permissions: + authme.player.*: + description: Gives access to all authme player commands + default: true + children: + authme.register: true + authme.login: true + authme.changepassword: true + authme.logout: true + authme.unregister: true + authme.passpartu: true + authme.l: true + authme.reg: true + authme.admin.*: + description: Gives access to all authme admin commands + children: + authme.admin.reload: true + authme.admin.register: true + authme.admin.changepassword: true + authme.admin.unregister: true + authme.admin.purge: true + authme.seeOtherAccounts: true + authme.admin.lastlogin: true + authme.admin.getemail: true + authme.admin.chgemail: true + authme.register: + description: Register an account + default: true + authme.login: + description: Login into a account + default: true + authme.changepassword: + description: Change password of a account + default: true + authme.logout: + description: Logout + default: true + authme.email: + description: Email + default: true + authme.passpartu: + description: passpartu + default: true + authme.allow2accounts: + description: allow more accounts for same ip + default: false + authme.seeOtherAccounts: + description: display other accounts about a player when he logs in + default: false + authme.unregister: + description: unregister your account + default: true + authme.admin.reload: + description: AuthMe reload commands + default: op + authme.admin.register: + description: AuthMe register command + default: op + authme.admin.changepassword: + description: AuthMe changepassword command + default: op + authme.admin.unregister: + description: AuthMe unregister command + default: op + authme.admin.purge: + description: AuthMe unregister command + default: op + authme.admin.convertflattosql: + description: Convert File to Sql method + default: op + authme.admin.convertfromrakamak: + description: Convert from Rakamak database to AuthMe + default: op + authme.admin.lastlogin: + description: Get last login date about a player + default: op + authme.admin.getemail: + description: Get last email about a player + default: op + authme.admin.chgemail: + description: Change a player email + default: op + authme.admin.accounts: + description: Display Players Accounts + default: op + authme.admin.xauthimport: + description: Import xAuth Database to AuthMe Database + default: op + authme.captcha: + description: Captcha + default: true diff --git a/src/plugin.yml b/src/plugin.yml new file mode 100644 index 00000000..14add553 --- /dev/null +++ b/src/plugin.yml @@ -0,0 +1,97 @@ +name: AuthMe +author: darkwarriros,Xephi +website: http://www.multiplayer-italia.com/ +description: AuthMe prevents people, which aren't logged in, from doing stuff like placing blocks, moving, typing commands or seeing the inventory of the current player. +main: uk.org.whoami.authme.AuthMe +version: 2.7.2b3 +softdepend: [Vault] +commands: + register: + description: Register an account + usage: /register password confirmpassword + aliases: reg + login: + description: Login into a account + usage: /login password + aliases: l + changepassword: + description: Change password of a account + usage: /changepassword oldPassword newPassword + logout: + description: Logout + usage: /logout + unregister: + description: unregister your account + usage: /unregister password + passpartu: + description: compare passpartu token + usage: /passpartu token + authme: + description: AuthMe op commands + usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version' +permissions: + authme.player.*: + description: Gives access to all authme player commands + default: true + children: + authme.register: true + authme.login: true + authme.changepassword: true + authme.logout: true + authme.unregister: true + authme.passpartu: true + authme.l: true + authme.reg: true + authme.admin.*: + description: Gives access to all authme admin commands + children: + authme.admin.reload: true + authme.admin.register: true + authme.admin.changepassword: true + authme.admin.unregister: true + authme.admin.purge: true + authme.register: + description: Register an account + default: true + authme.login: + description: Login into a account + default: true + authme.changepassword: + description: Change password of a account + default: true + authme.logout: + description: Logout + default: true + authme.passpartu: + description: passpartu + default: true + authme.allow2accounts: + description: allow more accounts for same ip + default: false + authme.unregister: + description: unregister your account + default: true + authme.admin.reload: + description: AuthMe reload commands + default: op + authme.admin.register: + description: AuthMe register command + default: op + authme.admin.changepassword: + description: AuthMe changepassword command + default: op + authme.admin.unregister: + description: AuthMe unregister command + default: op + authme.admin.purge: + description: AuthMe unregister command + default: op + authme.admin.convertflattosql: + description: Convert File to Sql method + default: op + authme.admin.convertfromrakamak: + description: Convert from Rakamak database to AuthMe + default: op + authme.admin.lastlogin: + description: Get last login date about a player + default: op \ No newline at end of file