Merge pull request #201 from AuthMe-Team/master

stuff from the team repo
This commit is contained in:
Alexandre Vanhecke 2015-09-21 01:14:57 +02:00
commit 638374418c
92 changed files with 2775 additions and 4243 deletions

View File

@ -126,7 +126,7 @@ EUR: <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_but
USD: <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=PWQMYCP2SAH6L"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif"></a></p> USD: <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=PWQMYCP2SAH6L"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif"></a></p>
#####Sponsor #####Sponsor
GameHosting.it is leader in Italy in Game Server Provider. With its own DataCenter offers Anti-DDoS solutions at affordable prices. Game Server of Minecraft based on Multicraft are equipped with the latest technology in hardware. GameHosting.it is leader in Italy as Game Server Provider. With its own DataCenter offers Anti-DDoS solutions at affordable prices. Game Server of Minecraft based on Multicraft are equipped with the latest technology in hardware.
[![GameHosting](http://www.gamehosting.it/images/bn3.png)](http://www.gamehosting.it) [![GameHosting](http://www.gamehosting.it/images/bn3.png)](http://www.gamehosting.it)
#####Credits #####Credits

123
pom.xml
View File

@ -5,7 +5,7 @@
<groupId>fr.xephi</groupId> <groupId>fr.xephi</groupId>
<artifactId>authme</artifactId> <artifactId>authme</artifactId>
<version>5.0-SNAPSHOT</version> <version>5.1-SNAPSHOT</version>
<name>AuthMeReloaded</name> <name>AuthMeReloaded</name>
<description>Authentication plugin for CraftBukkit/Spigot!</description> <description>Authentication plugin for CraftBukkit/Spigot!</description>
@ -13,6 +13,11 @@
<url>http://dev.bukkit.org/bukkit-plugins/authme-reloaded/</url> <url>http://dev.bukkit.org/bukkit-plugins/authme-reloaded/</url>
<!-- See also: https://www.spigotmc.org/resources/authme-reloaded.6269/ --> <!-- See also: https://www.spigotmc.org/resources/authme-reloaded.6269/ -->
<organization>
<name>AuthMe-Team</name>
<url>https://github.com/AuthMe-Team</url>
</organization>
<scm> <scm>
<connection>scm:git:https://github.com/Xephi/AuthMeReloaded.git</connection> <connection>scm:git:https://github.com/Xephi/AuthMeReloaded.git</connection>
<developerConnection>scm:git:git@github.com:Xephi/AuthMeReloaded.git</developerConnection> <developerConnection>scm:git:git@github.com:Xephi/AuthMeReloaded.git</developerConnection>
@ -56,6 +61,14 @@
<include>*.yml</include> <include>*.yml</include>
</includes> </includes>
</resource> </resource>
<resource>
<targetPath>./messages/</targetPath>
<filtering>false</filtering>
<directory>${basedir}/src/main/resources/messages/</directory>
<includes>
<include>*.yml</include>
</includes>
</resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
@ -74,13 +87,14 @@
<configuration> <configuration>
<artifactSet> <artifactSet>
<includes> <includes>
<include>com.maxmind.geoip:*</include> <include>com.zaxxer:HikariCP</include>
<include>javax.mail:*</include> <include>org.slf4j:slf4j-simple</include>
<include>com.sun.mail:*</include> <include>org.slf4j:slf4j-api</include>
<include>com.comphenix.attribute:*</include> <include>com.google.code.gson:gson</include>
<include>org.mcstats.*:*</include> <include>com.maxmind.geoip:geoip-api</include>
<include>com.zaxxer:*</include> <include>com.sun.mail:javax.mail</include>
<include>org.slf4j:*</include> <include>com.comphenix.attribute:AttributeStorage</include>
<include>org.mcstats.bukkit:metrics</include>
</includes> </includes>
</artifactSet> </artifactSet>
<relocations> <relocations>
@ -116,12 +130,6 @@
<url>https://ci.drtshock.net/plugin/repository/everything</url> <url>https://ci.drtshock.net/plugin/repository/everything</url>
</repository> </repository>
<!-- Citizens API 2.X Repo -->
<repository>
<id>citizensapi-repo</id>
<url>http://ci.citizensnpcs.co/plugin/repository/project/CitizensAPI/LastSuccessful/repository</url>
</repository>
<!-- CombatTagPlus Repo --> <!-- CombatTagPlus Repo -->
<repository> <repository>
<id>minelink-thirdparty</id> <id>minelink-thirdparty</id>
@ -170,18 +178,7 @@
<!-- Maven Dependencies --> <!-- Maven Dependencies -->
<!-- MySql Connection Pool --> <!-- Database Connection Pool -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.12</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
@ -189,17 +186,19 @@
<scope>compile</scope> <scope>compile</scope>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.12</version>
<scope>compile</scope>
</dependency>
<!-- SQLite Library --> <!-- SQLite Connector -->
<dependency> <dependency>
<groupId>org.xerial</groupId> <groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId> <artifactId>sqlite-jdbc</artifactId>
@ -207,12 +206,32 @@
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<!-- Java Email API --> <!-- Google JSON Library -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
<scope>compile</scope>
</dependency>
<!-- Java Email API and Implementation -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.4</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>com.sun.mail</groupId> <groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId> <artifactId>javax.mail</artifactId>
<version>1.5.4</version> <version>1.5.4</version>
<scope>compile</scope> <scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>activation</artifactId>
<groupId>javax.activation</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
@ -283,24 +302,6 @@
</exclusions> </exclusions>
</dependency> </dependency>
<!-- Citizens 2.X, NPC plugin, http://dev.bukkit.org/bukkit-plugins/citizens/ -->
<dependency>
<groupId>net.citizensnpcs</groupId>
<artifactId>citizensapi</artifactId>
<version>2.0.16-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Multi World plugin, http://www.spigotmc.org/resources/multiverse-core.390/ --> <!-- Multi World plugin, http://www.spigotmc.org/resources/multiverse-core.390/ -->
<dependency> <dependency>
<groupId>com.onarandombox.multiversecore</groupId> <groupId>com.onarandombox.multiversecore</groupId>
@ -420,24 +421,6 @@
</exclusions> </exclusions>
</dependency> </dependency>
<!-- Anti PvPLogging plugin, http://www.spigotmc.org/resources/combat-tag.3182/ -->
<dependency>
<groupId>com.trc202</groupId>
<artifactId>CombatTag</artifactId>
<version>6.2.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- XAuth, another authentication plugin, required by the database converter --> <!-- XAuth, another authentication plugin, required by the database converter -->
<dependency> <dependency>
<groupId>de.luricos.bukkit</groupId> <groupId>de.luricos.bukkit</groupId>
@ -557,9 +540,7 @@
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>simplechestlock</artifactId> <artifactId>simplechestlock</artifactId>
<groupId> <groupId>com.webkonsept.bukkit.simplechestlock</groupId>
com.webkonsept.bukkit.simplechestlock
</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>commandbook</artifactId> <artifactId>commandbook</artifactId>

File diff suppressed because it is too large Load Diff

View File

@ -1,63 +1,62 @@
package fr.xephi.authme; package fr.xephi.authme;
import java.io.BufferedWriter; import com.google.common.base.Throwables;
import java.io.File; import fr.xephi.authme.api.NewAPI;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
public class ConsoleLogger { public class ConsoleLogger {
private static final Logger log = Logger.getLogger("AuthMe"); private static final Logger log = AuthMe.getInstance().getLogger();
private static final DateFormat df = new SimpleDateFormat("[MM-dd HH:mm:ss]");
public static void info(String message) { public static void info(String message) {
if (AuthMe.getInstance().isEnabled()) { if (AuthMe.getInstance().isEnabled()) {
log.info("[AuthMe] " + message); log.info("[AuthMe] " + message);
if (Settings.useLogging) { if (Settings.useLogging) {
Calendar date = Calendar.getInstance(); String dateTime;
final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] " + message; synchronized (df) {
Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() { dateTime = df.format(new Date());
@Override }
public void run() { writeLog(dateTime + " " + message);
writeLog(actually);
}
});
} }
} }
} }
public static void showError(String message) { public static void showError(String message) {
if (AuthMe.getInstance().isEnabled()) { if (AuthMe.getInstance().isEnabled()) {
log.warning("[AuthMe] ERROR: " + message); log.warning("[AuthMe] " + message);
if (Settings.useLogging) { if (Settings.useLogging) {
Calendar date = Calendar.getInstance(); String dateTime;
final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] ERROR : " + message; synchronized (df) {
Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() { dateTime = df.format(new Date());
@Override }
public void run() { writeLog(dateTime + " ERROR: " + message);
writeLog(actually);
}
});
} }
} }
} }
public static void writeLog(String string) { public static void writeLog(String message) {
try { try {
FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder() + File.separator + "authme.log", true); Files.write(Settings.LOG_FILE.toPath(), (message + NewAPI.newline).getBytes(),
BufferedWriter w = new BufferedWriter(fw); StandardOpenOption.APPEND,
w.write(string); StandardOpenOption.CREATE);
w.newLine(); } catch (IOException ignored) {
w.close();
} catch (IOException e) {
e.printStackTrace();
} }
} }
public static void writeStackTrace(Exception ex) {
String dateTime;
synchronized (df) {
dateTime = df.format(new Date());
}
writeLog(dateTime + " " + Throwables.getStackTraceAsString(ex));
}
} }

View File

@ -1,5 +1,11 @@
package fr.xephi.authme; package fr.xephi.authme;
import fr.xephi.authme.settings.Settings;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -7,13 +13,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import fr.xephi.authme.settings.Settings;
import net.milkbowl.vault.permission.Permission;
public class DataManager { public class DataManager {
public AuthMe plugin; public AuthMe plugin;
@ -134,10 +133,13 @@ public class DataManager {
playerFile.delete(); playerFile.delete();
i++; i++;
} else { } else {
playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + Bukkit.getOfflinePlayer(name).getUniqueId() + ".yml"); try {
if (playerFile.exists()) { playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + Bukkit.getOfflinePlayer(name).getUniqueId() + ".yml");
playerFile.delete(); if (playerFile.exists()) {
i++; playerFile.delete();
i++;
}
} catch (Exception e) { // Don't do nothing if the method getUniqueId() isn't avariable ( MC version < 1.7.5 )
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -147,7 +149,7 @@ public class DataManager {
} }
public synchronized void purgePermissions(List<String> cleared, public synchronized void purgePermissions(List<String> cleared,
Permission permission) { Permission permission) {
int i = 0; int i = 0;
for (String name : cleared) { for (String name : cleared) {
try { try {
@ -167,24 +169,19 @@ public class DataManager {
return true; return true;
ExecutorService executor = Executors.newSingleThreadExecutor(); ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> result = executor.submit(new Callable<Boolean>() { Future<Boolean> result = executor.submit(new Callable<Boolean>() {
@Override
public synchronized Boolean call() throws Exception { public synchronized Boolean call() throws Exception {
Boolean result = null; for (OfflinePlayer op : Utils.getOnlinePlayers())
try { if (op.getName().equalsIgnoreCase(name)) {
for (OfflinePlayer op : Bukkit.getOnlinePlayers()) return true;
if (op.getName().equalsIgnoreCase(name)) { }
result = true; return false;
break;
}
} catch (Exception e) {
}
return result;
} }
}); });
try { try {
return result.get().booleanValue(); return result.get();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} finally { } finally {
executor.shutdown(); executor.shutdown();
} }

View File

@ -30,18 +30,16 @@ public class PerformBackup {
this.setInstance(instance); this.setInstance(instance);
} }
public boolean DoBackup() { public boolean doBackup() {
switch (Settings.getDataSource) { switch (Settings.getDataSource) {
case FILE: case FILE:
return FileBackup("auths.db"); return FileBackup("auths.db");
case MYSQL: case MYSQL:
return MySqlBackup(); return MySqlBackup();
case SQLITEHIKARI:
case SQLITE: case SQLITE:
return FileBackup(Settings.getMySQLDatabase + ".db"); return FileBackup(Settings.getMySQLDatabase + ".db");
} }
return false; return false;

View File

@ -1,93 +1,154 @@
package fr.xephi.authme; package fr.xephi.authme;
import java.io.File; import com.maxmind.geoip.LookupService;
import java.util.Iterator; import fr.xephi.authme.cache.auth.PlayerCache;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.events.AuthMeTeleportEvent; import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.zip.GZIPInputStream;
public class Utils { public class Utils {
private String currentGroup; public static AuthMe plugin;
private static Utils singleton;
int id;
public AuthMe plugin;
public Utils(AuthMe plugin) { private static boolean getOnlinePlayersIsCollection;
this.plugin = plugin; private static Method getOnlinePlayers;
private static LookupService lookupService;
static {
plugin = AuthMe.getInstance();
checkGeoIP();
try {
Method m = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
getOnlinePlayersIsCollection = m.getReturnType() == Collection.class;
} catch (Exception ignored) {
}
} }
public void setGroup(Player player, groupType group) { // Check and Download GeoIP data if not exist
setGroup(player.getName(), group); public static boolean checkGeoIP() {
if (lookupService != null) {
return true;
}
ConsoleLogger.info("[LICENSE] This product uses data from the GeoLite API created by MaxMind, available at http://www.maxmind.com");
File file = new File(Settings.PLUGIN_FOLDER, "GeoIP.dat");
try {
if (file.exists()) {
if (lookupService == null) {
lookupService = new LookupService(file);
return true;
}
}
String url = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz";
URL downloadUrl = new URL(url);
URLConnection conn = downloadUrl.openConnection();
conn.setConnectTimeout(10000);
conn.connect();
InputStream input = conn.getInputStream();
if (conn.getURL().toString().endsWith(".gz")) {
input = new GZIPInputStream(input);
}
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int length = input.read(buffer);
while (length >= 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
output.close();
input.close();
} catch (Exception e) {
ConsoleLogger.writeStackTrace(e);
return false;
}
return checkGeoIP();
} }
@SuppressWarnings("deprecation") public static String getCountryCode(String ip) {
public void setGroup(String player, groupType group) { if (checkGeoIP()) {
return lookupService.getCountry(ip).getCode();
}
return "--";
}
public static String getCountryName(String ip) {
if (checkGeoIP()) {
return lookupService.getCountry(ip).getName();
}
return "N/A";
}
public static void setGroup(Player player, GroupType group) {
if (!Settings.isPermissionCheckEnabled) if (!Settings.isPermissionCheckEnabled)
return; return;
if (plugin.permission == null) if (plugin.permission == null)
return; return;
String name = player; String currentGroup;
try { try {
World world = null; currentGroup = plugin.permission.getPrimaryGroup(player);
currentGroup = plugin.permission.getPrimaryGroup(world, name);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission plugin (" + plugin.permission.getName() + ") doesn't support the Group system... unhook!"); ConsoleLogger.showError("Your permission plugin (" + plugin.permission.getName() + ") doesn't support the Group system... unhook!");
plugin.permission = null; plugin.permission = null;
return; return;
} }
World world = null;
switch (group) { switch (group) {
case UNREGISTERED: { case UNREGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.unRegisteredGroup); plugin.permission.playerAddGroup(player, Settings.unRegisteredGroup);
break; break;
} }
case REGISTERED: { case REGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.getRegisteredGroup); plugin.permission.playerAddGroup(player, Settings.getRegisteredGroup);
break; break;
} }
case NOTLOGGEDIN: { case NOTLOGGEDIN: {
if (!useGroupSystem()) if (!useGroupSystem())
break; break;
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.getUnloggedinGroup); plugin.permission.playerAddGroup(player, Settings.getUnloggedinGroup);
break; break;
} }
case LOGGEDIN: { case LOGGEDIN: {
if (!useGroupSystem()) if (!useGroupSystem())
break; break;
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name.toLowerCase()); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
if (limbo == null) if (limbo == null)
break; break;
String realGroup = limbo.getGroup(); String realGroup = limbo.getGroup();
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(world, name, realGroup); plugin.permission.playerAddGroup(player, realGroup);
break; break;
} }
} }
return;
} }
@SuppressWarnings("deprecation") public static boolean addNormal(Player player, String group) {
public boolean addNormal(Player player, String group) {
if (!useGroupSystem()) { if (!useGroupSystem()) {
return false; return false;
} }
if (plugin.permission == null) if (plugin.permission == null)
return false; return false;
World world = null;
try { try {
if (plugin.permission.playerRemoveGroup(world, player.getName().toString(), Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(world, player.getName().toString(), group)) { if (plugin.permission.playerRemoveGroup(player, Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(player, group)) {
return true; return true;
} }
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
@ -98,39 +159,45 @@ public class Utils {
return false; return false;
} }
public void hasPermOnJoin(Player player) { // TODO: remove if not needed
@SuppressWarnings("unused")
public static void hasPermOnJoin(Player player) {
if (plugin.permission == null) if (plugin.permission == null)
return; return;
Iterator<String> iter = Settings.getJoinPermissions.iterator(); for (String permission : Settings.getJoinPermissions) {
while (iter.hasNext()) {
String permission = iter.next();
if (plugin.permission.playerHas(player, permission)) { if (plugin.permission.playerHas(player, permission)) {
plugin.permission.playerAddTransient(player, permission); plugin.permission.playerAddTransient(player, permission);
} }
} }
} }
public boolean isUnrestricted(Player player) { // TODO: Move to a Manager
if (!Settings.isAllowRestrictedIp) public static boolean checkAuth(Player player) {
return false; if (player == null || Utils.isUnrestricted(player)) {
if (Settings.getUnrestrictedName == null || Settings.getUnrestrictedName.isEmpty())
return false;
return (Settings.getUnrestrictedName.contains(player.getName()));
}
public static Utils getInstance() {
singleton = new Utils(AuthMe.getInstance());
return singleton;
}
private boolean useGroupSystem() {
if (Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty())
return true; return true;
}
String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name)) {
return true;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return true;
}
}
return false; return false;
} }
public void packCoords(double x, double y, double z, String w, public static boolean isUnrestricted(Player player) {
final Player pl) { return Settings.isAllowRestrictedIp && !(Settings.getUnrestrictedName == null || Settings.getUnrestrictedName.isEmpty()) && (Settings.getUnrestrictedName.contains(player.getName()));
}
private static boolean useGroupSystem() {
return Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty();
}
public static void packCoords(double x, double y, double z, String w,
final Player pl) {
World theWorld; World theWorld;
if (w.equals("unavailableworld")) { if (w.equals("unavailableworld")) {
theWorld = pl.getWorld(); theWorld = pl.getWorld();
@ -161,29 +228,66 @@ public class Utils {
* Used for force player GameMode * Used for force player GameMode
*/ */
public static void forceGM(Player player) { public static void forceGM(Player player) {
if (!AuthMe.getInstance().authmePermissible(player, "authme.bypassforcesurvival")) if (!plugin.authmePermissible(player, "authme.bypassforcesurvival"))
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
} }
public enum groupType { public enum GroupType {
UNREGISTERED, UNREGISTERED,
REGISTERED, REGISTERED,
NOTLOGGEDIN, NOTLOGGEDIN,
LOGGEDIN LOGGEDIN
} }
public static void purgeDirectory(File file){ public static void purgeDirectory(File file) {
String files[] = file.list(); if (!file.isDirectory()) {
if (files != null && files.length != 0){ return;
for (String temp : files) { }
File fileDelete = new File(file, temp); File[] files = file.listFiles();
if (fileDelete.isDirectory()){ if (files == null) {
purgeDirectory(fileDelete); return;
fileDelete.delete(); }
} else { for (File target : files) {
fileDelete.delete(); if (target.isDirectory()) {
} purgeDirectory(target);
target.delete();
} else {
target.delete();
} }
} }
} }
@SuppressWarnings("unchecked")
public static Collection<? extends Player> getOnlinePlayers() {
if (getOnlinePlayersIsCollection) {
return Bukkit.getOnlinePlayers();
}
try {
if (getOnlinePlayers == null) {
getOnlinePlayers = Bukkit.class.getMethod("getOnlinePlayers");
}
Object obj = getOnlinePlayers.invoke(null);
if (obj instanceof Collection) {
return (Collection<? extends Player>) obj;
}
return Arrays.asList((Player[]) obj);
} catch (Exception ignored) {
}
return Collections.emptyList();
}
public static boolean isNPC(final Entity player) {
try {
if (player.hasMetadata("NPC")) {
return true;
} else if (plugin.combatTagPlus != null
&& player instanceof Player
&& plugin.combatTagPlus.getNpcPlayerHelper().isNpc((Player) player)) {
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
} }

View File

@ -12,7 +12,6 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -65,9 +64,7 @@ public class API {
*/ */
@Deprecated @Deprecated
public boolean isaNPC(Player player) { public boolean isaNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player)) return Utils.isNPC(player);
return true;
return CombatTagComunicator.isNPC(player);
} }
/** /**
@ -77,9 +74,7 @@ public class API {
*/ */
@Deprecated @Deprecated
public boolean isNPC(Player player) { public boolean isNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player)) return Utils.isNPC(player);
return true;
return CombatTagComunicator.isNPC(player);
} }
/** /**
@ -89,7 +84,7 @@ public class API {
*/ */
@Deprecated @Deprecated
public static boolean isUnrestricted(Player player) { public static boolean isUnrestricted(Player player) {
return Utils.getInstance().isUnrestricted(player); return Utils.isUnrestricted(player);
} }
@Deprecated @Deprecated

View File

@ -14,7 +14,6 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -34,9 +33,7 @@ public class NewAPI {
/** /**
* Hook into AuthMe * Hook into AuthMe
* *
* @return
*
* @return AuthMe plugin * @return AuthMe plugin
*/ */
public static NewAPI getInstance() { public static NewAPI getInstance() {
@ -70,9 +67,7 @@ public class NewAPI {
* @return true if player is a npc * @return true if player is a npc
*/ */
public boolean isNPC(Player player) { public boolean isNPC(Player player) {
if (plugin.getCitizensCommunicator().isNPC(player)) return Utils.isNPC(player);
return true;
return CombatTagComunicator.isNPC(player);
} }
/** /**
@ -81,7 +76,7 @@ public class NewAPI {
* @return true if the player is unrestricted * @return true if the player is unrestricted
*/ */
public boolean isUnrestricted(Player player) { public boolean isUnrestricted(Player player) {
return Utils.getInstance().isUnrestricted(player); return Utils.isUnrestricted(player);
} }
public Location getLastLocation(Player player) { public Location getLastLocation(Player player) {
@ -89,8 +84,7 @@ public class NewAPI {
PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
if (auth != null) { if (auth != null) {
Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); return new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
return loc;
} else { } else {
return null; return null;
} }
@ -152,10 +146,7 @@ public class NewAPI {
return false; return false;
} }
PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0, "your@email.com"); PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0, "your@email.com");
if (!plugin.database.saveAuth(auth)) { return plugin.database.saveAuth(auth);
return false;
}
return true;
} catch (NoSuchAlgorithmException ex) { } catch (NoSuchAlgorithmException ex) {
return false; return false;
} }

View File

@ -8,7 +8,7 @@ public class PlayerCache {
private ConcurrentHashMap<String, PlayerAuth> cache; private ConcurrentHashMap<String, PlayerAuth> cache;
private PlayerCache() { private PlayerCache() {
cache = new ConcurrentHashMap<String, PlayerAuth>(); cache = new ConcurrentHashMap<>();
} }
public void addPlayer(PlayerAuth auth) { public void addPlayer(PlayerAuth auth) {

View File

@ -11,8 +11,7 @@ public class DataFileCache {
private boolean flying; private boolean flying;
public DataFileCache(ItemStack[] inventory, ItemStack[] armor) { public DataFileCache(ItemStack[] inventory, ItemStack[] armor) {
this.inventory = inventory; this(inventory, armor, "", false, false);
this.armor = armor;
} }
public DataFileCache(ItemStack[] inventory, ItemStack[] armor, public DataFileCache(ItemStack[] inventory, ItemStack[] armor,

View File

@ -1,570 +0,0 @@
package fr.xephi.authme.cache.backup;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.comphenix.attribute.Attributes;
import com.comphenix.attribute.Attributes.Attribute;
import com.comphenix.attribute.Attributes.Attribute.Builder;
import com.comphenix.attribute.Attributes.AttributeType;
import com.comphenix.attribute.Attributes.Operation;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.api.API;
import fr.xephi.authme.settings.Settings;
public class FileCache {
private AuthMe plugin;
public FileCache(AuthMe plugin) {
this.plugin = plugin;
final File file = new File(plugin.getDataFolder() + File.separator + "cache");
if (!file.exists())
file.mkdir();
}
public void createCache(Player player, DataFileCache playerData,
String group, boolean operator, boolean flying) {
String path = "";
if (player == null)
return;
try {
path = player.getUniqueId().toString();
} catch (Exception e) {
path = player.getName().toLowerCase();
} catch (Error e) {
path = player.getName().toLowerCase();
}
File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
if (file.exists()) {
return;
}
FileWriter writer = null;
try {
file.createNewFile();
writer = new FileWriter(file);
writer.write(group + API.newline);
writer.write(String.valueOf(operator) + API.newline);
writer.write(String.valueOf(flying) + API.newline);
writer.close();
file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory");
file.mkdirs();
ItemStack[] inv = playerData.getInventory();
for (int i = 0; i < inv.length; i++) {
ItemStack item = inv[i];
file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache");
file.createNewFile();
writer = new FileWriter(file);
if (item != null) {
if (item.getType() == Material.AIR) {
writer.write("AIR");
writer.close();
continue;
}
writer.write(item.getType().name() + API.newline);
writer.write(item.getDurability() + API.newline);
writer.write(item.getAmount() + API.newline);
writer.flush();
if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName())
writer.write("name=" + meta.getDisplayName() + API.newline);
if (meta.hasLore()) {
String lores = "";
for (String lore : meta.getLore())
lores = lore + "%newline%";
writer.write("lore=" + lores + API.newline);
}
if (meta.hasEnchants()) {
for (Enchantment ench : meta.getEnchants().keySet()) {
writer.write("metaenchant=" + ench.getName() + ":" + meta.getEnchants().get(ench) + API.newline);
}
}
writer.flush();
}
for (Enchantment ench : item.getEnchantments().keySet()) {
writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
}
if (Settings.customAttributes) {
try {
Attributes attributes = new Attributes(item);
if (attributes != null) {
Iterator<Attribute> iter = attributes.values().iterator();
Attribute a = null;
while (iter.hasNext()) {
Attribute b = iter.next();
if (a != null && a == b)
break;
a = b;
if (a != null) {
if (a.getName() != null && a.getAttributeType() != null && a.getOperation() != null && a.getUUID() != null)
writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
}
}
}
} catch (Exception e) {
} catch (Error e) {
}
}
} else {
writer.write("AIR");
}
writer.close();
}
file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours");
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
file.mkdirs();
ItemStack[] armors = playerData.getArmour();
for (int i = 0; i < armors.length; i++) {
ItemStack item = armors[i];
file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache");
file.createNewFile();
writer = new FileWriter(file);
if (item != null) {
if (item.getType() == Material.AIR) {
writer.write("AIR");
writer.close();
continue;
}
writer.write(item.getType().name() + API.newline);
writer.write(item.getDurability() + API.newline);
writer.write(item.getAmount() + API.newline);
writer.flush();
if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName())
writer.write("name=" + meta.getDisplayName() + API.newline);
if (meta.hasLore()) {
String lores = "";
for (String lore : meta.getLore())
lores = lore + "%newline%";
writer.write("lore=" + lores + API.newline);
}
writer.flush();
}
for (Enchantment ench : item.getEnchantments().keySet()) {
writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
}
if (Settings.customAttributes) {
try {
Attributes attributes = new Attributes(item);
if (attributes != null)
while (attributes.values().iterator().hasNext()) {
Attribute a = attributes.values().iterator().next();
if (a != null) {
if (a.getName() != null && a.getAttributeType() != null && a.getOperation() != null && a.getUUID() != null && a.getAttributeType().getMinecraftId() != null)
writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
}
}
} catch (Exception e) {
}
}
} else {
writer.write("AIR" + API.newline);
}
writer.close();
}
} catch (final Exception e) {
ConsoleLogger.showError("Some error on creating file cache...");
}
}
public DataFileCache readCache(Player player) {
String path = "";
try {
path = player.getUniqueId().toString();
} catch (Exception e) {
path = player.getName().toLowerCase();
} catch (Error e) {
path = player.getName().toLowerCase();
}
try {
File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
String playername = player.getName().toLowerCase();
if (!file.exists()) {
// OLD METHOD
file = new File("cache/" + playername + ".cache");
ItemStack[] stacki = new ItemStack[36];
ItemStack[] stacka = new ItemStack[4];
if (!file.exists()) {
return new DataFileCache(stacki, stacka);
}
String group = null;
boolean op = false;
boolean flying = false;
Scanner reader = new Scanner(file);
int i = 0;
int a = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
if (!line.contains(":")) {
// the fist line represent the player group,
// operator
// status
// and flying status
final String[] playerInfo = line.split(";");
group = playerInfo[0];
if (Integer.parseInt(playerInfo[1]) == 1) {
op = true;
} else op = false;
if (playerInfo.length > 2) {
if (Integer.parseInt(playerInfo[2]) == 1)
flying = true;
else flying = false;
}
continue;
}
if (!line.startsWith("i") && !line.startsWith("w")) {
continue;
}
String lores = "";
String name = "";
if (line.split("\\*").length > 1) {
lores = line.split("\\*")[1];
line = line.split("\\*")[0];
}
if (line.split(";").length > 1) {
name = line.split(";")[1];
line = line.split(";")[0];
}
final String[] in = line.split(":");
// can enchant item? size ofstring in file - 4 all / 2 =
// number
// of enchant
if (in[0].equals("i")) {
stacki[i] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
if (in.length > 4 && !in[4].isEmpty()) {
for (int k = 4; k < in.length - 1; k++) {
stacki[i].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
k++;
}
}
ItemMeta meta = stacki[i].getItemMeta();
if (!name.isEmpty()) {
meta.setDisplayName(name);
}
if (!lores.isEmpty()) {
List<String> loreList = new ArrayList<String>();
for (String s : lores.split("%newline%")) {
loreList.add(s);
}
meta.setLore(loreList);
}
if (meta != null)
stacki[i].setItemMeta(meta);
i++;
} else {
stacka[a] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
if (in.length > 4 && !in[4].isEmpty()) {
for (int k = 4; k < in.length - 1; k++) {
stacka[a].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
k++;
}
}
ItemMeta meta = stacka[a].getItemMeta();
if (!name.isEmpty())
meta.setDisplayName(name);
if (!lores.isEmpty()) {
List<String> loreList = new ArrayList<String>();
for (String s : lores.split("%newline%")) {
loreList.add(s);
}
meta.setLore(loreList);
}
if (meta != null)
stacki[i].setItemMeta(meta);
a++;
}
}
if (reader != null)
reader.close();
return new DataFileCache(stacki, stacka, group, op, flying);
} else {
// NEW METHOD
ItemStack[] inv = new ItemStack[36];
ItemStack[] armours = new ItemStack[4];
String group = null;
boolean op = false;
boolean flying = false;
Scanner reader = null;
try {
reader = new Scanner(file);
int count = 1;
while (reader.hasNextLine()) {
String line = reader.nextLine();
switch (count) {
case 1:
group = line;
break;
case 2:
op = Boolean.parseBoolean(line);
break;
case 3:
flying = Boolean.parseBoolean(line);
break;
default:
break;
}
count++;
}
if (reader != null)
reader.close();
for (int i = 0; i < inv.length; i++) {
reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache"));
ItemStack item = new ItemStack(Material.AIR);
ItemMeta meta = item.getItemMeta();
Attributes attributes = null;
count = 1;
boolean v = true;
while (reader.hasNextLine() && v == true) {
String line = reader.nextLine();
switch (count) {
case 1:
item = new ItemStack(Material.getMaterial(line));
if (item.getType() == Material.AIR)
v = false;
meta = item.getItemMeta();
count++;
continue;
case 2:
item.setDurability((short) Integer.parseInt(line));
count++;
continue;
case 3:
item.setAmount(Integer.parseInt(line));
count++;
continue;
default:
break;
}
meta = item.getItemMeta();
if (line.startsWith("name=")) {
line = line.substring(5);
meta.setDisplayName(line);
item.setItemMeta(meta);
continue;
}
if (line.startsWith("lore=")) {
line = line.substring(5);
List<String> lore = new ArrayList<String>();
for (String s : line.split("%newline%"))
lore.add(s);
meta.setLore(lore);
item.setItemMeta(meta);
continue;
}
if (line.startsWith("enchant=")) {
line = line.substring(8);
item.addEnchantment(Enchantment.getByName(line.split(":")[0]), Integer.parseInt(line.split(":")[1]));
continue;
}
if (Settings.customAttributes) {
if (line.startsWith("attribute=")) {
if (attributes == null)
attributes = new Attributes(item);
try {
line = line.substring(10);
String[] args = line.split(";");
if (args.length != 5)
continue;
String name = args[0];
AttributeType type = AttributeType.fromId(args[1]);
double amount = Double.parseDouble(args[2]);
Operation operation = Operation.fromId(Integer.parseInt(args[3]));
UUID uuid = UUID.fromString(args[4]);
Builder build = Attribute.newBuilder();
build.amount(amount);
build.operation(operation);
build.type(type);
build.name(name);
build.uuid(uuid);
attributes.add(build.build());
} catch (Exception e) {
}
}
}
count++;
}
if (reader != null)
reader.close();
if (Settings.customAttributes && attributes != null)
inv[i] = attributes.getStack();
else inv[i] = item;
}
for (int i = 0; i < armours.length; i++) {
reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache"));
ItemStack item = new ItemStack(Material.AIR);
ItemMeta meta = null;
Attributes attributes = null;
count = 1;
boolean v = true;
while (reader.hasNextLine() && v == true) {
String line = reader.nextLine();
switch (count) {
case 1:
item = new ItemStack(Material.getMaterial(line));
if (item.getType() == Material.AIR)
v = false;
meta = item.getItemMeta();
count++;
continue;
case 2:
item.setDurability((short) Integer.parseInt(line));
count++;
continue;
case 3:
item.setAmount(Integer.parseInt(line));
count++;
continue;
default:
break;
}
meta = item.getItemMeta();
if (line.startsWith("name=")) {
line = line.substring(5);
meta.setDisplayName(line);
item.setItemMeta(meta);
continue;
}
if (line.startsWith("lore=")) {
line = line.substring(5);
List<String> lore = new ArrayList<String>();
for (String s : line.split("%newline%"))
lore.add(s);
meta.setLore(lore);
item.setItemMeta(meta);
continue;
}
if (line.startsWith("enchant=")) {
line = line.substring(8);
item.addEnchantment(Enchantment.getByName(line.split(":")[0]), Integer.parseInt(line.split(":")[1]));
}
if (Settings.customAttributes) {
if (line.startsWith("attribute=")) {
if (attributes == null)
attributes = new Attributes(item);
try {
line = line.substring(10);
String[] args = line.split(";");
if (args.length != 5)
continue;
String name = args[0];
AttributeType type = AttributeType.fromId(args[1]);
double amount = Double.parseDouble(args[2]);
Operation operation = Operation.fromId(Integer.parseInt(args[3]));
UUID uuid = UUID.fromString(args[4]);
Builder build = Attribute.newBuilder();
build.amount(amount);
build.operation(operation);
build.type(type);
build.name(name);
build.uuid(uuid);
attributes.add(build.build());
} catch (Exception e) {
}
}
}
count++;
}
if (reader != null)
reader.close();
if (attributes != null)
armours[i] = attributes.getStack();
else armours[i] = item;
}
} catch (final RuntimeException e) {
ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
} catch (final Exception e) {
ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
} finally {
if (reader != null)
reader.close();
}
return new DataFileCache(inv, armours, group, op, flying);
}
} catch (RuntimeException e) {
ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
return null;
} catch (Exception e) {
ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
return null;
}
}
public void removeCache(Player player) {
String path = "";
try {
path = player.getUniqueId().toString();
} catch (Exception e) {
path = player.getName().toLowerCase();
} catch (Error e) {
path = player.getName().toLowerCase();
}
try {
File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path);
if (file.list() != null) {
Utils.purgeDirectory(file);
file.delete();
} else {
file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + player.getName().toLowerCase() + ".cache");
if (file.isFile()) {
file.delete();
} else {
ConsoleLogger.showError("Failed to remove" + player.getName() + "cache, it doesn't exist!");
}
}
} catch (Exception e) {
ConsoleLogger.showError("Failed to remove" + player.getName() + "cache :/");
}
}
public boolean doesCacheExist(Player player) {
String path = "";
try {
path = player.getUniqueId().toString();
} catch (Exception e) {
path = player.getName().toLowerCase();
} catch (Error e) {
path = player.getName().toLowerCase();
}
File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
if (!file.exists()) {
file = new File("cache/" + player.getName().toLowerCase() + ".cache");
}
return file.exists();
}
}

View File

@ -0,0 +1,232 @@
package fr.xephi.authme.cache.backup;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.gson.*;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.settings.Settings;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
public class JsonCache {
private final Gson gson;
private final AuthMe plugin;
private final File cacheDir;
public JsonCache(AuthMe plugin) {
this.plugin = plugin;
cacheDir = Settings.CACHE_FOLDER;
if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) {
ConsoleLogger.showError("Failed to create cache directory.");
}
gson = new GsonBuilder()
.registerTypeAdapter(DataFileCache.class, new PlayerDataSerializer())
.registerTypeAdapter(DataFileCache.class, new PlayerDataDeserializer())
.setPrettyPrinting()
.create();
}
public void createCache(Player player, DataFileCache playerData) {
if (player == null) {
return;
}
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path + File.separator + "cache.json");
if (file.exists()) {
return;
}
if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
return;
}
try {
String data = gson.toJson(playerData);
Files.touch(file);
Files.write(data, file, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public DataFileCache readCache(Player player) {
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path + File.separator + "cache.json");
if (!file.exists()) {
return null;
}
try {
String str = Files.toString(file, Charsets.UTF_8);
return gson.fromJson(str, DataFileCache.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private class PlayerDataSerializer implements JsonSerializer<DataFileCache> {
@Override
public JsonElement serialize(DataFileCache dataFileCache, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("group", dataFileCache.getGroup());
jsonObject.addProperty("operator", dataFileCache.getOperator());
jsonObject.addProperty("flying", dataFileCache.isFlying());
JsonArray arr;
ItemStack[] contents;
// inventory
contents = dataFileCache.getInventory();
arr = new JsonArray();
putItems(contents, arr);
jsonObject.add("inventory", arr);
// armour
contents = dataFileCache.getArmour();
arr = new JsonArray();
putItems(contents, arr);
jsonObject.add("armour", arr);
return jsonObject;
}
private void putItems(ItemStack[] contents, JsonArray target) {
for (ItemStack item : contents) {
if (item == null) {
item = new ItemStack(Material.AIR);
}
JsonObject val = new JsonObject();
if (item.getType() == Material.SKULL_ITEM) {
SkullMeta meta = (SkullMeta) item.getItemMeta();
if (meta.hasOwner() && (meta.getOwner() == null || meta.getOwner().isEmpty())) {
item.setItemMeta(plugin.getServer().getItemFactory().getItemMeta(Material.SKULL_ITEM));
}
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BukkitObjectOutputStream objectOut = new BukkitObjectOutputStream(baos);
objectOut.writeObject(item);
objectOut.close();
val.addProperty("item", Base64Coder.encodeLines(baos.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
continue;
}
target.add(val);
}
}
}
private static class PlayerDataDeserializer implements JsonDeserializer<DataFileCache> {
@Override
public DataFileCache deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject == null) {
return null;
}
JsonElement e;
String group = null;
boolean operator = false;
boolean flying = false;
if ((e = jsonObject.get("group")) != null) {
group = e.getAsString();
}
if ((e = jsonObject.get("operator")) != null) {
operator = e.getAsBoolean();
}
if ((e = jsonObject.get("flying")) != null) {
flying = e.getAsBoolean();
}
JsonArray arr;
ItemStack[] inv = null;
ItemStack[] armour = null;
if (jsonObject.has("inventory")) {
arr = jsonObject.get("inventory").getAsJsonArray();
inv = getItems(arr);
}
if (jsonObject.has("armour")) {
arr = jsonObject.get("armour").getAsJsonArray();
armour = getItems(arr);
}
return new DataFileCache(inv, armour, group, operator, flying);
}
private ItemStack[] getItems(JsonArray arr) {
ItemStack[] contents = new ItemStack[arr.size()];
for (int i = 0; i < arr.size(); i++) {
JsonObject item = arr.get(i).getAsJsonObject();
String encoded = item.get("item").getAsString();
byte[] decoded = Base64Coder.decodeLines(encoded);
try {
ByteArrayInputStream baos = new ByteArrayInputStream(decoded);
BukkitObjectInputStream objectIn = new BukkitObjectInputStream(baos);
contents[i] = (ItemStack) objectIn.readObject();
objectIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return contents;
}
}
public void removeCache(Player player) {
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path);
if (file.exists()) {
Utils.purgeDirectory(file);
if (!file.delete()) {
ConsoleLogger.showError("Failed to remove" + player.getName() + "cache.");
}
}
}
public boolean doesCacheExist(Player player) {
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path + File.separator + "cache.json");
return file.exists();
}
}

View File

@ -1,31 +1,31 @@
package fr.xephi.authme.cache.limbo; package fr.xephi.authme.cache.limbo;
import java.util.concurrent.ConcurrentHashMap; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.backup.DataFileCache;
import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.events.ResetInventoryEvent;
import fr.xephi.authme.events.StoreInventoryEvent;
import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import fr.xephi.authme.AuthMe; import java.util.concurrent.ConcurrentHashMap;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.backup.FileCache;
import fr.xephi.authme.events.ResetInventoryEvent;
import fr.xephi.authme.events.StoreInventoryEvent;
import fr.xephi.authme.settings.Settings;
public class LimboCache { public class LimboCache {
private volatile static LimboCache singleton = null; private volatile static LimboCache singleton;
public ConcurrentHashMap<String, LimboPlayer> cache; public ConcurrentHashMap<String, LimboPlayer> cache;
private FileCache playerData; private JsonCache playerData;
public AuthMe plugin; public AuthMe plugin;
private LimboCache(AuthMe plugin) { private LimboCache(AuthMe plugin) {
this.plugin = plugin; this.plugin = plugin;
this.cache = new ConcurrentHashMap<String, LimboPlayer>(); this.cache = new ConcurrentHashMap<>();
this.playerData = new FileCache(plugin); this.playerData = new JsonCache(plugin);
} }
public void addLimboPlayer(Player player) { public void addLimboPlayer(Player player) {
@ -48,12 +48,11 @@ public class LimboCache {
inv = null; inv = null;
arm = null; arm = null;
} }
try { DataFileCache cache = playerData.readCache(player);
playerGroup = playerData.readCache(player).getGroup(); if (cache != null) {
operator = playerData.readCache(player).getOperator(); playerGroup = cache.getGroup();
flying = playerData.readCache(player).isFlying(); operator = cache.getOperator();
} catch (Exception e) { flying = cache.isFlying();
ConsoleLogger.showError("Some error on reading cache of " + name);
} }
} else { } else {
StoreInventoryEvent event = new StoreInventoryEvent(player); StoreInventoryEvent event = new StoreInventoryEvent(player);
@ -65,12 +64,8 @@ public class LimboCache {
inv = null; inv = null;
arm = null; arm = null;
} }
if (player.isOp()) operator = player.isOp();
operator = true; flying = player.isFlying();
else operator = false;
if (player.isFlying())
flying = true;
else flying = false;
if (plugin.permission != null) { if (plugin.permission != null) {
try { try {
playerGroup = plugin.permission.getPrimaryGroup(player); playerGroup = plugin.permission.getPrimaryGroup(player);
@ -82,7 +77,7 @@ public class LimboCache {
} }
if (Settings.isForceSurvivalModeEnabled) { if (Settings.isForceSurvivalModeEnabled) {
if (Settings.isResetInventoryIfCreative && player.getGameMode() == GameMode.CREATIVE) { if (Settings.isResetInventoryIfCreative && gameMode == GameMode.CREATIVE) {
ResetInventoryEvent event = new ResetInventoryEvent(player); ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
@ -128,7 +123,7 @@ public class LimboCache {
if (this.hasLimboPlayer(player.getName().toLowerCase())) { if (this.hasLimboPlayer(player.getName().toLowerCase())) {
this.deleteLimboPlayer(player.getName().toLowerCase()); this.deleteLimboPlayer(player.getName().toLowerCase());
} }
this.addLimboPlayer(player); addLimboPlayer(player);
} }
} }

View File

@ -1,31 +1,9 @@
package fr.xephi.authme.commands; package fr.xephi.authme.commands;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.groupType; import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
@ -36,6 +14,23 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn; import fr.xephi.authme.settings.Spawn;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.task.TimeoutTask;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class AdminCommand implements CommandExecutor { public class AdminCommand implements CommandExecutor {
@ -48,7 +43,7 @@ public class AdminCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(final CommandSender sender, Command cmnd, public boolean onCommand(final CommandSender sender, Command cmnd,
String label, String[] args) { String label, String[] args) {
if (args.length == 0) { if (args.length == 0) {
sender.sendMessage("Usage:"); sender.sendMessage("Usage:");
sender.sendMessage("/authme reload - Reload the config"); sender.sendMessage("/authme reload - Reload the config");
@ -113,44 +108,23 @@ public class AdminCommand implements CommandExecutor {
return true; return true;
} }
} else if (args[0].equalsIgnoreCase("reload")) { } else if (args[0].equalsIgnoreCase("reload")) {
File newConfigFile = new File("plugins" + File.separator + "AuthMe", "config.yml"); try {
if (!newConfigFile.exists()) { plugin.getSettings().reload();
InputStream fis = getClass().getResourceAsStream("" + File.separator + "config.yml"); m.reloadMessages();
FileOutputStream fos = null; plugin.database.close();
try { plugin.setupDatabase();
fos = new FileOutputStream(newConfigFile); } catch (Exception e) {
byte[] buf = new byte[1024]; ConsoleLogger.showError("Fatal error occurred! Authme instance ABORTED!");
int i = 0; plugin.stopOrUnload();
return false;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (Exception e) {
ConsoleLogger.showError("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.reloadMessages();
plugin.database.close();
plugin.setupDatabase();
m.send(sender, "reload"); m.send(sender, "reload");
} else if (args[0].equalsIgnoreCase("lastlogin")) { } else if (args[0].equalsIgnoreCase("lastlogin")) {
if (args.length != 2) { if (args.length != 2) {
sender.sendMessage("Usage: /authme lastlogin <playername>"); sender.sendMessage("Usage: /authme lastlogin <playername>");
return true; return true;
} }
PlayerAuth auth = null; PlayerAuth auth;
try { try {
auth = plugin.database.getAuth(args[1].toLowerCase()); auth = plugin.database.getAuth(args[1].toLowerCase());
} catch (NullPointerException e) { } catch (NullPointerException e) {
@ -176,92 +150,89 @@ public class AdminCommand implements CommandExecutor {
return true; return true;
} }
if (!args[1].contains(".")) { if (!args[1].contains(".")) {
final CommandSender fSender = sender;
final String[] arguments = args; final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
PlayerAuth auth = null; PlayerAuth auth;
String message = "[AuthMe] "; StringBuilder message = new StringBuilder("[AuthMe] ");
try { try {
auth = plugin.database.getAuth(arguments[1].toLowerCase()); auth = plugin.database.getAuth(arguments[1].toLowerCase());
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
m.send(fSender, "unknown_user"); m.send(sender, "unknown_user");
return; return;
} }
if (auth == null) { if (auth == null) {
m.send(fSender, "unknown_user"); m.send(sender, "unknown_user");
return; return;
} }
List<String> accountList = plugin.database.getAllAuthsByName(auth); List<String> accountList = plugin.database.getAllAuthsByName(auth);
if (accountList == null || accountList.isEmpty()) { if (accountList == null || accountList.isEmpty()) {
m.send(fSender, "user_unknown"); m.send(sender, "user_unknown");
return; return;
} }
if (accountList.size() == 1) { if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return; return;
} }
int i = 0; int i = 0;
for (String account : accountList) { for (String account : accountList) {
i++; i++;
message = message + account; message.append(account);
if (i != accountList.size()) { if (i != accountList.size()) {
message = message + ", "; message.append(", ");
} else { } else {
message = message + "."; message.append(".");
} }
} }
fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
fSender.sendMessage(message); sender.sendMessage(message.toString());
} }
}); });
return true; return true;
} else { } else {
final CommandSender fSender = sender;
final String[] arguments = args; final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
String message = "[AuthMe] "; StringBuilder message = new StringBuilder("[AuthMe] ");
if (arguments[1] == null) { if (arguments[1] == null) {
fSender.sendMessage("[AuthMe] Please put a valid IP"); sender.sendMessage("[AuthMe] Please put a valid IP");
return; return;
} }
List<String> accountList = plugin.database.getAllAuthsByIp(arguments[1]); List<String> accountList = plugin.database.getAllAuthsByIp(arguments[1]);
if (accountList == null || accountList.isEmpty()) { if (accountList == null || accountList.isEmpty()) {
fSender.sendMessage("[AuthMe] This IP does not exist in the database"); sender.sendMessage("[AuthMe] This IP does not exist in the database");
return; return;
} }
if (accountList.size() == 1) { if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return; return;
} }
int i = 0; int i = 0;
for (String account : accountList) { for (String account : accountList) {
i++; i++;
message = message + account; message.append(account);
if (i != accountList.size()) { if (i != accountList.size()) {
message = message + ", "; message.append(", ");
} else { } else {
message = message + "."; message.append(".");
} }
} }
fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
fSender.sendMessage(message); sender.sendMessage(message.toString());
} }
}); });
return true; return true;
} }
} else } else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
if (args.length != 3) { if (args.length != 3) {
sender.sendMessage("Usage: /authme register <playername> <password>"); sender.sendMessage("Usage: /authme register <playername> <password>");
return true; return true;
} }
String lowpass = args[2].toLowerCase(); final String name = args[1].toLowerCase();
final String lowpass = args[2].toLowerCase();
if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) { if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
m.send(sender, "password_error"); m.send(sender, "password_error");
return true; return true;
@ -280,27 +251,32 @@ public class AdminCommand implements CommandExecutor {
return true; return true;
} }
} }
try { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
String name = args[1].toLowerCase(); @Override
if (plugin.database.isAuthAvailable(name)) { public void run() {
m.send(sender, "user_regged"); try {
return true; if (plugin.database.isAuthAvailable(name)) {
m.send(sender, "user_regged");
return;
}
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, lowpass, name);
PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com");
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
auth.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt("");
if (!plugin.database.saveAuth(auth)) {
m.send(sender, "error");
return;
}
m.send(sender, "registered");
ConsoleLogger.info(name + " registered");
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m.send(sender, "error");
}
} }
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name); });
PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com");
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
auth.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt("");
if (!plugin.database.saveAuth(auth)) {
m.send(sender, "error");
return true;
}
m.send(sender, "registered");
ConsoleLogger.info(args[1] + " registered");
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m.send(sender, "error");
}
return true; return true;
} else if (args[0].equalsIgnoreCase("getemail")) { } else if (args[0].equalsIgnoreCase("getemail")) {
if (args.length != 2) { if (args.length != 2) {
@ -368,7 +344,7 @@ public class AdminCommand implements CommandExecutor {
} }
return true; return true;
} else if (args[0].equalsIgnoreCase("purgebannedplayers")) { } else if (args[0].equalsIgnoreCase("purgebannedplayers")) {
List<String> bannedPlayers = new ArrayList<String>(); List<String> bannedPlayers = new ArrayList<>();
for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) { for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) {
bannedPlayers.add(off.getName().toLowerCase()); bannedPlayers.add(off.getName().toLowerCase());
} }
@ -409,8 +385,7 @@ public class AdminCommand implements CommandExecutor {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} }
return true; return true;
} else } else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
if (args.length != 3) { if (args.length != 3) {
sender.sendMessage("Usage: /authme changepassword <playername> <newpassword>"); sender.sendMessage("Usage: /authme changepassword <playername> <newpassword>");
return true; return true;
@ -486,9 +461,10 @@ public class AdminCommand implements CommandExecutor {
m.send(sender, "error"); m.send(sender, "error");
return true; return true;
} }
@SuppressWarnings("deprecation")
Player target = Bukkit.getPlayer(name); Player target = Bukkit.getPlayer(name);
PlayerCache.getInstance().removePlayer(name); PlayerCache.getInstance().removePlayer(name);
Utils.getInstance().setGroup(name, groupType.UNREGISTERED); Utils.setGroup(target, GroupType.UNREGISTERED);
if (target != null) { if (target != null) {
if (target.isOnline()) { if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
@ -510,18 +486,17 @@ public class AdminCommand implements CommandExecutor {
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval))); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect)
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
target.setWalkSpeed(0.0f);
target.setFlySpeed(0.0f);
}
m.send(target, "unregistered"); m.send(target, "unregistered");
} else {
// Player isn't online, do nothing else
} }
} else {
// Player does not exist, do nothing else
} }
m.send(sender, "unregistered"); m.send(sender, "unregistered");
ConsoleLogger.info(args[1] + " unregistered"); ConsoleLogger.info(args[1] + " unregistered");
return true; return true;
} else } else if (args[0].equalsIgnoreCase("purgelastpos") || args[0].equalsIgnoreCase("resetposition")) {
if (args[0].equalsIgnoreCase("purgelastpos") || args[0].equalsIgnoreCase("resetposition")) {
if (args.length != 2) { if (args.length != 2) {
sender.sendMessage("Usage: /authme purgelastpos <playername>"); sender.sendMessage("Usage: /authme purgelastpos <playername>");
return true; return true;
@ -568,6 +543,7 @@ public class AdminCommand implements CommandExecutor {
sender.sendMessage("Usage: /authme getip <onlineplayername>"); sender.sendMessage("Usage: /authme getip <onlineplayername>");
return true; return true;
} }
@SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(args[1]); Player player = Bukkit.getPlayer(args[1]);
if (player == null) { if (player == null) {
sender.sendMessage("This player is not actually online"); sender.sendMessage("This player is not actually online");
@ -583,6 +559,7 @@ public class AdminCommand implements CommandExecutor {
return true; return true;
} }
try { try {
@SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(args[1]); Player player = Bukkit.getPlayer(args[1]);
if (player == null || !player.isOnline()) { if (player == null || !player.isOnline()) {
sender.sendMessage("Player needs to be online!"); sender.sendMessage("Player needs to be online!");

View File

@ -1,20 +1,15 @@
package fr.xephi.authme.commands; package fr.xephi.authme.commands;
import java.security.NoSuchAlgorithmException; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.ChangePasswordTask;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class ChangePasswordCommand implements CommandExecutor { public class ChangePasswordCommand implements CommandExecutor {
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
@ -26,7 +21,7 @@ public class ChangePasswordCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) { String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }
@ -67,30 +62,7 @@ public class ChangePasswordCommand implements CommandExecutor {
return true; return true;
} }
} }
try { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, args[0]));
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, args[1], name);
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
auth.setHash(hashnew);
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
auth.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt("");
if (!plugin.database.updatePassword(auth)) {
m.send(player, "error");
return true;
}
plugin.database.updateSalt(auth);
PlayerCache.getInstance().updatePlayer(auth);
m.send(player, "pwd_changed");
ConsoleLogger.info(player.getName() + " changed his password");
} else {
m.send(player, "wrong_pwd");
}
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m.send(sender, "error");
}
return true; return true;
} }
} }

View File

@ -1,15 +1,14 @@
package fr.xephi.authme.commands; package fr.xephi.authme.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.security.RandomString; import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class RegisterCommand implements CommandExecutor { public class RegisterCommand implements CommandExecutor {
@ -23,26 +22,23 @@ public class RegisterCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) { String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead"); sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead");
return true; return true;
} }
if (args.length == 0) { final Player player = (Player) sender;
m.send(sender, "usage_reg"); if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
} m.send(player, "usage_reg");
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) { return true;
m.send(sender, "no_perm"); }
if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
m.send(player, "no_perm");
return true; return true;
} }
final Player player = (Player) sender;
if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) { if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
if (Settings.doubleEmailCheck) { if (Settings.doubleEmailCheck) {
if (args.length < 2) { if (args.length < 2 || !args[0].equals(args[1])) {
m.send(player, "usage_reg");
return true;
}
if (!args[0].equals(args[1])) {
m.send(player, "usage_reg"); m.send(player, "usage_reg");
return true; return true;
} }
@ -57,10 +53,6 @@ public class RegisterCommand implements CommandExecutor {
plugin.management.performRegister(player, thePass, email); plugin.management.performRegister(player, thePass, email);
return true; return true;
} }
if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
m.send(player, "usage_reg");
return true;
}
if (args.length > 1 && Settings.getEnablePasswordVerifier) if (args.length > 1 && Settings.getEnablePasswordVerifier)
if (!args[0].equals(args[1])) { if (!args[0].equals(args[1])) {
m.send(player, "password_error"); m.send(player, "password_error");

View File

@ -1,7 +1,18 @@
package fr.xephi.authme.commands; package fr.xephi.authme.commands;
import java.security.NoSuchAlgorithmException; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
@ -13,34 +24,22 @@ import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe; import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.groupType;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.FileCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class UnregisterCommand implements CommandExecutor { public class UnregisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
public AuthMe plugin; public AuthMe plugin;
private FileCache playerCache; private JsonCache playerCache;
public UnregisterCommand(AuthMe plugin) { public UnregisterCommand(AuthMe plugin) {
this.plugin = plugin; this.plugin = plugin;
this.playerCache = new FileCache(plugin); this.playerCache = new JsonCache(plugin);
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, public boolean onCommand(final CommandSender sender, Command cmnd, String label,
String[] args) { final String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }
@ -50,8 +49,8 @@ public class UnregisterCommand implements CommandExecutor {
return true; return true;
} }
Player player = (Player) sender; final Player player = (Player) sender;
String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) { if (!PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "not_logged_in"); m.send(player, "not_logged_in");
@ -62,72 +61,81 @@ public class UnregisterCommand implements CommandExecutor {
m.send(player, "usage_unreg"); m.send(player, "usage_unreg");
return true; return true;
} }
try { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) { @Override
if (!plugin.database.removeAuth(name)) { public void run() {
player.sendMessage("error"); try {
return true; if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
} if (!plugin.database.removeAuth(name)) {
if (Settings.isForcedRegistrationEnabled) { player.sendMessage("error");
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { return;
Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
player.teleport(tpEvent.getTo());
} }
} if (Settings.isForcedRegistrationEnabled) {
player.getInventory().setContents(new ItemStack[36]); if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
player.getInventory().setArmorContents(new ItemStack[4]); Location spawn = plugin.getSpawnLocation(player);
player.saveData(); SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!Settings.getRegisteredGroup.isEmpty()) if (!tpEvent.isCancelled()) {
Utils.getInstance().setGroup(player, groupType.UNREGISTERED); player.teleport(tpEvent.getTo());
LimboCache.getInstance().addLimboPlayer(player); }
int delay = Settings.getRegistrationTimeout * 20; }
int interval = Settings.getWarnMessageInterval; player.getInventory().setContents(new ItemStack[36]);
BukkitScheduler sched = sender.getServer().getScheduler(); player.getInventory().setArmorContents(new ItemStack[4]);
if (delay != 0) { player.saveData();
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay); PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); if (!Settings.getRegisteredGroup.isEmpty())
} Utils.setGroup(player, GroupType.UNREGISTERED);
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval))); LimboCache.getInstance().addLimboPlayer(player);
m.send(player, "unregistered"); int delay = Settings.getRegistrationTimeout * 20;
ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); int interval = Settings.getWarnMessageInterval;
return true; BukkitScheduler sched = sender.getServer().getScheduler();
} if (delay != 0) {
if (!Settings.unRegisteredGroup.isEmpty()) { BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay);
Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
} }
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
// check if Player cache File Exist and delete it, preventing m.send(player, "unregistered");
// duplication of items ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
if (playerCache.doesCacheExist(player)) { return;
playerCache.removeCache(player);
}
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
m.send(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
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()); if (!Settings.unRegisteredGroup.isEmpty()) {
Utils.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(player)) {
playerCache.removeCache(player);
}
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setWalkSpeed(0.0f);
player.setFlySpeed(0.0f);
}
m.send(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
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());
}
}
return;
} else {
m.send(player, "wrong_pwd");
} }
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Internal Error please read the server log");
} }
return true;
} else {
m.send(player, "wrong_pwd");
} }
} catch (NoSuchAlgorithmException ex) { });
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Internal Error please read the server log");
}
return true; return true;
} }
} }

View File

@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
@ -70,10 +69,9 @@ public class CrazyLoginConverter implements Converter {
} }
users.close(); users.close();
ConsoleLogger.info("CrazyLogin database has been imported correctly"); ConsoleLogger.info("CrazyLogin database has been imported correctly");
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
ConsoleLogger.showError("Can't open the crazylogin database file! Does it exist?");
} }
} }

View File

@ -3,7 +3,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
@ -79,10 +78,9 @@ public class FlatToSql implements Converter {
sql.close(); sql.close();
br.close(); br.close();
ConsoleLogger.info("The FlatFile has been converted to authme.sql file"); ConsoleLogger.info("The FlatFile has been converted to authme.sql file");
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
ConsoleLogger.showError("Can't open the flat database file! Does it exist?");
} }
} }
} }

View File

@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.sql.Connection; import java.sql.Connection;
@ -90,12 +89,10 @@ public class FlatToSqlite implements Converter {
close(); close();
sender.sendMessage("The FlatFile has been converted to " + database + ".db file"); sender.sendMessage("The FlatFile has been converted to " + database + ".db file");
return; return;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Can't open the flat database file! Does it exist?");
} }
sender.sendMessage("Errors appears while trying to convert to SQLite");
return; return;
} }

View File

@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -100,12 +99,9 @@ public class RakamakConverter implements Converter {
} }
ConsoleLogger.info("Rakamak database has been imported correctly"); ConsoleLogger.info("Rakamak database has been imported correctly");
sender.sendMessage("Rakamak database has been imported correctly"); sender.sendMessage("Rakamak database has been imported correctly");
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Error file not found");
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Error IOException"); sender.sendMessage("Can't open the rakamak database file! Does it exist?");
} }
} }
} }

View File

@ -1,30 +1,36 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import org.bukkit.entity.Player;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
public class CacheDataSource implements DataSource { public class CacheDataSource implements DataSource {
private DataSource source; private final DataSource source;
public AuthMe plugin; private final AuthMe plugin;
private ConcurrentHashMap<String, PlayerAuth> cache = new ConcurrentHashMap<String, PlayerAuth>(); private ConcurrentHashMap<String, PlayerAuth> cache = new ConcurrentHashMap<>();
public CacheDataSource(AuthMe plugin, DataSource source) { public CacheDataSource(AuthMe pl, DataSource src) {
this.plugin = plugin; this.plugin = pl;
this.source = source; this.source = src;
/* /*
* We need to load all players in cache ... It will took more time to * We need to load all players in cache ... It will took more time to
* load the server, but it will be much easier to check for an * load the server, but it will be much easier to check for an
* isAuthAvailable ! * isAuthAvailable !
*/ */
for (PlayerAuth auth : source.getAllAuths()) pl.getServer().getScheduler().runTaskAsynchronously(pl, new Runnable() {
cache.put(auth.getNickname().toLowerCase(), auth); @Override
public void run() {
for (PlayerAuth auth : source.getAllAuths()) {
cache.put(auth.getNickname().toLowerCase(), auth);
}
}
});
} }
@Override @Override
@ -37,21 +43,22 @@ public class CacheDataSource implements DataSource {
user = user.toLowerCase(); user = user.toLowerCase();
if (cache.containsKey(user)) { if (cache.containsKey(user)) {
return cache.get(user); return cache.get(user);
} else {
PlayerAuth auth = source.getAuth(user);
if (auth != null)
cache.put(user, auth);
return auth;
} }
return null;
} }
@Override @Override
public synchronized boolean saveAuth(PlayerAuth auth) { public synchronized boolean saveAuth(final PlayerAuth auth) {
if (source.saveAuth(auth)) { cache.put(auth.getNickname(), auth);
cache.put(auth.getNickname(), auth); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
return true; @Override
} public void run() {
return false; if (!source.saveAuth(auth)) {
cache.remove(auth.getNickname());
}
}
});
return true;
} }
@Override @Override
@ -140,15 +147,11 @@ public class CacheDataSource implements DataSource {
public void reload() { public void reload() {
cache.clear(); cache.clear();
source.reload(); source.reload();
for (Player player : plugin.getServer().getOnlinePlayers()) { for (Player player : Utils.getOnlinePlayers()) {
String user = player.getName().toLowerCase(); String user = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(user)) { if (PlayerCache.getInstance().isAuthenticated(user)) {
try { PlayerAuth auth = source.getAuth(user);
PlayerAuth auth = source.getAuth(user); cache.put(user, auth);
cache.put(user, auth);
} catch (NullPointerException npe) {
}
} }
} }
} }

View File

@ -1,16 +1,16 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import java.util.List;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import java.util.List;
public interface DataSource { public interface DataSource {
public enum DataSourceType { enum DataSourceType {
MYSQL, MYSQL,
FILE, FILE,
SQLITE SQLITE,
SQLITEHIKARI
} }
boolean isAuthAvailable(String user); boolean isAuthAvailable(String user);

View File

@ -1,67 +1,42 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import fr.xephi.authme.cache.auth.PlayerAuth;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import fr.xephi.authme.cache.auth.PlayerAuth;
public class DatabaseCalls implements DataSource { public class DatabaseCalls implements DataSource {
private DataSource database; private DataSource database;
private final ExecutorService exec;
public DatabaseCalls(DataSource database) { public DatabaseCalls(DataSource database) {
this.database = database; this.database = database;
this.exec = Executors.newCachedThreadPool();
} }
@Override @Override
public synchronized boolean isAuthAvailable(final String user) { public synchronized boolean isAuthAvailable(final String user) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.isAuthAvailable(user); return database.isAuthAvailable(user);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized PlayerAuth getAuth(final String user) { public synchronized PlayerAuth getAuth(final String user) {
ExecutorService executor = Executors.newSingleThreadExecutor();
PlayerAuth result;
try { try {
result = executor.submit(new Callable<PlayerAuth>() { return exec.submit(new Callable<PlayerAuth>() {
public PlayerAuth call() throws Exception { public PlayerAuth call() throws Exception {
return database.getAuth(user); return database.getAuth(user);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return null;
} catch (ExecutionException e1) {
return null;
} finally {
executor.shutdown();
}
try {
return result;
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
@ -69,332 +44,183 @@ public class DatabaseCalls implements DataSource {
@Override @Override
public synchronized boolean saveAuth(final PlayerAuth auth) { public synchronized boolean saveAuth(final PlayerAuth auth) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.saveAuth(auth); return database.saveAuth(auth);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized boolean updateSession(final PlayerAuth auth) { public synchronized boolean updateSession(final PlayerAuth auth) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.updateSession(auth); return database.updateSession(auth);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized boolean updatePassword(final PlayerAuth auth) { public synchronized boolean updatePassword(final PlayerAuth auth) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.updatePassword(auth); return database.updatePassword(auth);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized int purgeDatabase(final long until) { public synchronized int purgeDatabase(final long until) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Integer result;
try { try {
result = executor.submit(new Callable<Integer>() { return exec.submit(new Callable<Integer>() {
public Integer call() throws Exception { public Integer call() throws Exception {
return database.purgeDatabase(until); return database.purgeDatabase(until);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return 0;
} catch (ExecutionException e1) {
return 0;
} finally {
executor.shutdown();
}
try {
return result.intValue();
} catch (Exception e) { } catch (Exception e) {
return (0); return -1;
} }
} }
@Override @Override
public synchronized List<String> autoPurgeDatabase(final long until) { public synchronized List<String> autoPurgeDatabase(final long until) {
ExecutorService executor = Executors.newSingleThreadExecutor();
List<String> result;
try { try {
result = executor.submit(new Callable<List<String>>() { return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception { public List<String> call() throws Exception {
return database.autoPurgeDatabase(until); return database.autoPurgeDatabase(until);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return new ArrayList<String>();
} catch (ExecutionException e1) {
return new ArrayList<String>();
} finally {
executor.shutdown();
}
try {
return result;
} catch (Exception e) { } catch (Exception e) {
return (new ArrayList<String>()); return new ArrayList<>();
} }
} }
@Override @Override
public synchronized boolean removeAuth(final String user) { public synchronized boolean removeAuth(final String user) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.removeAuth(user); return database.removeAuth(user);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized boolean updateQuitLoc(final PlayerAuth auth) { public synchronized boolean updateQuitLoc(final PlayerAuth auth) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.updateQuitLoc(auth); return database.updateQuitLoc(auth);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized int getIps(final String ip) { public synchronized int getIps(final String ip) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Integer result;
try { try {
result = executor.submit(new Callable<Integer>() { return exec.submit(new Callable<Integer>() {
public Integer call() throws Exception { public Integer call() throws Exception {
return database.getIps(ip); return database.getIps(ip);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return 0;
} catch (ExecutionException e1) {
return 0;
} finally {
executor.shutdown();
}
try {
return result.intValue();
} catch (Exception e) { } catch (Exception e) {
return (0); return -1;
} }
} }
@Override @Override
public synchronized List<String> getAllAuthsByName(final PlayerAuth auth) { public synchronized List<String> getAllAuthsByName(final PlayerAuth auth) {
ExecutorService executor = Executors.newSingleThreadExecutor();
List<String> result;
try { try {
result = executor.submit(new Callable<List<String>>() { return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception { public List<String> call() throws Exception {
return database.getAllAuthsByName(auth); return database.getAllAuthsByName(auth);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return new ArrayList<String>();
} catch (ExecutionException e1) {
return new ArrayList<String>();
} finally {
executor.shutdown();
}
try {
return result;
} catch (Exception e) { } catch (Exception e) {
return (new ArrayList<String>()); return new ArrayList<>();
} }
} }
@Override @Override
public synchronized List<String> getAllAuthsByIp(final String ip) { public synchronized List<String> getAllAuthsByIp(final String ip) {
ExecutorService executor = Executors.newSingleThreadExecutor();
List<String> result;
try { try {
result = executor.submit(new Callable<List<String>>() { return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception { public List<String> call() throws Exception {
return database.getAllAuthsByIp(ip); return database.getAllAuthsByIp(ip);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return new ArrayList<String>();
} catch (ExecutionException e1) {
return new ArrayList<String>();
} finally {
executor.shutdown();
}
try {
return result;
} catch (Exception e) { } catch (Exception e) {
return (new ArrayList<String>()); return new ArrayList<>();
} }
} }
@Override @Override
public synchronized List<String> getAllAuthsByEmail(final String email) { public synchronized List<String> getAllAuthsByEmail(final String email) {
ExecutorService executor = Executors.newSingleThreadExecutor();
List<String> result;
try { try {
result = executor.submit(new Callable<List<String>>() { return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception { public List<String> call() throws Exception {
return database.getAllAuthsByEmail(email); return database.getAllAuthsByEmail(email);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return new ArrayList<String>();
} catch (ExecutionException e1) {
return new ArrayList<String>();
} finally {
executor.shutdown();
}
try {
return result;
} catch (Exception e) { } catch (Exception e) {
return (new ArrayList<String>()); return new ArrayList<>();
} }
} }
@Override @Override
public synchronized boolean updateEmail(final PlayerAuth auth) { public synchronized boolean updateEmail(final PlayerAuth auth) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.updateEmail(auth); return database.updateEmail(auth);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized boolean updateSalt(final PlayerAuth auth) { public synchronized boolean updateSalt(final PlayerAuth auth) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.updateSalt(auth); return database.updateSalt(auth);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized void close() { public synchronized void close() {
database.close(); try {
exec.shutdown();
exec.awaitTermination(10, TimeUnit.SECONDS);
database.close();
} catch (Exception e) {
e.printStackTrace();
}
} }
@Override @Override
@ -405,8 +231,6 @@ public class DatabaseCalls implements DataSource {
@Override @Override
public synchronized void purgeBanned(final List<String> banned) { public synchronized void purgeBanned(final List<String> banned) {
new Thread(new Runnable() { new Thread(new Runnable() {
@Override
public synchronized void run() { public synchronized void run() {
database.purgeBanned(banned); database.purgeBanned(banned);
} }
@ -420,139 +244,90 @@ public class DatabaseCalls implements DataSource {
@Override @Override
public synchronized boolean isLogged(final String user) { public synchronized boolean isLogged(final String user) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result;
try { try {
result = executor.submit(new Callable<Boolean>() { return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception { public Boolean call() throws Exception {
return database.isLogged(user); return database.isLogged(user);
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return false;
} catch (ExecutionException e1) {
return false;
} finally {
executor.shutdown();
}
try {
return result.booleanValue();
} catch (Exception e) { } catch (Exception e) {
return (false); return false;
} }
} }
@Override @Override
public synchronized void setLogged(final String user) { public synchronized void setLogged(final String user) {
new Thread(new Runnable() { exec.execute(new Runnable() {
@Override
public synchronized void run() { public synchronized void run() {
database.setLogged(user); database.setLogged(user);
} }
}).start(); });
} }
@Override @Override
public synchronized void setUnlogged(final String user) { public synchronized void setUnlogged(final String user) {
new Thread(new Runnable() { exec.execute(new Runnable() {
@Override
public synchronized void run() { public synchronized void run() {
database.setUnlogged(user); database.setUnlogged(user);
} }
}).start(); });
} }
@Override @Override
public synchronized void purgeLogged() { public synchronized void purgeLogged() {
new Thread(new Runnable() { exec.execute(new Runnable() {
@Override
public synchronized void run() { public synchronized void run() {
database.purgeLogged(); database.purgeLogged();
} }
}).start(); });
} }
@Override @Override
public synchronized int getAccountsRegistered() { public synchronized int getAccountsRegistered() {
ExecutorService executor = Executors.newSingleThreadExecutor();
Integer result;
try { try {
result = executor.submit(new Callable<Integer>() { return exec.submit(new Callable<Integer>() {
public Integer call() throws Exception { public Integer call() throws Exception {
return database.getAccountsRegistered(); return database.getAccountsRegistered();
} }
}).get(); }).get();
} catch (InterruptedException e1) {
return 0;
} catch (ExecutionException e1) {
return 0;
} finally {
executor.shutdown();
}
try {
return result.intValue();
} catch (Exception e) { } catch (Exception e) {
return (0); return -1;
} }
} }
@Override @Override
public synchronized void updateName(final String oldone, public synchronized void updateName(final String oldone, final String newone) {
final String newone) { exec.execute(new Runnable() {
new Thread(new Runnable() {
@Override
public synchronized void run() { public synchronized void run() {
database.updateName(oldone, newone); database.updateName(oldone, newone);
} }
}).start(); });
} }
@Override @Override
public synchronized List<PlayerAuth> getAllAuths() { public synchronized List<PlayerAuth> getAllAuths() {
ExecutorService executor = Executors.newSingleThreadExecutor();
List<PlayerAuth> result;
try { try {
result = executor.submit(new Callable<List<PlayerAuth>>() { return exec.submit(new Callable<List<PlayerAuth>>() {
public List<PlayerAuth> call() throws Exception { public List<PlayerAuth> call() throws Exception {
return database.getAllAuths(); return database.getAllAuths();
} }
}).get(); }).get();
} catch (InterruptedException e1) { } catch (Exception e) {
return (new ArrayList<PlayerAuth>()); return new ArrayList<>();
} catch (ExecutionException e1) {
return (new ArrayList<PlayerAuth>());
} finally {
executor.shutdown();
} }
return result;
} }
@Override @Override
public List<PlayerAuth> getLoggedPlayers() { public List<PlayerAuth> getLoggedPlayers() {
ExecutorService executor = Executors.newSingleThreadExecutor();
List<PlayerAuth> result;
try { try {
result = executor.submit(new Callable<List<PlayerAuth>>() { return exec.submit(new Callable<List<PlayerAuth>>() {
public List<PlayerAuth> call() throws Exception { public List<PlayerAuth> call() throws Exception {
return database.getLoggedPlayers(); return database.getLoggedPlayers();
} }
}).get(); }).get();
} catch (InterruptedException e1) { } catch (Exception e) {
return (new ArrayList<PlayerAuth>()); return new ArrayList<>();
} catch (ExecutionException e1) {
return (new ArrayList<PlayerAuth>());
} finally {
executor.shutdown();
} }
return result;
} }
} }

View File

@ -1,21 +1,15 @@
package fr.xephi.authme.datasource; package fr.xephi.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 fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class FlatFile implements DataSource { public class FlatFile implements DataSource {
/* /*
@ -32,7 +26,7 @@ public class FlatFile implements DataSource {
private File source; private File source;
public FlatFile() { public FlatFile() {
source = new File(Settings.AUTH_FILE); source = Settings.AUTH_FILE;
try { try {
source.createNewFile(); source.createNewFile();
} catch (IOException e) { } catch (IOException e) {
@ -41,9 +35,10 @@ public class FlatFile implements DataSource {
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN..."); ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) {
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return; }
e.printStackTrace();
} }
} }
@ -108,7 +103,7 @@ public class FlatFile implements DataSource {
BufferedReader br = null; BufferedReader br = null;
try { try {
br = new BufferedReader(new FileReader(source)); br = new BufferedReader(new FileReader(source));
String line = ""; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
@ -167,7 +162,7 @@ public class FlatFile implements DataSource {
BufferedReader br = null; BufferedReader br = null;
try { try {
br = new BufferedReader(new FileReader(source)); br = new BufferedReader(new FileReader(source));
String line = ""; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args[0].equalsIgnoreCase(auth.getNickname())) { if (args[0].equalsIgnoreCase(auth.getNickname())) {
@ -226,7 +221,7 @@ public class FlatFile implements DataSource {
BufferedReader br = null; BufferedReader br = null;
try { try {
br = new BufferedReader(new FileReader(source)); br = new BufferedReader(new FileReader(source));
String line = ""; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args[0].equalsIgnoreCase(auth.getNickname())) { if (args[0].equalsIgnoreCase(auth.getNickname())) {

View File

@ -1,25 +1,18 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import java.sql.Blob;
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 java.util.concurrent.TimeoutException;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.PoolInitializationException; import com.zaxxer.hikari.pool.PoolInitializationException;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class MySQL implements DataSource { public class MySQL implements DataSource {
private String host; private String host;
@ -44,8 +37,9 @@ public class MySQL implements DataSource {
private List<String> columnOthers; private List<String> columnOthers;
private HikariDataSource ds; private HikariDataSource ds;
private String columnRealName; private String columnRealName;
private int maxConnections;
public MySQL() { public MySQL() throws ClassNotFoundException, SQLException, PoolInitializationException {
this.host = Settings.getMySQLHost; this.host = Settings.getMySQLHost;
this.port = Settings.getMySQLPort; this.port = Settings.getMySQLPort;
this.username = Settings.getMySQLUsername; this.username = Settings.getMySQLUsername;
@ -67,73 +61,78 @@ public class MySQL implements DataSource {
this.columnID = Settings.getMySQLColumnId; this.columnID = Settings.getMySQLColumnId;
this.columnLogged = Settings.getMySQLColumnLogged; this.columnLogged = Settings.getMySQLColumnLogged;
this.columnRealName = Settings.getMySQLColumnRealName; this.columnRealName = Settings.getMySQLColumnRealName;
this.maxConnections = Settings.getMySQLMaxConnections;
// Set the connection arguments (and check if connection is ok)
try { try {
this.connect(); this.setConnectionArguments();
this.setup(); } catch (RuntimeException e) {
} catch (ClassNotFoundException e) { if (e instanceof IllegalArgumentException) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError("Invalid database arguments! Please check your configuration!");
if (Settings.isStopEnabled) { ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); throw new IllegalArgumentException(e);
AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (e instanceof PoolInitializationException) {
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); ConsoleLogger.showError("Can't initialize database connection! Please check your configuration!");
return; ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
throw new PoolInitializationException(e);
}
ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer! SHUTDOWN...");
throw e;
}
// Initialize the database
try {
this.setupConnection();
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.showError(e.getMessage()); this.close();
if (Settings.isStopEnabled) { ConsoleLogger.showError("Can't initialize the MySQL database... Please check your database settings in the config.yml file! SHUTDOWN...");
ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); throw e;
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} catch (TimeoutException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} catch (PoolInitializationException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} }
} }
private synchronized void connect() private synchronized void setConnectionArguments()
throws ClassNotFoundException, SQLException, TimeoutException, throws ClassNotFoundException, IllegalArgumentException {
NumberFormatException, PoolInitializationException {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();
config.setPoolName("AuthMeMYSQLPool");
config.setDriverClassName("com.mysql.jdbc.Driver"); config.setDriverClassName("com.mysql.jdbc.Driver");
config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database); config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database);
config.setUsername(this.username); config.setUsername(this.username);
config.setPassword(this.password); config.setPassword(this.password);
config.setPoolName("AuthMeMYSQLPool");
config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("autoReconnect", true); config.addDataSourceProperty("autoReconnect", false);
config.setMaxLifetime(30000); config.setInitializationFailFast(true); // Don't start the plugin if the database is unavariable
config.setInitializationFailFast(false); config.setMaxLifetime(180000); // 3 Min
config.setIdleTimeout(60000); // 1 Min
config.setMaximumPoolSize(maxConnections);
ds = new HikariDataSource(config); ds = new HikariDataSource(config);
ConsoleLogger.info("Connection pool ready"); ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
} }
private synchronized void setup() throws SQLException { private synchronized void reloadArguments()
throws ClassNotFoundException, IllegalArgumentException {
if (ds != null) {
ds.close();
}
setConnectionArguments();
ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!");
}
private synchronized Connection getConnection() throws SQLException {
Connection con;
con = ds.getConnection();
return con;
}
private synchronized void setupConnection() throws SQLException {
Connection con = null; Connection con = null;
Statement st = null; Statement st = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
st = con.createStatement(); 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 DEFAULT '127.0.0.1'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); 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 DEFAULT '127.0.0.1'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword); rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
@ -185,6 +184,7 @@ public class MySQL implements DataSource {
close(st); close(st);
close(con); close(con);
} }
ConsoleLogger.info("MySQL Setup finished");
} }
@Override @Override
@ -193,7 +193,7 @@ public class MySQL implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -208,16 +208,15 @@ public class MySQL implements DataSource {
} }
} }
@SuppressWarnings("resource")
@Override @Override
public synchronized PlayerAuth getAuth(String user) { public synchronized PlayerAuth getAuth(String user) {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
PlayerAuth pAuth = null; PlayerAuth pAuth = null;
int id = -1; int id;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -229,13 +228,15 @@ public class MySQL implements DataSource {
if (!columnSalt.isEmpty()) { if (!columnSalt.isEmpty()) {
if (!columnGroup.isEmpty()) if (!columnGroup.isEmpty())
pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
else pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); else
pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else { } else {
pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} }
} }
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
rs.close(); rs.close();
pst.close();
pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;");
pst.setInt(1, id); pst.setInt(1, id);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -263,8 +264,9 @@ public class MySQL implements DataSource {
public synchronized boolean saveAuth(PlayerAuth auth) { public synchronized boolean saveAuth(PlayerAuth auth) {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
if ((columnSalt == null || columnSalt.isEmpty()) || (auth.getSalt() == null || auth.getSalt().isEmpty())) { if ((columnSalt == null || columnSalt.isEmpty()) || (auth.getSalt() == null || auth.getSalt().isEmpty())) {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnRealName + ") VALUES (?,?,?,?,?);"); pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnRealName + ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
@ -295,13 +297,11 @@ public class MySQL implements DataSource {
} }
} }
if (Settings.getPasswordHash == HashAlgorithm.PHPBB) { if (Settings.getPasswordHash == HashAlgorithm.PHPBB) {
int id;
ResultSet rs = null;
PreparedStatement pst2 = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); PreparedStatement pst2 = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
pst2.setString(1, auth.getNickname()); pst2.setString(1, auth.getNickname());
rs = pst2.executeQuery(); rs = pst2.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); int id = rs.getInt(columnID);
// Insert player in phpbb_user_group // Insert player in phpbb_user_group
pst = con.prepareStatement("INSERT INTO " + Settings.getPhpbbPrefix + "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);"); pst = con.prepareStatement("INSERT INTO " + Settings.getPhpbbPrefix + "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);");
pst.setInt(1, Settings.getPhpbbGroup); pst.setInt(1, Settings.getPhpbbGroup);
@ -341,16 +341,15 @@ public class MySQL implements DataSource {
pst.executeUpdate(); pst.executeUpdate();
pst.close(); pst.close();
} }
rs.close();
pst2.close(); pst2.close();
} }
if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) { if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) {
int id;
ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); int id = rs.getInt(columnID);
// First Name // First Name
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
@ -436,15 +435,14 @@ public class MySQL implements DataSource {
pst.executeUpdate(); pst.executeUpdate();
pst.close(); pst.close();
} }
rs.close();
} }
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id;
ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); int id = rs.getInt(columnID);
// Insert password in the correct table // Insert password in the correct table
pst = con.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);"); pst = con.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
@ -455,13 +453,13 @@ public class MySQL implements DataSource {
pst.setBlob(3, blob); pst.setBlob(3, blob);
pst.executeUpdate(); pst.executeUpdate();
} }
if (rs != null && !rs.isClosed()) rs.close();
rs.close();
} }
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
close(rs);
close(pst); close(pst);
close(con); close(con);
} }
@ -472,21 +470,20 @@ public class MySQL implements DataSource {
public synchronized boolean updatePassword(PlayerAuth auth) { public synchronized boolean updatePassword(PlayerAuth auth) {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getHash()); pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
pst.close(); pst.close();
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id;
ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); int id = rs.getInt(columnID);
// Insert password in the correct table // Insert password in the correct table
pst = con.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE " + columnID + "=?;"); pst = con.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE " + columnID + "=?;");
byte[] bytes = auth.getHash().getBytes(); byte[] bytes = auth.getHash().getBytes();
@ -500,13 +497,13 @@ public class MySQL implements DataSource {
pst.setInt(2, id); pst.setInt(2, id);
pst.executeUpdate(); pst.executeUpdate();
} }
if (rs != null && !rs.isClosed()) rs.close();
rs.close();
} }
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
close(rs);
close(pst); close(pst);
close(con); close(con);
} }
@ -518,7 +515,7 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=?, " + columnRealName + "=? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=?, " + columnRealName + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin()); pst.setLong(2, auth.getLastLogin());
@ -540,7 +537,7 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
return pst.executeUpdate(); return pst.executeUpdate();
@ -558,9 +555,9 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<>();
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -574,7 +571,7 @@ public class MySQL implements DataSource {
return list; return list;
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -587,10 +584,10 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id; int id;
ResultSet rs = null; ResultSet rs;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -623,7 +620,7 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setDouble(1, auth.getQuitLocX()); pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY()); pst.setDouble(2, auth.getQuitLocY());
@ -648,7 +645,7 @@ public class MySQL implements DataSource {
ResultSet rs = null; ResultSet rs = null;
int countIp = 0; int countIp = 0;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip); pst.setString(1, ip);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -671,7 +668,7 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + " =? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + " =? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getEmail()); pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
@ -694,7 +691,7 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + " =? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + " =? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getSalt()); pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
@ -709,23 +706,14 @@ public class MySQL implements DataSource {
return true; return true;
} }
@Override
public synchronized void close() {
try {
if (ds != null)
ds.close();
} catch (Exception e) {
}
}
@Override @Override
public void reload() { public void reload() {
try { try {
reconnect(true); reloadArguments();
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled)
@ -733,30 +721,16 @@ public class MySQL implements DataSource {
} }
} }
private void close(Statement st) { @Override
if (st != null) { public synchronized void close() {
try { if (ds != null)
st.close(); ds.close();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
} }
private void close(ResultSet rs) { private void close(AutoCloseable o) {
if (rs != null) { if (o != null) {
try { try {
rs.close(); o.close();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
private void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} }
@ -768,9 +742,9 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<>();
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -780,7 +754,7 @@ public class MySQL implements DataSource {
return countIp; return countIp;
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -793,9 +767,9 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<>();
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip); pst.setString(1, ip);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -805,7 +779,7 @@ public class MySQL implements DataSource {
return countIp; return countIp;
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -818,9 +792,9 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> countEmail = new ArrayList<String>(); List<String> countEmail = new ArrayList<>();
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
pst.setString(1, email); pst.setString(1, email);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -830,7 +804,7 @@ public class MySQL implements DataSource {
return countEmail; return countEmail;
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -844,7 +818,7 @@ public class MySQL implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
for (String name : banned) { for (String name : banned) {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, name); pst.setString(1, name);
pst.executeUpdate(); pst.executeUpdate();
@ -857,75 +831,6 @@ public class MySQL implements DataSource {
} }
} }
private synchronized Connection makeSureConnectionIsReady() {
Connection con = null;
try {
con = ds.getConnection();
} catch (Exception te) {
try {
con = null;
reconnect(false);
} catch (Exception e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
}
} catch (AssertionError ae) {
// Make sure assertionerror is caused by the connectionpoolmanager,
// else re-throw it
if (!ae.getMessage().equalsIgnoreCase("AuthMeDatabaseError"))
throw new AssertionError(ae.getMessage());
try {
con = null;
reconnect(false);
} catch (Exception e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
}
}
while (con == null)
try {
con = ds.getConnection();
} catch (Exception e) {
try {
reconnect(false);
con = ds.getConnection();
} catch (Exception ex) {
}
}
return con;
}
private synchronized void reconnect(boolean reload)
throws ClassNotFoundException, SQLException, TimeoutException,
PoolInitializationException {
if (ds != null)
ds.close();
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database);
config.setUsername(this.username);
config.setPassword(this.password);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("autoReconnect", true);
config.setInitializationFailFast(false);
config.setMaxLifetime(12000);
config.setPoolName("AuthMeMYSQLPool");
ds = new HikariDataSource(config);
if (!reload)
ConsoleLogger.info("ConnectionPool was unavailable... Reconnected!");
}
@Override @Override
public DataSourceType getType() { public DataSourceType getType() {
return DataSourceType.MYSQL; return DataSourceType.MYSQL;
@ -937,7 +842,7 @@ public class MySQL implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -959,19 +864,17 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 1); pst.setInt(1, 1);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
@ -980,19 +883,17 @@ public class MySQL implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
if (user != null) if (user != null)
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
@ -1000,19 +901,17 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setInt(2, 1); pst.setInt(2, 1);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
@ -1020,9 +919,9 @@ public class MySQL implements DataSource {
int result = 0; int result = 0;
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs != null && rs.next()) { if (rs != null && rs.next()) {
@ -1043,33 +942,31 @@ public class MySQL implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, newone); pst.setString(1, newone);
pst.setString(2, oldone); pst.setString(2, oldone);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
public List<PlayerAuth> getAllAuths() { public List<PlayerAuth> getAllAuths() {
List<PlayerAuth> auths = new ArrayList<PlayerAuth>(); List<PlayerAuth> auths = new ArrayList<>();
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + ";"); pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
PlayerAuth pAuth = null; PlayerAuth pAuth;
int id = rs.getInt(columnID); int id = rs.getInt(columnID);
if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
@ -1077,13 +974,14 @@ public class MySQL implements DataSource {
if (!columnSalt.isEmpty()) { if (!columnSalt.isEmpty()) {
if (!columnGroup.isEmpty()) if (!columnGroup.isEmpty())
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
else pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); else
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else { } else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} }
} }
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
ResultSet rsid = null; ResultSet rsid;
pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;");
pst.setInt(1, id); pst.setInt(1, id);
rsid = pst.executeQuery(); rsid = pst.executeQuery();
@ -1092,11 +990,9 @@ public class MySQL implements DataSource {
byte[] bytes = blob.getBytes(1, (int) blob.length()); byte[] bytes = blob.getBytes(1, (int) blob.length());
pAuth.setHash(new String(bytes)); pAuth.setHash(new String(bytes));
} }
if (rsid != null) rsid.close();
rsid.close();
} }
if (pAuth != null) auths.add(pAuth);
auths.add(pAuth);
} }
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
@ -1111,16 +1007,16 @@ public class MySQL implements DataSource {
@Override @Override
public List<PlayerAuth> getLoggedPlayers() { public List<PlayerAuth> getLoggedPlayers() {
List<PlayerAuth> auths = new ArrayList<PlayerAuth>(); List<PlayerAuth> auths = new ArrayList<>();
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
PlayerAuth pAuth = null; PlayerAuth pAuth;
int id = rs.getInt(columnID); int id = rs.getInt(columnID);
if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
@ -1128,13 +1024,14 @@ public class MySQL implements DataSource {
if (!columnSalt.isEmpty()) { if (!columnSalt.isEmpty()) {
if (!columnGroup.isEmpty()) if (!columnGroup.isEmpty())
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
else pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); else
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else { } else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} }
} }
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
ResultSet rsid = null; ResultSet rsid;
pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;");
pst.setInt(1, id); pst.setInt(1, id);
rsid = pst.executeQuery(); rsid = pst.executeQuery();
@ -1143,11 +1040,9 @@ public class MySQL implements DataSource {
byte[] bytes = blob.getBytes(1, (int) blob.length()); byte[] bytes = blob.getBytes(1, (int) blob.length());
pAuth.setHash(new String(bytes)); pAuth.setHash(new String(bytes));
} }
if (rsid != null) rsid.close();
rsid.close();
} }
if (pAuth != null) auths.add(pAuth);
auths.add(pAuth);
} }
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());

View File

@ -1,19 +1,13 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class SQLite implements DataSource { public class SQLite implements DataSource {
private String database; private String database;
@ -34,7 +28,7 @@ public class SQLite implements DataSource {
private String columnLogged; private String columnLogged;
private String columnRealName; private String columnRealName;
public SQLite() { public SQLite() throws ClassNotFoundException, SQLException {
this.database = Settings.getMySQLDatabase; this.database = Settings.getMySQLDatabase;
this.tableName = Settings.getMySQLTablename; this.tableName = Settings.getMySQLTablename;
this.columnName = Settings.getMySQLColumnName; this.columnName = Settings.getMySQLColumnName;
@ -55,29 +49,13 @@ public class SQLite implements DataSource {
try { try {
this.connect(); this.connect();
this.setup(); this.setup();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException | SQLException cnf) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError("Can't use SQLITE... !");
if (Settings.isStopEnabled) { throw cnf;
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} catch (SQLException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} }
} }
private synchronized void connect() private synchronized void connect() throws ClassNotFoundException, SQLException {
throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded"); ConsoleLogger.info("SQLite driver loaded");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db"); this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
@ -273,7 +251,7 @@ public class SQLite implements DataSource {
public List<String> autoPurgeDatabase(long until) { public List<String> autoPurgeDatabase(long until) {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
@ -284,7 +262,7 @@ public class SQLite implements DataSource {
return list; return list;
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -423,7 +401,7 @@ public class SQLite implements DataSource {
public List<String> getAllAuthsByName(PlayerAuth auth) { public List<String> getAllAuthsByName(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
@ -434,9 +412,9 @@ public class SQLite implements DataSource {
return countIp; return countIp;
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -447,7 +425,7 @@ public class SQLite implements DataSource {
public List<String> getAllAuthsByIp(String ip) { public List<String> getAllAuthsByIp(String ip) {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip); pst.setString(1, ip);
@ -458,9 +436,9 @@ public class SQLite implements DataSource {
return countIp; return countIp;
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -471,7 +449,7 @@ public class SQLite implements DataSource {
public List<String> getAllAuthsByEmail(String email) { public List<String> getAllAuthsByEmail(String email) {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> countEmail = new ArrayList<String>(); List<String> countEmail = new ArrayList<>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
pst.setString(1, email); pst.setString(1, email);
@ -482,9 +460,9 @@ public class SQLite implements DataSource {
return countEmail; return countEmail;
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -542,11 +520,9 @@ public class SQLite implements DataSource {
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
} }
return;
} }
@Override @Override
@ -560,11 +536,9 @@ public class SQLite implements DataSource {
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
} }
return;
} }
@Override @Override
@ -577,18 +551,16 @@ public class SQLite implements DataSource {
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
} }
return;
} }
@Override @Override
public int getAccountsRegistered() { public int getAccountsRegistered() {
int result = 0; int result = 0;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs;
try { try {
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -614,23 +586,21 @@ public class SQLite implements DataSource {
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
} }
return;
} }
@Override @Override
public List<PlayerAuth> getAllAuths() { public List<PlayerAuth> getAllAuths() {
List<PlayerAuth> auths = new ArrayList<PlayerAuth>(); List<PlayerAuth> auths = new ArrayList<>();
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs;
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + ";"); pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
PlayerAuth pAuth = null; PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) { if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else { } else {
@ -640,8 +610,7 @@ public class SQLite implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} }
} }
if (pAuth != null) auths.add(pAuth);
auths.add(pAuth);
} }
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
@ -654,14 +623,14 @@ public class SQLite implements DataSource {
@Override @Override
public List<PlayerAuth> getLoggedPlayers() { public List<PlayerAuth> getLoggedPlayers() {
List<PlayerAuth> auths = new ArrayList<PlayerAuth>(); List<PlayerAuth> auths = new ArrayList<>();
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs;
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
PlayerAuth pAuth = null; PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) { if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else { } else {
@ -671,8 +640,7 @@ public class SQLite implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} }
} }
if (pAuth != null) auths.add(pAuth);
auths.add(pAuth);
} }
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());

View File

@ -1,23 +1,16 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import java.io.EOFException;
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 java.util.Properties;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class SQLite_HIKARI implements DataSource { public class SQLite_HIKARI implements DataSource {
private String database; private String database;
@ -38,7 +31,7 @@ public class SQLite_HIKARI implements DataSource {
private String columnLogged; private String columnLogged;
private String columnRealName; private String columnRealName;
public SQLite_HIKARI() { public SQLite_HIKARI() throws ClassNotFoundException, SQLException {
this.database = Settings.getMySQLDatabase; this.database = Settings.getMySQLDatabase;
this.tableName = Settings.getMySQLTablename; this.tableName = Settings.getMySQLTablename;
this.columnName = Settings.getMySQLColumnName; this.columnName = Settings.getMySQLColumnName;
@ -56,60 +49,57 @@ public class SQLite_HIKARI implements DataSource {
this.columnLogged = Settings.getMySQLColumnLogged; this.columnLogged = Settings.getMySQLColumnLogged;
this.columnRealName = Settings.getMySQLColumnRealName; this.columnRealName = Settings.getMySQLColumnRealName;
// Set the connection arguments
try { try {
this.connect(); this.setConnectionArguments();
this.setup(); } catch (RuntimeException rt) {
} catch (ClassNotFoundException e) { ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer!");
ConsoleLogger.showError(e.getMessage()); throw rt;
if (Settings.isStopEnabled) { }
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); // Initialize the database
} try {
if (!Settings.isStopEnabled) this.setupConnection();
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.showError(e.getMessage()); this.close();
if (Settings.isStopEnabled) { ConsoleLogger.showError("Can't initialize the SQLite database... Please check your database settings in the config.yml file! SHUTDOWN...");
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN..."); ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); throw e;
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} catch (EOFException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} }
} }
private Connection getConnection() throws SQLException, EOFException { @Override
return this.ds.getConnection(); public DataSourceType getType() {
return DataSourceType.SQLITEHIKARI;
} }
private synchronized void connect() private synchronized void setConnectionArguments() throws RuntimeException {
throws ClassNotFoundException, SQLException, EOFException { HikariConfig config = new HikariConfig();
/* config.setPoolName("AuthMeSQLitePool");
* Class.forName("org.sqlite.JDBC"); ConsoleLogger.info( config.setDriverClassName("org.sqlite.JDBC"); // RuntimeException
* "SQLite driver loaded"); this.con = config.setJdbcUrl("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
* DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database config.setConnectionTestQuery("SELECT 1");
* + ".db"); config.setMaxLifetime(180000); // 3 Min
*/ config.setIdleTimeout(60000); // 1 Min
Properties props = new Properties(); config.setMaximumPoolSize(50); // 50 (including idle connections)
props.setProperty("dataSourceClassName", "org.sqlite.SQLiteDataSource");
HikariConfig config = new HikariConfig(props);
config.setPoolName("AuthMeSQLiteLPool");
ds = new HikariDataSource(config); ds = new HikariDataSource(config);
ConsoleLogger.info("Connection pool ready"); ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
} }
private synchronized void setup() throws SQLException, EOFException { private synchronized void reloadArguments()
throws ClassNotFoundException, IllegalArgumentException {
if (ds != null) {
ds.close();
}
setConnectionArguments();
ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!");
}
private synchronized Connection getConnection() throws SQLException {
return ds.getConnection();
}
private synchronized void setupConnection() throws SQLException {
Connection con = null; Connection con = null;
Statement st = null; Statement st = null;
ResultSet rs = null; ResultSet rs = null;
@ -166,14 +156,6 @@ public class SQLite_HIKARI implements DataSource {
ConsoleLogger.info("SQLite Setup finished"); ConsoleLogger.info("SQLite Setup finished");
} }
private void close(Connection con) {
try {
if (con != null)
con.close();
} catch (Exception e) {
}
}
@Override @Override
public synchronized boolean isAuthAvailable(String user) { public synchronized boolean isAuthAvailable(String user) {
Connection con = null; Connection con = null;
@ -185,7 +167,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
return rs.next(); return rs.next();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -218,7 +200,7 @@ public class SQLite_HIKARI implements DataSource {
} else { } else {
return null; return null;
} }
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return null; return null;
} finally { } finally {
@ -230,8 +212,8 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public synchronized boolean saveAuth(PlayerAuth auth) { public synchronized boolean saveAuth(PlayerAuth auth) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) { if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
@ -252,7 +234,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(6, auth.getRealName()); pst.setString(6, auth.getRealName());
pst.executeUpdate(); pst.executeUpdate();
} }
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -272,7 +254,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, auth.getHash()); pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -294,7 +276,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(3, auth.getRealName()); pst.setString(3, auth.getRealName());
pst.setString(4, auth.getNickname()); pst.setString(4, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -313,7 +295,7 @@ public class SQLite_HIKARI implements DataSource {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
return pst.executeUpdate(); return pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return 0; return 0;
} finally { } finally {
@ -327,7 +309,7 @@ public class SQLite_HIKARI implements DataSource {
Connection con = null; Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<>();
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
@ -337,9 +319,9 @@ public class SQLite_HIKARI implements DataSource {
list.add(rs.getString(columnName)); list.add(rs.getString(columnName));
} }
return list; return list;
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -349,14 +331,14 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public synchronized boolean removeAuth(String user) { public synchronized boolean removeAuth(String user) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -368,8 +350,8 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public boolean updateQuitLoc(PlayerAuth auth) { public boolean updateQuitLoc(PlayerAuth auth) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
@ -379,7 +361,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(4, auth.getWorld()); pst.setString(4, auth.getWorld());
pst.setString(5, auth.getNickname()); pst.setString(5, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -391,9 +373,9 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public int getIps(String ip) { public int getIps(String ip) {
Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
Connection con = null;
int countIp = 0; int countIp = 0;
try { try {
con = getConnection(); con = getConnection();
@ -404,7 +386,7 @@ public class SQLite_HIKARI implements DataSource {
countIp++; countIp++;
} }
return countIp; return countIp;
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return 0; return 0;
} finally { } finally {
@ -416,15 +398,15 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public boolean updateEmail(PlayerAuth auth) { public boolean updateEmail(PlayerAuth auth) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail()); pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -447,7 +429,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, auth.getSalt()); pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -457,57 +439,12 @@ public class SQLite_HIKARI implements DataSource {
return true; return true;
} }
@Override
public synchronized void close() {
try {
if (ds != null)
ds.close();
} catch (Exception e) {
}
}
@Override
public void reload() {
try {
connect();
setup();
} catch (Exception e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't reconnect to SQLite database... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
}
}
private void close(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
private void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
@Override @Override
public List<String> getAllAuthsByName(PlayerAuth auth) { public List<String> getAllAuthsByName(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
Connection con = null; List<String> countIp = new ArrayList<>();
List<String> countIp = new ArrayList<String>();
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
@ -517,11 +454,11 @@ public class SQLite_HIKARI implements DataSource {
countIp.add(rs.getString(columnName)); countIp.add(rs.getString(columnName));
} }
return countIp; return countIp;
} catch (NullPointerException ex) { } catch (SQLException ex) {
return new ArrayList<String>();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -531,10 +468,10 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public List<String> getAllAuthsByIp(String ip) { public List<String> getAllAuthsByIp(String ip) {
Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
Connection con = null; List<String> countIp = new ArrayList<>();
List<String> countIp = new ArrayList<String>();
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
@ -544,11 +481,11 @@ public class SQLite_HIKARI implements DataSource {
countIp.add(rs.getString(columnName)); countIp.add(rs.getString(columnName));
} }
return countIp; return countIp;
} catch (NullPointerException ex) { } catch (SQLException ex) {
return new ArrayList<String>();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -558,10 +495,10 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public List<String> getAllAuthsByEmail(String email) { public List<String> getAllAuthsByEmail(String email) {
Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
Connection con = null; List<String> countEmail = new ArrayList<>();
List<String> countEmail = new ArrayList<String>();
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
@ -571,11 +508,11 @@ public class SQLite_HIKARI implements DataSource {
countEmail.add(rs.getString(columnName)); countEmail.add(rs.getString(columnName));
} }
return countEmail; return countEmail;
} catch (NullPointerException ex) { } catch (SQLException ex) {
return new ArrayList<String>();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>(); return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally { } finally {
close(rs); close(rs);
close(pst); close(pst);
@ -585,8 +522,8 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public void purgeBanned(List<String> banned) { public void purgeBanned(List<String> banned) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
for (String name : banned) { for (String name : banned) {
@ -594,7 +531,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, name); pst.setString(1, name);
pst.executeUpdate(); pst.executeUpdate();
} }
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} finally { } finally {
close(pst); close(pst);
@ -602,16 +539,11 @@ public class SQLite_HIKARI implements DataSource {
} }
} }
@Override
public DataSourceType getType() {
return DataSourceType.SQLITE;
}
@Override @Override
public boolean isLogged(String user) { public boolean isLogged(String user) {
Connection con = null;
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
Connection con = null;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
@ -619,7 +551,7 @@ public class SQLite_HIKARI implements DataSource {
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) if (rs.next())
return (rs.getInt(columnLogged) == 1); return (rs.getInt(columnLogged) == 1);
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
} finally { } finally {
@ -632,28 +564,26 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public void setLogged(String user) { public void setLogged(String user) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 1); pst.setInt(1, 1);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
public void setUnlogged(String user) { public void setUnlogged(String user) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
if (user != null) if (user != null)
try { try {
con = getConnection(); con = getConnection();
@ -661,42 +591,38 @@ public class SQLite_HIKARI implements DataSource {
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
public void purgeLogged() { public void purgeLogged() {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setInt(2, 1); pst.setInt(2, 1);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
public int getAccountsRegistered() { public int getAccountsRegistered() {
int result = 0;
PreparedStatement pst = null;
ResultSet rs = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
ResultSet rs;
int result = 0;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
@ -704,7 +630,7 @@ public class SQLite_HIKARI implements DataSource {
if (rs != null && rs.next()) { if (rs != null && rs.next()) {
result = rs.getInt(1); result = rs.getInt(1);
} }
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return result; return result;
} finally { } finally {
@ -716,36 +642,34 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public void updateName(String oldone, String newone) { public void updateName(String oldone, String newone) {
PreparedStatement pst = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE " + columnName + "=?;");
pst.setString(1, newone); pst.setString(1, newone);
pst.setString(2, oldone); pst.setString(2, oldone);
pst.executeUpdate(); pst.executeUpdate();
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return;
} }
@Override @Override
public List<PlayerAuth> getAllAuths() { public List<PlayerAuth> getAllAuths() {
List<PlayerAuth> auths = new ArrayList<PlayerAuth>();
PreparedStatement pst = null;
ResultSet rs = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
ResultSet rs;
List<PlayerAuth> auths = new ArrayList<>();
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + ";"); pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
PlayerAuth pAuth = null; PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) { if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else { } else {
@ -755,10 +679,9 @@ public class SQLite_HIKARI implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} }
} }
if (pAuth != null) auths.add(pAuth);
auths.add(pAuth);
} }
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return auths; return auths;
} finally { } finally {
@ -770,16 +693,16 @@ public class SQLite_HIKARI implements DataSource {
@Override @Override
public List<PlayerAuth> getLoggedPlayers() { public List<PlayerAuth> getLoggedPlayers() {
List<PlayerAuth> auths = new ArrayList<PlayerAuth>();
PreparedStatement pst = null;
ResultSet rs = null;
Connection con = null; Connection con = null;
PreparedStatement pst = null;
ResultSet rs;
List<PlayerAuth> auths = new ArrayList<>();
try { try {
con = getConnection(); con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
PlayerAuth pAuth = null; PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) { if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else { } else {
@ -789,16 +712,45 @@ public class SQLite_HIKARI implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} }
} }
if (pAuth != null) auths.add(pAuth);
auths.add(pAuth);
} }
} catch (Exception ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return auths;
} finally { } finally {
close(pst); close(pst);
close(con); close(con);
} }
return auths; return auths;
} }
@Override
public void reload() {
try {
reloadArguments();
} catch (Exception e) {
ConsoleLogger.showError(e.getMessage());
ConsoleLogger.showError("Can't reconnect to SQLite database... Please check your SQLite informations ! SHUTDOWN...");
if (Settings.isStopEnabled) {
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
}
}
@Override
public synchronized void close() {
if (ds != null)
ds.close();
}
private void close(AutoCloseable o) {
if (o != null) {
try {
o.close();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
} }

View File

@ -1,12 +1,11 @@
package fr.xephi.authme.events; package fr.xephi.authme.events;
import fr.xephi.authme.cache.backup.DataFileCache;
import fr.xephi.authme.cache.backup.JsonCache;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import fr.xephi.authme.cache.backup.FileCache;
/** /**
*
* This event is call just before write inventory content to cache * This event is call just before write inventory content to cache
* *
* @author Xephi59 * @author Xephi59
@ -23,12 +22,13 @@ public class StoreInventoryEvent extends CustomEvent {
this.armor = player.getInventory().getArmorContents(); this.armor = player.getInventory().getArmorContents();
} }
public StoreInventoryEvent(Player player, FileCache fileCache) { public StoreInventoryEvent(Player player, JsonCache jsonCache) {
this.player = player; this.player = player;
try { DataFileCache cache = jsonCache.readCache(player);
this.inventory = fileCache.readCache(player).getInventory(); if (cache != null) {
this.armor = fileCache.readCache(player).getArmour(); this.inventory = cache.getInventory();
} catch (Exception e) { this.armor = cache.getArmour();
} else {
this.inventory = player.getInventory().getContents(); this.inventory = player.getInventory().getContents();
this.armor = player.getInventory().getArmorContents(); this.armor = player.getInventory().getArmorContents();
} }

View File

@ -1,16 +1,13 @@
package fr.xephi.authme.listener; package fr.xephi.authme.listener;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Settings;
public class AuthMeBlockListener implements Listener { public class AuthMeBlockListener implements Listener {
public AuthMe instance; public AuthMe instance;
@ -22,51 +19,17 @@ public class AuthMeBlockListener implements Listener {
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) { public void onBlockPlace(BlockPlaceEvent event) {
if (event.getPlayer() == null) { if (Utils.checkAuth(event.getPlayer()))
return; return;
}
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) {
return;
}
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) { public void onBlockBreak(BlockBreakEvent event) {
if (event.getPlayer() == null) {
return;
}
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); if (player == null || Utils.checkAuth(player)) {
if (Utils.getInstance().isUnrestricted(player)) {
return; return;
} }
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }

View File

@ -1,17 +1,12 @@
package fr.xephi.authme.listener; package fr.xephi.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;
import com.Acrobot.ChestShop.Events.PreTransactionEvent.TransactionOutcome; import com.Acrobot.ChestShop.Events.PreTransactionEvent.TransactionOutcome;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerCache; import org.bukkit.event.EventHandler;
import fr.xephi.authme.settings.Settings; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public class AuthMeChestShopListener implements Listener { public class AuthMeChestShopListener implements Listener {
@ -23,26 +18,8 @@ public class AuthMeChestShopListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPreTransaction(PreTransactionEvent event) { public void onPreTransaction(PreTransactionEvent event) {
if (event.getClient() == null) { if (Utils.checkAuth(event.getClient()))
return; return;
}
Player player = event.getClient();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) {
return;
}
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(TransactionOutcome.OTHER); event.setCancelled(TransactionOutcome.OTHER);
} }
} }

View File

@ -1,22 +1,14 @@
package fr.xephi.authme.listener; package fr.xephi.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.EntityDamageByEntityEvent;
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 fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerCache; import org.bukkit.entity.Entity;
import fr.xephi.authme.plugin.manager.CombatTagComunicator; import org.bukkit.entity.Player;
import fr.xephi.authme.settings.Settings; import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.*;
public class AuthMeEntityListener implements Listener { public class AuthMeEntityListener implements Listener {
@ -29,32 +21,13 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityDamage(EntityDamageEvent event) { public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
if (!(entity instanceof Player)) {
return; return;
} }
if (Utils.getInstance().isUnrestricted((Player) entity)) {
return;
}
if (instance.citizens.isNPC(entity))
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); if (Utils.checkAuth(player)) {
if (CombatTagComunicator.isNPC(player))
return; return;
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
} }
player.setFireTicks(0); player.setFireTicks(0);
event.setDamage(0.0); event.setDamage(0.0);
@ -63,28 +36,15 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityTarget(EntityTargetEvent event) { public void onEntityTarget(EntityTargetEvent event) {
if (event.getTarget() == null)
return;
Entity entity = event.getTarget(); Entity entity = event.getTarget();
if (!(entity instanceof Player)) { if (entity == null || !(entity instanceof Player)) {
return; return;
} }
if (instance.citizens.isNPC(entity)) if (Utils.checkAuth((Player) entity)) {
return;
Player player = (Player) entity;
String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name)) {
return; return;
} }
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setTarget(null); event.setTarget(null);
event.setCancelled(true); event.setCancelled(true);
} }
@ -92,75 +52,41 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onDmg(EntityDamageByEntityEvent event) { public void onDmg(EntityDamageByEntityEvent event) {
Entity entity = event.getDamager(); Entity entity = event.getDamager();
if (entity == null || !(entity instanceof Player)) { if (entity == null || !(entity instanceof Player)) {
return; return;
} }
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); if (Utils.checkAuth(player)) {
if (PlayerCache.getInstance().isAuthenticated(name)) {
return; return;
} }
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onFoodLevelChange(FoodLevelChangeEvent event) { public void onFoodLevelChange(FoodLevelChangeEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (!(entity instanceof Player)) { if (entity == null || !(entity instanceof Player)) {
return; return;
} }
if (instance.citizens.isNPC(entity)) if (Utils.checkAuth((Player) entity)) {
return; return;
Player player = (Player) entity;
String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
} }
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void EntityRegainHealthEvent(EntityRegainHealthEvent event) { public void entityRegainHealthEvent(EntityRegainHealthEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (!(entity instanceof Player)) { if (entity == null || !(entity instanceof Player)) {
return; return;
} }
if (instance.citizens.isNPC(entity)) if (Utils.checkAuth((Player) entity)) {
return; return;
Player player = (Player) entity;
String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
} }
event.setAmount(0.0); event.setAmount(0.0);
@ -169,57 +95,63 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onEntityInteract(EntityInteractEvent event) { public void onEntityInteract(EntityInteractEvent event) {
if (!(event.getEntity() instanceof Player)) { Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return; return;
} }
Player player = (Player) event.getEntity(); if (Utils.checkAuth((Player) entity)) {
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
return; return;
} }
if (instance.citizens.isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName())) {
return;
}
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onLowestEntityInteract(EntityInteractEvent event) { public void onLowestEntityInteract(EntityInteractEvent event) {
if (!(event.getEntity() instanceof Player)) { Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return; return;
} }
Player player = (Player) event.getEntity(); if (Utils.checkAuth((Player) entity)) {
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
return; return;
} }
if (instance.citizens.isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName())) {
return;
}
if (!instance.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(priority = EventPriority.HIGHEST)
public void onProjectileLaunch(ProjectileLaunchEvent event) {
Projectile projectile = event.getEntity();
if (projectile == null)
return;
Entity shooter = (Entity) projectile.getShooter();
if (shooter == null || !(shooter instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) shooter)) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onShoot(EntityShootBowEvent event) {
Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
if (Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
} }

View File

@ -1,20 +1,20 @@
package fr.xephi.authme.listener; package fr.xephi.authme.listener;
import java.io.ByteArrayOutputStream; import com.google.common.io.ByteArrayDataOutput;
import java.io.DataOutputStream; import com.google.common.io.ByteStreams;
import java.io.IOException; import fr.xephi.authme.AuthMe;
import java.lang.reflect.InvocationTargetException; import fr.xephi.authme.ConsoleLogger;
import java.util.ArrayList; import fr.xephi.authme.Utils;
import java.util.Arrays; import fr.xephi.authme.cache.auth.PlayerAuth;
import java.util.Collection; import fr.xephi.authme.cache.auth.PlayerCache;
import java.util.List; import fr.xephi.authme.cache.limbo.LimboCache;
import java.util.concurrent.ConcurrentHashMap; import fr.xephi.authme.cache.limbo.LimboPlayer;
import java.util.regex.PatternSyntaxException; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -24,65 +24,51 @@ import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.*;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
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.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import fr.xephi.authme.AuthMe; import java.util.ArrayList;
import fr.xephi.authme.ConsoleLogger; import java.util.Arrays;
import fr.xephi.authme.Utils; import java.util.List;
import fr.xephi.authme.cache.auth.PlayerAuth; import java.util.concurrent.ConcurrentHashMap;
import fr.xephi.authme.cache.auth.PlayerCache; import java.util.regex.PatternSyntaxException;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class AuthMePlayerListener implements Listener { public class AuthMePlayerListener implements Listener {
public static ConcurrentHashMap<String, GameMode> gameMode = new ConcurrentHashMap<String, GameMode>(); public static ConcurrentHashMap<String, GameMode> gameMode = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, String> joinMessage = new ConcurrentHashMap<String, String>(); public static ConcurrentHashMap<String, String> joinMessage = new ConcurrentHashMap<>();
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
public AuthMe plugin; public AuthMe plugin;
public static ConcurrentHashMap<String, Boolean> causeByAuthMe = new ConcurrentHashMap<String, Boolean>(); public static ConcurrentHashMap<String, Boolean> causeByAuthMe = new ConcurrentHashMap<>();
private List<String> antibot = new ArrayList<String>(); private List<String> antibot = new ArrayList<>();
public AuthMePlayerListener(AuthMe plugin) { public AuthMePlayerListener(AuthMe plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
private void handleChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (!Utils.checkAuth(player)) {
String cmd = event.getMessage().split(" ")[0];
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
}
if (plugin.database.isAuthAvailable(player.getName().toLowerCase())) {
m.send(player, "login_msg");
} else {
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
} else {
m.send(player, "reg_msg");
}
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (event.getPlayer() == null) if (Utils.checkAuth(event.getPlayer()))
return; return;
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
if (!plugin.database.isAuthAvailable(name))
if (!Settings.isForcedRegistrationEnabled)
return;
String msg = event.getMessage(); String msg = event.getMessage();
if (msg.equalsIgnoreCase("/worldedit cui")) if (msg.equalsIgnoreCase("/worldedit cui"))
return; return;
@ -101,246 +87,39 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerNormalChat(AsyncPlayerChatEvent event) { public void onPlayerNormalChat(AsyncPlayerChatEvent event) {
if (event.getPlayer() == null) handleChat(event);
return;
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
String cmd = event.getMessage().split(" ")[0];
if (plugin.database.isAuthAvailable(name)) {
m.send(player, "login_msg");
} else {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
return;
} else {
m.send(player, "reg_msg");
return;
}
}
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
return;
}
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerHighChat(AsyncPlayerChatEvent event) { public void onPlayerHighChat(AsyncPlayerChatEvent event) {
if (event.getPlayer() == null) handleChat(event);
return;
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
String cmd = event.getMessage().split(" ")[0];
if (plugin.database.isAuthAvailable(name)) {
m.send(player, "login_msg");
} else {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
return;
} else {
m.send(player, "reg_msg");
return;
}
}
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
return;
}
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerChat(AsyncPlayerChatEvent event) { public void onPlayerChat(AsyncPlayerChatEvent event) {
if (event.getPlayer() == null) handleChat(event);
return;
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
String cmd = event.getMessage().split(" ")[0];
if (plugin.database.isAuthAvailable(name)) {
m.send(player, "login_msg");
} else {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
return;
} else {
m.send(player, "reg_msg");
return;
}
}
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
return;
}
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerHighestChat(AsyncPlayerChatEvent event) { public void onPlayerHighestChat(AsyncPlayerChatEvent event) {
if (event.getPlayer() == null) handleChat(event);
return;
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
String cmd = event.getMessage().split(" ")[0];
if (plugin.database.isAuthAvailable(name)) {
m.send(player, "login_msg");
} else {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
return;
} else {
m.send(player, "reg_msg");
return;
}
}
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
return;
}
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerEarlyChat(final AsyncPlayerChatEvent event) { public void onPlayerEarlyChat(AsyncPlayerChatEvent event) {
if (event.getPlayer() == null) handleChat(event);
return;
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
String cmd = event.getMessage().split(" ")[0];
if (plugin.database.isAuthAvailable(name)) {
m.send(player, "login_msg");
} else {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
return;
} else {
m.send(player, "reg_msg");
return;
}
}
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
return;
}
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void onPlayerLowChat(AsyncPlayerChatEvent event) { public void onPlayerLowChat(AsyncPlayerChatEvent event) {
if (event.getPlayer() == null) handleChat(event);
return;
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
String cmd = event.getMessage().split(" ")[0];
if (plugin.database.isAuthAvailable(name)) {
m.send(player, "login_msg");
} else {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
} else {
m.send(player, "reg_msg");
}
}
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
return;
}
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) { public void onPlayerMove(PlayerMoveEvent event) {
if (event.getPlayer() == null) {
return;
}
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); if (Utils.checkAuth(player))
if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
return; return;
}
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!Settings.isForcedRegistrationEnabled) {
if (!plugin.database.isAuthAvailable(name))
return;
}
if (!Settings.isMovementAllowed) { if (!Settings.isMovementAllowed) {
if (!event.getFrom().getBlock().equals(event.getTo().getBlock())) if (!event.getFrom().getBlock().equals(event.getTo().getBlock()))
@ -362,7 +141,6 @@ public class AuthMePlayerListener implements Listener {
} }
if ((spawn.distance(player.getLocation()) > radius)) { if ((spawn.distance(player.getLocation()) > radius)) {
event.getPlayer().teleport(spawn); event.getPlayer().teleport(spawn);
return;
} }
} }
} }
@ -401,16 +179,14 @@ public class AuthMePlayerListener implements Listener {
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(PlayerJoinEvent e) { public void onPlayerJoin(final PlayerJoinEvent event) {
final PlayerJoinEvent event = e;
if (event.getPlayer() == null) { if (event.getPlayer() == null) {
return; return;
} }
// Shedule login task so works after the prelogin // Shedule login task so works after the prelogin
// (Fix found by Koolaid5000) // (Fix found by Koolaid5000)
Bukkit.getScheduler().runTask(plugin, new Runnable(){ Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
Player player = event.getPlayer(); Player player = event.getPlayer();
@ -419,20 +195,20 @@ public class AuthMePlayerListener implements Listener {
plugin.management.performJoin(player); plugin.management.performJoin(player);
// Remove the join message while the player isn't logging in // Remove the join message while the player isn't logging in
if ((Settings.enableProtection || Settings.delayJoinMessage) && name != null && event.getJoinMessage() != null) { if ((Settings.enableProtection || Settings.delayJoinMessage) && event.getJoinMessage() != null) {
joinMessage.put(name, event.getJoinMessage()); joinMessage.put(name, event.getJoinMessage());
event.setJoinMessage(null); event.setJoinMessage(null);
} }
} }
}); });
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPreLogin(AsyncPlayerPreLoginEvent event){ public void onPreLogin(AsyncPlayerPreLoginEvent event) {
final String name = event.getName().toLowerCase(); final String name = event.getName().toLowerCase();
final Player player = Bukkit.getServer().getPlayer(name); final Player player = Bukkit.getServer().getPlayer(name);
if (player == null) if (player == null)
return; return;
@ -443,18 +219,17 @@ public class AuthMePlayerListener implements Listener {
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
if (LimboCache.getInstance().hasLimboPlayer(name)) if (LimboCache.getInstance().hasLimboPlayer(name))
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
if (limbo != null && PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (limbo != null && PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
Utils.getInstance().addNormal(player, limbo.getGroup()); Utils.addNormal(player, limbo.getGroup());
LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase()); LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase());
} }
} }
}); });
return;
} }
} }
@ -466,7 +241,7 @@ public class AuthMePlayerListener implements Listener {
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
boolean isAuthAvailable = plugin.database.isAuthAvailable(name); boolean isAuthAvailable = plugin.database.isAuthAvailable(name);
if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return; return;
} }
@ -474,7 +249,7 @@ public class AuthMePlayerListener implements Listener {
return; return;
if (!Settings.countriesBlacklist.isEmpty()) { if (!Settings.countriesBlacklist.isEmpty()) {
String code = plugin.getCountryCode(event.getAddress().getHostAddress()); String code = Utils.getCountryCode(event.getAddress().getHostAddress());
if (((code == null) || (Settings.countriesBlacklist.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) { if (((code == null) || (Settings.countriesBlacklist.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) {
event.setKickMessage(m.send("country_banned")[0]); event.setKickMessage(m.send("country_banned")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER); event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
@ -482,7 +257,7 @@ public class AuthMePlayerListener implements Listener {
} }
} }
if (Settings.enableProtection && !Settings.countries.isEmpty()) { if (Settings.enableProtection && !Settings.countries.isEmpty()) {
String code = plugin.getCountryCode(event.getAddress().getHostAddress()); String code = Utils.getCountryCode(event.getAddress().getHostAddress());
if (((code == null) || (!Settings.countries.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) { if (((code == null) || (!Settings.countries.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) {
event.setKickMessage(m.send("country_banned")[0]); event.setKickMessage(m.send("country_banned")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER); event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
@ -491,7 +266,7 @@ public class AuthMePlayerListener implements Listener {
} }
if (Settings.isKickNonRegisteredEnabled && !Settings.antiBotInAction) { if (Settings.isKickNonRegisteredEnabled && !Settings.antiBotInAction) {
if (!plugin.database.isAuthAvailable(name)) { if (!isAuthAvailable) {
event.setKickMessage(m.send("reg_only")[0]); event.setKickMessage(m.send("reg_only")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER); event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return; return;
@ -499,14 +274,14 @@ public class AuthMePlayerListener implements Listener {
} }
if (Settings.antiBotInAction) { if (Settings.antiBotInAction) {
if (!plugin.database.isAuthAvailable(name)) { if (!isAuthAvailable) {
event.setKickMessage("AntiBot service in action! You actually need to be registered!"); event.setKickMessage("AntiBot service in action! You actually need to be registered!");
event.setResult(PlayerLoginEvent.Result.KICK_OTHER); event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return; return;
} }
} }
if (plugin.database.isAuthAvailable(name) && plugin.database.getType() != DataSource.DataSourceType.FILE) { if (isAuthAvailable && plugin.database.getType() != DataSource.DataSourceType.FILE) {
PlayerAuth auth = plugin.database.getAuth(name); PlayerAuth auth = plugin.database.getAuth(name);
if (auth.getRealName() != null && !auth.getRealName().isEmpty() && !auth.getRealName().equalsIgnoreCase("Player") && !auth.getRealName().equals(player.getName())) { if (auth.getRealName() != null && !auth.getRealName().isEmpty() && !auth.getRealName().equalsIgnoreCase("Player") && !auth.getRealName().equals(player.getName())) {
event.setKickMessage(m.send("same_nick")[0]); event.setKickMessage(m.send("same_nick")[0]);
@ -556,14 +331,9 @@ public class AuthMePlayerListener implements Listener {
if (event.getResult() == PlayerLoginEvent.Result.ALLOWED) { if (event.getResult() == PlayerLoginEvent.Result.ALLOWED) {
checkAntiBotMod(player); checkAntiBotMod(player);
if (Settings.bungee) { if (Settings.bungee) {
final ByteArrayOutputStream b = new ByteArrayOutputStream(); ByteArrayDataOutput out = ByteStreams.newDataOutput();
DataOutputStream out = new DataOutputStream(b); out.writeUTF("IP");
player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
try {
out.writeUTF("IP");
} catch (IOException e) {
}
player.sendPluginMessage(plugin, "BungeeCord", b.toByteArray());
} }
return; return;
} }
@ -575,31 +345,18 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
int playersOnline = 0; int playersOnline = Utils.getOnlinePlayers().size();
try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class)
playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).size();
else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).length;
} catch (NoSuchMethodException ex) {
} // can never happen
catch (InvocationTargetException ex) {
} // can also never happen
catch (IllegalAccessException ex) {
} // can still never happen
if (playersOnline > plugin.getServer().getMaxPlayers()) { if (playersOnline > plugin.getServer().getMaxPlayers()) {
event.allow(); event.allow();
return;
} else { } else {
final Player pl = plugin.generateKickPlayer(plugin.getServer().getOnlinePlayers()); final Player pl = plugin.generateKickPlayer(Utils.getOnlinePlayers());
if (pl != null) { if (pl != null) {
pl.kickPlayer(m.send("kick_forvip")[0]); pl.kickPlayer(m.send("kick_forvip")[0]);
event.allow(); event.allow();
return;
} else { } else {
ConsoleLogger.info("The player " + player.getName() + " tryed to join, but the server was full"); ConsoleLogger.info("The player " + player.getName() + " tryed to join, but the server was full");
event.setKickMessage(m.send("kick_fullserver")[0]); event.setKickMessage(m.send("kick_fullserver")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_FULL); event.setResult(PlayerLoginEvent.Result.KICK_FULL);
return;
} }
} }
} }
@ -615,7 +372,7 @@ public class AuthMePlayerListener implements Listener {
plugin.management.performQuit(player, false); plugin.management.performQuit(player, false);
if (plugin.database.getAuth(name) != null && !PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection) if (plugin.database.isAuthAvailable(name) && !PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection)
event.setQuitMessage(null); event.setQuitMessage(null);
} }
@ -625,94 +382,42 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
Player player = event.getPlayer();
if ((!Settings.isForceSingleSessionEnabled) && (event.getReason().contains(m.getString("same_nick")))) { if ((!Settings.isForceSingleSessionEnabled) && (event.getReason().contains(m.getString("same_nick")))) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
Player player = event.getPlayer();
plugin.management.performQuit(player, true); plugin.management.performQuit(player, true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerPickupItem(PlayerPickupItemEvent event) { public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if (event.getPlayer() == null) { if (Utils.checkAuth(event.getPlayer()))
return; return;
}
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) {
return;
}
if (plugin.getCitizensCommunicator().isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getPlayer() == null)
return;
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); if (player == null || Utils.checkAuth(player))
if (Utils.getInstance().isUnrestricted(player)) {
return; return;
}
if (plugin.getCitizensCommunicator().isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
if (event.getClickedBlock() != null && event.getClickedBlock().getType() != Material.AIR)
event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY);
event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerConsumeItem(PlayerItemConsumeEvent event) {
if (Utils.checkAuth(event.getPlayer()))
return;
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerInventoryOpen(InventoryOpenEvent event) { public void onPlayerInventoryOpen(InventoryOpenEvent event) {
if (event.getPlayer() == null)
return;
final Player player = (Player) event.getPlayer(); final Player player = (Player) event.getPlayer();
String name = player.getName().toLowerCase(); if (Utils.checkAuth(player))
if (Utils.getInstance().isUnrestricted(player)) {
return; return;
}
if (plugin.getCitizensCommunicator().isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
/* /*
@ -724,7 +429,6 @@ public class AuthMePlayerListener implements Listener {
@Override @Override
public void run() { public void run() {
player.closeInventory(); player.closeInventory();
;
} }
}, 1); }, 1);
@ -736,219 +440,115 @@ public class AuthMePlayerListener implements Listener {
return; return;
if (!(event.getWhoClicked() instanceof Player)) if (!(event.getWhoClicked() instanceof Player))
return; return;
Player player = (Player) event.getWhoClicked(); if (Utils.checkAuth((Player) event.getWhoClicked()))
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) {
return; return;
}
if (plugin.getCitizensCommunicator().isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setResult(org.bukkit.event.Event.Result.DENY);
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void playerHitPlayerEvent(EntityDamageByEntityEvent event) { public void playerHitPlayerEvent(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager(); Entity damager = event.getDamager();
if (!(damager instanceof Player)){ if (!(damager instanceof Player)) {
return; return;
} }
if (Utils.checkAuth((Player) damager))
Player player = (Player) damager;
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) {
return; return;
}
if (plugin.getCitizensCommunicator().isNPC(player)) {
return;
}
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
return;
}
if (!plugin.database.isAuthAvailable(name) && !Settings.isForcedRegistrationEnabled) {
return;
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (event.getPlayer() == null) {
return;
}
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); if (player == null || Utils.checkAuth(player))
if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
return; return;
} event.setCancelled(true);
}
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player))
return; return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerDropItem(PlayerDropItemEvent event) { public void onPlayerDropItem(PlayerDropItemEvent event) {
if (event.getPlayer() == null) { if (Utils.checkAuth(event.getPlayer()))
return; return;
}
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
return;
}
if (plugin.getCitizensCommunicator().isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerBedEnter(PlayerBedEnterEvent event) { public void onPlayerBedEnter(PlayerBedEnterEvent event) {
if (event.getPlayer() == null) { if (Utils.checkAuth(event.getPlayer()))
return; return;
}
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) {
return;
}
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onSignChange(SignChangeEvent event) { public void onSignChange(SignChangeEvent event) {
if (event.getPlayer() == null) { if (Utils.checkAuth(event.getPlayer()))
return; return;
}
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) {
return;
}
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
}
if (!plugin.database.isAuthAvailable(name)) {
if (!Settings.isForcedRegistrationEnabled) {
return;
}
}
event.setCancelled(true); event.setCancelled(true);
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) { public void onPlayerRespawn(PlayerRespawnEvent event) {
if (event.getPlayer() == null) {
return;
}
Player player = event.getPlayer(); Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player))
return;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player))
return;
if (plugin.getCitizensCommunicator().isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
if (!plugin.database.isAuthAvailable(name))
if (!Settings.isForcedRegistrationEnabled)
return;
Location spawn = plugin.getSpawnLocation(player); Location spawn = plugin.getSpawnLocation(player);
if (Settings.isSaveQuitLocationEnabled && plugin.database.isAuthAvailable(name)) { if (Settings.isSaveQuitLocationEnabled && plugin.database.isAuthAvailable(name)) {
final PlayerAuth auth = new PlayerAuth(name, spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getWorld().getName(), player.getName()); final PlayerAuth auth = new PlayerAuth(name, spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getWorld().getName(), player.getName());
try { plugin.database.updateQuitLoc(auth);
plugin.database.updateQuitLoc(auth);
} catch (NullPointerException npe) {
}
} }
if (spawn != null && spawn.getWorld() != null) if (spawn != null && spawn.getWorld() != null) {
event.setRespawnLocation(spawn); event.setRespawnLocation(spawn);
}
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
if (event.getPlayer() == null)
return;
Player player = event.getPlayer(); Player player = event.getPlayer();
if (player == null)
return;
if (plugin.authmePermissible(player, "authme.bypassforcesurvival")) if (plugin.authmePermissible(player, "authme.bypassforcesurvival"))
return; return;
if (Utils.checkAuth(player))
return;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player))
return;
if (plugin.getCitizensCommunicator().isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name))
return;
if (!plugin.database.isAuthAvailable(name))
if (!Settings.isForcedRegistrationEnabled)
return;
if (causeByAuthMe.containsKey(name)) { if (causeByAuthMe.containsKey(name)) {
causeByAuthMe.remove(name); causeByAuthMe.remove(name);
return; return;
} }
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerShear(PlayerShearEntityEvent event) {
Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player))
return;
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerFish(PlayerFishEvent event) {
Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player))
return;
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerEditBook(PlayerEditBookEvent event) {
Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player))
return;
event.setCancelled(true); event.setCancelled(true);
} }
} }

View File

@ -1,5 +1,10 @@
package fr.xephi.authme.listener; package fr.xephi.authme.listener;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@ -7,11 +12,6 @@ import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.ServerListPingEvent; import org.bukkit.event.server.ServerListPingEvent;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class AuthMeServerListener implements Listener { public class AuthMeServerListener implements Listener {
public AuthMe plugin; public AuthMe plugin;
@ -28,10 +28,10 @@ public class AuthMeServerListener implements Listener {
if (Settings.countries.isEmpty()) if (Settings.countries.isEmpty())
return; return;
if (!Settings.countriesBlacklist.isEmpty()) { if (!Settings.countriesBlacklist.isEmpty()) {
if (Settings.countriesBlacklist.contains(plugin.getCountryCode(event.getAddress().getHostAddress()))) if (Settings.countriesBlacklist.contains(Utils.getCountryCode(event.getAddress().getHostAddress())))
event.setMotd(m.send("country_banned")[0]); event.setMotd(m.send("country_banned")[0]);
} }
if (Settings.countries.contains(plugin.getCountryCode(event.getAddress().getHostAddress()))) { if (Settings.countries.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) {
event.setMotd(plugin.getServer().getMotd()); event.setMotd(plugin.getServer().getMotd());
} else { } else {
event.setMotd(m.send("country_banned")[0]); event.setMotd(m.send("country_banned")[0]);
@ -57,16 +57,12 @@ public class AuthMeServerListener implements Listener {
return; return;
} }
if (pluginName.equalsIgnoreCase("ChestShop")) { if (pluginName.equalsIgnoreCase("ChestShop")) {
plugin.ChestShop = 0; plugin.legacyChestShop = false;
ConsoleLogger.info("ChestShop has been disabled, unhook!"); ConsoleLogger.info("ChestShop has been disabled, unhook!");
} }
if (pluginName.equalsIgnoreCase("CombatTag")) { if (pluginName.equalsIgnoreCase("CombatTagPlus")) {
plugin.CombatTag = false; plugin.combatTagPlus = null;
ConsoleLogger.info("CombatTag has been disabled, unhook!"); ConsoleLogger.info("CombatTagPlus has been disabled, unhook!");
}
if (pluginName.equalsIgnoreCase("Citizens")) {
plugin.isCitizensActive = false;
ConsoleLogger.info("Citizens has been disabled, unhook!");
} }
if (pluginName.equalsIgnoreCase("Vault")) { if (pluginName.equalsIgnoreCase("Vault")) {
plugin.permission = null; plugin.permission = null;
@ -83,10 +79,8 @@ public class AuthMeServerListener implements Listener {
plugin.checkMultiverse(); plugin.checkMultiverse();
if (pluginName.equalsIgnoreCase("ChestShop")) if (pluginName.equalsIgnoreCase("ChestShop"))
plugin.checkChestShop(); plugin.checkChestShop();
if (pluginName.equalsIgnoreCase("CombatTag")) if (pluginName.equalsIgnoreCase("CombatTagPlus"))
plugin.checkCombatTag(); plugin.checkCombatTagPlus();
if (pluginName.equalsIgnoreCase("Citizens"))
plugin.checkCitizens();
if (pluginName.equalsIgnoreCase("Vault")) if (pluginName.equalsIgnoreCase("Vault"))
plugin.checkVault(); plugin.checkVault();
} }

View File

@ -1,28 +1,24 @@
package fr.xephi.authme.modules; package fr.xephi.authme.modules;
import fr.xephi.authme.AuthMe; public abstract class Module {
public interface Module { enum ModuleType {
public String getName();
public AuthMe getInstanceOfAuthMe();
public Module getInstance();
public enum ModuleType {
MANAGER, MANAGER,
MYSQL, MYSQL,
REDIS, REDIS,
ACTIONS, ACTIONS,
CONVERTERS, CONVERTERS,
EMAILS, EMAILS,
CUSTOM; CUSTOM
} }
public ModuleType getType(); public abstract String getName();
public boolean load(); public abstract ModuleType getType();
public boolean unload(); public void load() {
}
public void unload() {
}
} }

View File

@ -1,63 +1,80 @@
package fr.xephi.authme.modules; package fr.xephi.authme.modules;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import fr.xephi.authme.AuthMe; public class ModuleManager {
import fr.xephi.authme.ConsoleLogger;
public class ModuleManager implements Module { private List<Module> modules = new ArrayList<>();
private AuthMe plugin;
private ModuleManager instance;
private List<Module> modules = new ArrayList<Module>();
public ModuleManager(AuthMe plugin) { public ModuleManager(AuthMe plugin) {
this.plugin = plugin;
} }
@Override public boolean isModuleEnabled(String name) {
public String getName() { for (Module m : modules) {
return "AuthMe Module Manager"; if (m.getName().equalsIgnoreCase(name))
return true;
}
return false;
} }
@Override public boolean isModuleEnabled(Module.ModuleType type) {
public AuthMe getInstanceOfAuthMe() { for (Module m : modules) {
return this.plugin; if (m.getType() == type)
return true;
}
return false;
} }
@Override public Module getModule(String name) {
public Module getInstance() { for (Module m : modules) {
if (this.instance == null) if (m.getName().equalsIgnoreCase(name))
instance = new ModuleManager(AuthMe.getInstance()); return m;
return instance; }
return null;
} }
@Override public Module getModule(Module.ModuleType type) {
public ModuleType getType() { for (Module m : modules) {
return (Module.ModuleType.MANAGER); if (m.getType() == type)
return m;
}
return null;
} }
@Override public int loadModules() {
public boolean load() { File dir = Settings.MODULE_FOLDER;
File dir = new File(plugin.getDataFolder() + File.separator + "modules"); int count = 0;
if (dir == null || !dir.exists() || !dir.isDirectory() || dir.listFiles() == null || dir.listFiles().length <= 0) if (!dir.isDirectory()) {
return false; dir.mkdirs();
for (File pathToJar : dir.listFiles()) { return count;
}
File[] files = dir.listFiles();
if (files == null) {
return count;
}
for (File pathToJar : files) {
JarFile jarFile = null; JarFile jarFile = null;
URLClassLoader cl = null;
try { try {
jarFile = new JarFile(pathToJar); jarFile = new JarFile(pathToJar);
Enumeration<?> e = jarFile.entries(); URL[] urls = {new URL("jar:file:" + pathToJar.getAbsolutePath() + "!/")};
URL[] urls = { new URL("jar:file:" + pathToJar.getAbsolutePath() + "!/") }; cl = URLClassLoader.newInstance(urls);
URLClassLoader cl = URLClassLoader.newInstance(urls);
Enumeration<?> e = jarFile.entries();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement(); JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith("Main.class")) { if (je.isDirectory() || !je.getName().endsWith("Main.class")) {
@ -66,35 +83,53 @@ public class ModuleManager implements Module {
String className = je.getName().substring(0, je.getName().length() - 6); String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.'); className = className.replace('/', '.');
Class<?> c = cl.loadClass(className); Class<?> c = cl.loadClass(className);
if (!Module.class.isAssignableFrom(c)) {
continue;
}
Module mod = (Module) c.newInstance(); Module mod = (Module) c.newInstance();
mod.load(); mod.load();
modules.add(mod); modules.add(mod);
count++;
break; break;
} }
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.writeStackTrace(ex);
ConsoleLogger.showError("Cannot load " + pathToJar.getName() + " jar file !"); ConsoleLogger.showError("Cannot load " + pathToJar.getName() + " jar file !");
} finally { } finally {
if (jarFile != null) try {
try { if (jarFile != null) {
jarFile.close(); jarFile.close();
} catch (IOException e) {
} }
if (cl != null) {
cl.close();
}
} catch (IOException ignored) {
}
} }
} }
return true; return count;
} }
@Override public void unloadModule(String name) {
public boolean unload() { Iterator<Module> it = modules.iterator();
try { while (it.hasNext()) {
for (Module mod : modules) { Module m = it.next();
mod.unload(); if (m.getName().equalsIgnoreCase(name)) {
modules.remove(mod); m.unload();
it.remove();
return;
} }
} catch (Exception e) {
} }
return true; }
public void unloadModules() {
Iterator<Module> it = modules.iterator();
while (it.hasNext()) {
it.next().unload();
it.remove();
}
} }
} }

View File

@ -1,14 +1,11 @@
package fr.xephi.authme.plugin.manager; package fr.xephi.authme.plugin.manager;
import java.io.ByteArrayInputStream; import com.google.common.io.ByteArrayDataInput;
import java.io.DataInputStream; import com.google.common.io.ByteStreams;
import java.io.IOException; import fr.xephi.authme.AuthMe;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener; import org.bukkit.plugin.messaging.PluginMessageListener;
import fr.xephi.authme.AuthMe;
public class BungeeCordMessage implements PluginMessageListener { public class BungeeCordMessage implements PluginMessageListener {
public AuthMe plugin; public AuthMe plugin;
@ -19,19 +16,16 @@ public class BungeeCordMessage implements PluginMessageListener {
@Override @Override
public void onPluginMessageReceived(String channel, Player player, public void onPluginMessageReceived(String channel, Player player,
byte[] message) { byte[] message) {
if (!channel.equals("BungeeCord")) { if (!channel.equals("BungeeCord")) {
return; return;
} }
try { ByteArrayDataInput in = ByteStreams.newDataInput(message);
final DataInputStream in = new DataInputStream(new ByteArrayInputStream(message)); String subChannel = in.readUTF();
String subchannel = in.readUTF(); if (subChannel.equals("IP")) { // We need only the IP channel
if (subchannel.equals("IP")) { // We need only the IP channel String ip = in.readUTF();
String ip = in.readUTF(); // Put the IP (only the ip not the port) in the hashMap
plugin.realIp.put(player.getName().toLowerCase(), ip); plugin.realIp.put(player.getName().toLowerCase(), ip);
// Put the IP (only the ip not the port) in the hashmap
}
} catch (IOException ex) {
} }
} }

View File

@ -1,27 +0,0 @@
package fr.xephi.authme.plugin.manager;
import org.bukkit.entity.Entity;
import fr.xephi.authme.AuthMe;
import net.citizensnpcs.api.CitizensAPI;
public class CitizensCommunicator {
public AuthMe instance;
public CitizensCommunicator(AuthMe instance) {
this.instance = instance;
}
public boolean isNPC(final Entity player) {
if (!this.instance.isCitizensActive)
return false;
try {
return CitizensAPI.getNPCRegistry().isNPC(player);
} catch (NoClassDefFoundError ncdfe) {
return false;
} catch (Exception npe) {
return false;
}
}
}

View File

@ -1,49 +0,0 @@
package fr.xephi.authme.plugin.manager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.trc202.CombatTag.CombatTag;
import com.trc202.CombatTagApi.CombatTagApi;
import fr.xephi.authme.AuthMe;
import net.minelink.ctplus.CombatTagPlus;
public abstract class CombatTagComunicator {
public static CombatTagApi combatApi;
/**
* Returns if the entity is an NPC
*
* @param player
* @return true if the player is an NPC
*/
public static boolean isNPC(Entity player) {
if (!AuthMe.getInstance().CombatTag)
return false;
try {
if (Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null) {
combatApi = new CombatTagApi((CombatTag) Bukkit.getServer().getPluginManager().getPlugin("CombatTag"));
try {
combatApi.getClass().getMethod("isNPC");
} catch (Exception e) {
return false;
}
return combatApi.isNPC(player);
} else {
Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("CombatTagPlus");
return (plugin != null && plugin instanceof CombatTagPlus && player instanceof Player && ((CombatTagPlus) plugin).getNpcPlayerHelper().isNpc((Player) player));
}
} catch (ClassCastException ex) {
return false;
} catch (NullPointerException npe) {
return false;
} catch (NoClassDefFoundError ncdfe) {
return false;
}
}
}

View File

@ -30,8 +30,7 @@ public class Management {
this.pm = plugin.getServer().getPluginManager(); this.pm = plugin.getServer().getPluginManager();
} }
public void performLogin(final Player player, final String password, public void performLogin(final Player player, final String password, final boolean forceLogin) {
final boolean forceLogin) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override @Override
@ -41,8 +40,7 @@ public class Management {
}); });
} }
public void performRegister(final Player player, final String password, public void performRegister(final Player player, final String password, final String email) {
final String email) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override @Override

View File

@ -1,5 +1,25 @@
package fr.xephi.authme.process.join; package fr.xephi.authme.process.join;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.DataFileCache;
import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.FirstSpawnTeleportEvent;
import fr.xephi.authme.events.ProtectInventoryEvent;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
@ -12,43 +32,20 @@ import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.groupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.DataFileCache;
import fr.xephi.authme.cache.backup.FileCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.FirstSpawnTeleportEvent;
import fr.xephi.authme.events.ProtectInventoryEvent;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class AsyncronousJoin { public class AsyncronousJoin {
protected Player player; protected Player player;
protected DataSource database; protected DataSource database;
protected AuthMe plugin; protected AuthMe plugin;
protected String name; protected String name;
private Utils utils = Utils.getInstance();
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
private FileCache playerBackup; private JsonCache playerBackup;
public AsyncronousJoin(Player player, AuthMe plugin, DataSource database) { public AsyncronousJoin(Player player, AuthMe plugin, DataSource database) {
this.player = player; this.player = player;
this.plugin = plugin; this.plugin = plugin;
this.database = database; this.database = database;
this.playerBackup = new FileCache(plugin); this.playerBackup = new JsonCache(plugin);
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
} }
@ -58,15 +55,12 @@ public class AsyncronousJoin {
AuthMePlayerListener.gameMode.putIfAbsent(name, player.getGameMode()); AuthMePlayerListener.gameMode.putIfAbsent(name, player.getGameMode());
BukkitScheduler sched = plugin.getServer().getScheduler(); BukkitScheduler sched = plugin.getServer().getScheduler();
if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return; return;
} }
if (plugin.ess != null && Settings.disableSocialSpy) { if (plugin.ess != null && Settings.disableSocialSpy) {
try { plugin.ess.getUser(player).setSocialSpyEnabled(false);
plugin.ess.getUser(player.getName().toLowerCase()).setSocialSpyEnabled(false);
} catch (NoSuchMethodError e) {
}
} }
final String ip = plugin.getIP(player); final String ip = plugin.getIP(player);
@ -100,7 +94,8 @@ public class AsyncronousJoin {
} }
} }
final Location spawnLoc = plugin.getSpawnLocation(player); final Location spawnLoc = plugin.getSpawnLocation(player);
if (database.isAuthAvailable(name)) { final boolean isAuthAvailable = database.isAuthAvailable(name);
if (isAuthAvailable) {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() { sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@ -132,52 +127,10 @@ public class AsyncronousJoin {
} }
placePlayerSafely(player, spawnLoc); placePlayerSafely(player, spawnLoc);
LimboCache.getInstance().updateLimboPlayer(player); LimboCache.getInstance().updateLimboPlayer(player);
try { DataFileCache dataFile = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour());
DataFileCache dataFile = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour()); playerBackup.createCache(player, dataFile);
playerBackup.createCache(player, dataFile, LimboCache.getInstance().getLimboPlayer(name).getGroup(), LimboCache.getInstance().getLimboPlayer(name).getOperator(), LimboCache.getInstance().getLimboPlayer(name).isFlying()); // protect inventory
} catch (Exception e) { if (Settings.protectInventoryBeforeLogInEnabled) {
ConsoleLogger.showError("Error on creating an inventory cache for " + name + ", maybe inventory wipe in preparation...");
}
} else {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
Utils.forceGM(player);
}
});
}
if (!Settings.unRegisteredGroup.isEmpty()) {
utils.setGroup(player, Utils.groupType.UNREGISTERED);
}
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (!Settings.noTeleport)
if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name));
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (player.isOnline() && tpEvent.getTo() != null) {
if (tpEvent.getTo().getWorld() != null)
player.teleport(tpEvent.getTo());
}
}
}
});
}
}
if (Settings.protectInventoryBeforeLogInEnabled) {
try {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
ProtectInventoryEvent ev = new ProtectInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); ProtectInventoryEvent ev = new ProtectInventoryEvent(player, limbo.getInventory(), limbo.getArmour());
plugin.getServer().getPluginManager().callEvent(ev); plugin.getServer().getPluginManager().callEvent(ev);
@ -196,14 +149,49 @@ public class AsyncronousJoin {
}); });
} }
} catch (NullPointerException ex) {
} }
} else {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
Utils.forceGM(player);
}
});
}
if (!Settings.unRegisteredGroup.isEmpty()) {
Utils.setGroup(player, Utils.GroupType.UNREGISTERED);
}
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (!Settings.noTeleport)
if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name));
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (player.isOnline() && tpEvent.getTo() != null) {
if (tpEvent.getTo().getWorld() != null)
player.teleport(tpEvent.getTo());
}
}
}
});
}
} }
String[] msg; String[] msg;
if (Settings.emailRegistration) { if (Settings.emailRegistration) {
msg = database.isAuthAvailable(name) ? m.send("login_msg") : m.send("reg_email_msg"); msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_email_msg");
} else { } else {
msg = database.isAuthAvailable(name) ? m.send("login_msg") : m.send("reg_msg"); msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_msg");
} }
int time = Settings.getRegistrationTimeout * 20; int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval; int msgInterval = Settings.getWarnMessageInterval;
@ -215,10 +203,10 @@ public class AsyncronousJoin {
} }
if (!LimboCache.getInstance().hasLimboPlayer(name)) if (!LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
if (database.isAuthAvailable(name)) { if (isAuthAvailable) {
utils.setGroup(player, groupType.NOTLOGGEDIN); Utils.setGroup(player, GroupType.NOTLOGGEDIN);
} else { } else {
utils.setGroup(player, groupType.UNREGISTERED); Utils.setGroup(player, GroupType.UNREGISTERED);
} }
sched.scheduleSyncDelayedTask(plugin, new Runnable() { sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@ -235,10 +223,14 @@ public class AsyncronousJoin {
player.performCommand("motd"); player.performCommand("motd");
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setWalkSpeed(0.0f);
player.setFlySpeed(0.0f);
}
} }
}); });
if (Settings.isSessionsEnabled && database.isAuthAvailable(name) && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) { if (Settings.isSessionsEnabled && isAuthAvailable && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) {
if (plugin.sessions.containsKey(name)) if (plugin.sessions.containsKey(name))
plugin.sessions.get(name).cancel(); plugin.sessions.get(name).cancel();
plugin.sessions.remove(name); plugin.sessions.remove(name);
@ -260,32 +252,31 @@ public class AsyncronousJoin {
} }
private boolean needFirstspawn() { private boolean needFirstspawn() {
if (database.isAuthAvailable(player.getName().toLowerCase()) && player.hasPlayedBefore()) if (player.hasPlayedBefore())
return false; return false;
else { if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null)
if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null) return false;
return false; FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn());
FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn()); plugin.getServer().getPluginManager().callEvent(tpEvent);
plugin.getServer().getPluginManager().callEvent(tpEvent); if (!tpEvent.isCancelled()) {
if (!tpEvent.isCancelled()) { if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) {
if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) { final Location fLoc = tpEvent.getTo();
final Location fLoc = tpEvent.getTo(); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
player.teleport(fLoc); player.teleport(fLoc);
} }
}); });
}
} }
return true;
} }
return true;
} }
private void placePlayerSafely(final Player player, private void placePlayerSafely(final Player player,
final Location spawnLoc) { final Location spawnLoc) {
Location loc = null; Location loc = null;
if (spawnLoc == null) if (spawnLoc == null)
return; return;
@ -293,7 +284,7 @@ public class AsyncronousJoin {
return; return;
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())))
return; return;
if (!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) if (!player.hasPlayedBefore())
return; return;
Block b = player.getLocation().getBlock(); Block b = player.getLocation().getBlock();
if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL) { if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL) {

View File

@ -1,14 +1,8 @@
package fr.xephi.authme.process.login; package fr.xephi.authme.process.login;
import java.util.Date;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
@ -20,6 +14,12 @@ import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import java.util.Date;
import java.util.List;
public class AsyncronousLogin { public class AsyncronousLogin {
@ -34,7 +34,7 @@ public class AsyncronousLogin {
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
public AsyncronousLogin(Player player, String password, boolean forceLogin, public AsyncronousLogin(Player player, String password, boolean forceLogin,
AuthMe plugin, DataSource data) { AuthMe plugin, DataSource data) {
this.player = player; this.player = player;
this.password = password; this.password = password;
name = player.getName().toLowerCase(); name = player.getName().toLowerCase();
@ -63,13 +63,9 @@ public class AsyncronousLogin {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)).replace("<theCaptcha>", plugin.cap.get(name))); player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)).replace("<theCaptcha>", plugin.cap.get(name)));
} }
return true; return true;
} else } else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) { plugin.captcha.remove(name);
try { plugin.cap.remove(name);
plugin.captcha.remove(name);
plugin.cap.remove(name);
} catch (NullPointerException npe) {
}
} }
} }
return false; return false;
@ -197,7 +193,6 @@ public class AsyncronousLogin {
}); });
} else { } else {
m.send(player, "wrong_pwd"); m.send(player, "wrong_pwd");
return;
} }
} else { } else {
ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... "); ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... ");
@ -220,17 +215,17 @@ public class AsyncronousLogin {
if (auths.size() == 1) { if (auths.size() == 1) {
return; return;
} }
String message = "[AuthMe] "; StringBuilder message = new StringBuilder("[AuthMe] ");
// String uuidaccounts = // String uuidaccounts =
// "[AuthMe] PlayerNames has %size% links to this UUID : "; // "[AuthMe] PlayerNames has %size% links to this UUID : ";
int i = 0; int i = 0;
for (String account : auths) { for (String account : auths) {
i++; i++;
message = message + account; message.append(account);
if (i != auths.size()) { if (i != auths.size()) {
message = message + ", "; message.append(", ");
} else { } else {
message = message + "."; message.append(".");
} }
} }
/* /*
@ -239,10 +234,10 @@ public class AsyncronousLogin {
* uuidaccounts = uuidaccounts + ", "; } else { uuidaccounts = * uuidaccounts = uuidaccounts + ", "; } else { uuidaccounts =
* uuidaccounts + "."; } } * uuidaccounts + "."; } }
*/ */
for (Player player : plugin.getServer().getOnlinePlayers()) { for (Player player : Utils.getOnlinePlayers()) {
if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) { if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) {
player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts"); player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts");
player.sendMessage(message); player.sendMessage(message.toString());
// player.sendMessage(uuidaccounts.replace("%size%", // player.sendMessage(uuidaccounts.replace("%size%",
// ""+uuidlist.size())); // ""+uuidlist.size()));
} }

View File

@ -9,9 +9,9 @@ import org.bukkit.potion.PotionEffectType;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.groupType; import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.backup.FileCache; import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
@ -31,7 +31,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
private AuthMe plugin; private AuthMe plugin;
private DataSource database; private DataSource database;
private PluginManager pm; private PluginManager pm;
private FileCache playerCache; private JsonCache playerCache;
public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin, public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin,
DataSource data) { DataSource data) {
@ -42,7 +42,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
this.limbo = LimboCache.getInstance().getLimboPlayer(name); this.limbo = LimboCache.getInstance().getLimboPlayer(name);
this.auth = database.getAuth(name); this.auth = database.getAuth(name);
this.playerCache = new FileCache(plugin); this.playerCache = new JsonCache(plugin);
} }
public LimboPlayer getLimbo() { public LimboPlayer getLimbo() {
@ -63,7 +63,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
} }
protected void packQuitLocation() { protected void packQuitLocation() {
Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player); Utils.packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player);
} }
protected void teleportBackFromSpawn() { protected void teleportBackFromSpawn() {
@ -103,7 +103,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
for (String command : Settings.forceCommands) { for (String command : Settings.forceCommands) {
try { try {
player.performCommand(command.replace("%p", player.getName())); player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) { } catch (Exception ignored) {
} }
} }
for (String command : Settings.forceCommandsAsConsole) { for (String command : Settings.forceCommandsAsConsole) {
@ -125,20 +125,13 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
* world inventory ! * world inventory !
*/ */
player.setGameMode(limbo.getGameMode()); player.setGameMode(limbo.getGameMode());
if (!Settings.forceOnlyAfterLogin) { // Inventory - Make it after restore GameMode , cause we need to
// Inventory - Make it after restore GameMode , cause we need to // restore the
// restore the // right inventory in the right gamemode
// right inventory in the right gamemode if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) { restoreInventory();
restoreInventory(); }
} if (Settings.forceOnlyAfterLogin) {
} else {
// Inventory - Make it before force the survival GameMode to
// cancel all
// inventory problem
if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
restoreInventory();
}
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
} }
@ -166,7 +159,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
Utils.forceGM(player); Utils.forceGM(player);
// Restore Permission Group // Restore Permission Group
Utils.getInstance().setGroup(player, groupType.LOGGEDIN); Utils.setGroup(player, GroupType.LOGGEDIN);
// Cleanup no longer used temporary data // Cleanup no longer used temporary data
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
@ -177,7 +170,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
// We can now display the join message // We can now display the join message
if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) { if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) { for (Player p : Utils.getOnlinePlayers()) {
if (p.isOnline()) if (p.isOnline())
p.sendMessage(AuthMePlayerListener.joinMessage.get(name)); p.sendMessage(AuthMePlayerListener.joinMessage.get(name));
} }
@ -186,6 +179,10 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS); player.removePotionEffect(PotionEffectType.BLINDNESS);
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setWalkSpeed(0.2f);
player.setFlySpeed(0.1f);
}
// The Loginevent now fires (as intended) after everything is processed // The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true));

View File

@ -6,11 +6,11 @@ import org.bukkit.scheduler.BukkitScheduler;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.groupType; import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.DataFileCache; import fr.xephi.authme.cache.backup.DataFileCache;
import fr.xephi.authme.cache.backup.FileCache; import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeTeleportEvent; import fr.xephi.authme.events.AuthMeTeleportEvent;
@ -25,8 +25,7 @@ public class AsyncronousLogout {
protected DataSource database; protected DataSource database;
protected boolean canLogout = true; protected boolean canLogout = true;
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
private Utils utils = Utils.getInstance(); private JsonCache playerBackup;
private FileCache playerBackup;
public AsyncronousLogout(Player player, AuthMe plugin, public AsyncronousLogout(Player player, AuthMe plugin,
DataSource database) { DataSource database) {
@ -34,7 +33,7 @@ public class AsyncronousLogout {
this.plugin = plugin; this.plugin = plugin;
this.database = database; this.database = database;
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
this.playerBackup = new FileCache(plugin); this.playerBackup = new JsonCache(plugin);
} }
private void preLogout() { private void preLogout() {
@ -79,14 +78,13 @@ public class AsyncronousLogout {
if (LimboCache.getInstance().hasLimboPlayer(name)) if (LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
utils.setGroup(player, groupType.NOTLOGGEDIN); Utils.setGroup(player, GroupType.NOTLOGGEDIN);
if (Settings.protectInventoryBeforeLogInEnabled) { if (Settings.protectInventoryBeforeLogInEnabled) {
player.getInventory().clear(); player.getInventory().clear();
// create cache file for handling lost of inventories on unlogged in // create cache file for handling lost of inventories on unlogged in
// status // status
DataFileCache playerData = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour()); DataFileCache playerData = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour());
if (playerData != null) playerBackup.createCache(player, playerData);
playerBackup.createCache(player, playerData, LimboCache.getInstance().getLimboPlayer(name).getGroup(), LimboCache.getInstance().getLimboPlayer(name).getOperator(), LimboCache.getInstance().getLimboPlayer(name).isFlying());
} }
sched.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin)); sched.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin));
} }

View File

@ -43,22 +43,23 @@ public class ProcessSyncronousPlayerLogout implements Runnable {
} }
BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval)); BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
try { if (player.isInsideVehicle() && player.getVehicle() != null)
if (player.isInsideVehicle()) player.getVehicle().eject();
player.getVehicle().eject();
} catch (NullPointerException npe) {
}
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
player.setOp(false); player.setOp(false);
if (!Settings.isMovementAllowed) { if (!Settings.isMovementAllowed) {
player.setAllowFlight(true); player.setAllowFlight(true);
player.setFlying(true); player.setFlying(true);
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setFlySpeed(0.0f);
player.setWalkSpeed(0.0f);
}
} }
// Player is now logout... Time to fire event ! // Player is now logout... Time to fire event !
Bukkit.getServer().getPluginManager().callEvent(new LogoutEvent(player)); Bukkit.getServer().getPluginManager().callEvent(new LogoutEvent(player));
m.send(player, "logout"); m.send(player, "logout");
ConsoleLogger.info(player.getDisplayName() + " logged out"); ConsoleLogger.info(player.getName() + " logged out");
} }
} }

View File

@ -15,7 +15,6 @@ import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.RestoreInventoryEvent; import fr.xephi.authme.events.RestoreInventoryEvent;
import fr.xephi.authme.listener.AuthMePlayerListener; import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class AsyncronousQuit { public class AsyncronousQuit {
@ -23,7 +22,6 @@ public class AsyncronousQuit {
protected AuthMe plugin; protected AuthMe plugin;
protected DataSource database; protected DataSource database;
protected Player player; protected Player player;
protected Utils utils = Utils.getInstance();
private String name; private String name;
private ItemStack[] armor = null; private ItemStack[] armor = null;
private ItemStack[] inv = null; private ItemStack[] inv = null;
@ -44,7 +42,7 @@ public class AsyncronousQuit {
public void process() { public void process() {
if (player == null) if (player == null)
return; return;
if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return; return;
} }
@ -67,7 +65,7 @@ public class AsyncronousQuit {
armor = limbo.getArmour(); armor = limbo.getArmour();
} }
if (limbo.getGroup() != null && !limbo.getGroup().equals("")) if (limbo.getGroup() != null && !limbo.getGroup().equals(""))
utils.addNormal(player, limbo.getGroup()); Utils.addNormal(player, limbo.getGroup());
needToChange = true; needToChange = true;
isOp = limbo.getOperator(); isOp = limbo.getOperator();
isFlying = limbo.isFlying(); isFlying = limbo.isFlying();

View File

@ -112,7 +112,7 @@ public class AsyncronousRegister {
return; return;
} }
} }
PlayerAuth auth = null; PlayerAuth auth;
try { try {
final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
auth = new PlayerAuth(name, hashnew, getIp(), 0, (int) player.getLocation().getX(), (int) player.getLocation().getY(), (int) player.getLocation().getZ(), player.getLocation().getWorld().getName(), email, player.getName()); auth = new PlayerAuth(name, hashnew, getIp(), 0, (int) player.getLocation().getX(), (int) player.getLocation().getY(), (int) player.getLocation().getZ(), player.getLocation().getWorld().getName(), email, player.getName());
@ -130,12 +130,11 @@ public class AsyncronousRegister {
plugin.mail.main(auth, password); plugin.mail.main(auth, password);
ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin); ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
return;
} }
protected void passwordRegister() { protected void passwordRegister() {
PlayerAuth auth = null; PlayerAuth auth;
String hash = ""; String hash;
try { try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
@ -159,6 +158,5 @@ public class AsyncronousRegister {
plugin.otherAccounts.addPlayer(player.getUniqueId()); plugin.otherAccounts.addPlayer(player.getUniqueId());
ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin); ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
return;
} }
} }

View File

@ -31,7 +31,7 @@ public class ProcessSyncronousEmailRegister implements Runnable {
public void run() { public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (!Settings.getRegisteredGroup.isEmpty()) { if (!Settings.getRegisteredGroup.isEmpty()) {
Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED); Utils.setGroup(player, Utils.GroupType.REGISTERED);
} }
m.send(player, "vb_nonActiv"); m.send(player, "vb_nonActiv");
int time = Settings.getRegistrationTimeout * 20; int time = Settings.getRegistrationTimeout * 20;
@ -39,12 +39,12 @@ public class ProcessSyncronousEmailRegister implements Runnable {
BukkitScheduler sched = plugin.getServer().getScheduler(); BukkitScheduler sched = plugin.getServer().getScheduler();
if (time != 0 && limbo != null) { if (time != 0 && limbo != null) {
limbo.getTimeoutTaskId().cancel(); limbo.getTimeoutTaskId().cancel();
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time); BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time);
limbo.setTimeoutTaskId(id); limbo.setTimeoutTaskId(id);
} }
if (limbo != null){ if (limbo != null){
limbo.getMessageTaskId().cancel(); limbo.getMessageTaskId().cancel();
BukkitTask nwMsg = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), msgInterval)); BukkitTask nwMsg = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), msgInterval));
limbo.setMessageTaskId(nwMsg); limbo.setMessageTaskId(nwMsg);
} }

View File

@ -1,13 +1,5 @@
package fr.xephi.authme.process.register; package fr.xephi.authme.process.register;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils; import fr.xephi.authme.Utils;
@ -21,6 +13,13 @@ import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.task.TimeoutTask;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
public class ProcessSyncronousPasswordRegister implements Runnable { public class ProcessSyncronousPasswordRegister implements Runnable {
@ -39,7 +38,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
for (String command : Settings.forceRegisterCommands) { for (String command : Settings.forceRegisterCommands) {
try { try {
player.performCommand(command.replace("%p", player.getName())); player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) { } catch (Exception ignored) {
} }
} }
for (String command : Settings.forceRegisterCommandsAsConsole) { for (String command : Settings.forceRegisterCommandsAsConsole) {
@ -71,10 +70,8 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
} }
BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval)); BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
try { if (player.isInsideVehicle() && player.getVehicle() != null) {
if (player.isInsideVehicle()) player.getVehicle().eject();
player.getVehicle().eject();
} catch (NullPointerException npe) {
} }
} }
@ -108,7 +105,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
} }
if (!Settings.getRegisteredGroup.isEmpty()) { if (!Settings.getRegisteredGroup.isEmpty()) {
Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED); Utils.setGroup(player, Utils.GroupType.REGISTERED);
} }
m.send(player, "registered"); m.send(player, "registered");
if (!Settings.getmailAccount.isEmpty()) if (!Settings.getmailAccount.isEmpty())
@ -119,8 +116,12 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
} }
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS); player.removePotionEffect(PotionEffectType.BLINDNESS);
// The Loginevent now fires (as intended) after everything is processed if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); player.setWalkSpeed(0.2f);
player.setFlySpeed(0.1f);
}
// The LoginEvent now fires (as intended) after everything is processed
plugin.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
player.saveData(); player.saveData();
if (!Settings.noConsoleSpam) if (!Settings.noConsoleSpam)
@ -132,7 +133,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
return; return;
} }
// Request Login after Registation // Request Login after Registration
if (Settings.forceRegLogin) { if (Settings.forceRegLogin) {
forceLogin(player); forceLogin(player);
return; return;
@ -142,7 +143,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
if (Settings.useWelcomeMessage) if (Settings.useWelcomeMessage)
if (Settings.broadcastWelcomeMessage) { if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) { for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player)); plugin.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
} }
} else { } else {
for (String s : Settings.welcomeMsg) { for (String s : Settings.welcomeMsg) {

View File

@ -25,6 +25,7 @@ public enum HashAlgorithm {
SHA512(fr.xephi.authme.security.crypts.SHA512.class), SHA512(fr.xephi.authme.security.crypts.SHA512.class),
DOUBLEMD5(fr.xephi.authme.security.crypts.DOUBLEMD5.class), DOUBLEMD5(fr.xephi.authme.security.crypts.DOUBLEMD5.class),
PBKDF2(fr.xephi.authme.security.crypts.CryptPBKDF2.class), PBKDF2(fr.xephi.authme.security.crypts.CryptPBKDF2.class),
PBKDF2DJANGO(fr.xephi.authme.security.crypts.CryptPBKDF2Django.class),
WORDPRESS(fr.xephi.authme.security.crypts.WORDPRESS.class), WORDPRESS(fr.xephi.authme.security.crypts.WORDPRESS.class),
ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class), ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class),
CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class), CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class),

View File

@ -1,24 +1,23 @@
package fr.xephi.authme.security; package fr.xephi.authme.security;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import org.bukkit.Bukkit;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.events.PasswordEncryptionEvent; import fr.xephi.authme.events.PasswordEncryptionEvent;
import fr.xephi.authme.security.crypts.BCRYPT; import fr.xephi.authme.security.crypts.BCRYPT;
import fr.xephi.authme.security.crypts.EncryptionMethod; import fr.xephi.authme.security.crypts.EncryptionMethod;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
public class PasswordSecurity { public class PasswordSecurity {
private static SecureRandom rnd = new SecureRandom(); private static SecureRandom rnd = new SecureRandom();
public static HashMap<String, String> userSalt = new HashMap<String, String>(); public static HashMap<String, String> userSalt = new HashMap<>();
public static String createSalt(int length) public static String createSalt(int length)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
@ -31,15 +30,13 @@ public class PasswordSecurity {
} }
public static String getHash(HashAlgorithm alg, String password, public static String getHash(HashAlgorithm alg, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
EncryptionMethod method; EncryptionMethod method;
try { try {
if (alg != HashAlgorithm.CUSTOM) if (alg != HashAlgorithm.CUSTOM)
method = (EncryptionMethod) alg.getclasse().newInstance(); method = (EncryptionMethod) alg.getclasse().newInstance();
else method = null; else method = null;
} catch (InstantiationException e) { } catch (InstantiationException | IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
} catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm"); throw new NoSuchAlgorithmException("Problem with this hash algorithm");
} }
String salt = ""; String salt = "";
@ -85,6 +82,7 @@ public class PasswordSecurity {
salt = BCRYPT.gensalt(8); salt = BCRYPT.gensalt(8);
userSalt.put(playerName, salt); userSalt.put(playerName, salt);
break; break;
case PBKDF2DJANGO:
case PBKDF2: case PBKDF2:
salt = createSalt(12); salt = createSalt(12);
userSalt.put(playerName, salt); userSalt.put(playerName, salt);
@ -127,43 +125,39 @@ public class PasswordSecurity {
} }
public static boolean comparePasswordWithHash(String password, String hash, public static boolean comparePasswordWithHash(String password, String hash,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
HashAlgorithm algo = Settings.getPasswordHash; HashAlgorithm algo = Settings.getPasswordHash;
EncryptionMethod method; EncryptionMethod method;
try { try {
if (algo != HashAlgorithm.CUSTOM) if (algo != HashAlgorithm.CUSTOM)
method = (EncryptionMethod) algo.getclasse().newInstance(); method = (EncryptionMethod) algo.getclasse().newInstance();
else method = null; else
} catch (InstantiationException e) { method = null;
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
} catch (IllegalAccessException e) { PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
throw new NoSuchAlgorithmException("Problem with this hash algorithm"); Bukkit.getPluginManager().callEvent(event);
} method = event.getMethod();
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
Bukkit.getPluginManager().callEvent(event); if (method == null)
method = event.getMethod(); throw new NoSuchAlgorithmException("Unknown hash algorithm");
if (method == null)
throw new NoSuchAlgorithmException("Unknown hash algorithm");
try {
if (method.comparePassword(hash, password, playerName)) if (method.comparePassword(hash, password, playerName))
return true; return true;
} catch (Exception e) {
} if (Settings.supportOldPassword) {
if (Settings.supportOldPassword) {
try {
if (compareWithAllEncryptionMethod(password, hash, playerName)) if (compareWithAllEncryptionMethod(password, hash, playerName))
return true; return true;
} catch (Exception e) {
} }
} catch (InstantiationException | IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
} }
return false; return false;
} }
private static boolean compareWithAllEncryptionMethod(String password, private static boolean compareWithAllEncryptionMethod(String password,
String hash, String playerName) throws NoSuchAlgorithmException { String hash, String playerName) throws NoSuchAlgorithmException {
for (HashAlgorithm algo : HashAlgorithm.values()) { for (HashAlgorithm algo : HashAlgorithm.values()) {
if (algo != HashAlgorithm.CUSTOM) if (algo != HashAlgorithm.CUSTOM) {
try { try {
EncryptionMethod method = (EncryptionMethod) algo.getclasse().newInstance(); EncryptionMethod method = (EncryptionMethod) algo.getclasse().newInstance();
if (method.comparePassword(hash, password, playerName)) { if (method.comparePassword(hash, password, playerName)) {
@ -176,8 +170,9 @@ public class PasswordSecurity {
} }
return true; return true;
} }
} catch (Exception e) { } catch (Exception ignored) {
} }
}
} }
return false; return false;
} }

File diff suppressed because one or more lines are too long

View File

@ -28,4 +28,4 @@ public class CryptPBKDF2 implements EncryptionMethod {
return engine.verifyKey(password); return engine.verifyKey(password);
} }
} }

View File

@ -0,0 +1,32 @@
package fr.xephi.authme.security.crypts;
import fr.xephi.authme.security.pbkdf2.PBKDF2Engine;
import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters;
import javax.xml.bind.DatatypeConverter;
import java.security.NoSuchAlgorithmException;
public class CryptPBKDF2Django implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
String result = "pbkdf2_sha256$15000$" + salt + "$";
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000);
PBKDF2Engine engine = new PBKDF2Engine(params);
return result + String.valueOf(DatatypeConverter.printBase64Binary(engine.deriveKey(password, 32)));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
String salt = line[2];
byte[] derivedKey = DatatypeConverter.parseBase64Binary(line[3]);
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000, derivedKey);
PBKDF2Engine engine = new PBKDF2Engine(params);
return engine.verifyKey(password);
}
}

View File

@ -10,29 +10,24 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
/** /**
*
* @author stefano * @author stefano
*/ */
public class PHPBB implements EncryptionMethod { public class PHPBB implements EncryptionMethod {
private static final int PHP_VERSION = 4;
private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public String phpbb_hash(String password, String salt) { public String phpbb_hash(String password, String salt) {
String random_state = salt; String random_state = salt;
String random = ""; StringBuilder random = new StringBuilder();
int count = 6; int count = 6;
if (random.length() < count) { for (int i = 0; i < count; i += 16) {
random = ""; random_state = md5(salt + random_state);
for (int i = 0; i < count; i += 16) { random.append(pack(md5(random_state)));
random_state = md5(salt + random_state);
random += pack(md5(random_state));
}
random = random.substring(0, count);
} }
String hash = _hash_crypt_private(password, _hash_gensalt_private(random, itoa64)); String hash = _hash_crypt_private(password, _hash_gensalt_private(random.substring(0, count), itoa64));
if (hash.length() == 34) if (hash.length() == 34) {
return hash; return hash;
}
return md5(password); return md5(password);
} }
@ -40,14 +35,13 @@ public class PHPBB implements EncryptionMethod {
return _hash_gensalt_private(input, itoa64, 6); return _hash_gensalt_private(input, itoa64, 6);
} }
@SuppressWarnings("unused")
private String _hash_gensalt_private(String input, String itoa64, private String _hash_gensalt_private(String input, String itoa64,
int iteration_count_log2) { int iteration_count_log2) {
if (iteration_count_log2 < 4 || iteration_count_log2 > 31) { if (iteration_count_log2 < 4 || iteration_count_log2 > 31) {
iteration_count_log2 = 8; iteration_count_log2 = 8;
} }
String output = "$H$"; String output = "$H$";
output += itoa64.charAt(Math.min(iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)); output += itoa64.charAt(Math.min(iteration_count_log2 + 3, 30)); // PHP_VERSION >= 5 ? 5 : 3
output += _hash_encode64(input, 6); output += _hash_encode64(input, 6);
return output; return output;
} }
@ -56,24 +50,24 @@ public class PHPBB implements EncryptionMethod {
* Encode hash * Encode hash
*/ */
private String _hash_encode64(String input, int count) { private String _hash_encode64(String input, int count) {
String output = ""; StringBuilder output = new StringBuilder();
int i = 0; int i = 0;
do { do {
int value = input.charAt(i++); int value = input.charAt(i++);
output += itoa64.charAt(value & 0x3f); output.append(itoa64.charAt(value & 0x3f));
if (i < count) if (i < count)
value |= input.charAt(i) << 8; value |= input.charAt(i) << 8;
output += itoa64.charAt((value >> 6) & 0x3f); output.append(itoa64.charAt((value >> 6) & 0x3f));
if (i++ >= count) if (i++ >= count)
break; break;
if (i < count) if (i < count)
value |= input.charAt(i) << 16; value |= input.charAt(i) << 16;
output += itoa64.charAt((value >> 12) & 0x3f); output.append(itoa64.charAt((value >> 12) & 0x3f));
if (i++ >= count) if (i++ >= count)
break; break;
output += itoa64.charAt((value >> 18) & 0x3f); output.append(itoa64.charAt((value >> 18) & 0x3f));
} while (i < count); } while (i < count);
return output; return output.toString();
} }
String _hash_crypt_private(String password, String setting) { String _hash_crypt_private(String password, String setting) {
@ -109,9 +103,7 @@ public class PHPBB implements EncryptionMethod {
MessageDigest md5er = MessageDigest.getInstance("MD5"); MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] hash = md5er.digest(bytes); byte[] hash = md5er.digest(bytes);
return bytes2hex(hash); return bytes2hex(hash);
} catch (GeneralSecurityException e) { } catch (GeneralSecurityException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -126,9 +118,9 @@ public class PHPBB implements EncryptionMethod {
} }
private static String bytes2hex(byte[] bytes) { private static String bytes2hex(byte[] bytes) {
StringBuffer r = new StringBuffer(32); StringBuilder r = new StringBuilder(32);
for (int i = 0; i < bytes.length; i++) { for (byte b : bytes) {
String x = Integer.toHexString(bytes[i] & 0xff); String x = Integer.toHexString(b & 0xff);
if (x.length() < 2) if (x.length() < 2)
r.append("0"); r.append("0");
r.append(x); r.append(x);
@ -137,7 +129,7 @@ public class PHPBB implements EncryptionMethod {
} }
static String pack(String hex) { static String pack(String hex) {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
for (int i = 0; i < hex.length(); i += 2) { for (int i = 0; i < hex.length(); i += 2) {
char c1 = hex.charAt(i); char c1 = hex.charAt(i);
char c2 = hex.charAt(i + 1); char c2 = hex.charAt(i + 1);
@ -155,7 +147,7 @@ public class PHPBB implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
return phpbb_check_hash(password, hash); return phpbb_check_hash(password, hash);
} }
} }

View File

@ -8,13 +8,12 @@ import java.util.Arrays;
public class WORDPRESS implements EncryptionMethod { public class WORDPRESS implements EncryptionMethod {
private static String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private int iterationCountLog2 = 8;
private SecureRandom randomGen = new SecureRandom(); private SecureRandom randomGen = new SecureRandom();
private String encode64(byte[] src, int count) { private String encode64(byte[] src, int count) {
int i, value; int i, value;
String output = ""; StringBuilder output = new StringBuilder();
i = 0; i = 0;
if (src.length < count) { if (src.length < count) {
@ -26,24 +25,24 @@ public class WORDPRESS implements EncryptionMethod {
do { do {
value = src[i] + (src[i] < 0 ? 256 : 0); value = src[i] + (src[i] < 0 ? 256 : 0);
++i; ++i;
output += itoa64.charAt(value & 63); output.append(itoa64.charAt(value & 63));
if (i < count) { if (i < count) {
value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 8; value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 8;
} }
output += itoa64.charAt((value >> 6) & 63); output.append(itoa64.charAt((value >> 6) & 63));
if (i++ >= count) { if (i++ >= count) {
break; break;
} }
if (i < count) { if (i < count) {
value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 16; value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 16;
} }
output += itoa64.charAt((value >> 12) & 63); output.append(itoa64.charAt((value >> 12) & 63));
if (i++ >= count) { if (i++ >= count) {
break; break;
} }
output += itoa64.charAt((value >> 18) & 63); output.append(itoa64.charAt((value >> 18) & 63));
} while (i < count); } while (i < count);
return output; return output.toString();
} }
private String crypt(String password, String setting) { private String crypt(String password, String setting) {
@ -86,7 +85,8 @@ public class WORDPRESS implements EncryptionMethod {
private String gensaltPrivate(byte[] input) { private String gensaltPrivate(byte[] input) {
String output = "$P$"; String output = "$P$";
output += itoa64.charAt(Math.min(this.iterationCountLog2 + 5, 30)); int iterationCountLog2 = 8;
output += itoa64.charAt(Math.min(iterationCountLog2 + 5, 30));
output += encode64(input, 6); output += encode64(input, 6);
return output; return output;
} }

View File

@ -1,21 +1,16 @@
package fr.xephi.authme.settings; package fr.xephi.authme.settings;
import java.io.BufferedReader; import fr.xephi.authme.AuthMe;
import java.io.BufferedWriter; import fr.xephi.authme.ConsoleLogger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import fr.xephi.authme.ConsoleLogger; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class CustomConfiguration extends YamlConfiguration { public class CustomConfiguration extends YamlConfiguration {
@ -23,7 +18,6 @@ public class CustomConfiguration extends YamlConfiguration {
public CustomConfiguration(File file) { public CustomConfiguration(File file) {
this.configFile = file; this.configFile = file;
load(); load();
} }
@ -43,7 +37,7 @@ public class CustomConfiguration extends YamlConfiguration {
public boolean reLoad() { public boolean reLoad() {
boolean out = true; boolean out = true;
if (!configFile.exists()) { if (!configFile.exists()) {
out = loadRessource(configFile); out = loadResource(configFile);
} }
if (out) if (out)
load(); load();
@ -58,28 +52,28 @@ public class CustomConfiguration extends YamlConfiguration {
} }
} }
public boolean loadRessource(File file) { public File getConfigFile() {
boolean out = true; return configFile;
}
public boolean loadResource(File file) {
if (!file.exists()) { if (!file.exists()) {
try { try {
String charset = System.getProperty("file.encoding"); if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
String newline = System.getProperty("line.separator"); return false;
InputStream fis = getClass().getResourceAsStream("/" + file.getName()); }
BufferedReader reader = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8)); int i = file.getPath().indexOf("AuthMe");
String str; if (i > -1) {
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)); String path = file.getPath().substring(i + 6).replace('\\', '/');
while ((str = reader.readLine()) != null) { InputStream is = AuthMe.class.getResourceAsStream(path);
writer.append(str).append(newline); Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
return true;
} }
writer.flush();
writer.close();
reader.close();
fis.close();
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError("Failed to load config from JAR"); ConsoleLogger.showError("Failed to load config from JAR");
out = false;
} }
} }
return out; return false;
} }
} }

View File

@ -1,13 +1,8 @@
package fr.xephi.authme.settings; package fr.xephi.authme.settings;
import java.io.File;
import java.io.InputStream;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import org.bukkit.command.CommandSender;
import java.io.File;
public class Messages extends CustomConfiguration { public class Messages extends CustomConfiguration {
@ -16,70 +11,18 @@ public class Messages extends CustomConfiguration {
public Messages(File file, String lang) { public Messages(File file, String lang) {
super(file); super(file);
loadDefaults(file); load();
loadFile();
saveDefaults(file);
singleton = this; singleton = this;
this.lang = lang; this.lang = lang;
} }
/**
* Loads a file from the plugin jar and sets as default
*
* @param filename
* The filename to open
*/
@SuppressWarnings("deprecation")
public final void loadDefaults(File file) {
InputStream stream = AuthMe.getInstance().getResource(file.getName());
if (stream == null)
return;
setDefaults(YamlConfiguration.loadConfiguration(stream));
}
/**
* Saves the configuration to disk
*
* @return True if saved successfully
*/
public final boolean saved(File file) {
try {
save(file);
return true;
} catch (Exception ex) {
return false;
}
}
/**
* 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(File file) {
options().copyDefaults(true);
options().copyHeader(true);
boolean success = saved(file);
options().copyDefaults(false);
options().copyHeader(false);
return success;
}
private void loadFile() {
load();
save();
}
public void send(CommandSender sender, String msg) { public void send(CommandSender sender, String msg) {
if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang))
singleton.reloadMessages(); singleton.reloadMessages();
String loc = (String) singleton.get(msg); String loc = (String) singleton.get(msg);
if (loc == null) { if (loc == null) {
loc = "Error with Translation files, please contact the admin for verify or update translation"; loc = "Error with Translation files, please contact the admin for verify or update translation";
ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !"); ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + getConfigFile() + " !");
} }
for (String l : loc.split("&n")) { for (String l : loc.split("&n")) {
sender.sendMessage(l.replace("&", "\u00a7")); sender.sendMessage(l.replace("&", "\u00a7"));
@ -87,15 +30,12 @@ public class Messages extends CustomConfiguration {
} }
public String[] send(String msg) { public String[] send(String msg) {
if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) {
singleton.reloadMessages(); singleton.reloadMessages();
String s = null;
try {
s = (String) singleton.get(msg);
} catch (Exception e) {
} }
String s = (String) singleton.get(msg);
if (s == null) { if (s == null) {
ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !"); ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + getConfigFile() + " !");
String[] loc = new String[1]; String[] loc = new String[1];
loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files"; loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files";
return (loc); return (loc);
@ -106,7 +46,7 @@ public class Messages extends CustomConfiguration {
for (a = 0; a < i; a++) { for (a = 0; a < i; a++) {
loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&", "\u00a7"); loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&", "\u00a7");
} }
if (loc == null || loc.length == 0) { if (loc.length == 0) {
loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files"; loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files";
} }
return loc; return loc;
@ -114,13 +54,13 @@ public class Messages extends CustomConfiguration {
public static Messages getInstance() { public static Messages getInstance() {
if (singleton == null) { if (singleton == null) {
singleton = new Messages(new File(Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml"), Settings.messagesLanguage); singleton = new Messages(Settings.messageFile, Settings.messagesLanguage);
} }
return singleton; return singleton;
} }
public void reloadMessages() { public void reloadMessages() {
singleton = new Messages(new File(Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml"), Settings.messagesLanguage); singleton = new Messages(Settings.messageFile, Settings.messagesLanguage);
} }
} }

View File

@ -1,59 +1,54 @@
package fr.xephi.authme.settings; package fr.xephi.authme.settings;
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.Iterator;
import java.util.List;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DataSource.DataSourceType; import fr.xephi.authme.datasource.DataSource.DataSourceType;
import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.HashAlgorithm;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public final class Settings extends YamlConfiguration { public final class Settings extends YamlConfiguration {
private AuthMe plugin;
// This is not an option! // This is not an option!
public static Boolean antiBotInAction = false; public static Boolean antiBotInAction = false;
public static String PLUGIN_FOLDER = "." + File.separator + "plugins" + File.separator + "AuthMe"; public static final File PLUGIN_FOLDER = AuthMe.getInstance().getDataFolder();
public static final String CACHE_FOLDER = Settings.PLUGIN_FOLDER + File.separator + "cache"; public static final File MODULE_FOLDER = new File(PLUGIN_FOLDER, "modules");
public static final String AUTH_FILE = Settings.PLUGIN_FOLDER + File.separator + "auths.db"; public static final File CACHE_FOLDER = new File(PLUGIN_FOLDER, "cache");
public static final String MESSAGE_FILE = Settings.PLUGIN_FOLDER + File.separator + "messages"; public static final File AUTH_FILE = new File(PLUGIN_FOLDER, "auths.db");
public static final String SETTINGS_FILE = Settings.PLUGIN_FOLDER + File.separator + "config.yml"; public static final File SETTINGS_FILE = new File(PLUGIN_FOLDER, "config.yml");
public static List<String> allowCommands = null; public static final File LOG_FILE = new File(PLUGIN_FOLDER, "authme.log");
public static List<String> getJoinPermissions = null;
public static List<String> getUnrestrictedName = null; public static File messageFile;
private static List<String> getRestrictedIp; public static List<String> allowCommands;
public static List<String> getMySQLOtherUsernameColumn = null; public static List<String> getJoinPermissions;
public static List<String> getForcedWorlds = null; public static List<String> getUnrestrictedName;
public static List<String> countries = null; public static List<String> getRestrictedIp;
public static List<String> countriesBlacklist = null; public static List<String> getMySQLOtherUsernameColumn;
public static List<String> forceCommands = null; public static List<String> getForcedWorlds;
public static List<String> forceCommandsAsConsole = null; public static List<String> countries;
public static List<String> forceRegisterCommands = null; public static List<String> countriesBlacklist;
public static List<String> forceRegisterCommandsAsConsole = null; public static List<String> forceCommands;
private AuthMe plugin; public static List<String> forceCommandsAsConsole;
private final File file; public static List<String> forceRegisterCommands;
public static List<String> forceRegisterCommandsAsConsole;
public static List<String> welcomeMsg;
public static List<String> unsafePasswords;
public static List<String> emailBlacklist;
public static List<String> emailWhitelist;
public static DataSourceType getDataSource; public static DataSourceType getDataSource;
public static HashAlgorithm getPasswordHash; public static HashAlgorithm getPasswordHash;
public static Boolean useLogging = false; public static boolean useLogging = false;
public static int purgeDelay = 60; public static int purgeDelay = 60;
public static List<String> welcomeMsg = null;
public static List<String> unsafePasswords;
public static List<String> emailBlacklist = null;
public static List<String> emailWhitelist = null;
public static Boolean isPermissionCheckEnabled, isRegistrationEnabled, public static boolean isPermissionCheckEnabled, isRegistrationEnabled,
isForcedRegistrationEnabled, isTeleportToSpawnEnabled, isForcedRegistrationEnabled, isTeleportToSpawnEnabled,
isSessionsEnabled, isChatAllowed, isAllowRestrictedIp, isSessionsEnabled, isChatAllowed, isAllowRestrictedIp,
isMovementAllowed, isKickNonRegisteredEnabled, isMovementAllowed, isKickNonRegisteredEnabled,
@ -64,7 +59,7 @@ public final class Settings extends YamlConfiguration {
protectInventoryBeforeLogInEnabled, isBackupActivated, protectInventoryBeforeLogInEnabled, isBackupActivated,
isBackupOnStart, isBackupOnStop, isStopEnabled, reloadSupport, isBackupOnStart, isBackupOnStop, isStopEnabled, reloadSupport,
rakamakUseIp, noConsoleSpam, removePassword, displayOtherAccounts, rakamakUseIp, noConsoleSpam, removePassword, displayOtherAccounts,
useCaptcha, emailRegistration, multiverse, chestshop, bungee, useCaptcha, emailRegistration, multiverse, legacyChestShop, bungee,
banUnsafeIp, doubleEmailCheck, sessionExpireOnIpChange, banUnsafeIp, doubleEmailCheck, sessionExpireOnIpChange,
disableSocialSpy, forceOnlyAfterLogin, useEssentialsMotd, usePurge, disableSocialSpy, forceOnlyAfterLogin, useEssentialsMotd, usePurge,
purgePlayerDat, purgeEssentialsFile, supportOldPassword, purgePlayerDat, purgeEssentialsFile, supportOldPassword,
@ -72,14 +67,14 @@ public final class Settings extends YamlConfiguration {
enableProtection, enableAntiBot, recallEmail, useWelcomeMessage, enableProtection, enableAntiBot, recallEmail, useWelcomeMessage,
broadcastWelcomeMessage, forceRegKick, forceRegLogin, broadcastWelcomeMessage, forceRegKick, forceRegLogin,
checkVeryGames, delayJoinMessage, noTeleport, applyBlindEffect, checkVeryGames, delayJoinMessage, noTeleport, applyBlindEffect,
customAttributes, generateImage; customAttributes, generateImage, isRemoveSpeedEnabled;
public static String getNickRegex, getUnloggedinGroup, getMySQLHost, public static String getNickRegex, getUnloggedinGroup, getMySQLHost,
getMySQLPort, getMySQLUsername, getMySQLPassword, getMySQLDatabase, getMySQLPort, getMySQLUsername, getMySQLPassword, getMySQLDatabase,
getMySQLTablename, getMySQLColumnName, getMySQLColumnPassword, getMySQLTablename, getMySQLColumnName, getMySQLColumnPassword,
getMySQLColumnIp, getMySQLColumnLastLogin, getMySQLColumnSalt, getMySQLColumnIp, getMySQLColumnLastLogin, getMySQLColumnSalt,
getMySQLColumnGroup, getMySQLColumnEmail, unRegisteredGroup, getMySQLColumnGroup, getMySQLColumnEmail, unRegisteredGroup,
backupWindowsPath, getcUnrestrictedName, getRegisteredGroup, backupWindowsPath, getRegisteredGroup,
messagesLanguage, getMySQLlastlocX, getMySQLlastlocY, messagesLanguage, getMySQLlastlocX, getMySQLlastlocY,
getMySQLlastlocZ, rakamakUsers, rakamakUsersIp, getmailAccount, getMySQLlastlocZ, rakamakUsers, rakamakUsersIp, getmailAccount,
getmailPassword, getmailSMTP, getMySQLColumnId, getmailSenderName, getmailPassword, getmailSMTP, getMySQLColumnId, getmailSenderName,
@ -95,36 +90,33 @@ public final class Settings extends YamlConfiguration {
getMailPort, maxLoginTry, captchaLength, saltLength, getMailPort, maxLoginTry, captchaLength, saltLength,
getmaxRegPerEmail, bCryptLog2Rounds, getPhpbbGroup, getmaxRegPerEmail, bCryptLog2Rounds, getPhpbbGroup,
antiBotSensibility, antiBotDuration, delayRecall, getMaxLoginPerIp, antiBotSensibility, antiBotDuration, delayRecall, getMaxLoginPerIp,
getMaxJoinPerIp; getMaxJoinPerIp, getMySQLMaxConnections;
protected static YamlConfiguration configFile; protected static YamlConfiguration configFile;
public Settings(AuthMe plugin) { public Settings(AuthMe plugin) {
this.file = new File(plugin.getDataFolder(), "config.yml");
this.plugin = plugin;
boolean exist = exists();
if (exist) {
load();
} else {
plugin.saveDefaultConfig();
load();
}
configFile = (YamlConfiguration) plugin.getConfig(); configFile = (YamlConfiguration) plugin.getConfig();
PLUGIN_FOLDER = plugin.getDataFolder().toString(); this.plugin = plugin;
loadConfigOptions(exist);
} }
public void loadConfigOptions(boolean exist) { public final void reload() throws Exception {
plugin.getLogger().info("Loading Configuration File..."); plugin.getLogger().info("Loading Configuration File...");
if (exist) boolean exist = SETTINGS_FILE.exists();
if (!exist) {
plugin.saveDefaultConfig();
}
load(SETTINGS_FILE);
if (exist) {
mergeConfig(); mergeConfig();
}
loadVariables(); loadVariables();
if (exist) {
if (exist)
saveDefaults(); saveDefaults();
}
messageFile = new File(PLUGIN_FOLDER, "messages" + File.separator + "messages_" + messagesLanguage + ".yml");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void loadVariables() { public static void loadVariables() {
messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en").toLowerCase()); messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en").toLowerCase());
@ -144,6 +136,7 @@ public final class Settings extends YamlConfiguration {
isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser", false); isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser", false);
getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser"); getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser");
isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement", false); isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement", false);
isRemoveSpeedEnabled = configFile.getBoolean("settings.restrictions.removeSpeed", true);
getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius", 100); getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius", 100);
getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin"); getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin");
isKickOnWrongPasswordEnabled = configFile.getBoolean("settings.restrictions.kickOnWrongPassword", false); isKickOnWrongPasswordEnabled = configFile.getBoolean("settings.restrictions.kickOnWrongPassword", false);
@ -160,6 +153,7 @@ public final class Settings extends YamlConfiguration {
isCachingEnabled = configFile.getBoolean("DataSource.caching", true); isCachingEnabled = configFile.getBoolean("DataSource.caching", true);
getMySQLHost = configFile.getString("DataSource.mySQLHost", "127.0.0.1"); getMySQLHost = configFile.getString("DataSource.mySQLHost", "127.0.0.1");
getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306"); getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306");
getMySQLMaxConnections = configFile.getInt("DataSource.mySQLMaxConections", 25);
getMySQLUsername = configFile.getString("DataSource.mySQLUsername", "authme"); getMySQLUsername = configFile.getString("DataSource.mySQLUsername", "authme");
getMySQLPassword = configFile.getString("DataSource.mySQLPassword", "12345"); getMySQLPassword = configFile.getString("DataSource.mySQLPassword", "12345");
getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", "authme"); getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", "authme");
@ -227,12 +221,12 @@ public final class Settings extends YamlConfiguration {
saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8); saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8);
getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1);
multiverse = configFile.getBoolean("Hooks.multiverse", true); multiverse = configFile.getBoolean("Hooks.multiverse", true);
chestshop = configFile.getBoolean("Hooks.legacyChestshop", false); legacyChestShop = configFile.getBoolean("Hooks.legacyChestshop", false);
bungee = configFile.getBoolean("Hooks.bungeecord", false); bungee = configFile.getBoolean("Hooks.bungeecord", false);
getForcedWorlds = configFile.getStringList("settings.restrictions.ForceSpawnOnTheseWorlds"); getForcedWorlds = configFile.getStringList("settings.restrictions.ForceSpawnOnTheseWorlds");
banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false); banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false);
doubleEmailCheck = configFile.getBoolean("settings.registration.doubleEmailCheck", false); doubleEmailCheck = configFile.getBoolean("settings.registration.doubleEmailCheck", false);
sessionExpireOnIpChange = configFile.getBoolean("settings.sessions.sessionExpireOnIpChange", false); sessionExpireOnIpChange = configFile.getBoolean("settings.sessions.sessionExpireOnIpChange", true);
useLogging = configFile.getBoolean("Security.console.logConsole", false); useLogging = configFile.getBoolean("Security.console.logConsole", false);
disableSocialSpy = configFile.getBoolean("Hooks.disableSocialSpy", true); disableSocialSpy = configFile.getBoolean("Hooks.disableSocialSpy", true);
bCryptLog2Rounds = configFile.getInt("ExternalBoardOptions.bCryptLog2Round", 10); bCryptLog2Rounds = configFile.getInt("ExternalBoardOptions.bCryptLog2Round", 10);
@ -287,24 +281,30 @@ public final class Settings extends YamlConfiguration {
} }
public static void reloadConfigOptions(YamlConfiguration newConfig) {
configFile = newConfig;
loadVariables();
}
public void mergeConfig() { public void mergeConfig() {
boolean changes = false; boolean changes = false;
if (contains("Xenoforo.predefinedSalt")) if (contains("Xenoforo.predefinedSalt")) {
set("Xenoforo.predefinedSalt", null); set("Xenoforo.predefinedSalt", null);
if (configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA1") || configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA256")) changes = true;
}
if (configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA1") || configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA256")) {
set("settings.security.passwordHash", "XENFORO"); set("settings.security.passwordHash", "XENFORO");
changes = true;
}
if (!contains("Protection.enableProtection")) { if (!contains("Protection.enableProtection")) {
set("Protection.enableProtection", false); set("Protection.enableProtection", false);
changes = true; changes = true;
} }
if (!contains("settings.restrictions.removeSpeed")) {
set("settings.restrictions.removeSpeed", true);
changes = true;
}
if (!contains("DataSource.mySQLMaxConections")) {
set("DataSource.mySQLMaxConections", 25);
changes = true;
}
if (!contains("Protection.countries")) { if (!contains("Protection.countries")) {
countries = new ArrayList<String>(); countries = new ArrayList<>();
countries.add("US"); countries.add("US");
countries.add("GB"); countries.add("GB");
set("Protection.countries", countries); set("Protection.countries", countries);
@ -343,14 +343,14 @@ public final class Settings extends YamlConfiguration {
changes = true; changes = true;
} }
if (!contains("settings.security.unsafePasswords")) { if (!contains("settings.security.unsafePasswords")) {
List<String> str = new ArrayList<String>(); List<String> str = new ArrayList<>();
str.add("123456"); str.add("123456");
str.add("password"); str.add("password");
set("settings.security.unsafePasswords", str); set("settings.security.unsafePasswords", str);
changes = true; changes = true;
} }
if (!contains("Protection.countriesBlacklist")) { if (!contains("Protection.countriesBlacklist")) {
countriesBlacklist = new ArrayList<String>(); countriesBlacklist = new ArrayList<>();
countriesBlacklist.add("A1"); countriesBlacklist.add("A1");
set("Protection.countriesBlacklist", countriesBlacklist); set("Protection.countriesBlacklist", countriesBlacklist);
changes = true; changes = true;
@ -387,8 +387,10 @@ public final class Settings extends YamlConfiguration {
set("VeryGames.enableIpCheck", false); set("VeryGames.enableIpCheck", false);
changes = true; changes = true;
} }
if (getString("settings.restrictions.allowedNicknameCharacters").equals("[a-zA-Z0-9_?]*")) if (getString("settings.restrictions.allowedNicknameCharacters").equals("[a-zA-Z0-9_?]*")) {
set("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_]*"); set("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_]*");
changes = true;
}
if (!contains("settings.delayJoinMessage")) { if (!contains("settings.delayJoinMessage")) {
set("settings.delayJoinMessage", false); set("settings.delayJoinMessage", false);
changes = true; changes = true;
@ -397,8 +399,10 @@ public final class Settings extends YamlConfiguration {
set("settings.restrictions.noTeleport", false); set("settings.restrictions.noTeleport", false);
changes = true; changes = true;
} }
if (contains("Converter.Rakamak.newPasswordHash")) if (contains("Converter.Rakamak.newPasswordHash")) {
set("Converter.Rakamak.newPasswordHash", null); set("Converter.Rakamak.newPasswordHash", null);
changes = true;
}
if (!contains("Converter.CrazyLogin.fileName")) { if (!contains("Converter.CrazyLogin.fileName")) {
set("Converter.CrazyLogin.fileName", "accounts.db"); set("Converter.CrazyLogin.fileName", "accounts.db");
changes = true; changes = true;
@ -415,18 +419,22 @@ public final class Settings extends YamlConfiguration {
set("Email.emailBlacklisted", new ArrayList<String>()); set("Email.emailBlacklisted", new ArrayList<String>());
changes = true; changes = true;
} }
if (contains("Performances.useMultiThreading")) if (contains("Performances.useMultiThreading")) {
set("Performances.useMultiThreading", null); set("Performances.useMultiThreading", null);
changes = true;
if (contains("Performances")) }
if (contains("Performances")) {
set("Performances", null); set("Performances", null);
changes = true;
if (contains("Passpartu.enablePasspartu")) }
if (contains("Passpartu.enablePasspartu")) {
set("Passpartu.enablePasspartu", null); set("Passpartu.enablePasspartu", null);
changes = true;
if (contains("Passpartu")) }
if (contains("Passpartu")) {
set("Passpartu", null); set("Passpartu", null);
changes = true;
}
if (!contains("Email.emailWhitelisted")) { if (!contains("Email.emailWhitelisted")) {
set("Email.emailWhitelisted", new ArrayList<String>()); set("Email.emailWhitelisted", new ArrayList<String>());
changes = true; changes = true;
@ -447,14 +455,17 @@ public final class Settings extends YamlConfiguration {
set("Purge.removePermissions", false); set("Purge.removePermissions", false);
changes = true; changes = true;
} }
if (contains("Hooks.notifications")) if (contains("Hooks.notifications")) {
set("Hooks.notifications", null); set("Hooks.notifications", null);
boolean useChestShop = false; changes = true;
if (contains("Hooks.chestshop")) { }
useChestShop = getBoolean("Hooks.chestshop"); if (contains("Hooks.chestshop")) {
set("Hooks.chestshop", null); if(getBoolean("Hooks.chestshop")) {
set("Hooks.legacyChestshop", true);
}
set("Hooks.chestshop", null);
changes = true;
} }
set("Hooks.legacyChestshop", useChestShop);
if (!contains("Email.generateImage")) { if (!contains("Email.generateImage")) {
set("Email.generateImage", true); set("Email.generateImage", true);
changes = true; changes = true;
@ -465,11 +476,9 @@ public final class Settings extends YamlConfiguration {
} }
if (changes) { if (changes) {
plugin.getLogger().warning("Merge new Config Options - I'm not an error, please don't report me"); plugin.getLogger().warning("Merged new Config Options - I'm not an error, please don't report me");
plugin.getLogger().warning("Please check your config.yml file for new configs!"); plugin.getLogger().warning("Please check your config.yml file for new configs!");
} }
return;
} }
public void setValue(String key, Object value) { public void setValue(String key, Object value) {
@ -516,40 +525,15 @@ public final class Settings extends YamlConfiguration {
if (testip.equalsIgnoreCase(ip)) { if (testip.equalsIgnoreCase(ip)) {
trueonce = true; trueonce = true;
} }
;
} }
} }
if (namefound == false) { if (!namefound) {
return true; return true;
} else { } else {
if (trueonce == true) { return trueonce;
return true;
} 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() {
if (!exists())
plugin.saveDefaultConfig();
load();
}
/** /**
* Saves the configuration to disk * Saves the configuration to disk
* *
@ -557,25 +541,16 @@ public final class Settings extends YamlConfiguration {
*/ */
public final boolean save() { public final boolean save() {
try { try {
save(file); save(SETTINGS_FILE);
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
return false; return false;
} }
} }
/**
* Simple function for if the Configuration file exists
*
* @return True if configuration exists on disk
*/
public final boolean exists() {
return file.exists();
}
/** /**
* Saves current configuration (plus defaults) to disk. * Saves current configuration (plus defaults) to disk.
* * <p>
* If defaults and configuration are empty, saves blank file. * If defaults and configuration are empty, saves blank file.
* *
* @return True if saved successfully * @return True if saved successfully
@ -589,27 +564,12 @@ public final class Settings extends YamlConfiguration {
return success; 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 String checkLang(String lang) { public static String checkLang(String lang) {
if (new File(MESSAGE_FILE + "_" + lang + ".yml").exists()) { if (new File(PLUGIN_FOLDER, "messages" + File.separator + "messages_" + lang + ".yml").exists()) {
ConsoleLogger.info("Set Language to: " + lang);
return lang;
}
if (AuthMe.class.getResourceAsStream("/messages/messages_" + lang + ".yml") != null) {
ConsoleLogger.info("Set Language to: " + lang); ConsoleLogger.info("Set Language to: " + lang);
return lang; return lang;
} }
@ -629,7 +589,7 @@ public final class Settings extends YamlConfiguration {
private static void getWelcomeMessage() { private static void getWelcomeMessage() {
AuthMe plugin = AuthMe.getInstance(); AuthMe plugin = AuthMe.getInstance();
welcomeMsg = new ArrayList<String>(); welcomeMsg = new ArrayList<>();
if (!useWelcomeMessage) { if (!useWelcomeMessage) {
return; return;
} }
@ -648,13 +608,11 @@ public final class Settings extends YamlConfiguration {
try { try {
FileReader fr = new FileReader(plugin.getDataFolder() + File.separator + "welcome.txt"); FileReader fr = new FileReader(plugin.getDataFolder() + File.separator + "welcome.txt");
BufferedReader br = new BufferedReader(fr); BufferedReader br = new BufferedReader(fr);
String line = ""; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
welcomeMsg.add(line); welcomeMsg.add(line);
} }
br.close(); br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -0,0 +1,55 @@
package fr.xephi.authme.task;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.entity.Player;
import java.security.NoSuchAlgorithmException;
public class ChangePasswordTask implements Runnable {
private final AuthMe plugin;
private final Player player;
private String password;
public ChangePasswordTask(AuthMe plugin, Player player, String password) {
this.plugin = plugin;
this.player = player;
this.password = password;
}
@Override
public void run() {
Messages m = Messages.getInstance();
try {
String name = player.getName().toLowerCase();
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
if (PasswordSecurity.comparePasswordWithHash(password, PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
auth.setHash(hashnew);
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
auth.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt("");
if (!plugin.database.updatePassword(auth)) {
m.send(player, "error");
return;
}
plugin.database.updateSalt(auth);
PlayerCache.getInstance().updatePlayer(auth);
m.send(player, "pwd_changed");
ConsoleLogger.info(player.getName() + " changed his password");
} else {
m.send(player, "wrong_pwd");
}
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m.send(player, "error");
}
}
}

View File

@ -1,11 +1,11 @@
package fr.xephi.authme.task; package fr.xephi.authme.task;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
public class MessageTask implements Runnable { public class MessageTask implements Runnable {
@ -15,7 +15,7 @@ public class MessageTask implements Runnable {
private int interval; private int interval;
public MessageTask(AuthMe plugin, String name, String[] strings, public MessageTask(AuthMe plugin, String name, String[] strings,
int interval) { int interval) {
this.plugin = plugin; this.plugin = plugin;
this.name = name; this.name = name;
this.msg = strings; this.msg = strings;
@ -27,7 +27,7 @@ public class MessageTask implements Runnable {
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name))
return; return;
for (Player player : plugin.getServer().getOnlinePlayers()) { for (Player player : Utils.getOnlinePlayers()) {
if (player.getName().toLowerCase().equals(name)) { if (player.getName().toLowerCase().equals(name)) {
for (String ms : msg) { for (String ms : msg) {
player.sendMessage(ms); player.sendMessage(ms);

View File

@ -1,5 +1,7 @@
DataSource: DataSource:
# Can be set to: sqlite, mysql # What type of database do you want to use?
# Can be set to: sqlite, sqlitehikari, mysql
# (sqlitehikari should be more fast than normal sqlite but it's an experimental feature!)
backend: sqlite backend: sqlite
# Enable database caching # Enable database caching
caching: true caching: true
@ -7,6 +9,8 @@ DataSource:
mySQLHost: 127.0.0.1 mySQLHost: 127.0.0.1
# Database Port # Database Port
mySQLPort: '3306' mySQLPort: '3306'
# MySql Max Connections
mySQLMaxConections: 25
# Username about Database Connection Infos # Username about Database Connection Infos
mySQLUsername: authme mySQLUsername: authme
# Password about Database Connection Infos # Password about Database Connection Infos
@ -39,46 +43,30 @@ DataSource:
mySQLlastlocWorld: world mySQLlastlocWorld: world
# Column for RealName # Column for RealName
mySQLRealName: realname mySQLRealName: realname
GroupOptions:
# if you want to set up a particulary Permission Group for
# users that arent registered yet. Pay attention this option
# is casesensitive!
# Example: UnregisteredPlayerGroup: GuestUser
UnregisteredPlayerGroup: ''
# Same as UnregisteredGroup if u want to set a switch
# between unregistered and registered player group
# set the group name below
RegisteredPlayerGroup: ''
# with this option you can add specified permission onJoin
# like for example LoginBonus from another plugins, AuthMe
# will check onJoin if player has that permissions in his Group
# if true it add a temporany permissions to that user. This Field
# is needed beacuse AuthMe switch all unlogged players on a
# specified restricted Permission Group, so plugins that will use
# some particolary permissions on join doesnt work, without
# compiling option below!
Permissions:
PermissionsOnJoin: []
settings: settings:
sessions: sessions:
# Do you want to enable session? When enabled # Do you want to enable the session feature?
# the ip of a player will be bound to the nickname # If enabled, when a player authenticates successfully,
# of the player on login. As long as neither of those # his IP and his nickname is saved.
# two change players don't have to login on a reconnect # The next time the player joins the server, if his IP
# is the same of the last time, and the timeout time
# hasn't expired, he will not need to authenticate.
enabled: false enabled: false
# After how many minutes a session should timeout? # After how many minutes a session should expire?
# 0 for unlimitted sessions, use 0 at your own risk! # 0 for unlimited time (Very dangerous, use it at your own risk!)
# consider that session will end only after timeout, and # Consider that session will end only after the timeout time, and
# if player's ip is changed but the timeout treshould isent # if the player's ip has changed but the timeout hasn't expired,
# ended, player will kick out of sever for invalidSession! # player will be kicked out of sever due to invalidSession!
timeout: 10 timeout: 10
# Do we need to timeout the session if the player is offline # Should the session expire if the player try to login with an
# And try to login with an another IP Address? # another IP Address?
sessionExpireOnIpChange: false sessionExpireOnIpChange: true
restrictions: restrictions:
# Can unregistered/unlogged players chat and see chat, care , that block all commands except followers # Can not authenticated players chat and see the chat log?
# Care that this feature blocks also all the commands not
# listed in the list below.
allowChat: false allowChat: false
# Commands allowed when a player is unlogged # Commands allowed when a player is not authenticated
allowCommands: allowCommands:
- /login - /login
- /register - /register
@ -86,54 +74,52 @@ settings:
- /reg - /reg
- /email - /email
- /captcha - /captcha
# Maximum Registration per IP default: 1 # Max number of allowed registrations per IP (default: 1)
maxRegPerIp: 1 maxRegPerIp: 1
# Max allowed nick length # Max allowed username length
maxNicknameLength: 16 maxNicknameLength: 16
# Player that is online arent # When this setting is enabled, online players can't be kicked out
# kick out for "logged in from another # due to "Logged in from another Location"
# Location", this options will prevent players that would exploit # This setting will prevent potetial security exploits.
# your account when you are playing
ForceSingleSession: true ForceSingleSession: true
# Teleport every time player join at World Spawn location, # If enabled, every player will be teleported to the world spawnpoint
# even if they loggedin successfully, # after successful authentication.
# all quit and previus location will # The quit location of the player will be overwritten.
# overwrite with World Spawn. Different From # This is different from "teleportUnAuthedToSpawn" that teleport player
# "teleportUnAuthedToSpawn" # back to his quit location after the authentication.
# that teleport player back to his quit or kick position,
# when he loggedin
ForceSpawnLocOnJoinEnabled: false ForceSpawnLocOnJoinEnabled: false
# This will prevent all lost of quit position, when player # This option will save the quit location of the players.
# isent loggedin
SaveQuitLocation: false SaveQuitLocation: false
# For activate Restricted user by ip u need # To activate the restricted user feature you need
# to set True this option and configure the field # to enable this option and configure the
# AllowedRestrctedUser as show below # AllowedRestrctedUser field.
AllowRestrictedUser: false AllowRestrictedUser: false
# Restricted user will kick players that # The restricted user feature will kick players listed below
# is listed below and they dont # if they dont match of the defined ip address.
# meet the match of username;ip # Example:
# Example playername;127.0.0.1 , if playername # AllowedRestrictedUser:
# hasent 127.0.0.1 as ip address # - playername;127.0.0.1
# he will not be allowed to join the server
AllowedRestrictedUser: AllowedRestrictedUser:
- playername;127.0.0.1 - playername;127.0.0.1
# Should unregistered players be kicked immediatly? # Should unregistered players be kicked immediatly?
kickNonRegistered: false kickNonRegistered: false
# Should fail password players be kicked immediatly? # Should players be kicked on wrong password?
kickOnWrongPassword: false kickOnWrongPassword: false
# should not loged in players be teleported to spawn? # Should not logged in players be teleported to the spawn?
# On login they will be teleported back to their normal # After the authentication they will be teleported back to
# position # their normal position.
teleportUnAuthedToSpawn: false teleportUnAuthedToSpawn: false
# min allowed nick length # Minimum allowed nick length
minNicknameLength: 4 minNicknameLength: 4
# Can unregistered players walk around? # Can unregistered players walk around?
allowMovement: false allowMovement: false
# After what time players who fail to login or register # Should not authenticated players have speed = 0?
# should be kicked. Set to 0 to disable. # This will reset the fly/walk speed to default value after the login.
removeSpeed: true
# After how many time players who fail to login or register
# should be kicked? Set to 0 to disable.
timeout: 30 timeout: 30
# Regex sintax for allowed Char in player name. # Regex sintax of allowed characters in the player name.
allowedNicknameCharacters: '[a-zA-Z0-9_]*' allowedNicknameCharacters: '[a-zA-Z0-9_]*'
# How far can unregistered players walk? Set to 0 # How far can unregistered players walk? Set to 0
# for unlimited radius # for unlimited radius
@ -200,7 +186,7 @@ settings:
# possible values: MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, # possible values: MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB,
# PLAINTEXT ( unhashed password), # PLAINTEXT ( unhashed password),
# MYBB, IPB3, PHPFUSION, SMF, XENFORO, SALTED2MD5, JOOMLA, BCRYPT, WBB3, SHA512, # MYBB, IPB3, PHPFUSION, SMF, XENFORO, SALTED2MD5, JOOMLA, BCRYPT, WBB3, SHA512,
# DOUBLEMD5, PBKDF2, WORDPRESS, ROYALAUTH, CUSTOM(for developpers only) # DOUBLEMD5, PBKDF2, PBKDF2DJANGO, WORDPRESS, ROYALAUTH, CUSTOM(for developpers only)
passwordHash: SHA256 passwordHash: SHA256
# salt length for the SALTED2MD5 MD5(MD5(password)+salt) # salt length for the SALTED2MD5 MD5(MD5(password)+salt)
doubleMD5SaltLength: 8 doubleMD5SaltLength: 8
@ -290,10 +276,10 @@ ExternalBoardOptions:
# WordPress prefix defined during WordPress installation process # WordPress prefix defined during WordPress installation process
wordpressTablePrefix: 'wp_' wordpressTablePrefix: 'wp_'
permission: permission:
# take care with this options, if u dont want # Take care with this options, if you dont want
# to use Vault and Group Switching of # to use Vault and Group Switching of
# AuthMe for unloggedIn players put False # AuthMe for unloggedIn players put true
# below, default is true. # below, default is false.
EnablePermissionCheck: false EnablePermissionCheck: false
BackupSystem: BackupSystem:
# Enable or Disable Automatic Backup # Enable or Disable Automatic Backup

View File

@ -37,8 +37,6 @@ usage_changepassword: '&fКоманда: /changepassword СтараПарола
name_len: '&cТвоя никнейм е твърде малък или голям' name_len: '&cТвоя никнейм е твърде малък или голям'
regex: '&cТвоя никнейм съдържа забранени знацхи. Позволените са: REG_EX' regex: '&cТвоя никнейм съдържа забранени знацхи. Позволените са: REG_EX'
add_email: '&cМоля добави своя имейл с : /email add имейл имейл' add_email: '&cМоля добави своя имейл с : /email add имейл имейл'
bad_database_email: '[AuthMe] Тази /email команда работи само с БД (MySQL и SQLite),
свържи се с Админ'
recovery_email: '&cЗабравихте своята парола? Моля използвай /email recovery <имейл>' recovery_email: '&cЗабравихте своята парола? Моля използвай /email recovery <имейл>'
usage_captcha: '&cYou need to type a captcha, please type: /captcha <код>' usage_captcha: '&cYou need to type a captcha, please type: /captcha <код>'
wrong_captcha: '&cГрешен код, използвай : /captcha THE_CAPTCHA' wrong_captcha: '&cГрешен код, използвай : /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&fUse: /changepassword PasswordAntiga PasswordNova'
name_len: '&cO seu nickname é muito curto, ou muito longo.' name_len: '&cO seu nickname é muito curto, ou muito longo.'
regex: '&cO seu nickname contém caracteres não permitidos. Permitido: REG_EX' regex: '&cO seu nickname contém caracteres não permitidos. Permitido: REG_EX'
add_email: '&cPor favor adicione o seu email com : /email add seuEmail confirmarSeuEmail' add_email: '&cPor favor adicione o seu email com : /email add seuEmail confirmarSeuEmail'
bad_database_email: '[AuthMe] O comando /email não está disponível contacte o staff via ticket'
recovery_email: '&cPerdeu/esqueceu a sua password(senha)? Para a recupera-la escreva /email recovery <seuEmail>' recovery_email: '&cPerdeu/esqueceu a sua password(senha)? Para a recupera-la escreva /email recovery <seuEmail>'
usage_captcha: '&cVocê precisa digitar um captcha, escreva: /captcha <theCaptcha>' usage_captcha: '&cVocê precisa digitar um captcha, escreva: /captcha <theCaptcha>'
wrong_captcha: '&cCaptcha errado, por favor escreva: /captcha THE_CAPTCHA' wrong_captcha: '&cCaptcha errado, por favor escreva: /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&cPouzij: "/changepassword stareHeslo noveHeslo".'
name_len: '&cTvuj nick je prilis kratky, nebo prilis dlouhy' name_len: '&cTvuj nick je prilis kratky, nebo prilis dlouhy'
regex: '&cTvuj nick obsahuje nepovolene znaky. Pripustne znaky jsou: REG_EX' regex: '&cTvuj nick obsahuje nepovolene znaky. Pripustne znaky jsou: REG_EX'
add_email: '&cPridej prosim svuj email pomoci : /email add TvujEmail TvujEmail' add_email: '&cPridej prosim svuj email pomoci : /email add TvujEmail TvujEmail'
bad_database_email: '[AuthMe] Prikaz /email je mozno pouzit jen s MySQL a SQLite, kontaktuj Admina'
recovery_email: '&cZapomel jsi heslo? Zadej: /email recovery <TvujEmail>' recovery_email: '&cZapomel jsi heslo? Zadej: /email recovery <TvujEmail>'
usage_captcha: '&cPouzij: /captcha <Captcha_text>' usage_captcha: '&cPouzij: /captcha <Captcha_text>'
wrong_captcha: '&cSpatne opsana Captcha, pouzij prosim: /captcha CAPTCHA_TEXT' wrong_captcha: '&cSpatne opsana Captcha, pouzij prosim: /captcha CAPTCHA_TEXT'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&cBenutze: /changepassword <altesPasswort> <neuesPasswort
name_len: '&4Dein Nickname ist zu kurz oder zu lang' name_len: '&4Dein Nickname ist zu kurz oder zu lang'
regex: '&4Dein Nickname enthält nicht erlaubte Zeichen. Zulässige Zeichen: REG_EX' regex: '&4Dein Nickname enthält nicht erlaubte Zeichen. Zulässige Zeichen: REG_EX'
add_email: '&3Bitte hinterlege Deine E-Mail Adresse: /email add <deineEmail> <emailBestätigen>' add_email: '&3Bitte hinterlege Deine E-Mail Adresse: /email add <deineEmail> <emailBestätigen>'
bad_database_email: '&4Der /email Befehl ist nur mit MySQL und SQLite kompatibel. Bitte kontaktiere einen Administrator!'
recovery_email: '&3Passwort vergessen? Nutze "/email recovery <deineEmail>" für ein neues Passwort' recovery_email: '&3Passwort vergessen? Nutze "/email recovery <deineEmail>" für ein neues Passwort'
usage_captcha: '&3Um dich einzuloggen, tippe dieses Captcha so ein: /captcha <theCaptcha>' usage_captcha: '&3Um dich einzuloggen, tippe dieses Captcha so ein: /captcha <theCaptcha>'
wrong_captcha: '&cFalsches Captcha, bitte nutze: /captcha THE_CAPTCHA' wrong_captcha: '&cFalsches Captcha, bitte nutze: /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&cUsage: /changepassword <oldPassword> <newPassword>'
name_len: '&4Your username is either too short or too long!' name_len: '&4Your username is either too short or too long!'
regex: '&4Your username contains illegal characters. Allowed chars: REG_EX' regex: '&4Your username contains illegal characters. Allowed chars: REG_EX'
add_email: '&3Please add your email to your account with the command "/email add <yourEmail> <confirmEmail>"' add_email: '&3Please add your email to your account with the command "/email add <yourEmail> <confirmEmail>"'
bad_database_email: '&4The /email command is available only with MySQL and SQLite databases, please contact an Admin!' #This should be removed!
recovery_email: '&3Forgot your password? Please use the command "/email recovery <yourEmail>"' recovery_email: '&3Forgot your password? Please use the command "/email recovery <yourEmail>"'
usage_captcha: '&3To login you have to solve a captcha code, please use the command "/captcha <theCaptcha>"' usage_captcha: '&3To login you have to solve a captcha code, please use the command "/captcha <theCaptcha>"'
wrong_captcha: '&cWrong Captcha, please type "/captcha THE_CAPTCHA" into the chat!' wrong_captcha: '&cWrong Captcha, please type "/captcha THE_CAPTCHA" into the chat!'

View File

@ -37,7 +37,6 @@ usage_changepassword: '&fUso: /changepw contraseñaaActual contraseñaNueva'
name_len: '&cTu nombre de usuario es muy largo o muy corto' 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' 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' 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 <tuEmail>' recovery_email: '&c¿Olvidaste tu contraseña? Por favor usa /email recovery <tuEmail>'
usage_captcha: '&cUso: /captcha <elCaptcha>' usage_captcha: '&cUso: /captcha <elCaptcha>'
wrong_captcha: '&cCaptcha incorrecto, please use : /captcha EL_CAPTCHA' wrong_captcha: '&cCaptcha incorrecto, please use : /captcha EL_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&fErabili: /changepassword pasahitzZaharra pasahitzBerria
name_len: '&cZure erabiltzaile izena motzegia edo luzeegia da' name_len: '&cZure erabiltzaile izena motzegia edo luzeegia da'
regex: '&cZure erabiltzaileak karaktere debekatuak ditu. Karaktere onartuak: REG_EX' regex: '&cZure erabiltzaileak karaktere debekatuak ditu. Karaktere onartuak: REG_EX'
add_email: '&cMesedez gehitu zure emaila : /email add yourEmail confirmEmail' add_email: '&cMesedez gehitu zure emaila : /email add yourEmail confirmEmail'
bad_database_email: '[AuthMe] /email komandoa MySql-rekin bakarrik dago erabilgarri. Jarri kontaktuan administratzaile batekin'
recovery_email: '&cPasahitza ahaztu duzu? Erabili /email recovery <zureemaila>' recovery_email: '&cPasahitza ahaztu duzu? Erabili /email recovery <zureemaila>'
usage_captcha: '&cYou need to type a captcha, please type: /captcha <theCaptcha>' usage_captcha: '&cYou need to type a captcha, please type: /captcha <theCaptcha>'
wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&fKäyttötapa: /changepassword vanhaSalasana uusiSalasan
name_len: '&cPelaajanimesi on liian lyhyt tai pitkä' name_len: '&cPelaajanimesi on liian lyhyt tai pitkä'
regex: '&cPelaajanimesi sisältää luvattomia merkkejä. Hyväksytyt merkit: REG_EX' regex: '&cPelaajanimesi sisältää luvattomia merkkejä. Hyväksytyt merkit: REG_EX'
add_email: '&cLisää sähköpostisi: /email add sähköpostisi sähköpostisiUudelleen' add_email: '&cLisää sähköpostisi: /email add sähköpostisi sähköpostisiUudelleen'
bad_database_email: '[AuthMe] Tämä /email komento on vain käytössä MySQLlän kanssa. Ota yhteys palveluntarjoojaan'
recovery_email: '&cUnohtuiko salasana? Käytä komentoa: /email recovery <Sähköpostisi>' recovery_email: '&cUnohtuiko salasana? Käytä komentoa: /email recovery <Sähköpostisi>'
usage_captcha: '&cKäyttötapa: /captcha <Captcha>' usage_captcha: '&cKäyttötapa: /captcha <Captcha>'
wrong_captcha: '&cVäärä varmistus, käytä : /captcha CAPTCHA' wrong_captcha: '&cVäärä varmistus, käytä : /captcha CAPTCHA'

View File

@ -37,7 +37,6 @@ usage_changepassword: '&fPour changer de mot de passe, utilisez: /changepassword
name_len: '&cVotre pseudo est trop long ou trop court' name_len: '&cVotre pseudo est trop long ou trop court'
regex: '&cCaractères autorisés: REG_EX' regex: '&cCaractères autorisés: REG_EX'
add_email: '&cMerci d''ajouter votre email : /email add yourEmail confirmEmail' 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: '&cVous avez oublié votre MotdePasse? Utilisez /email recovery <yourEmail>' recovery_email: '&cVous avez oublié votre MotdePasse? Utilisez /email recovery <yourEmail>'
usage_captcha: '&cTrop de tentatives de connexion échouées, utilisez: /captcha <leCaptcha>' usage_captcha: '&cTrop de tentatives de connexion échouées, utilisez: /captcha <leCaptcha>'
wrong_captcha: '&cCaptcha incorrect, écrivez de nouveau : /captcha THE_CAPTCHA' wrong_captcha: '&cCaptcha incorrect, écrivez de nouveau : /captcha THE_CAPTCHA'

View File

@ -37,8 +37,6 @@ usage_changepassword: '&fUso: /changepassword <contrasinalVello> <contrasinalNov
name_len: '&cO teu nome é demasiado curto ou demasiado longo' name_len: '&cO teu nome é demasiado curto ou demasiado longo'
regex: '&cO teu nome contén caracteres ilegais. Caracteres permitidos: REG_EX' regex: '&cO teu nome contén caracteres ilegais. Caracteres permitidos: REG_EX'
add_email: '&cPor favor, engade o teu correo electrónico con: /email add <oTeuCorreo> <confirmarCorreo>' add_email: '&cPor favor, engade o teu correo electrónico con: /email add <oTeuCorreo> <confirmarCorreo>'
bad_database_email: '[AuthMe] Este comando /email só está dispoñible con MySQL e SQLite,
contacta cun administrador'
recovery_email: '&cOlvidaches o contrasinal? Por favor, usa /email recovery <oTeuCorreo>' recovery_email: '&cOlvidaches o contrasinal? Por favor, usa /email recovery <oTeuCorreo>'
usage_captcha: '&cNecesitas escribir un captcha, por favor escribe: /captcha <oCaptcha>' usage_captcha: '&cNecesitas escribir un captcha, por favor escribe: /captcha <oCaptcha>'
wrong_captcha: '&cCaptcha equivocado, por favor usa: /captcha THE_CAPTCHA' wrong_captcha: '&cCaptcha equivocado, por favor usa: /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: 'használat: /changepassword régiJelszó újJelszó'
name_len: '&cYour nickname is too Short or too long' name_len: '&cYour nickname is too Short or too long'
regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX'
add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' 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 <yourEmail>' recovery_email: '&cForgot your password? Please use /email recovery <yourEmail>'
usage_captcha: '&cUsage: /captcha <theCaptcha>' usage_captcha: '&cUsage: /captcha <theCaptcha>'
wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA'

View File

@ -0,0 +1,58 @@
unknown_user: '&cTidak dapat menemukan user yg diminta di database!'
unsafe_spawn: '&cLokasi quit kamu tidak aman, kamu telah diteleport ke titik spawn world.'
not_logged_in: '&cKamu belum login!'
reg_voluntarily: 'Kamu bisa register menggunakan command "/register <password> <ulangiPassword>"'
usage_log: '&cUsage: /login <password>'
wrong_pwd: '&cPassword salah!'
unregistered: '&cUnregister berhasil!'
reg_disabled: '&cRegister dalam game tidak diaktifkan!'
valid_session: '&2Otomatis login, karena sesi masih terhubung.'
login: '&2Login berhasil!'
vb_nonActiv: '&cAkunmu belum diaktifkan, silahkan periksa email kamu!'
user_regged: '&cKamu telah mendaftarkan username ini!'
usage_reg: '&cUsage: /register <password> <ulangiPassword>'
max_reg: '&Kamu telah mencapai batas maksimum pendaftaran di server ini!'
no_perm: '&4Kamu tidak mempunyai izin melakukan ini!'
error: '&4Terjadi kesalahan tak dikenal, silahkan hubungi Administrator!'
login_msg: '&cSilahkan login menggunakan command "/login <password>"'
reg_msg: '&3Silahkan mendaftar ke server menggunakan command "/register <password> <ulangiPassword>"'
reg_email_msg: '&3Silahkan mendaftar ke server menggunakan command "/register <email> <ulangiEmail>"'
usage_unreg: '&cUsage: /unregister <password>'
pwd_changed: '&2Berhasil mengubah password!'
user_unknown: '&cUser ini belum terdaftar!'
password_error: '&cPassword tidak cocok, silahkan periksa dan ulangi kembali!'
password_error_nick: '&cKamu tidak bisa menggunakan namamu sebagai password, silahkan coba yg lain...'
password_error_unsafe: '&cPassword yg kamu pilih tidak aman, silahkan coba yg lain...'
invalid_session: '&cIP kamu telah berubah, dan sesi kamu telah berakhir!'
reg_only: '&4Hanya pengguna terdaftar yg bisa bergabung! Silahkan kunjungi http://example.com untuk mendaftar!'
logged_in: '&cKamu telah login!'
logout: '&2Berhasil logout!'
same_nick: '&4Username yg sama telah bermain di server ini!'
registered: '&2Register berhasil!'
pass_len: '&cPassword kamu terlalu panjang/pendek! Silahkan pilih yg lain!'
reload: '&2Konfigurasi dan database telah dimuat ulang!'
timeout: '&4Jangka waktu login telah habis, kamu di keluarkan dari server. Silahkan coba lagi!'
usage_changepassword: '&cUsage: /changepassword <passwordLama> <passwordBaru>'
name_len: '&4Username kamu terlalu panjang atau terlalu pendek!'
regex: '&4Username kamu mengandung karakter illegal. Karakter yg diijinkan: REG_EX'
add_email: '&3Silahkan tambahkan email ke akunmu menggunakan command "/email add <emailKamu> <ulangiEmail>"'
recovery_email: '&3Lupa password? silahkan gunakan command "/email recovery <emailKamu>"'
usage_captcha: '&3Kamu harus menyelesaikan kode captcha untuk login, silahkan gunakan command "/captcha <theCaptcha>"'
wrong_captcha: '&cCaptcha salah, gunakan command "/captcha THE_CAPTCHA" pada chat!'
valid_captcha: '&2Kode captcha terselesaikan!'
kick_forvip: '&3Player VIP mencoba masuk pada saat server sedang penuh!'
kick_fullserver: '&4Server sedang penuh, silahkan coba lagi nanti!'
usage_email_add: '&cUsage: /email add <email> <ulangiEmail>'
usage_email_change: '&cUsage: /email change <emailLama> <emailBaru>'
usage_email_recovery: '&cUsage: /email recovery <Email>'
new_email_invalid: '&cEmail baru tidak valid, coba lagi!'
old_email_invalid: '&cEmail lama tidak valid, coba lagi!'
email_invalid: '&cAlamat email tidak valid, coba lagi!'
email_added: '&2Berhasil menambahkan alamat email ke akunmu!'
email_confirm: '&cSilahkan konfirmasi alamat email kamu!'
email_changed: '&2Alamat email telah diubah dengan benar!'
email_send: '&2Email pemulihan akun telah dikirim! Silahkan periksa kotak masuk emailmu!'
email_exists: '&cEmail pemulihan sudah dikirim! kamu bisa membatalkan dan mengirimkan yg baru dengan command dibawah:'
country_banned: '&4Your country is banned from this server!'
antibot_auto_enabled: '&4[AntiBotService] AntiBot diaktifkan dikarenakan banyak koneksi yg diterima!'
antibot_auto_disabled: '&2[AntiBotService] AntiBot dimatikan setelah %m menit!'

View File

@ -36,7 +36,6 @@ usage_changepassword: 'Utilizzo: /changepassword <vecchiaPassword> <nuovaPasswor
name_len: '&cIl tuo nome utente è troppo corto o troppo lungo!' name_len: '&cIl tuo nome utente è troppo corto o troppo lungo!'
regex: '&cIl tuo nome utente contiene caratteri non consentiti. I caratteri consentiti sono: REG_EX' regex: '&cIl tuo nome utente contiene caratteri non consentiti. I caratteri consentiti sono: REG_EX'
add_email: '&cPer poter recuperare la password in futuro, aggiungi un indirizzo email al tuo account con il comando: "/email add <tuaEmail> <confermaEmail>"' add_email: '&cPer poter recuperare la password in futuro, aggiungi un indirizzo email al tuo account con il comando: "/email add <tuaEmail> <confermaEmail>"'
bad_database_email: 'Il comando /email è utilizzabile solo con un database MySQL o SQLite, riporta questo errore ad un Admin!'
recovery_email: '&cHai dimenticato la tua password? Puoi recuperarla eseguendo il comando: "/email recovery <tuaEmail>"' recovery_email: '&cHai dimenticato la tua password? Puoi recuperarla eseguendo il comando: "/email recovery <tuaEmail>"'
usage_captcha: '&cAbbiamo bisogno che tu inserisca un captcha, perfavore scrivi: "/captcha THE_CAPTCHA"' usage_captcha: '&cAbbiamo bisogno che tu inserisca un captcha, perfavore scrivi: "/captcha THE_CAPTCHA"'
wrong_captcha: '&cCaptcha sbagliato, perfavore riprova con il comando: "/captcha THE_CAPTCHA"' wrong_captcha: '&cCaptcha sbagliato, perfavore riprova con il comando: "/captcha THE_CAPTCHA"'

View File

@ -40,7 +40,6 @@ usage_changepassword: '&f사용법: /changepassword 기존비밀번호 새로운
name_len: '&c당신의 이름은 너무 짧거나 너무 깁니다' name_len: '&c당신의 이름은 너무 짧거나 너무 깁니다'
regex: '&c당신의 이름에는 불법적인 글자들이 포함되어있습니다. 허용된 글자: REG_EX' regex: '&c당신의 이름에는 불법적인 글자들이 포함되어있습니다. 허용된 글자: REG_EX'
add_email: '&c당신의 이메일을 추가해주세요 : /email add 당신의이메일 이메일재입력' add_email: '&c당신의 이메일을 추가해주세요 : /email add 당신의이메일 이메일재입력'
bad_database_email: '[AuthMe] 이 /email 명령어는 오직 MySQL와 SQLite에서만 가능합니다, 관리자에게 문의해주세요'
recovery_email: '&c비밀번호를 잊어버리셨다고요? /email recovery <당신의이메일>을 사용하세요' recovery_email: '&c비밀번호를 잊어버리셨다고요? /email recovery <당신의이메일>을 사용하세요'
usage_captcha: '&c보안문자 입력이 필요합니다, 입력해주세요: /captcha <theCaptcha>' usage_captcha: '&c보안문자 입력이 필요합니다, 입력해주세요: /captcha <theCaptcha>'
wrong_captcha: '&c잘못된 보안문자, 사용해주세요 : /captcha THE_CAPTCHA' wrong_captcha: '&c잘못된 보안문자, 사용해주세요 : /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&ePanaudojimas: /changepassword senasSlaptazodis naujasSl
name_len: '&cJusu varsdas yra per ilgas arba per trumpas.' name_len: '&cJusu varsdas yra per ilgas arba per trumpas.'
regex: '&cJusu varde yra neledziamu simboliu, leidziami: REG_EX' regex: '&cJusu varde yra neledziamu simboliu, leidziami: REG_EX'
add_email: '&ePrasau pridekite savo el.pasta : /email add Email confirmEmail' add_email: '&ePrasau pridekite savo el.pasta : /email add Email confirmEmail'
bad_database_email: '&c[AuthMe] si /email komanda leidziama tik su MySQL ir SQLite, susisiekite su administratorium'
recovery_email: '&cPamirsote slaptazodi? Rasykite: /email recovery el.pastas' recovery_email: '&cPamirsote slaptazodi? Rasykite: /email recovery el.pastas'
usage_captcha: '&cPanaudojimas: /captcha <theCaptcha>' usage_captcha: '&cPanaudojimas: /captcha <theCaptcha>'
wrong_captcha: '&cNeteisinga Captcha, naudokite : /captcha THE_CAPTCHA' wrong_captcha: '&cNeteisinga Captcha, naudokite : /captcha THE_CAPTCHA'

View File

@ -35,7 +35,6 @@ usage_changepassword: 'Gebruik: /changepassword <oudWachtwoord> <nieuwWachtwoord
name_len: '&cJouw gebruikersnaam is te kort' name_len: '&cJouw gebruikersnaam is te kort'
regex: '&cJouw gebruikersnaam bestaat uit illegale tekens. tegestaan chars: REG_EX' regex: '&cJouw gebruikersnaam bestaat uit illegale tekens. tegestaan chars: REG_EX'
add_email: '&cVoeg uw email toe Alstublieft met: /email add jouw wachtwoord herhaalwachtwoord' add_email: '&cVoeg uw email toe Alstublieft met: /email add jouw wachtwoord herhaalwachtwoord'
bad_database_email: '[AuthMe] deze /email command is alleen beschikbaar met MySQL en SQLite, neem contact op met een Admin'
recovery_email: '&cWachtwoord vergeten? gebruik alstublieft /email recovery <Jouwemail>' recovery_email: '&cWachtwoord vergeten? gebruik alstublieft /email recovery <Jouwemail>'
usage_captcha: '&cGebruik: /captcha <deCaptcha>' usage_captcha: '&cGebruik: /captcha <deCaptcha>'
wrong_captcha: '&cverkeerde Captcha, Gebruik alstublieft : /captcha THE_CAPTCHA' wrong_captcha: '&cverkeerde Captcha, Gebruik alstublieft : /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&fUzycie: /changepassword starehaslo nowehaslo'
name_len: '&cTwoje konto ma za dluga badz za krotka nazwe' name_len: '&cTwoje konto ma za dluga badz za krotka nazwe'
regex: '&cTwoje konto ma w nazwie niedozwolone znaki. Dozwolone znaki: REG_EX' regex: '&cTwoje konto ma w nazwie niedozwolone znaki. Dozwolone znaki: REG_EX'
add_email: '&cProsze dodac swoj email: /email add twojEmail powtorzEmail' add_email: '&cProsze dodac swoj email: /email add twojEmail powtorzEmail'
bad_database_email: '[AuthMe] Ta komenda /email dostepna jedynie z baza adnych MySQL lub SQLite, skontaktuj sie z Administratorem'
recovery_email: '&cZapomniales hasla? Prosze uzyj komendy /email recovery <TwojEmail>' recovery_email: '&cZapomniales hasla? Prosze uzyj komendy /email recovery <TwojEmail>'
usage_captcha: '&cWpisz: /captcha <kod>' usage_captcha: '&cWpisz: /captcha <kod>'
wrong_captcha: '&cZly kod, prosze wpisac: /captcha THE_CAPTCHA' wrong_captcha: '&cZly kod, prosze wpisac: /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&fUse: /changepassword passwordAntiga passwordNova'
name_len: '&cO seu nick é demasiado curto ou muito longo.' name_len: '&cO seu nick é demasiado curto ou muito longo.'
regex: '&cO seu nickname contém caracteres não permitidos. Permitido: REG_EX' regex: '&cO seu nickname contém caracteres não permitidos. Permitido: REG_EX'
add_email: '&cPor favor adicione o seu email com : /email add seuEmail confirmarSeuEmail' add_email: '&cPor favor adicione o seu email com : /email add seuEmail confirmarSeuEmail'
bad_database_email: '[AuthMe] O comando /email não está disponível contacte o staff via ticket'
recovery_email: '&cPerdeu a sua password? Para a recuperar escreva /email recovery <seuEmail>' recovery_email: '&cPerdeu a sua password? Para a recuperar escreva /email recovery <seuEmail>'
usage_captcha: '&cVocê precisa digitar um captcha, escreva: /captcha <theCaptcha>' usage_captcha: '&cVocê precisa digitar um captcha, escreva: /captcha <theCaptcha>'
wrong_captcha: '&cCaptcha errado, por favor escreva: /captcha THE_CAPTCHA' wrong_captcha: '&cCaptcha errado, por favor escreva: /captcha THE_CAPTCHA'

View File

@ -1,58 +1,57 @@
unknown_user: '&fПользователь не найден в Базе Данных' unknown_user: '&fПользователь не найден в Базе Данных'
unsafe_spawn: '&eВаше расположение перед выходом было опасным - вы перенесены на спавн' unsafe_spawn: '&eВаше расположение перед выходом было опасным - вы перенесены на спавн'
not_logged_in: '&cВы еще не вошли!' not_logged_in: '&cВы еще не вошли!'
reg_voluntarily: '&aЧтобы зарегистрироваться введите: &5/reg ПАРОЛЬ ПОВТОРАРОЛЯ' reg_voluntarily: '&aЧтобы зарегистрироваться введите: &5/reg ПАРОЛЬ ПОВТОРАРОЛЯ'
usage_log: '&eСинтаксис: &d/l ПАРОЛЬ &eили &d/login ПАРОЛЬ' usage_log: '&eСинтаксис: &d/l ПАРОЛЬ &eили &d/login ПАРОЛЬ'
wrong_pwd: '&4Неправильный пароль!' wrong_pwd: '&4Неправильный пароль!'
unregistered: '&6Вы успешно удалили свой аккаунт!' unregistered: '&6Вы успешно удалили свой аккаунт!'
reg_disabled: '&4Регистрация отключена' reg_disabled: '&4Регистрация отключена'
valid_session: '&aСессия открыта' valid_session: '&aСессия открыта'
login: '&2Вы успешно вошли!' login: '&2Вы успешно вошли!'
vb_nonActiv: '&6Ваш аккаунт еще не активирован! Проверьте вашу почту!' vb_nonActiv: '&6Ваш аккаунт еще не активирован! Проверьте вашу почту!'
user_regged: '&4Такой игрок уже зарегистрирован' user_regged: '&4Такой игрок уже зарегистрирован'
usage_reg: '&4Использование: &5/reg ПАРОЛЬ ПОВТОРАРОЛЯ' usage_reg: '&4Использование: &5/reg ПАРОЛЬ ПОВТОРАРОЛЯ'
max_reg: '&4Вы превысили макс количество регистраций на ваш IP' max_reg: '&4Вы превысили макс количество регистраций на ваш IP'
no_perm: '&4Недостаточно прав' no_perm: '&4Недостаточно прав'
error: '&4Произошла ошибка. Свяжитесь с администратором' error: '&4Произошла ошибка. Свяжитесь с администратором'
login_msg: '&4Авторизация: &5/l ПАРОЛЬ' login_msg: '&4Авторизация: &5/l ПАРОЛЬ'
reg_msg: '&4Регистрация: &5/reg ПАРОЛЬ ПОВТОРАРОЛЯ' reg_msg: '&4Регистрация: &5/reg ПАРОЛЬ ПОВТОРАРОЛЯ'
password_error_nick: '&fВы не можете использовать ваш ник в роли пароля' password_error_nick: '&fВы не можете использовать ваш ник в роли пароля'
password_error_unsafe: '&fВы не можете использовать небезопасный пароль' password_error_unsafe: '&fВы не можете использовать небезопасный пароль'
reg_email_msg: '&4Регистрация: &5/reg EMAIL ПОВТОР_EMAIL' reg_email_msg: '&4Регистрация: &5/reg EMAIL ПОВТОР_EMAIL'
usage_unreg: '&4Использование: &5/unregister ПАРОЛЬ' usage_unreg: '&4Использование: &5/unregister ПАРОЛЬ'
pwd_changed: '&2Пароль изменен!' pwd_changed: '&2Пароль изменен!'
user_unknown: '&4Такой игрок не зарегистрирован' user_unknown: '&4Такой игрок не зарегистрирован'
password_error: '&4Пароль не совпадает' password_error: '&4Пароль не совпадает'
invalid_session: '&4Сессия некорректна. Дождитесь, пока она закончится' invalid_session: '&4Сессия некорректна. Дождитесь, пока она закончится'
reg_only: '&4Только для зарегистрированных! Посетите http://сайт_сервера.com/register/ для регистрации' reg_only: '&4Только для зарегистрированных! Посетите http://сайт_сервера.com/register/ для регистрации'
logged_in: '&4Вы уже авторизированы!' logged_in: '&4Вы уже авторизированы!'
logout: '&2Вы успешно вышли' logout: '&2Вы успешно вышли'
same_nick: '&4Такой игрок уже играет на сервере' same_nick: '&4Такой игрок уже играет на сервере'
registered: '&2Успешная регистрация!' registered: '&2Успешная регистрация!'
pass_len: '&4Твой пароль либо слишком длинный, либо слишком короткий' pass_len: '&4Твой пароль либо слишком длинный, либо слишком короткий'
reload: '&6Конфигурация и база данных перезагружены' reload: '&6Конфигурация и база данных перезагружены'
timeout: '&4Время для авторизации истекло' timeout: '&4Время для авторизации истекло'
usage_changepassword: '&4Использование: &5/changepassword СТАРЫЙ_ПАРОЛЬ НОВЫЙ_ПАРОЛЬ' usage_changepassword: '&4Использование: &5/changepassword СТАРЫЙ_ПАРОЛЬ НОВЫЙ_ПАРОЛЬ'
name_len: '&4Ваш логин слишком длинный или слишком короткий' name_len: '&4Ваш логин слишком длинный или слишком короткий'
regex: '&4Ваш логин содержит запрещенные символы. Разрешенные символы: REG_EX' regex: '&4Ваш логин содержит запрещенные символы. Разрешенные символы: REG_EX'
add_email: '&4Добавьте свой email: &5/email add ВАШ_EMAIL ВАШ_EMAIL' add_email: '&4Добавьте свой email: &5/email add ВАШ_EMAIL ВАШ_EMAIL'
bad_database_email: '&4[AuthMe] Команда &5/email&4 доступна только при работе с MySQL или SQLite. Обратититесь к администрации сервера' recovery_email: '&4Забыли пароль? Используйте &5/email recovery ВАШ_EMAIL'
recovery_email: '&4Забыли пароль? Используйте &5/email recovery ВАШ_EMAIL' usage_captcha: '&4Вы должны ввести код, используйте: &5/captcha <theCaptcha>'
usage_captcha: '&4Вы должны ввести код, используйте: &5/captcha <theCaptcha>' wrong_captcha: '&4Неверный код, используйте: &5/captcha THE_CAPTCHA'
wrong_captcha: '&4Неверный код, используйте: &5/captcha THE_CAPTCHA' valid_captcha: '&2Вы успешно ввели код!'
valid_captcha: '&2Вы успешно ввели код!' kick_forvip: '&6VIP игрок зашел на переполненный сервер!'
kick_forvip: '&6VIP игрок зашел на переполненный сервер!' kick_fullserver: '&4Сервер переполнен!'
kick_fullserver: '&4Сервер переполнен!' usage_email_add: '&4Использование: &5/email add ВАШ_EMAIL ПОВТОР_EMAIL'
usage_email_add: '&4Использование: &5/email add ВАШ_EMAIL ПОВТОР_EMAIL' usage_email_change: '&4Использование: &5/email change СТАРЫЙ_EMAIL НОВЫЙ_EMAIL'
usage_email_change: '&4Использование: &5/email change СТАРЫЙ_EMAIL НОВЫЙ_EMAIL' usage_email_recovery: '&4Использование: /email recovery EMAIL'
usage_email_recovery: '&4Использование: /email recovery EMAIL' new_email_invalid: '[AuthMe] Недействительный новый email!'
new_email_invalid: '[AuthMe] Недействительный новый email!' old_email_invalid: '[AuthMe] Недействительный старый email!'
old_email_invalid: '[AuthMe] Недействительный старый email!' email_invalid: '[AuthMe] Недействительный email'
email_invalid: '[AuthMe] Недействительный email' email_added: '[AuthMe] Email добавлен!'
email_added: '[AuthMe] Email добавлен!' email_confirm: '[AuthMe] Подтвердите ваш Email!'
email_confirm: '[AuthMe] Подтвердите ваш Email!' email_changed: '[AuthMe] Email изменен!'
email_changed: '[AuthMe] Email изменен!' email_send: '[AuthMe] Письмо с инструкциями для восстановления было отправлено на ваш Email!'
email_send: '[AuthMe] Письмо с инструкциями для восстановления было отправлено на ваш Email!' country_banned: 'Вход с IP-адресов вашей страны воспрещен на этом сервере'
country_banned: 'Вход с IP-адресов вашей страны воспрещен на этом сервере' antibot_auto_enabled: '[AuthMe] AntiBot-режим автоматически включен из-за большого количества входов!'
antibot_auto_enabled: '[AuthMe] AntiBot-режим автоматически включен из-за большого количества входов!' antibot_auto_disabled: '[AuthMe] AntiBot-режим автоматичски отключен после %m мин. Надеюсь атака закончилась'
antibot_auto_disabled: '[AuthMe] AntiBot-режим автоматичски отключен после %m мин. Надеюсь атака закончилась'

View File

@ -40,7 +40,6 @@ usage_changepassword: '&fPríkaz: /changepassword stareHeslo noveHeslo'
name_len: '&cTvoje meno je velmi krátke alebo dlhé' name_len: '&cTvoje meno je velmi krátke alebo dlhé'
regex: '&cTvoje meno obsahuje zakázané znaky. Povolené znaky: REG_EX' regex: '&cTvoje meno obsahuje zakázané znaky. Povolené znaky: REG_EX'
add_email: '&cPridaj svoj e-mail príkazom "/email add email zopakujEmail"' 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 <tvojEmail>' recovery_email: '&cZabudol si heslo? Pouzi príkaz /email recovery <tvojEmail>'
usage_captcha: '&cUsage: /captcha <theCaptcha>' usage_captcha: '&cUsage: /captcha <theCaptcha>'
wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&fkullanimi: /changepassword eskisifre yenisifre'
name_len: '&cKullanici adin cok kisa ya da cok uzun' name_len: '&cKullanici adin cok kisa ya da cok uzun'
regex: '&cKullanici adin ozel karakterler iceriyor. Uygun karakterler: REG_EX' regex: '&cKullanici adin ozel karakterler iceriyor. Uygun karakterler: REG_EX'
add_email: '&cLutfen emailini ekle : /email add <epostan> <epostantekrar>' add_email: '&cLutfen emailini ekle : /email add <epostan> <epostantekrar>'
bad_database_email: '[AuthMe] Bu /email komutu sadece MySql ve SQLite ile etkinlestireilebilir'
recovery_email: '&cSifreni mi unuttun? Degistirmek icin : /email recovery <eposta adresin>' recovery_email: '&cSifreni mi unuttun? Degistirmek icin : /email recovery <eposta adresin>'
usage_captcha: '&cBir captcha yazman lazim , yazmak icin: /captcha <theCaptcha>' usage_captcha: '&cBir captcha yazman lazim , yazmak icin: /captcha <theCaptcha>'
wrong_captcha: '&cYanlis Captcha, kullanmak icin : /captcha THE_CAPTCHA' wrong_captcha: '&cYanlis Captcha, kullanmak icin : /captcha THE_CAPTCHA'

View File

@ -36,7 +36,6 @@ usage_changepassword: '&fВикористовуйте: /changepassword Стар
name_len: '&cВаш нікнейм занадто довгий, або занадто короткий' name_len: '&cВаш нікнейм занадто довгий, або занадто короткий'
regex: '&cВаш нікнейм містить заборонені символи. Доступні символи: REG_EX' regex: '&cВаш нікнейм містить заборонені символи. Доступні символи: REG_EX'
add_email: '&cБудь ласка додайте свою електронну скриньку: /email add ВашEmail ВашEmail' add_email: '&cБудь ласка додайте свою електронну скриньку: /email add ВашEmail ВашEmail'
bad_database_email: '[AuthMe] Команда /email доступна лише при роботі з MySQL, або SQLite, зверніться до адміністратора.'
recovery_email: '&cЗабули пароль? Введіть /email recovery ВашПароль' recovery_email: '&cЗабули пароль? Введіть /email recovery ВашПароль'
usage_captcha: '&cБудь ласка введіть капчу: /captcha <theCaptcha>' usage_captcha: '&cБудь ласка введіть капчу: /captcha <theCaptcha>'
wrong_captcha: '&cНевірне значення капчи: /captcha THE_CAPTCHA' wrong_captcha: '&cНевірне значення капчи: /captcha THE_CAPTCHA'

View File

@ -1,59 +1,55 @@
unknown_user: '&fNgười chơi không tồn tại trong cơ sở dữ liệu' unknown_user: '&fNgười chơi không tồn tại trong cơ sở dữ liệu'
unsafe_spawn: '&fNơi thoát server của bạn không an toàn, đang dịch chuyển bạn tới điểm spawn của server' unsafe_spawn: '&fNơi thoát server của bạn không an toàn, đang dịch chuyển bạn tới điểm spawn của server'
not_logged_in: '&cChưa đăng nhập!' not_logged_in: '&cChưa đăng nhập!'
reg_voluntarily: '&fBạn có thể đăng kí tài khoản với lệnh reg_voluntarily: '&fBạn có thể đăng kí tài khoản với lệnh "/register mật-khẩu nhập-lại-mật-khẩu"'
"/register mật-khẩu nhập-lại-mật-khẩu"' usage_log: '&eSử dụng: /login password'
usage_log: '&eSử dụng: /login password' wrong_pwd: '&cSai mật khẩu'
wrong_pwd: '&cSai mật khẩu' unregistered: '&cHuỷ đăng kí thành công!'
unregistered: '&cHuỷ đăng kí thành công!' reg_disabled: '&cHệ thống đăng kí đã bị vô hiệu'
reg_disabled: '&cHệ thống đăng kí đã bị vô hiệu' valid_session: '&cPhiên đăng nhập còn tồn tại, bạn không cần nhập mật khẩu'
valid_session: '&cPhiên đăng nhập còn tồn tại, bạn không cần nhập mật khẩu' login: '&cĐăng nhập thành công!'
login: '&cĐăng nhập thành công!' vb_nonActiv: '&fTài khoản của bạn chưa được kích hoạt, kiểm tra email!'
vb_nonActiv: '&fTài khoản của bạn chưa được kích hoạt, kiểm tra email!' user_regged: '&cTên đăng nhập này đã được đăng kí'
user_regged: '&cTên đăng nhập này đã được đăng kí' usage_reg: '&eSử dụng: /register mật-khẩu nhập-lại-mật-khẩu'
usage_reg: '&eSử dụng: /register mật-khẩu nhập-lại-mật-khẩu' max_reg: '&fSố lượng tài khoản ở IP của bạn trong server này đã quá giới hạn cho phép'
max_reg: '&fSố lượng tài khoản ở IP của bạn trong server này đã quá giới hạn cho phép' no_perm: '&cKhông có quyền'
no_perm: '&cKhông có quyền' error: '&fCó lỗi xảy ra; Báo lại cho người điều hành server'
error: '&fCó lỗi xảy ra; Báo lại cho người điều hành server' login_msg: '&cĐăng nhập với lệnh "/login mật-khẩu"'
login_msg: '&cĐăng nhập với lệnh "/login mật-khẩu"' reg_msg: '&cĐăng kí tài khoản với lệnh "/register mật-khẩu nhập-lại-mật-khẩu"'
reg_msg: '&cĐăng kí tài khoản với lệnh "/register mật-khẩu nhập-lại-mật-khẩu"' reg_email_msg: '&cĐăng kí email cho tài khoản với lệnh "/register <email> <nhập-lại-email>"'
reg_email_msg: '&cĐăng kí email cho tài khoản với lệnh "/register <email> <nhập-lại-email>"' usage_unreg: '&eSử dụng: /unregister mật-khẩu'
usage_unreg: '&eSử dụng: /unregister mật-khẩu' pwd_changed: '&cĐã đổi mật khẩu!'
pwd_changed: '&cĐã đổi mật khẩu!' user_unknown: '&cTài khoản này chưa được đăng kí'
user_unknown: '&cTài khoản này chưa được đăng kí' password_error: '&fMật khẩu không khớp'
password_error: '&fMật khẩu không khớp' unvalid_session: '&fPhiên đăng nhập không hồi đáp, vui lòng chờ phiên đăng nhập kết thúc'
unvalid_session: '&fPhiên đăng nhập không hồi đáp, vui lòng chờ phiên đăng nhập kết thúc' reg_only: '&fChỉ cho phép người đã đăng kí! Hãy vào trang http://web-của.bạn/ để đăng kí'
reg_only: '&fChỉ cho phép người đã đăng kí! Hãy vào trang http://web-của.bạn/ để đăng kí' logged_in: '&cĐã đăng nhập!'
logged_in: '&cĐã đăng nhập!' logout: '&cThoát đăng nhập thành công'
logout: '&cThoát đăng nhập thành công' same_nick: '&fTài khoản đang được người khác sử dụng trong server'
same_nick: '&fTài khoản đang được người khác sử dụng trong server' registered: '&cĐăng kí thành công!'
registered: '&cĐăng kí thành công!' pass_len: '&fMật khẩu của bạn quá ngắn hoặc quá dài'
pass_len: '&fMật khẩu của bạn quá ngắn hoặc quá dài' reload: '&fThiết lập và dữ liệu đã được nạp lại'
reload: '&fThiết lập và dữ liệu đã được nạp lại' timeout: '&fQuá thời gian đăng nhập'
timeout: '&fQuá thời gian đăng nhập' usage_changepassword: '&eSử dụng: /changepassword mật-khẩu-cũ mật-khẩu-mới'
usage_changepassword: '&eSử dụng: /changepassword mật-khẩu-cũ mật-khẩu-mới' name_len: '&cTên đăng nhập của bạn quá ngắn hoặc quá dài'
name_len: '&cTên đăng nhập của bạn quá ngắn hoặc quá dài' regex: '&cTên đăng nhập của bạn có chứa kí tự đặc biệt không được cho phép. Các kí tự hợp lệ: REG_EX'
regex: '&cTên đăng nhập của bạn có chứa kí tự đặc biệt không được cho phép. Các kí tự hợp lệ: REG_EX' add_email: '&cVui lòng thêm địa chỉ email cho tài khoản với lệnh: /email add email-của-bạn nhập-lại-email-của-bạn'
add_email: '&cVui lòng thêm địa chỉ email cho tài khoản với lệnh: /email add email-của-bạn nhập-lại-email-của-bạn' recovery_email: '&cQuên mật khẩu? Hãy dùng lệnh /email recovery <email-của-bạn>'
bad_database_email: '[AuthMe] Lệnh /email chỉ hoạt động với cơ sở dữ liệu MySQL và SQLite, usage_captcha: '&cBạn cần nhập mã xác nhận: /captcha <mã-xác-nhận>'
hãy liên hệ điều hành viên của server' wrong_captcha: '&cSai mã xác nhận, nhập lại: /captcha <mã-xác-nhận>'
recovery_email: '&cQuên mật khẩu? Hãy dùng lệnh /email recovery <email-của-bạn>' valid_captcha: '&aMã xác nhận hợp lệ!'
usage_captcha: '&cBạn cần nhập mã xác nhận: /captcha <mã-xác-nhận>' kick_forvip: '&cNgười chơi VIP đã vào server hiện đang full!'
wrong_captcha: '&cSai mã xác nhận, nhập lại: /captcha <mã-xác-nhận>' kick_fullserver: '&cXin lỗi, hiện tại server không còn trống slot để bạn có thể vào!'
valid_captcha: '&aMã xác nhận hợp lệ!' usage_email_add: '&eSử dụng: /email add <email> <nhập-lại-email> '
kick_forvip: '&cNgười chơi VIP đã vào server hiện đang full!' usage_email_change: '&eSử dụng: /email change <email-cũ> <email-mới> '
kick_fullserver: '&cXin lỗi, hiện tại server không còn trống slot để bạn có thể vào!' usage_email_recovery: '&eSử dụng: /email recovery <Email>'
usage_email_add: '&eSử dụng: /email add <email> <nhập-lại-email> ' new_email_invalid: '[AuthMe] Địa chỉ email mới không hợp lệ!'
usage_email_change: '&eSử dụng: /email change <email-cũ> <email-mới> ' old_email_invalid: '[AuthMe] Địa chỉ email cũ không hợp lệ!'
usage_email_recovery: '&eSử dụng: /email recovery <Email>' email_invalid: '[AuthMe] Sai địa chỉ email'
new_email_invalid: '[AuthMe] Địa chỉ email mới không hợp lệ!' email_added: '[AuthMe] Đã thêm địa chỉ email !'
old_email_invalid: '[AuthMe] Địa chỉ email cũ không hợp lệ!' email_confirm: '[AuthMe] Xác nhận email !'
email_invalid: '[AuthMe] Sai địa chỉ email' email_changed: '[AuthMe] Đã thay đổi email !'
email_added: '[AuthMe] Đã thêm địa chỉ email !' email_send: '[AuthMe] Đã gửi email khôi phục mật khẩu tới bạn !'
email_confirm: '[AuthMe] Xác nhận email !' country_banned: 'Rất tiếc, quốc gia của bạn không được phép gia nhập server'
email_changed: '[AuthMe] Đã thay đổi email !' antibot_auto_enabled: '[AuthMe] AntiBot đã được kích hoạt vì lượng người chơi kết nối vượt quá giới hạn!'
email_send: '[AuthMe] Đã gửi email khôi phục mật khẩu tới bạn !' antibot_auto_disabled: '[AuthMe] AntiBot tự huỷ kích hoạt sau %m phút, hi vọng lượng kết nối sẽ giảm bớt'
country_banned: 'Rất tiếc, quốc gia của bạn không được phép gia nhập server'
antibot_auto_enabled: '[AuthMe] AntiBot đã được kích hoạt vì lượng người chơi kết nối vượt quá giới hạn!'
antibot_auto_disabled: '[AuthMe] AntiBot tự huỷ kích hoạt sau %m phút,
hi vọng lượng kết nối sẽ giảm bớt'

View File

@ -0,0 +1,59 @@
# Translator: uSoc_lifehome (http://lifeho.me) #
# -------------------------------------------- #
unknown_user: '&8[&6用戶系統&8] &f用戶資料並不存在於資料庫中。'
unsafe_spawn: '&8[&6用戶系統&8] &f你的登出位置不安全現在將傳送你到重生點。'
not_logged_in: '&8[&6用戶系統&8] &c你還沒有登入 '
reg_voluntarily: '&8[&6用戶系統&8] &f你可以使用這個的指令來註冊 《 /register <密碼> <重覆密碼> 》'
usage_log: '&8[&6用戶系統&8] &c用法 《 /login <密碼> 》'
wrong_pwd: '&8[&6用戶系統&8] &c你輸入了錯誤的密碼。'
unregistered: '&8[&6用戶系統&8] &c你已成功取消會員註冊記錄。'
reg_disabled: '&8[&6用戶系統&8] &c本伺服器已停止新玩家註冊。'
valid_session: '&8[&6用戶系統&8] &b嗨 我記得你,歡迎回來~'
login: '&8[&6用戶系統&8] &c你成功的登入了。'
password_error_nick: '&fYou can''t use your name as password'
password_error_unsafe: '&fYou can''t use unsafe passwords'
vb_nonActiv: '&8[&6用戶系統&8] &f你的帳戶還沒有經過電郵驗證 '
user_regged: '&8[&6用戶系統&8] &c此用戶名已經註冊過了。'
usage_reg: '&8[&6用戶系統&8] &c用法 《 /register <密碼> <重覆密碼> 》'
max_reg: '&8[&6用戶系統&8] &f你的IP地址已達到註冊數上限。'
no_perm: '&8[&6用戶系統&8] &b你可以到 CraftingHK 玩家百科中查看說明文件。'
error: '&8[&6用戶系統&8] &f發生錯誤請與管理員聯絡。'
login_msg: '&8[&6用戶系統&8] &c請使用這個指令來登入 《 /login <密碼> 》'
reg_msg: '&8[&6用戶系統&8] &c請使用這個的指令來註冊 《 /register <密碼> <重覆密碼> 》'
reg_email_msg: '&8[&6用戶系統&8] &c請使用這個的指令來註冊 《 /register <電郵> <重覆電郵> 》'
usage_unreg: '&8[&6用戶系統&8] &c用法 《 /unregister <密碼> 》'
pwd_changed: '&8[&6用戶系統&8] &c你成功的更換了你的密碼 '
user_unknown: '&8[&6用戶系統&8] &c此用戶名沒有已登記資料。'
password_error: '&8[&6用戶系統&8] &f密碼不符合。'
invalid_session: '&8[&6用戶系統&8] &f登入階段資料已損壞請等待登入階段結束。'
reg_only: '&8[&6用戶系統&8] &f限已註冊會員請先到 https://www.example.com/ 註冊。'
logged_in: '&8[&6用戶系統&8] &c你已經登入過了。'
logout: '&8[&6用戶系統&8] &b你成功的登出了。'
same_nick: '&8[&6用戶系統&8] &f同名玩家已在遊玩。'
registered: '&8[&6用戶系統&8] &b你成功的註冊了。'
pass_len: '&8[&6用戶系統&8] &f你的密碼並不符合規定長度。'
reload: '&8[&6用戶系統&8] &b登入系統設定及資料庫重新載入完畢。'
timeout: '&8[&6用戶系統&8] &f登入逾時。'
usage_changepassword: '&8[&6用戶系統&8] &f用法 《 /changepassword <舊密碼> <新密碼> 》'
name_len: '&8[&6用戶系統&8] &c你的用戶名不符合規定長度。'
regex: '&8[&6用戶系統&8] &c你的用戶名含有不容許之字符。以下為准許之字母 REG_EX'
add_email: '&8[&6用戶系統&8] &b請為你的帳戶立即添加電郵地址 《 /email add <電郵地址> <重覆電郵地址> 》'
recovery_email: '&8[&6用戶系統&8] &c忘記密碼 請使用這個的指令來更新密碼: 《 /email recovery <電郵地址> 》'
usage_captcha: '&8[&6用戶系統&8] &c用法 《 /captcha <驗證碼> 》'
wrong_captcha: '&8[&6用戶系統&8] &c你輸入了錯誤的驗證碼請使用 《 /captcha <驗證碼> 》 再次輸入。'
valid_captcha: '&8[&6用戶系統&8] &c你所輸入的驗證碼是無效的 '
kick_forvip: '&c因為有VIP玩家登入了伺服器。'
kick_fullserver: '&c抱歉 因為伺服器滿人了,所以你目前未能登入伺服器。'
usage_email_add: '&8[&6用戶系統&8] &f用法 《 /email add <電郵> <重覆電郵> 》'
usage_email_change: '&8[&6用戶系統&8] &f用法 《 /email change <舊電郵> <新電郵> 》'
usage_email_recovery: '&8[&6用戶系統&8] &f用法 《 /email recovery <電郵> 》'
new_email_invalid: '&8[&6用戶系統&8] 你所填寫的新電郵地址並不正確。'
old_email_invalid: '&8[&6用戶系統&8] 你所填寫的舊電郵地址並不正確。'
email_invalid: '&8[&6用戶系統&8] 你所填寫的電郵地址並不正確。'
email_added: '&8[&6用戶系統&8] 已加入你的電郵地址記錄。'
email_confirm: '&8[&6用戶系統&8] 請重覆輸入你的電郵地址。'
email_changed: '&8[&6用戶系統&8] 你的電郵地址記錄已更改。'
email_send: '&8[&6用戶系統&8] 忘記密碼信件已寄出,請查收。'
country_banned: '&8[&6用戶系統&8] 本伺服器已停止對你的國家提供遊戲服務。'
antibot_auto_enabled: '&8[&6用戶系統&8] 防止機械人程序已因應現時大量不尋常的連線而啟用。'
antibot_auto_disabled: '&8[&6用戶系統&8] 防止機械人程序檢查到不正常連接數已減少,並於 %m 分鐘後停止運作。'

View File

@ -1,62 +1,61 @@
# Translator: MineWolf50 # Translator: MineWolf50
# Last Time Edit : 2015 / 7 / 14 , A.M.10:14 # Last Time Edit : 2015 / 7 / 14 , A.M.10:14
# = = = = = = = = = = = = = = = = = = = = = = = # # = = = = = = = = = = = = = = = = = = = = = = = #
unknown_user: "&b【AuthMe】&6沒有在資料庫內找到該玩家。" unknown_user: "&b【AuthMe】&6沒有在資料庫內找到該玩家。"
unsafe_spawn: '&b【AuthMe】&6你登出的地點不安全已傳送你到安全的地點。' unsafe_spawn: '&b【AuthMe】&6你登出的地點不安全已傳送你到安全的地點。'
not_logged_in: '&b【AuthMe】&6你還沒有登入!' not_logged_in: '&b【AuthMe】&6你還沒有登入!'
reg_voluntarily: '&b【AuthMe】&6使用 &c"/register <密碼> <確認密碼>" &6來註冊你的暱稱' reg_voluntarily: '&b【AuthMe】&6使用 &c"/register <密碼> <確認密碼>" &6來註冊你的暱稱'
usage_log: '&b【AuthMe】&6用法: &c"/login <密碼>"' usage_log: '&b【AuthMe】&6用法: &c"/login <密碼>"'
wrong_pwd: '&b【AuthMe】&6密碼錯誤!' wrong_pwd: '&b【AuthMe】&6密碼錯誤!'
unregistered: '&b【AuthMe】&6你已經成功取消註冊。' unregistered: '&b【AuthMe】&6你已經成功取消註冊。'
reg_disabled: '&b【AuthMe】&6已關閉註冊功能' reg_disabled: '&b【AuthMe】&6已關閉註冊功能'
password_error_nick: '&b【AuthMe】&6你不可以用你的 ID ( 名稱 ) 來當作密碼 !' password_error_nick: '&b【AuthMe】&6你不可以用你的 ID ( 名稱 ) 來當作密碼 !'
password_error_unsafe: '&b【AuthMe】&6你不可以使用這個不安全的密碼' password_error_unsafe: '&b【AuthMe】&6你不可以使用這個不安全的密碼'
valid_session: '&b【AuthMe】&6你已經成功登入!' valid_session: '&b【AuthMe】&6你已經成功登入!'
login: '&b【AuthMe】&6密碼正確你已成功登入!' login: '&b【AuthMe】&6密碼正確你已成功登入!'
vb_nonActiv: '&b【AuthMe】&6你的帳號還沒有經過驗證! 檢查看看你的電子信箱 (Email) 吧!' vb_nonActiv: '&b【AuthMe】&6你的帳號還沒有經過驗證! 檢查看看你的電子信箱 (Email) 吧!'
user_regged: '&b【AuthMe】&6這個帳號已經被註冊過了!' user_regged: '&b【AuthMe】&6這個帳號已經被註冊過了!'
usage_reg: '&b【AuthMe】&6用法: &c"/register <密碼> <確認密碼>"' usage_reg: '&b【AuthMe】&6用法: &c"/register <密碼> <確認密碼>"'
max_reg: '&b【AuthMe】&6你的 IP 位置所註冊的帳號數量已經達到最大。' max_reg: '&b【AuthMe】&6你的 IP 位置所註冊的帳號數量已經達到最大。'
no_perm: '&b【AuthMe】&6你沒有使用該指令的權限。' no_perm: '&b【AuthMe】&6你沒有使用該指令的權限。'
error: '&b【AuthMe】&6發生錯誤請聯繫管理員' error: '&b【AuthMe】&6發生錯誤請聯繫管理員'
login_msg: '&b【AuthMe】&6請使用 &c"/login <密碼>" &6來登入。' login_msg: '&b【AuthMe】&6請使用 &c"/login <密碼>" &6來登入。'
reg_msg: '&b【AuthMe】&6請使用 "&c/register <密碼> <確認密碼>" 來註冊。' reg_msg: '&b【AuthMe】&6請使用 "&c/register <密碼> <確認密碼>" 來註冊。'
reg_email_msg: '&b【AuthMe】&6請使用 &c"/register <email> <重複Email>" 來註冊' reg_email_msg: '&b【AuthMe】&6請使用 &c"/register <email> <重複Email>" 來註冊'
usage_unreg: '&b【AuthMe】&6用法: &c"/unregister <密碼>"' usage_unreg: '&b【AuthMe】&6用法: &c"/unregister <密碼>"'
pwd_changed: '&b【AuthMe】&6密碼變更成功!' pwd_changed: '&b【AuthMe】&6密碼變更成功!'
user_unknown: '&b【AuthMe】&6這個帳號還沒有註冊過' user_unknown: '&b【AuthMe】&6這個帳號還沒有註冊過'
password_error: '&b【AuthMe】&6兩次輸入的密碼不一致!' password_error: '&b【AuthMe】&6兩次輸入的密碼不一致!'
invalid_session: '&b【AuthMe】&6憑證日期不相符!' invalid_session: '&b【AuthMe】&6憑證日期不相符!'
reg_only: '&b【AuthMe】&6請到下列網站 :「 http://example.com 」 進行註冊' reg_only: '&b【AuthMe】&6請到下列網站 :「 http://example.com 」 進行註冊'
logged_in: '&b【AuthMe】&6你已經登入了!' logged_in: '&b【AuthMe】&6你已經登入了!'
logout: '&b【AuthMe】&6你已成功登出' logout: '&b【AuthMe】&6你已成功登出'
same_nick: '&b【AuthMe】&6有同樣帳號的玩家在線上!' same_nick: '&b【AuthMe】&6有同樣帳號的玩家在線上!'
registered: '&b【AuthMe】&6你已成功註冊' registered: '&b【AuthMe】&6你已成功註冊'
pass_len: '&b【AuthMe】&6你的密碼 超過最大字數 / 小於最小字數' pass_len: '&b【AuthMe】&6你的密碼 超過最大字數 / 小於最小字數'
reload: '&b【AuthMe】&6已重新讀取設定檔及資料庫' reload: '&b【AuthMe】&6已重新讀取設定檔及資料庫'
timeout: '&b【AuthMe】&6超過登入時間請稍後再試一次' timeout: '&b【AuthMe】&6超過登入時間請稍後再試一次'
usage_changepassword: '&b【AuthMe】&6用法: &c"/changepassword <舊密碼> <新密碼>"' usage_changepassword: '&b【AuthMe】&6用法: &c"/changepassword <舊密碼> <新密碼>"'
name_len: '&b【AuthMe】&6你的暱稱 太長 / 太短 了!' name_len: '&b【AuthMe】&6你的暱稱 太長 / 太短 了!'
regex: '&b【AuthMe】&6暱稱裡包含不能使用的字符' regex: '&b【AuthMe】&6暱稱裡包含不能使用的字符'
add_email: '&b【AuthMe】&6請使用 &c"/email add <你的Email> <再次輸入你的Email>" &6來添加 Email' add_email: '&b【AuthMe】&6請使用 &c"/email add <你的Email> <再次輸入你的Email>" &6來添加 Email'
bad_database_email: '&b【AuthMe】&6此指令只適用於有使用MySQL和SQLite的伺服器。' recovery_email: '&b【AuthMe】&6忘記密碼了嗎? 使用 &c"/email recovery <你的Email>"'
recovery_email: '&b【AuthMe】&6忘記密碼了嗎? 使用 &c"/email recovery <你的Email>"' usage_captcha: '&b【AuthMe】&6請用 &c"/captcha <theCaptcha>" &6來輸入你的驗證碼'
usage_captcha: '&b【AuthMe】&6請用 &c"/captcha <theCaptcha>" &6來輸入你的驗證碼' wrong_captcha: '&b【AuthMe】&6錯誤的驗證碼'
wrong_captcha: '&b【AuthMe】&6錯誤的驗證碼' valid_captcha: '&b【AuthMe】&6驗證碼無效!'
valid_captcha: '&b【AuthMe】&6驗證碼無效!' kick_forvip: '&b【AuthMe】&6你已經被請出。&c原因 : 有 VIP 玩家登入伺服器'
kick_forvip: '&b【AuthMe】&6你已經被請出。&c原因 : 有 VIP 玩家登入伺服器' kick_fullserver: '&b【AuthMe】&6伺服器已經滿了請等等再試一次'
kick_fullserver: '&b【AuthMe】&6伺服器已經滿了請等等再試一次' usage_email_add: '&b【AuthMe】&6用法: &c"/email add <你的Email> <重複Email>"'
usage_email_add: '&b【AuthMe】&6用法: &c"/email add <你的Email> <重複Email>"' usage_email_change: '&b【AuthMe】&6用法: &c"/email change <舊的Email> <新的Email>"'
usage_email_change: '&b【AuthMe】&6用法: &c"/email change <舊的Email> <新的Email>"' usage_email_recovery: '&b【AuthMe】&6用法: &c"/email recovery <你的Email>"'
usage_email_recovery: '&b【AuthMe】&6用法: &c"/email recovery <你的Email>"' new_email_invalid: '&b【AuthMe】&6新的Email無效!'
new_email_invalid: '&b【AuthMe】&6新的Email無效!' old_email_invalid: '&b【AuthMe】&6舊的Email無效!'
old_email_invalid: '&b【AuthMe】&6舊的Email無效!' email_invalid: '&b【AuthMe】&6無效的Email!'
email_invalid: '&b【AuthMe】&6無效的Email!' email_added: '&b【AuthMe】&6已添加Email!'
email_added: '&b【AuthMe】&6已添加Email!' email_confirm: '&b【AuthMe】&6請驗證你的Email!'
email_confirm: '&b【AuthMe】&6請驗證你的Email!' email_changed: '&b【AuthMe】&6Email已變更!'
email_changed: '&b【AuthMe】&6Email已變更!' email_send: '&b【AuthMe】&6已經送出重設密碼要求至你的Email , 請查收。'
email_send: '&b【AuthMe】&6已經送出重設密碼要求至你的Email , 請查收。' email_exists: '&b【AuthMe】&6這個帳戶已經有設定電子郵件了'
email_exists: '&b【AuthMe】&6這個帳戶已經有設定電子郵件了' country_banned: '&b【AuthMe】&6你所在的地區無法進入此伺服器'
country_banned: '&b【AuthMe】&6你所在的地區無法進入此伺服器' antibot_auto_enabled: '&b【AuthMe】&6AntiBotMod已自動啟用!'
antibot_auto_enabled: '&b【AuthMe】&6AntiBotMod已自動啟用!'
antibot_auto_disabled: '&b【AuthMe】&6AntiBotMod將會於 &c%m &6分鐘後自動關閉' antibot_auto_disabled: '&b【AuthMe】&6AntiBotMod將會於 &c%m &6分鐘後自動關閉'

View File

@ -1,61 +0,0 @@
# Translator: uSoc_lifehome (http://lifeho.me) #
# Translator: WaterXCubic 水方塊 #
# -------------------------------------------- #
unknown_user: '&8[&6用戶系統&8] &f用戶資料並不存在於資料庫中。'
unsafe_spawn: '&8[&6用戶系統&8] &f你的登出位置不安全現在將傳送你到重生點。'
not_logged_in: '&8[&6用戶系統&8] &c你還沒有登入 '
reg_voluntarily: '&8[&6用戶系統&8] &f你可以使用這個的指令來註冊 《 /register <密碼> <重覆密碼> 》'
usage_log: '&8[&6用戶系統&8] &c用法 《 /login <密碼> 》'
wrong_pwd: '&8[&6用戶系統&8] &c你輸入了錯誤的密碼。'
unregistered: '&8[&6用戶系統&8] &c你已成功取消會員註冊記錄。'
reg_disabled: '&8[&6用戶系統&8] &c本伺服器已停止新玩家註冊。'
valid_session: '&8[&6用戶系統&8] &b嗨 我記得你,歡迎回來~'
login: '&8[&6用戶系統&8] &c你成功的登入了。'
password_error_nick: '&f你不可以使用你的名字為密碼!'
password_error_unsafe: '&f你不可以使用不安全的密碼'
vb_nonActiv: '&8[&6用戶系統&8] &f你的帳戶還沒有經過電郵驗證 '
user_regged: '&8[&6用戶系統&8] &c此用戶名已經註冊過了。'
usage_reg: '&8[&6用戶系統&8] &c用法 《 /register <密碼> <重覆密碼> 》'
max_reg: '&8[&6用戶系統&8] &f你的IP地址已達到註冊數上限。'
no_perm: '&8[&6用戶系統&8] &b你可以到 CraftingHK 玩家百科中查看說明文件。'
error: '&8[&6用戶系統&8] &f發生錯誤請與管理員聯絡。'
login_msg: '&8[&6用戶系統&8] &c請使用這個指令來登入 《 /login <密碼> 》'
reg_msg: '&8[&6用戶系統&8] &c請使用這個的指令來註冊 《 /register <密碼> <重覆密碼> 》'
reg_email_msg: '&8[&6用戶系統&8] &c請使用這個的指令來註冊 《 /register <電郵> <重覆電郵> 》'
usage_unreg: '&8[&6用戶系統&8] &c用法 《 /unregister <密碼> 》'
pwd_changed: '&8[&6用戶系統&8] &c你成功的更換了你的密碼 '
user_unknown: '&8[&6用戶系統&8] &c此用戶名沒有已登記資料。'
password_error: '&8[&6用戶系統&8] &f密碼不符合。'
invalid_session: '&8[&6用戶系統&8] &f登入階段資料已損壞請等待登入階段結束。'
reg_only: '&8[&6用戶系統&8] &f限已註冊會員請先到 https://www.example.com/ 註冊。'
logged_in: '&8[&6用戶系統&8] &c你已經登入過了。'
logout: '&8[&6用戶系統&8] &b你成功的登出了。'
same_nick: '&8[&6用戶系統&8] &f同名玩家已在遊玩。'
registered: '&8[&6用戶系統&8] &b你成功的註冊了。'
pass_len: '&8[&6用戶系統&8] &f你的密碼並不符合規定長度。'
reload: '&8[&6用戶系統&8] &b登入系統設定及資料庫重新載入完畢。'
timeout: '&8[&6用戶系統&8] &f登入逾時。'
usage_changepassword: '&8[&6用戶系統&8] &f用法 《 /changepassword <舊密碼> <新密碼> 》'
name_len: '&8[&6用戶系統&8] &c你的用戶名不符合規定長度。'
regex: '&8[&6用戶系統&8] &c你的用戶名含有不容許之字符。以下為准許之字母 REG_EX'
add_email: '&8[&6用戶系統&8] &b請為你的帳戶立即添加電郵地址 《 /email add <電郵地址> <重覆電郵地址> 》'
bad_database_email: '&8[&6用戶系統&8] 此指令只適用於使用MySQL或SQLite之伺服器。'
recovery_email: '&8[&6用戶系統&8] &c忘記密碼 請使用這個的指令來更新密碼: 《 /email recovery <電郵地址> 》'
usage_captcha: '&8[&6用戶系統&8] &c用法 《 /captcha <theCaptcha> 》'
wrong_captcha: '&8[&6用戶系統&8] &c你輸入了錯誤的驗證碼請使用 《 /captcha <驗證碼> 》 再次輸入。'
valid_captcha: '&8[&6用戶系統&8] &c你所輸入的驗證碼是無效的 '
kick_forvip: '&c因為有VIP玩家登入了伺服器。'
kick_fullserver: '&c抱歉 因為伺服器滿人了,所以你目前未能登入伺服器。'
usage_email_add: '&8[&6用戶系統&8] &f用法 《 /email add <電郵> <重覆電郵> 》'
usage_email_change: '&8[&6用戶系統&8] &f用法 《 /email change <舊電郵> <新電郵> 》'
usage_email_recovery: '&8[&6用戶系統&8] &f用法 《 /email recovery <電郵> 》'
new_email_invalid: '&8[&6用戶系統&8] 你所填寫的新電郵地址並不正確。'
old_email_invalid: '&8[&6用戶系統&8] 你所填寫的舊電郵地址並不正確。'
email_invalid: '&8[&6用戶系統&8] 你所填寫的電郵地址並不正確。'
email_added: '&8[&6用戶系統&8] 已加入你的電郵地址記錄。'
email_confirm: '&8[&6用戶系統&8] 請重覆輸入你的電郵地址。'
email_changed: '&8[&6用戶系統&8] 你的電郵地址記錄已更改。'
email_send: '&8[&6用戶系統&8] 忘記密碼信件已寄出,請查收。'
country_banned: '&8[&6用戶系統&8] 本伺服器已停止對你的國家提供遊戲服務。'
antibot_auto_enabled: '&8[&6用戶系統&8] 防止機械人程序已因應現時大量不尋常的連線而啟用。'
antibot_auto_disabled: '&8[&6用戶系統&8] 防止機械人程序檢查到不正常連接數已減少,並於 %m 分鐘後停止運作。'

View File

@ -4,7 +4,7 @@ website: http://dev.bukkit.org/bukkit-plugins/authme-reloaded/
description: AuthMe prevents people, which aren't logged in, from doing stuff like placing blocks, moving, typing commands or seeing the inventory of the player. description: AuthMe prevents people, which aren't logged in, from doing stuff like placing blocks, moving, typing commands or seeing the inventory of the player.
main: fr.xephi.authme.AuthMe main: fr.xephi.authme.AuthMe
version: ${project.version} version: ${project.version}
softdepend: [Vault, ChestShop, Multiverse-Core, Citizens, CombatTag, Essentials, EssentialsSpawn] softdepend: [Vault, ChestShop, Multiverse-Core, Citizens, CombatTag, Essentials, EssentialsSpawn, PerWorldInventories]
commands: commands:
register: register:
description: Register an account description: Register an account

View File

@ -1,12 +1,19 @@
AuthMe-Team: AuthMe-Team:
Active staff:
Xephi (Xephi59) - Leader, Main developer Xephi (Xephi59) - Leader, Main developer
darkwarriors (d4rkwarriors) - Old AuthMe Reloaded Author
Kloudy - Developer (Inactive, Will be avariable soon)
Gabriele C. (sgdc3) - Ticket Manager, Project Page and Structure Manager, Contributor Gabriele C. (sgdc3) - Ticket Manager, Project Page and Structure Manager, Contributor
Maxetto - Ticket Manager, Italian Translator, Basic Developer, Contributor DNx5 - Developer
CryLegend - Contributor, AuthMeBridge Developer (Need activation)
External Contributors:
Gnat008 - Contributor Gnat008 - Contributor
Trojaner25 - Ticket manager, Basic Developer (Need activation)
Inactive staff:
Maxetto - Ticket Manager, Italian Translator, Basic Developer, Contributor (Inactive)
darkwarriors (d4rkwarriors) - Original AuthMeReloaded Author (Inactive)
Translators:
irobin591 - DE Translator irobin591 - DE Translator
WaterCXubic - ZHHK Translator WaterCXubic - ZHHK Translator
Bodyash - Russian/Ukrainian translator Bodyash - Russian/Ukrainian translator