Code Refactor - Whitespace Refactor

This commit is contained in:
Xephi 2014-08-08 23:14:56 +02:00
parent ec7ac60340
commit afc1ea9111
114 changed files with 8277 additions and 7103 deletions

File diff suppressed because it is too large Load Diff

View File

@ -4,27 +4,35 @@ import java.util.logging.Filter;
import java.util.logging.LogRecord;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class ConsoleFilter implements Filter {
public ConsoleFilter() {}
public ConsoleFilter() {
}
@Override
public boolean isLoggable(LogRecord record) {
try {
if (record == null || record.getMessage() == null) return true;
try {
if (record == null || record.getMessage() == null) return true;
String logM = record.getMessage().toLowerCase();
if (!logM.contains("issued server command:")) return true;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return true;
if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return true;
String playername = record.getMessage().split(" ")[0];
record.setMessage(playername + " issued an AuthMe command!");
return true;
} catch (NullPointerException npe) {
return true;
}
} catch (NullPointerException npe) {
return true;
}
}
}

View File

@ -12,53 +12,63 @@ import org.bukkit.Bukkit;
import fr.xephi.authme.settings.Settings;
public class ConsoleLogger {
private static final Logger log = Logger.getLogger("AuthMe");
public static void info(String message) {
if (AuthMe.getInstance().isEnabled()) {
log.info("[AuthMe] " + message);
if (Settings.useLogging) {
Calendar date = Calendar.getInstance();
final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] " + message;
Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
@Override
public void run() {
writeLog(actually);
}
});
}
}
if (AuthMe.getInstance().isEnabled()) {
log.info("[AuthMe] " + message);
if (Settings.useLogging) {
Calendar date = Calendar.getInstance();
final String actually = "["
+ DateFormat.getDateInstance().format(date.getTime())
+ ", " + date.get(Calendar.HOUR_OF_DAY) + ":"
+ date.get(Calendar.MINUTE) + ":"
+ date.get(Calendar.SECOND) + "] " + message;
Bukkit.getScheduler().runTaskAsynchronously(
AuthMe.getInstance(), new Runnable() {
@Override
public void run() {
writeLog(actually);
}
});
}
}
}
public static void showError(String message) {
if (AuthMe.getInstance().isEnabled()) {
if (AuthMe.getInstance().isEnabled()) {
log.warning("[AuthMe] ERROR: " + message);
if (Settings.useLogging) {
Calendar date = Calendar.getInstance();
final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] ERROR : " + message;
Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
@Override
public void run() {
writeLog(actually);
}
});
final String actually = "["
+ DateFormat.getDateInstance().format(date.getTime())
+ ", " + date.get(Calendar.HOUR_OF_DAY) + ":"
+ date.get(Calendar.MINUTE) + ":"
+ date.get(Calendar.SECOND) + "] ERROR : " + message;
Bukkit.getScheduler().runTaskAsynchronously(
AuthMe.getInstance(), new Runnable() {
@Override
public void run() {
writeLog(actually);
}
});
}
}
}
}
public static void writeLog(String string) {
public static void writeLog(String string) {
try {
FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder() + File.separator + "authme.log", true);
BufferedWriter w = new BufferedWriter(fw);
w.write(string);
w.newLine();
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder()
+ File.separator + "authme.log", true);
BufferedWriter w = new BufferedWriter(fw);
w.write(string);
w.newLine();
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -19,12 +19,15 @@ public class DataManager extends Thread {
this.database = database;
}
public void run() {}
public void run() {
}
public OfflinePlayer getOfflinePlayer(String name) {
OfflinePlayer result = null;
try {
if (org.bukkit.Bukkit.class.getMethod("getOfflinePlayer", new Class[]{String.class}).isAnnotationPresent(Deprecated.class)) {
if (org.bukkit.Bukkit.class.getMethod("getOfflinePlayer",
new Class[] { String.class }).isAnnotationPresent(
Deprecated.class)) {
for (OfflinePlayer op : Bukkit.getOfflinePlayers())
if (op.getName().equalsIgnoreCase(name)) {
result = op;
@ -38,20 +41,23 @@ public class DataManager extends Thread {
}
return result;
}
public void purgeAntiXray(List<String> cleared) {
int i = 0;
for (String name : cleared) {
org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) continue;
String playerName = player.getName();
File playerFile = new File("." + File.separator + "plugins" + File.separator + "AntiXRayData" + File.separator + "PlayerData" + File.separator + playerName);
File playerFile = new File("." + File.separator + "plugins"
+ File.separator + "AntiXRayData" + File.separator
+ "PlayerData" + File.separator + playerName);
if (playerFile.exists()) {
playerFile.delete();
i++;
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " AntiXRayData Files");
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i
+ " AntiXRayData Files");
}
public void purgeLimitedCreative(List<String> cleared) {
@ -60,23 +66,32 @@ public class DataManager extends Thread {
org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) continue;
String playerName = player.getName();
File playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + ".yml");
File playerFile = new File("." + File.separator + "plugins"
+ File.separator + "LimitedCreative" + File.separator
+ "inventories" + File.separator + playerName + ".yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_creative.yml");
playerFile = new File("." + File.separator + "plugins"
+ File.separator + "LimitedCreative" + File.separator
+ "inventories" + File.separator + playerName
+ "_creative.yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_adventure.yml");
playerFile = new File("." + File.separator + "plugins"
+ File.separator + "LimitedCreative" + File.separator
+ "inventories" + File.separator + playerName
+ "_adventure.yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " LimitedCreative Survival, Creative and Adventure files");
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i
+ " LimitedCreative Survival, Creative and Adventure files");
}
public void purgeDat(List<String> cleared) {
@ -85,7 +100,9 @@ public class DataManager extends Thread {
org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) continue;
String playerName = player.getName();
File playerFile = new File (plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + playerName + ".dat");
File playerFile = new File(plugin.getServer().getWorldContainer()
+ File.separator + Settings.defaultWorld + File.separator
+ "players" + File.separator + playerName + ".dat");
if (playerFile.exists()) {
playerFile.delete();
i++;
@ -97,12 +114,15 @@ public class DataManager extends Thread {
public void purgeEssentials(List<String> cleared) {
int i = 0;
for (String name : cleared) {
File playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml");
File playerFile = new File(plugin.ess.getDataFolder()
+ File.separator + "userdata" + File.separator + name
+ ".yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " EssentialsFiles");
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i
+ " EssentialsFiles");
}
}

View File

@ -7,80 +7,110 @@ import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.message.Message;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
public Log4JFilter() {}
public Log4JFilter() {
}
@Override
public Result filter(LogEvent record) {
try {
if (record == null || record.getMessage() == null) return Result.NEUTRAL;
String logM = record.getMessage().getFormattedMessage().toLowerCase();
@Override
public Result filter(LogEvent record) {
try {
if (record == null || record.getMessage() == null) return Result.NEUTRAL;
String logM = record.getMessage().getFormattedMessage()
.toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, String message,
Object... arg4) {
try {
if (message == null) return Result.NEUTRAL;
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, String message,
Object... arg4) {
try {
if (message == null) return Result.NEUTRAL;
String logM = message.toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, Object message,
Throwable arg4) {
try {
if (message == null) return Result.NEUTRAL;
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, Object message,
Throwable arg4) {
try {
if (message == null) return Result.NEUTRAL;
String logM = message.toString().toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, Message message,
Throwable arg4) {
try {
if (message == null) return Result.NEUTRAL;
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, Message message,
Throwable arg4) {
try {
if (message == null) return Result.NEUTRAL;
String logM = message.getFormattedMessage().toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result getOnMatch() {
return Result.NEUTRAL;
}
@Override
public Result getOnMatch() {
return Result.NEUTRAL;
}
@Override
public Result getOnMismatch() {
return Result.NEUTRAL;
}
@Override
public Result getOnMismatch() {
return Result.NEUTRAL;
}
}
}

View File

@ -17,127 +17,137 @@ import fr.xephi.authme.settings.Settings;
*/
public class PerformBackup {
private String dbName = Settings.getMySQLDatabase;
private String dbUserName = Settings.getMySQLUsername;
private String dbPassword = Settings.getMySQLPassword;
private String tblname = Settings.getMySQLTablename;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
String dateString = format.format( new Date() );
private String path = AuthMe.getInstance().getDataFolder()+"/backups/backup"+dateString;
private AuthMe instance;
private String dbName = Settings.getMySQLDatabase;
private String dbUserName = Settings.getMySQLUsername;
private String dbPassword = Settings.getMySQLPassword;
private String tblname = Settings.getMySQLTablename;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
String dateString = format.format(new Date());
private String path = AuthMe.getInstance().getDataFolder()
+ "/backups/backup" + dateString;
private AuthMe instance;
public PerformBackup(AuthMe instance) {
this.setInstance(instance);
}
public PerformBackup(AuthMe instance) {
this.setInstance(instance);
}
public boolean DoBackup() {
public boolean DoBackup() {
switch(Settings.getDataSource) {
case FILE: return FileBackup("auths.db");
switch (Settings.getDataSource) {
case FILE:
return FileBackup("auths.db");
case MYSQL: return MySqlBackup();
case MYSQL:
return MySqlBackup();
case SQLITE: return FileBackup(Settings.getMySQLDatabase+".db");
case SQLITE:
return FileBackup(Settings.getMySQLDatabase + ".db");
}
return false;
}
private boolean MySqlBackup() {
File dirBackup = new File(AuthMe.getInstance().getDataFolder()+"/backups");
if(!dirBackup.exists())
dirBackup.mkdir();
if(checkWindows(Settings.backupWindowsPath)) {
String executeCmd = Settings.backupWindowsPath+"\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path+".sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
ConsoleLogger.info("Backup created successfully");
return true;
} else {
ConsoleLogger.info("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path+".sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
ConsoleLogger.info("Backup created successfully");
return true;
} else {
ConsoleLogger.info("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return false;
}
private boolean FileBackup(String backend) {
File dirBackup = new File(AuthMe.getInstance().getDataFolder()+"/backups");
private boolean MySqlBackup() {
File dirBackup = new File(AuthMe.getInstance().getDataFolder()
+ "/backups");
if(!dirBackup.exists())
dirBackup.mkdir();
try {
copy(new File("plugins/AuthMe/"+backend),new File(path+".db"));
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
/*
* Check if we are under Windows and correct location
* of mysqldump.exe otherwise return error.
*/
private boolean checkWindows(String windowsPath) {
String isWin = System.getProperty("os.name").toLowerCase();
if(isWin.indexOf("win") >= 0) {
if(new File(windowsPath+"\\bin\\mysqldump.exe").exists()) {
return true;
} else {
ConsoleLogger.showError("Mysql Windows Path is incorrect please check it");
return true;
}
} else return false;
}
/*
* Copyr src bytefile into dst file
*/
void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
if (!dirBackup.exists()) dirBackup.mkdir();
if (checkWindows(Settings.backupWindowsPath)) {
String executeCmd = Settings.backupWindowsPath
+ "\\bin\\mysqldump.exe -u " + dbUserName + " -p"
+ dbPassword + " " + dbName + " --tables " + tblname
+ " -r " + path + ".sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
ConsoleLogger.info("Backup created successfully");
return true;
} else {
ConsoleLogger.info("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
String executeCmd = "mysqldump -u " + dbUserName + " -p"
+ dbPassword + " " + dbName + " --tables " + tblname
+ " -r " + path + ".sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
ConsoleLogger.info("Backup created successfully");
return true;
} else {
ConsoleLogger.info("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return false;
}
public void setInstance(AuthMe instance) {
this.instance = instance;
}
private boolean FileBackup(String backend) {
File dirBackup = new File(AuthMe.getInstance().getDataFolder()
+ "/backups");
public AuthMe getInstance() {
return instance;
}
if (!dirBackup.exists()) dirBackup.mkdir();
try {
copy(new File("plugins/AuthMe/" + backend), new File(path + ".db"));
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
/*
* Check if we are under Windows and correct location of mysqldump.exe
* otherwise return error.
*/
private boolean checkWindows(String windowsPath) {
String isWin = System.getProperty("os.name").toLowerCase();
if (isWin.indexOf("win") >= 0) {
if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) {
return true;
} else {
ConsoleLogger
.showError("Mysql Windows Path is incorrect please check it");
return true;
}
} else return false;
}
/*
* Copyr src bytefile into dst file
*/
void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public void setInstance(AuthMe instance) {
this.instance = instance;
}
public AuthMe getInstance() {
return instance;
}
}

View File

@ -17,73 +17,79 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class SendMailSSL {
public AuthMe plugin;
public AuthMe plugin;
public SendMailSSL(AuthMe plugin) {
this.plugin = plugin;
}
public SendMailSSL(AuthMe plugin) {
this.plugin = plugin;
}
public void main(final PlayerAuth auth, final String newPass) {
String sendername;
public void main(final PlayerAuth auth, final String newPass) {
String sendername;
if (Settings.getmailSenderName.isEmpty() || Settings.getmailSenderName == null) {
sendername = Settings.getmailAccount;
} else {
sendername = Settings.getmailSenderName;
}
if (Settings.getmailSenderName.isEmpty()
|| Settings.getmailSenderName == null) {
sendername = Settings.getmailAccount;
} else {
sendername = Settings.getmailSenderName;
}
Properties props = new Properties();
props.put("mail.smtp.host", Settings.getmailSMTP);
props.put("mail.smtp.socketFactory.port", String.valueOf(Settings.getMailPort));
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", String.valueOf(Settings.getMailPort));
Properties props = new Properties();
props.put("mail.smtp.host", Settings.getmailSMTP);
props.put("mail.smtp.socketFactory.port",
String.valueOf(Settings.getMailPort));
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", String.valueOf(Settings.getMailPort));
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Settings.getmailAccount,Settings.getmailPassword);
}
});
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
Settings.getmailAccount,
Settings.getmailPassword);
}
});
try {
try {
final Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(Settings.getmailAccount, sendername));
} catch (UnsupportedEncodingException uee) {
message.setFrom(new InternetAddress(Settings.getmailAccount));
}
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(auth.getEmail()));
message.setSubject(Settings.getMailSubject);
message.setSentDate(new Date());
String text = Settings.getMailText;
text = text.replace("<playername>", auth.getNickname());
text = text.replace("<servername>", plugin.getServer().getServerName());
text = text.replace("<generatedpass>", newPass);
message.setContent(text, "text/html");
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
});
if(!Settings.noConsoleSpam)
ConsoleLogger.info("Email sent to : " + auth.getNickname());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
final Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(Settings.getmailAccount,
sendername));
} catch (UnsupportedEncodingException uee) {
message.setFrom(new InternetAddress(Settings.getmailAccount));
}
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(auth.getEmail()));
message.setSubject(Settings.getMailSubject);
message.setSentDate(new Date());
String text = Settings.getMailText;
text = text.replace("<playername>", auth.getNickname());
text = text.replace("<servername>", plugin.getServer()
.getServerName());
text = text.replace("<generatedpass>", newPass);
message.setContent(text, "text/html");
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
});
if (!Settings.noConsoleSpam) ConsoleLogger.info("Email sent to : "
+ auth.getNickname());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -25,157 +25,164 @@ public class Utils {
public AuthMe plugin;
public Utils(AuthMe plugin) {
this.plugin = plugin;
this.plugin = plugin;
}
public void setGroup(Player player, groupType group) {
setGroup(player.getName(), group);
}
public void setGroup(String player, groupType group) {
if(!Settings.isPermissionCheckEnabled)
return;
if(plugin.permission == null)
return;
try {
World world = null;
currentGroup = plugin.permission.getPrimaryGroup(world, player);
} catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
plugin.permission = null;
return;
}
World world = null;
String name = player;
switch(group) {
case UNREGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.unRegisteredGroup);
break;
}
case REGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.getRegisteredGroup);
break;
}
case NOTLOGGEDIN: {
if(!useGroupSystem()) break;
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.getUnloggedinGroup);
break;
}
case LOGGEDIN: {
if(!useGroupSystem()) break;
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name.toLowerCase());
if (limbo == null) break;
String realGroup = limbo.getGroup();
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, realGroup);
break;
}
}
return;
}
public boolean addNormal(Player player, String group) {
if(!useGroupSystem()){
return false;
}
if(plugin.permission == null) return false;
World world = null;
try {
if(plugin.permission.playerRemoveGroup(world,player.getName().toString(),Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(world,player.getName().toString(),group)) {
return true;
}
} catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
plugin.permission = null;
return false;
}
return false;
}
public void hasPermOnJoin(Player player) {
if (plugin.permission == null) return;
Iterator<String> iter = Settings.getJoinPermissions.iterator();
while (iter.hasNext()) {
String permission = iter.next();
if(plugin.permission.playerHas(player, permission)){
plugin.permission.playerAddTransient(player, permission);
}
}
}
public boolean isUnrestricted(Player player) {
if(!Settings.isAllowRestrictedIp)
return false;
if(Settings.getUnrestrictedName.isEmpty() || Settings.getUnrestrictedName == null)
return false;
if(Settings.getUnrestrictedName.contains(player.getName()))
return true;
return false;
setGroup(player.getName(), group);
}
public static Utils getInstance() {
singleton = new Utils(AuthMe.getInstance());
return singleton;
public void setGroup(String player, groupType group) {
if (!Settings.isPermissionCheckEnabled) return;
if (plugin.permission == null) return;
try {
World world = null;
currentGroup = plugin.permission.getPrimaryGroup(world, player);
} catch (UnsupportedOperationException e) {
ConsoleLogger
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null;
return;
}
World world = null;
String name = player;
switch (group) {
case UNREGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name,
Settings.unRegisteredGroup);
break;
}
case REGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name,
Settings.getRegisteredGroup);
break;
}
case NOTLOGGEDIN: {
if (!useGroupSystem()) break;
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name,
Settings.getUnloggedinGroup);
break;
}
case LOGGEDIN: {
if (!useGroupSystem()) break;
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(
name.toLowerCase());
if (limbo == null) break;
String realGroup = limbo.getGroup();
plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, realGroup);
break;
}
}
return;
}
private boolean useGroupSystem() {
if(Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty())
return true;
public boolean addNormal(Player player, String group) {
if (!useGroupSystem()) {
return false;
}
if (plugin.permission == null) return false;
World world = null;
try {
if (plugin.permission.playerRemoveGroup(world, player.getName()
.toString(), Settings.getUnloggedinGroup)
&& plugin.permission.playerAddGroup(world, player.getName()
.toString(), group)) {
return true;
}
} catch (UnsupportedOperationException e) {
ConsoleLogger
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null;
return false;
}
return false;
}
public void packCoords(double x, double y, double z, String w, final Player pl)
{
World theWorld;
if (w.equals("unavailableworld")) {
theWorld = pl.getWorld();
} else {
theWorld = Bukkit.getWorld(w);
}
if (theWorld == null)
theWorld = pl.getWorld();
final World world = theWorld;
final Location locat = new Location(world, x, y, z);
public void hasPermOnJoin(Player player) {
if (plugin.permission == null) return;
Iterator<String> iter = Settings.getJoinPermissions.iterator();
while (iter.hasNext()) {
String permission = iter.next();
if (plugin.permission.playerHas(player, permission)) {
plugin.permission.playerAddTransient(player, permission);
}
}
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if(!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getChunk().isLoaded())
tpEvent.getTo().getChunk().load();
pl.teleport(tpEvent.getTo());
}
}
});
}
public boolean isUnrestricted(Player player) {
if (!Settings.isAllowRestrictedIp) return false;
if (Settings.getUnrestrictedName.isEmpty()
|| Settings.getUnrestrictedName == null) return false;
if (Settings.getUnrestrictedName.contains(player.getName())) return true;
return false;
}
/*
public static Utils getInstance() {
singleton = new Utils(AuthMe.getInstance());
return singleton;
}
private boolean useGroupSystem() {
if (Settings.isPermissionCheckEnabled
&& !Settings.getUnloggedinGroup.isEmpty()) return true;
return false;
}
public void packCoords(double x, double y, double z, String w,
final Player pl) {
World theWorld;
if (w.equals("unavailableworld")) {
theWorld = pl.getWorld();
} else {
theWorld = Bukkit.getWorld(w);
}
if (theWorld == null) theWorld = pl.getWorld();
final World world = theWorld;
final Location locat = new Location(world, x, y, z);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getChunk().isLoaded()) tpEvent.getTo()
.getChunk().load();
pl.teleport(tpEvent.getTo());
}
}
});
}
/*
* Random Token for passpartu
*
*/
public boolean obtainToken() {
File file = new File("plugins/AuthMe/passpartu.token");
if (file.exists())
file.delete();
File file = new File("plugins/AuthMe/passpartu.token");
if (file.exists()) file.delete();
FileWriter writer = null;
try {
file.createNewFile();
writer = new FileWriter(file);
String token = generateToken();
writer.write(token + ":" + System.currentTimeMillis() / 1000 + API.newline);
writer.flush();
ConsoleLogger.info("[AuthMe] Security passpartu token: "+ token);
writer.close();
return true;
} catch(Exception e) {
e.printStackTrace();
}
FileWriter writer = null;
try {
file.createNewFile();
writer = new FileWriter(file);
String token = generateToken();
writer.write(token + ":" + System.currentTimeMillis() / 1000
+ API.newline);
writer.flush();
ConsoleLogger.info("[AuthMe] Security passpartu token: " + token);
writer.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@ -185,52 +192,53 @@ public class Utils {
public boolean readToken(String inputToken) {
File file = new File("plugins/AuthMe/passpartu.token");
if (!file.exists())
return false;
if (!file.exists()) return false;
if (inputToken.isEmpty())
return false;
Scanner reader = null;
try {
reader = new Scanner(file);
while (reader.hasNextLine()) {
final String line = reader.nextLine();
if (line.contains(":")) {
String[] tokenInfo = line.split(":");
if(tokenInfo[0].equals(inputToken) && System.currentTimeMillis()/1000-30 <= Integer.parseInt(tokenInfo[1]) ) {
file.delete();
reader.close();
return true;
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
reader.close();
return false;
if (inputToken.isEmpty()) return false;
Scanner reader = null;
try {
reader = new Scanner(file);
while (reader.hasNextLine()) {
final String line = reader.nextLine();
if (line.contains(":")) {
String[] tokenInfo = line.split(":");
if (tokenInfo[0].equals(inputToken)
&& System.currentTimeMillis() / 1000 - 30 <= Integer
.parseInt(tokenInfo[1])) {
file.delete();
reader.close();
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
reader.close();
return false;
}
/*
* Generate Random Token
*/
private String generateToken() {
// obtain new random token
Random rnd = new Random ();
char[] arr = new char[5];
for (int i=0; i<5; i++) {
int n = rnd.nextInt (36);
arr[i] = (char) (n < 10 ? '0'+n : 'a'+n-10);
}
return new String(arr);
}
// obtain new random token
Random rnd = new Random();
char[] arr = new char[5];
for (int i = 0; i < 5; i++) {
int n = rnd.nextInt(36);
arr[i] = (char) (n < 10 ? '0' + n : 'a' + n - 10);
}
return new String(arr);
}
/*
* Used for force player GameMode
*/
public static void forceGM(Player player) {
if (!AuthMe.getInstance().authmePermissible(player, "authme.bypassforcesurvival"))
player.setGameMode(GameMode.SURVIVAL);
if (!AuthMe.getInstance().authmePermissible(player,
"authme.bypassforcesurvival")) player
.setGameMode(GameMode.SURVIVAL);
}
public enum groupType {

View File

@ -15,31 +15,33 @@ import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
public class API {
public static final String newline = System.getProperty("line.separator");
public static AuthMe instance;
public static DataSource database;
public static final String newline = System.getProperty("line.separator");
public static AuthMe instance;
public static DataSource database;
public API(AuthMe instance, DataSource database) {
API.instance = instance;
API.database = database;
}
/**
* Hook into AuthMe
* @return AuthMe instance
*/
public API(AuthMe instance, DataSource database) {
API.instance = instance;
API.database = database;
}
/**
* Hook into AuthMe
*
* @return AuthMe instance
*/
public static AuthMe hookAuthMe() {
Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
Plugin plugin = Bukkit.getServer().getPluginManager()
.getPlugin("AuthMe");
if (plugin == null || !(plugin instanceof AuthMe)) {
return null;
}
return (AuthMe) plugin;
return null;
}
return (AuthMe) plugin;
}
public AuthMe getPlugin() {
return instance;
return instance;
}
/**
@ -48,7 +50,8 @@ public class API {
* @return true if player is authenticate
*/
public static boolean isAuthenticated(Player player) {
return PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase());
return PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase());
}
/**
@ -58,9 +61,8 @@ public class API {
*/
@Deprecated
public boolean isaNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player, instance))
return true;
return CombatTagComunicator.isNPC(player);
if (instance.getCitizensCommunicator().isNPC(player, instance)) return true;
return CombatTagComunicator.isNPC(player);
}
/**
@ -69,9 +71,8 @@ public class API {
* @return true if player is a npc
*/
public boolean isNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player, instance))
return true;
return CombatTagComunicator.isNPC(player);
if (instance.getCitizensCommunicator().isNPC(player, instance)) return true;
return CombatTagComunicator.isNPC(player);
}
/**
@ -80,31 +81,35 @@ public class API {
* @return true if the player is unrestricted
*/
public static boolean isUnrestricted(Player player) {
return Utils.getInstance().isUnrestricted(player);
return Utils.getInstance().isUnrestricted(player);
}
public static Location getLastLocation(Player player) {
try {
PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
if (auth != null) {
Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY() , auth.getQuitLocZ());
return loc;
} else {
return null;
}
} catch (NullPointerException ex) {
return null;
}
try {
PlayerAuth auth = PlayerCache.getInstance().getAuth(
player.getName().toLowerCase());
if (auth != null) {
Location loc = new Location(Bukkit.getWorld(auth.getWorld()),
auth.getQuitLocX(), auth.getQuitLocY(),
auth.getQuitLocZ());
return loc;
} else {
return null;
}
} catch (NullPointerException ex) {
return null;
}
}
public static void setPlayerInventory(Player player, ItemStack[] content, ItemStack[] armor) {
try {
player.getInventory().setContents(content);
player.getInventory().setArmorContents(armor);
} catch (NullPointerException npe) {
}
public static void setPlayerInventory(Player player, ItemStack[] content,
ItemStack[] armor) {
try {
player.getInventory().setContents(content);
player.getInventory().setArmorContents(armor);
} catch (NullPointerException npe) {
}
}
/**
@ -113,67 +118,78 @@ public class API {
* @return true if player is registered
*/
public static boolean isRegistered(String playerName) {
String player = playerName.toLowerCase();
return database.isAuthAvailable(player);
String player = playerName.toLowerCase();
return database.isAuthAvailable(player);
}
/**
* @param String playerName, String passwordToCheck
* @param String
* playerName, String passwordToCheck
* @return true if the password is correct , false else
*/
public static boolean checkPassword(String playerName, String passwordToCheck) {
if (!isRegistered(playerName)) return false;
String player = playerName.toLowerCase();
PlayerAuth auth = database.getAuth(player);
try {
return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
} catch (NoSuchAlgorithmException e) {
return false;
}
public static boolean checkPassword(String playerName,
String passwordToCheck) {
if (!isRegistered(playerName)) return false;
String player = playerName.toLowerCase();
PlayerAuth auth = database.getAuth(player);
try {
return PasswordSecurity.comparePasswordWithHash(passwordToCheck,
auth.getHash(), playerName);
} catch (NoSuchAlgorithmException e) {
return false;
}
}
/**
* Register a player
* @param String playerName, String password
*
* @param String
* playerName, String password
* @return true if the player is register correctly
*/
public static boolean registerPlayer(String playerName, String password) {
try {
String name = playerName.toLowerCase();
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
String hash = PasswordSecurity.getHash(Settings.getPasswordHash,
password, name);
if (isRegistered(name)) {
return false;
}
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com", getPlayerRealName(name));
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0,
"your@email.com", getPlayerRealName(name));
if (!database.saveAuth(auth)) {
return false;
return false;
}
return true;
} catch (NoSuchAlgorithmException ex) {
return false;
return false;
}
}
/**
* Get Player realName from lowerCase nickname
* @param String playerName
* return String player real name
*
* @param String
* playerName return String player real name
*/
public static String getPlayerRealName(String nickname) {
try {
String realName = instance.dataManager.getOfflinePlayer(nickname).getName();
if (realName != null && !realName.isEmpty())
return realName;
} catch (NullPointerException npe) {}
return nickname;
try {
String realName = instance.dataManager.getOfflinePlayer(nickname)
.getName();
if (realName != null && !realName.isEmpty()) return realName;
} catch (NullPointerException npe) {
}
return nickname;
}
/**
* Force a player to login
* @param Player player
*
* @param Player
* player
*/
public static void forceLogin(Player player) {
instance.management.performLogin(player, "dontneed", true);
instance.management.performLogin(player, "dontneed", true);
}
}

View File

@ -19,7 +19,8 @@ public class PlayerAuth {
private String email = "your@email.com";
private String realName = "";
public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String email, String realName) {
public PlayerAuth(String nickname, String hash, String ip, long lastLogin,
String email, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
@ -29,7 +30,8 @@ public class PlayerAuth {
}
public PlayerAuth(String nickname, double x, double y, double z, String world) {
public PlayerAuth(String nickname, double x, double y, double z,
String world) {
this.nickname = nickname;
this.x = x;
this.y = y;
@ -39,7 +41,9 @@ public class PlayerAuth {
}
public PlayerAuth(String nickname, String hash, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) {
public PlayerAuth(String nickname, String hash, String ip, long lastLogin,
double x, double y, double z, String world, String email,
String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
@ -53,7 +57,9 @@ public class PlayerAuth {
}
public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) {
public PlayerAuth(String nickname, String hash, String salt, int groupId,
String ip, long lastLogin, double x, double y, double z,
String world, String email, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
@ -69,28 +75,32 @@ public class PlayerAuth {
}
public PlayerAuth(String nickname, String hash, String salt, int groupId , String ip, long lastLogin, String realName) {
public PlayerAuth(String nickname, String hash, String salt, int groupId,
String ip, long lastLogin, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.lastLogin = lastLogin;
this.salt = salt;
this.groupId = groupId;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, String realName) {
public PlayerAuth(String nickname, String hash, String salt, String ip,
long lastLogin, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.lastLogin = lastLogin;
this.salt = salt;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) {
public PlayerAuth(String nickname, String hash, String salt, String ip,
long lastLogin, double x, double y, double z, String world,
String email, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
@ -105,23 +115,22 @@ public class PlayerAuth {
}
public PlayerAuth(String nickname, String ip, long lastLogin) {
this.nickname = nickname;
this.ip = ip;
this.lastLogin = lastLogin;
this.nickname = nickname;
this.ip = ip;
this.lastLogin = lastLogin;
}
public PlayerAuth(String nickname, String hash, String ip, long lastLogin) {
this.nickname = nickname;
this.ip = ip;
this.lastLogin = lastLogin;
this.hash = hash;
this.nickname = nickname;
this.ip = ip;
this.lastLogin = lastLogin;
this.hash = hash;
}
public String getIp() {
if (ip == null || ip.isEmpty())
ip = "127.0.0.1";
return ip;
public String getIp() {
if (ip == null || ip.isEmpty()) ip = "127.0.0.1";
return ip;
}
public String getNickname() {
@ -129,17 +138,18 @@ public class PlayerAuth {
}
public String getHash() {
if (Settings.getPasswordHash == HashAlgorithm.MD5VB) {
if(salt != null && !salt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.MD5VB) {
vBhash = "$MD5vb$"+salt+"$"+hash;
if (Settings.getPasswordHash == HashAlgorithm.MD5VB) {
if (salt != null && !salt.isEmpty()
&& Settings.getPasswordHash == HashAlgorithm.MD5VB) {
vBhash = "$MD5vb$" + salt + "$" + hash;
return vBhash;
}
}
}
return hash;
}
public String getSalt() {
return this.salt;
return this.salt;
}
public int getGroupId() {
@ -149,31 +159,37 @@ public class PlayerAuth {
public double getQuitLocX() {
return x;
}
public double getQuitLocY() {
return y;
}
public double getQuitLocZ() {
return z;
}
public String getEmail() {
return email;
return email;
}
public void setQuitLocX(double d) {
this.x = d;
}
public void setQuitLocY(double d) {
this.y = d;
}
public void setQuitLocZ(double d) {
this.z = d;
}
}
public long getLastLogin() {
try {
if (Long.valueOf(lastLogin) == null)
lastLogin = 0L;
} catch (NullPointerException e) {
lastLogin = 0L;
}
try {
if (Long.valueOf(lastLogin) == null) lastLogin = 0L;
} catch (NullPointerException e) {
lastLogin = 0L;
}
return lastLogin;
}
@ -190,11 +206,11 @@ public class PlayerAuth {
}
public void setEmail(String email) {
this.email = email;
this.email = email;
}
public void setSalt(String salt) {
this.salt = salt;
this.salt = salt;
}
@Override
@ -203,34 +219,38 @@ public class PlayerAuth {
return false;
}
PlayerAuth other = (PlayerAuth) obj;
return other.getIp().equals(this.ip) && other.getNickname().equals(this.nickname);
return other.getIp().equals(this.ip)
&& other.getNickname().equals(this.nickname);
}
@Override
public int hashCode() {
int hashCode = 7;
hashCode = 71 * hashCode + (this.nickname != null ? this.nickname.hashCode() : 0);
hashCode = 71 * hashCode
+ (this.nickname != null ? this.nickname.hashCode() : 0);
hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0);
return hashCode;
}
public void setWorld(String world) {
this.world = world;
}
public void setWorld(String world) {
this.world = world;
}
public String getWorld() {
return world;
}
public String getWorld() {
return world;
}
@Override
public String toString() {
String s = "Player : " + nickname + " ! IP : " + ip + " ! LastLogin : " + lastLogin + " ! LastPosition : " + x + "," + y + "," + z + "," + world
+ " ! Email : " + email + " ! Hash : " + hash + " ! Salt : " + salt + " ! RealName : " + realName;
return s;
}
@Override
public String toString() {
String s = "Player : " + nickname + " ! IP : " + ip + " ! LastLogin : "
+ lastLogin + " ! LastPosition : " + x + "," + y + "," + z
+ "," + world + " ! Email : " + email + " ! Hash : " + hash
+ " ! Salt : " + salt + " ! RealName : " + realName;
return s;
public String getRealname() {
return realName;
}
}
public String getRealname() {
return realName;
}
}

View File

@ -40,7 +40,7 @@ public class PlayerCache {
}
public int getLogged() {
return cache.size();
return cache.size();
}
}

View File

@ -4,42 +4,43 @@ import org.bukkit.inventory.ItemStack;
public class DataFileCache {
private ItemStack[] inventory;
private ItemStack[] armor;
private String group;
private boolean operator;
private boolean flying;
private ItemStack[] inventory;
private ItemStack[] armor;
private String group;
private boolean operator;
private boolean flying;
public DataFileCache(ItemStack[] inventory, ItemStack[] armor){
this.inventory = inventory;
this.armor = armor;
}
public DataFileCache(ItemStack[] inventory, ItemStack[] armor) {
this.inventory = inventory;
this.armor = armor;
}
public DataFileCache(ItemStack[] inventory, ItemStack[] armor, String group, boolean operator, boolean flying){
this.inventory = inventory;
this.armor = armor;
this.group = group;
this.operator = operator;
this.flying = flying;
}
public DataFileCache(ItemStack[] inventory, ItemStack[] armor,
String group, boolean operator, boolean flying) {
this.inventory = inventory;
this.armor = armor;
this.group = group;
this.operator = operator;
this.flying = flying;
}
public ItemStack[] getInventory(){
return inventory;
}
public ItemStack[] getInventory() {
return inventory;
}
public ItemStack[] getArmour(){
return armor;
}
public ItemStack[] getArmour() {
return armor;
}
public String getGroup(){
return group;
}
public String getGroup() {
return group;
}
public boolean getOperator(){
return operator;
}
public boolean getOperator() {
return operator;
}
public boolean isFlying(){
return flying;
}
public boolean isFlying() {
return flying;
}
}

View File

@ -18,117 +18,122 @@ import fr.xephi.authme.api.API;
public class FileCache {
private AuthMe plugin = AuthMe.getInstance();
public FileCache() {
final File folder = new File("cache");
if (!folder.exists()) {
folder.mkdirs();
}
}
public void createCache(String playername, DataFileCache playerData, String group, boolean operator, boolean flying) {
final File file = new File("cache/" + playername
+ ".cache");
public FileCache() {
final File folder = new File("cache");
if (!folder.exists()) {
folder.mkdirs();
}
}
if (file.exists()) {
return;
}
public void createCache(String playername, DataFileCache playerData,
String group, boolean operator, boolean flying) {
final File file = new File("cache/" + playername + ".cache");
FileWriter writer = null;
try {
file.createNewFile();
if (file.exists()) {
return;
}
writer = new FileWriter(file);
FileWriter writer = null;
try {
file.createNewFile();
String s = group+";";
if (operator)
s = s + "1";
else s = s + "0";
writer = new FileWriter(file);
// line format Group|OperatorStatus|isFlying
if(flying)
writer.write(s+";1" + API.newline);
else writer.write(s+";0" + API.newline);
writer.flush();
String s = group + ";";
if (operator) s = s + "1";
else s = s + "0";
ItemStack[] invstack = playerData.getInventory();
// line format Group|OperatorStatus|isFlying
if (flying) writer.write(s + ";1" + API.newline);
else writer.write(s + ";0" + API.newline);
writer.flush();
for (int i = 0; i < invstack.length; i++) {
ItemStack[] invstack = playerData.getInventory();
String itemid = "AIR";
int amount = 0;
int durability = 0;
String enchList = "";
String name = "";
String lores = "";
if (invstack[i] != null) {
itemid = invstack[i].getType().name();
amount = invstack[i].getAmount();
durability = invstack[i].getDurability();
for(Enchantment e : invstack[i].getEnchantments().keySet()) {
enchList = enchList.concat(e.getName()+":"+invstack[i].getEnchantmentLevel(e)+":");
}
if (enchList.length() > 1)
enchList = enchList.substring(0, enchList.length() - 1);
if (invstack[i].hasItemMeta()) {
if (invstack[i].getItemMeta().hasDisplayName()) {
name = invstack[i].getItemMeta().getDisplayName();
}
if (invstack[i].getItemMeta().hasLore()) {
for (String lore : invstack[i].getItemMeta().getLore()) {
lores = lore + "%newline%";
}
}
}
}
String writeItem = "i" + ":" + itemid + ":" + amount + ":"
+ durability + ":"+ enchList + ";" + name + "\\*" + lores + "\r\n";
writer.write(writeItem);
writer.flush();
}
for (int i = 0; i < invstack.length; i++) {
ItemStack[] armorstack = playerData.getArmour();
String itemid = "AIR";
int amount = 0;
int durability = 0;
String enchList = "";
String name = "";
String lores = "";
if (invstack[i] != null) {
itemid = invstack[i].getType().name();
amount = invstack[i].getAmount();
durability = invstack[i].getDurability();
for (Enchantment e : invstack[i].getEnchantments().keySet()) {
enchList = enchList.concat(e.getName() + ":"
+ invstack[i].getEnchantmentLevel(e) + ":");
}
if (enchList.length() > 1) enchList = enchList.substring(0,
enchList.length() - 1);
if (invstack[i].hasItemMeta()) {
if (invstack[i].getItemMeta().hasDisplayName()) {
name = invstack[i].getItemMeta().getDisplayName();
}
if (invstack[i].getItemMeta().hasLore()) {
for (String lore : invstack[i].getItemMeta()
.getLore()) {
lores = lore + "%newline%";
}
}
}
}
String writeItem = "i" + ":" + itemid + ":" + amount + ":"
+ durability + ":" + enchList + ";" + name + "\\*"
+ lores + "\r\n";
writer.write(writeItem);
writer.flush();
}
for (int i = 0; i < armorstack.length; i++) {
String itemid = "AIR";
int amount = 0;
int durability = 0;
String enchList = "";
String name = "";
String lores = "";
if (armorstack[i] != null) {
itemid = armorstack[i].getType().name();
amount = armorstack[i].getAmount();
durability = armorstack[i].getDurability();
for(Enchantment e : armorstack[i].getEnchantments().keySet()) {
enchList = enchList.concat(e.getName()+":"+armorstack[i].getEnchantmentLevel(e)+":");
}
if (enchList.length() > 1)
enchList = enchList.substring(0, enchList.length() - 1);
if (armorstack[i].hasItemMeta()) {
if (armorstack[i].getItemMeta().hasDisplayName()) {
name = armorstack[i].getItemMeta().getDisplayName();
}
if (armorstack[i].getItemMeta().hasLore()) {
for (String lore : armorstack[i].getItemMeta().getLore()) {
lores = lore + "%newline%";
}
}
}
}
String writeItem = "w" + ":" + itemid + ":" + amount + ":"
+ durability + ":"+ enchList + ";" + name + "\\*" + lores + "\r\n";
writer.write(writeItem);
writer.flush();
}
writer.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
ItemStack[] armorstack = playerData.getArmour();
public DataFileCache readCache(String playername) {
final File file = new File("cache/" + playername
+ ".cache");
for (int i = 0; i < armorstack.length; i++) {
String itemid = "AIR";
int amount = 0;
int durability = 0;
String enchList = "";
String name = "";
String lores = "";
if (armorstack[i] != null) {
itemid = armorstack[i].getType().name();
amount = armorstack[i].getAmount();
durability = armorstack[i].getDurability();
for (Enchantment e : armorstack[i].getEnchantments()
.keySet()) {
enchList = enchList.concat(e.getName() + ":"
+ armorstack[i].getEnchantmentLevel(e) + ":");
}
if (enchList.length() > 1) enchList = enchList.substring(0,
enchList.length() - 1);
if (armorstack[i].hasItemMeta()) {
if (armorstack[i].getItemMeta().hasDisplayName()) {
name = armorstack[i].getItemMeta().getDisplayName();
}
if (armorstack[i].getItemMeta().hasLore()) {
for (String lore : armorstack[i].getItemMeta()
.getLore()) {
lores = lore + "%newline%";
}
}
}
}
String writeItem = "w" + ":" + itemid + ":" + amount + ":"
+ durability + ":" + enchList + ";" + name + "\\*"
+ lores + "\r\n";
writer.write(writeItem);
writer.flush();
}
writer.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
public DataFileCache readCache(String playername) {
final File file = new File("cache/" + playername + ".cache");
ItemStack[] stacki = new ItemStack[36];
ItemStack[] stacka = new ItemStack[4];
@ -149,20 +154,20 @@ public class FileCache {
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];
// 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;
}
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;
continue;
}
if (!line.startsWith("i") && !line.startsWith("w")) {
@ -179,18 +184,22 @@ public class FileCache {
line = line.split(";")[0];
}
final String[] in = line.split(":");
// can enchant item? size ofstring in file - 4 all / 2 = number of enchant
// 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]));
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++;
}
}
try {
ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacki[i].getType());
ItemMeta meta = plugin.getServer().getItemFactory()
.getItemMeta(stacki[i].getType());
if (!name.isEmpty()) {
meta.setDisplayName(name);
}
@ -201,23 +210,25 @@ public class FileCache {
}
meta.setLore(loreList);
}
if (meta != null)
stacki[i].setItemMeta(meta);
} catch (Exception e) {}
if (meta != null) stacki[i].setItemMeta(meta);
} catch (Exception e) {
}
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]));
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++;
}
}
try {
ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacka[a].getType());
if (!name.isEmpty())
meta.setDisplayName(name);
ItemMeta meta = plugin.getServer().getItemFactory()
.getItemMeta(stacka[a].getType());
if (!name.isEmpty()) meta.setDisplayName(name);
if (!lores.isEmpty()) {
List<String> loreList = new ArrayList<String>();
for (String s : lores.split("%newline%")) {
@ -225,9 +236,9 @@ public class FileCache {
}
meta.setLore(loreList);
}
if (meta != null)
stacki[i].setItemMeta(meta);
} catch (Exception e) {}
if (meta != null) stacki[i].setItemMeta(meta);
} catch (Exception e) {
}
a++;
}
}
@ -239,25 +250,23 @@ public class FileCache {
}
}
return new DataFileCache(stacki, stacka, group, op, flying);
}
}
public void removeCache(String playername) {
final File file = new File("cache/" + playername
+ ".cache");
public void removeCache(String playername) {
final File file = new File("cache/" + playername + ".cache");
if (file.exists()) {
file.delete();
}
}
if (file.exists()) {
file.delete();
}
}
public boolean doesCacheExist(String playername) {
final File file = new File("cache/" + playername
+ ".cache");
public boolean doesCacheExist(String playername) {
final File file = new File("cache/" + playername + ".cache");
if (file.exists()) {
return true;
}
return false;
}
if (file.exists()) {
return true;
}
return false;
}
}

View File

@ -15,7 +15,6 @@ import fr.xephi.authme.events.ResetInventoryEvent;
import fr.xephi.authme.events.StoreInventoryEvent;
import fr.xephi.authme.settings.Settings;
public class LimboCache {
private static LimboCache singleton = null;
@ -24,7 +23,7 @@ public class LimboCache {
public AuthMe plugin;
private LimboCache(AuthMe plugin) {
this.plugin = plugin;
this.plugin = plugin;
this.cache = new HashMap<String, LimboPlayer>();
}
@ -39,63 +38,70 @@ public class LimboCache {
boolean flying;
if (playerData.doesCacheExist(name)) {
StoreInventoryEvent event = new StoreInventoryEvent(player, playerData);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
inv = event.getInventory();
arm = event.getArmor();
} else {
inv = null;
arm = null;
}
playerGroup = playerData.readCache(name).getGroup();
operator = playerData.readCache(name).getOperator();
flying = playerData.readCache(name).isFlying();
StoreInventoryEvent event = new StoreInventoryEvent(player,
playerData);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null
&& event.getArmor() != null) {
inv = event.getInventory();
arm = event.getArmor();
} else {
inv = null;
arm = null;
}
playerGroup = playerData.readCache(name).getGroup();
operator = playerData.readCache(name).getOperator();
flying = playerData.readCache(name).isFlying();
} else {
StoreInventoryEvent event = new StoreInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
inv = event.getInventory();
arm = event.getArmor();
} else {
inv = null;
arm = null;
}
if(player.isOp())
operator = true;
StoreInventoryEvent event = new StoreInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null
&& event.getArmor() != null) {
inv = event.getInventory();
arm = event.getArmor();
} else {
inv = null;
arm = null;
}
if (player.isOp()) operator = true;
else operator = false;
if(player.isFlying())
flying = true;
if (player.isFlying()) flying = true;
else flying = false;
if (plugin.permission != null) {
try {
playerGroup = plugin.permission.getPrimaryGroup(player);
} catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
plugin.permission = null;
}
try {
playerGroup = plugin.permission.getPrimaryGroup(player);
} catch (UnsupportedOperationException e) {
ConsoleLogger
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null;
}
}
}
if(Settings.isForceSurvivalModeEnabled) {
if(Settings.isResetInventoryIfCreative && player.getGameMode() == GameMode.CREATIVE ) {
ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
player.getInventory().clear();
player.sendMessage("Your inventory has been cleaned!");
}
if (Settings.isForceSurvivalModeEnabled) {
if (Settings.isResetInventoryIfCreative
&& player.getGameMode() == GameMode.CREATIVE) {
ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
player.getInventory().clear();
player.sendMessage("Your inventory has been cleaned!");
}
}
gameMode = GameMode.SURVIVAL;
}
if(player.isDead()) {
loc = plugin.getSpawnLocation(player);
if (player.isDead()) {
loc = plugin.getSpawnLocation(player);
}
cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup, flying));
cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc,
inv, arm, gameMode, operator, playerGroup, flying));
}
public void addLimboPlayer(Player player, String group) {
cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group));
cache.put(player.getName().toLowerCase(), new LimboPlayer(player
.getName().toLowerCase(), group));
}
public void deleteLimboPlayer(String name) {
@ -117,11 +123,11 @@ public class LimboCache {
return singleton;
}
public void updateLimboPlayer(Player player) {
if (this.hasLimboPlayer(player.getName().toLowerCase())) {
this.deleteLimboPlayer(player.getName().toLowerCase());
}
this.addLimboPlayer(player);
}
public void updateLimboPlayer(Player player) {
if (this.hasLimboPlayer(player.getName().toLowerCase())) {
this.deleteLimboPlayer(player.getName().toLowerCase());
}
this.addLimboPlayer(player);
}
}

View File

@ -17,7 +17,9 @@ public class LimboPlayer {
private String group = "";
private boolean flying = false;
public LimboPlayer(String name, Location loc, ItemStack[] inventory, ItemStack[] armour, GameMode gameMode, boolean operator, String group, boolean flying) {
public LimboPlayer(String name, Location loc, ItemStack[] inventory,
ItemStack[] armour, GameMode gameMode, boolean operator,
String group, boolean flying) {
this.name = name;
this.loc = loc;
this.inventory = inventory;
@ -28,7 +30,8 @@ public class LimboPlayer {
this.flying = flying;
}
public LimboPlayer(String name, Location loc, GameMode gameMode, boolean operator, String group, boolean flying) {
public LimboPlayer(String name, Location loc, GameMode gameMode,
boolean operator, String group, boolean flying) {
this.name = name;
this.loc = loc;
this.gameMode = gameMode;
@ -59,11 +62,11 @@ public class LimboPlayer {
}
public void setArmour(ItemStack[] armour) {
this.armour = armour;
this.armour = armour;
}
public void setInventory(ItemStack[] inventory) {
this.inventory = inventory;
this.inventory = inventory;
}
public GameMode getGameMode() {
@ -78,24 +81,24 @@ public class LimboPlayer {
return group;
}
public void setTimeoutTaskId(int i) {
this.timeoutTaskId = i;
}
public void setTimeoutTaskId(int i) {
this.timeoutTaskId = i;
}
public int getTimeoutTaskId() {
return timeoutTaskId;
}
public int getTimeoutTaskId() {
return timeoutTaskId;
}
public void setMessageTaskId(int messageTaskId) {
this.messageTaskId = messageTaskId;
}
public void setMessageTaskId(int messageTaskId) {
this.messageTaskId = messageTaskId;
}
public int getMessageTaskId() {
return messageTaskId;
}
public int getMessageTaskId() {
return messageTaskId;
}
public boolean isFlying() {
return flying;
}
public boolean isFlying() {
return flying;
}
}

View File

@ -43,10 +43,9 @@ import fr.xephi.authme.settings.SpoutCfg;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class AdminCommand implements CommandExecutor {
public AuthMe plugin;
public AuthMe plugin;
private Messages m = Messages.getInstance();
private SpoutCfg s = SpoutCfg.getInstance();
public DataSource database;
@ -57,7 +56,8 @@ public class AdminCommand implements CommandExecutor {
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (args.length == 0) {
sender.sendMessage("Usage: /authme reload - Reload the config");
sender.sendMessage("/authme register <playername> <password> - Register a player");
@ -75,27 +75,33 @@ public class AdminCommand implements CommandExecutor {
sender.sendMessage("/authme switchantibot on/off - Enable/Disable antibot method");
return true;
}
if (!plugin.authmePermissible(sender, "authme.admin." + args[0].toLowerCase())) {
m._(sender, "no_perm");
return true;
}
if((sender instanceof ConsoleCommandSender) && args[0].equalsIgnoreCase("passpartuToken")) {
if(args.length > 1) {
System.out.println("[AuthMe] command usage: /authme passpartuToken");
return true;
}
if(Utils.getInstance().obtainToken()) {
System.out.println("[AuthMe] You have 30s for insert this token ingame with /passpartu [token]");
if (!plugin.authmePermissible(sender,
"authme.admin." + args[0].toLowerCase())) {
m._(sender, "no_perm");
return true;
}
if ((sender instanceof ConsoleCommandSender)
&& args[0].equalsIgnoreCase("passpartuToken")) {
if (args.length > 1) {
System.out
.println("[AuthMe] command usage: /authme passpartuToken");
return true;
}
if (Utils.getInstance().obtainToken()) {
System.out
.println("[AuthMe] You have 30s for insert this token ingame with /passpartu [token]");
} else {
System.out.println("[AuthMe] Security error on passpartu token, redo it. ");
System.out
.println("[AuthMe] Security error on passpartu token, redo it. ");
}
return true;
}
}
if (args[0].equalsIgnoreCase("version")) {
sender.sendMessage("AuthMe Version: "+AuthMe.getInstance().getDescription().getVersion());
sender.sendMessage("AuthMe Version: "
+ AuthMe.getInstance().getDescription().getVersion());
return true;
}
@ -109,15 +115,16 @@ public class AdminCommand implements CommandExecutor {
calendar.add(Calendar.DATE, -(Integer.parseInt(args[1])));
long until = calendar.getTimeInMillis();
List<String> purged = database.autoPurgeDatabase(until);
sender.sendMessage("Deleted " + purged.size() + " user accounts");
if (Settings.purgeEssentialsFile && plugin.ess != null)
plugin.dataManager.purgeEssentials(purged);
if (Settings.purgePlayerDat)
plugin.dataManager.purgeDat(purged);
if (Settings.purgeLimitedCreative)
plugin.dataManager.purgeLimitedCreative(purged);
if (Settings.purgeAntiXray)
plugin.dataManager.purgeAntiXray(purged);
sender.sendMessage("Deleted " + purged.size()
+ " user accounts");
if (Settings.purgeEssentialsFile && plugin.ess != null) plugin.dataManager
.purgeEssentials(purged);
if (Settings.purgePlayerDat) plugin.dataManager
.purgeDat(purged);
if (Settings.purgeLimitedCreative) plugin.dataManager
.purgeLimitedCreative(purged);
if (Settings.purgeAntiXray) plugin.dataManager
.purgeAntiXray(purged);
return true;
} catch (NumberFormatException e) {
sender.sendMessage("Usage: /authme purge <DAYS>");
@ -125,148 +132,176 @@ public class AdminCommand implements CommandExecutor {
}
} else if (args[0].equalsIgnoreCase("reload")) {
database.reload();
File newConfigFile = new File("plugins/AuthMe","config.yml");
File newConfigFile = new File("plugins/AuthMe", "config.yml");
if (!newConfigFile.exists()) {
InputStream fis = getClass().getResourceAsStream("/config.yml");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newConfigFile);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (Exception e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR");
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
}
}
InputStream fis = getClass().getResourceAsStream("/config.yml");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newConfigFile);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (Exception e) {
Logger.getLogger(JavaPlugin.class.getName()).log(
Level.SEVERE, "Failed to load config from JAR");
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
}
}
}
YamlConfiguration newConfig = YamlConfiguration.loadConfiguration(newConfigFile);
YamlConfiguration newConfig = YamlConfiguration
.loadConfiguration(newConfigFile);
Settings.reloadConfigOptions(newConfig);
m.reLoad();
s.reLoad();
m._(sender, "reload");
} else if (args[0].equalsIgnoreCase("lastlogin")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme lastlogin <playername>");
return true;
}
try {
if (database.getAuth(args[1].toLowerCase()) != null) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme lastlogin <playername>");
return true;
}
try {
if (database.getAuth(args[1].toLowerCase()) != null) {
PlayerAuth player = database.getAuth(args[1].toLowerCase());
long lastLogin = player.getLastLogin();
Date d = new Date(lastLogin);
final long diff = System.currentTimeMillis() - lastLogin;
final String msg = (int)(diff / 86400000) + " days " + (int)(diff / 3600000 % 24) + " hours " + (int)(diff / 60000 % 60) + " mins " + (int)(diff / 1000 % 60) + " secs.";
final String msg = (int) (diff / 86400000) + " days "
+ (int) (diff / 3600000 % 24) + " hours "
+ (int) (diff / 60000 % 60) + " mins "
+ (int) (diff / 1000 % 60) + " secs.";
String lastIP = player.getIp();
sender.sendMessage("[AuthMe] " + args[1].toLowerCase() + " lastlogin : " + d.toString());
sender.sendMessage("[AuthMe] The player : " + player.getNickname() + " is unlogged since " + msg);
sender.sendMessage("[AuthMe] " + args[1].toLowerCase()
+ " lastlogin : " + d.toString());
sender.sendMessage("[AuthMe] The player : "
+ player.getNickname() + " is unlogged since "
+ msg);
sender.sendMessage("[AuthMe] LastPlayer IP : " + lastIP);
} else {
m._(sender, "unknown_user");
return true;
}
} catch (NullPointerException e) {
m._(sender, "unknown_user");
return true;
}
} else {
m._(sender, "unknown_user");
return true;
}
} catch (NullPointerException e) {
m._(sender, "unknown_user");
return true;
}
} else if (args[0].equalsIgnoreCase("accounts")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme accounts <playername>");
sender.sendMessage("Or: /authme accounts <ip>");
return true;
}
if (!args[1].contains(".")) {
final CommandSender fSender = sender;
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
PlayerAuth pAuth = null;
String message = "[AuthMe] ";
try {
pAuth = database.getAuth(arguments[1].toLowerCase());
} catch (NullPointerException npe){
fSender.sendMessage("[AuthMe] This player is unknown");
return;
}
if (pAuth != null) {
List<String> accountList = database.getAllAuthsByName(pAuth);
if (accountList.isEmpty() || accountList == null) {
fSender.sendMessage("[AuthMe] This player is unknown");
return;
}
if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
message = message + account;
if (i != accountList.size()) {
message = message + ", ";
} else {
message = message + ".";
}
}
fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
fSender.sendMessage(message);
} else {
fSender.sendMessage("[AuthMe] This player is unknown");
return;
}
}
});
return true;
} else {
final CommandSender fSender = sender;
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
String message = "[AuthMe] ";
if (arguments[1] != null) {
List<String> accountList = database.getAllAuthsByIp(arguments[1]);
if (accountList.isEmpty() || accountList == null) {
fSender.sendMessage("[AuthMe] Please put a valid IP");
return;
}
if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
message = message + account;
if (i != accountList.size()) {
message = message + ", ";
} else {
message = message + ".";
}
}
fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
fSender.sendMessage(message);
} else {
fSender.sendMessage("[AuthMe] Please put a valid IP");
return;
}
}
});
return true;
}
} else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme accounts <playername>");
sender.sendMessage("Or: /authme accounts <ip>");
return true;
}
if (!args[1].contains(".")) {
final CommandSender fSender = sender;
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
PlayerAuth pAuth = null;
String message = "[AuthMe] ";
try {
pAuth = database.getAuth(arguments[1]
.toLowerCase());
} catch (NullPointerException npe) {
fSender.sendMessage("[AuthMe] This player is unknown");
return;
}
if (pAuth != null) {
List<String> accountList = database
.getAllAuthsByName(pAuth);
if (accountList.isEmpty()
|| accountList == null) {
fSender.sendMessage("[AuthMe] This player is unknown");
return;
}
if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
message = message + account;
if (i != accountList.size()) {
message = message + ", ";
} else {
message = message + ".";
}
}
fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " has "
+ String.valueOf(accountList.size())
+ " accounts");
fSender.sendMessage(message);
} else {
fSender.sendMessage("[AuthMe] This player is unknown");
return;
}
}
});
return true;
} else {
final CommandSender fSender = sender;
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
String message = "[AuthMe] ";
if (arguments[1] != null) {
List<String> accountList = database
.getAllAuthsByIp(arguments[1]);
if (accountList.isEmpty()
|| accountList == null) {
fSender.sendMessage("[AuthMe] Please put a valid IP");
return;
}
if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
message = message + account;
if (i != accountList.size()) {
message = message + ", ";
} else {
message = message + ".";
}
}
fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " has "
+ String.valueOf(accountList.size())
+ " accounts");
fSender.sendMessage(message);
} else {
fSender.sendMessage("[AuthMe] Please put a valid IP");
return;
}
}
});
return true;
}
} else if (args[0].equalsIgnoreCase("register")
|| args[0].equalsIgnoreCase("reg")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme register playername password");
return true;
@ -274,17 +309,19 @@ public class AdminCommand implements CommandExecutor {
try {
String name = args[1].toLowerCase();
if (database.isAuthAvailable(name)) {
m._(sender, "user_regged");
m._(sender, "user_regged");
return true;
}
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name);
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0L, "your@email.com", API.getPlayerRealName(name));
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
auth.setSalt(PasswordSecurity.userSalt.get(name));
else
auth.setSalt("");
String hash = PasswordSecurity.getHash(
Settings.getPasswordHash, args[2], name);
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0L,
"your@email.com", API.getPlayerRealName(name));
if (PasswordSecurity.userSalt.containsKey(name)
&& PasswordSecurity.userSalt.get(name) != null) auth
.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt("");
if (!database.saveAuth(auth)) {
m._(sender, "error");
m._(sender, "error");
return true;
}
m._(sender, "registered");
@ -299,118 +336,128 @@ public class AdminCommand implements CommandExecutor {
sender.sendMessage("Usage: /authme getemail playername");
return true;
}
String playername = args[1].toLowerCase();
PlayerAuth getAuth = database.getAuth(playername);
if (getAuth == null) {
m._(sender, "unknown_user");
return true;
}
sender.sendMessage("[AuthMe] " + args[1] + " email : " + getAuth.getEmail());
return true;
String playername = args[1].toLowerCase();
PlayerAuth getAuth = database.getAuth(playername);
if (getAuth == null) {
m._(sender, "unknown_user");
return true;
}
sender.sendMessage("[AuthMe] " + args[1] + " email : "
+ getAuth.getEmail());
return true;
} else if (args[0].equalsIgnoreCase("chgemail")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme chgemail playername email");
return true;
}
String playername = args[1].toLowerCase();
PlayerAuth getAuth = database.getAuth(playername);
if (getAuth == null) {
m._(sender, "unknown_user");
return true;
}
getAuth.setEmail(args[2]);
if (!database.updateEmail(getAuth)) {
m._(sender, "error");
String playername = args[1].toLowerCase();
PlayerAuth getAuth = database.getAuth(playername);
if (getAuth == null) {
m._(sender, "unknown_user");
return true;
}
if (PlayerCache.getInstance().getAuth(playername) != null)
PlayerCache.getInstance().updatePlayer(getAuth);
return true;
getAuth.setEmail(args[2]);
if (!database.updateEmail(getAuth)) {
m._(sender, "error");
return true;
}
if (PlayerCache.getInstance().getAuth(playername) != null) PlayerCache
.getInstance().updatePlayer(getAuth);
return true;
} else if (args[0].equalsIgnoreCase("setspawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setSpawn(((Player) sender).getLocation()))
sender.sendMessage("[AuthMe] Correctly define new spawn");
else sender.sendMessage("[AuthMe] SetSpawn fail , please retry");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setSpawn(
((Player) sender).getLocation())) sender
.sendMessage("[AuthMe] Correctly define new spawn");
else sender
.sendMessage("[AuthMe] SetSpawn fail , please retry");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("setfirstspawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation()))
sender.sendMessage("[AuthMe] Correctly define new first spawn");
else sender.sendMessage("[AuthMe] SetFirstSpawn fail , please retry");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setFirstSpawn(
((Player) sender).getLocation())) sender
.sendMessage("[AuthMe] Correctly define new first spawn");
else sender
.sendMessage("[AuthMe] SetFirstSpawn fail , please retry");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("purgebannedplayers")) {
List<String> bannedPlayers = new ArrayList<String>();
for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) {
bannedPlayers.add(off.getName().toLowerCase());
}
final List<String> bP = bannedPlayers;
if (database instanceof Thread) {
database.purgeBanned(bP);
} else {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
database.purgeBanned(bP);
}
});
}
if (Settings.purgeEssentialsFile && plugin.ess != null)
plugin.dataManager.purgeEssentials(bannedPlayers);
if (Settings.purgePlayerDat)
plugin.dataManager.purgeDat(bannedPlayers);
if (Settings.purgeLimitedCreative)
plugin.dataManager.purgeLimitedCreative(bannedPlayers);
if (Settings.purgeAntiXray)
plugin.dataManager.purgeAntiXray(bannedPlayers);
return true;
List<String> bannedPlayers = new ArrayList<String>();
for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) {
bannedPlayers.add(off.getName().toLowerCase());
}
final List<String> bP = bannedPlayers;
if (database instanceof Thread) {
database.purgeBanned(bP);
} else {
Bukkit.getScheduler().runTaskAsynchronously(plugin,
new Runnable() {
@Override
public void run() {
database.purgeBanned(bP);
}
});
}
if (Settings.purgeEssentialsFile && plugin.ess != null) plugin.dataManager
.purgeEssentials(bannedPlayers);
if (Settings.purgePlayerDat) plugin.dataManager
.purgeDat(bannedPlayers);
if (Settings.purgeLimitedCreative) plugin.dataManager
.purgeLimitedCreative(bannedPlayers);
if (Settings.purgeAntiXray) plugin.dataManager
.purgeAntiXray(bannedPlayers);
return true;
} else if (args[0].equalsIgnoreCase("spawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getSpawn() != null)
((Player) sender).teleport(Spawn.getInstance().getSpawn());
else sender.sendMessage("[AuthMe] Spawn fail , please try to define the spawn");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getSpawn() != null) ((Player) sender)
.teleport(Spawn.getInstance().getSpawn());
else sender
.sendMessage("[AuthMe] Spawn fail , please try to define the spawn");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("firstspawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getFirstSpawn() != null)
((Player) sender).teleport(Spawn.getInstance().getFirstSpawn());
else sender.sendMessage("[AuthMe] Spawn fail , please try to define the first spawn");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getFirstSpawn() != null) ((Player) sender)
.teleport(Spawn.getInstance().getFirstSpawn());
else sender
.sendMessage("[AuthMe] Spawn fail , please try to define the first spawn");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("changepassword")
|| args[0].equalsIgnoreCase("cp")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme changepassword playername newpassword");
return true;
}
try {
String name = args[1].toLowerCase();
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name);
String hash = PasswordSecurity.getHash(
Settings.getPasswordHash, args[2], name);
PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name);
@ -418,16 +465,16 @@ public class AdminCommand implements CommandExecutor {
auth = database.getAuth(name);
}
if (auth == null) {
m._(sender, "unknown_user");
m._(sender, "unknown_user");
return true;
}
auth.setHash(hash);
if (PasswordSecurity.userSalt.containsKey(name)) {
auth.setSalt(PasswordSecurity.userSalt.get(name));
auth.setSalt(PasswordSecurity.userSalt.get(name));
database.updateSalt(auth);
}
if (!database.updatePassword(auth)) {
m._(sender, "error");
m._(sender, "error");
return true;
}
sender.sendMessage("pwd_changed");
@ -437,51 +484,67 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "error");
}
return true;
} else if (args[0].equalsIgnoreCase("unregister") || args[0].equalsIgnoreCase("unreg") || args[0].equalsIgnoreCase("del") ) {
} else if (args[0].equalsIgnoreCase("unregister")
|| args[0].equalsIgnoreCase("unreg")
|| args[0].equalsIgnoreCase("del")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme unregister playername");
return true;
}
String name = args[1].toLowerCase();
if (!database.removeAuth(name)) {
m._(sender, "error");
m._(sender, "error");
return true;
}
Player target = Bukkit.getPlayer(name);
PlayerCache.getInstance().removePlayer(name);
Utils.getInstance().setGroup(name, groupType.UNREGISTERED);
if (target != null) {
if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(target);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(target, target.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if(!tpEvent.isCancelled()) {
target.teleport(tpEvent.getTo());
}
if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled
&& !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(target);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(
target, target.getLocation(), spawn, false);
plugin.getServer().getPluginManager()
.callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
target.teleport(tpEvent.getTo());
}
}
LimboCache.getInstance().addLimboPlayer(target);
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
int id = sched.scheduleSyncDelayedTask(plugin,
new TimeoutTask(plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name)
.setTimeoutTaskId(id);
}
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("reg_msg"), interval)));
if (Settings.applyBlindEffect)
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
LimboCache
.getInstance()
.getLimboPlayer(name)
.setMessageTaskId(
sched.scheduleSyncDelayedTask(
plugin,
new MessageTask(plugin, name, m
._("reg_msg"), interval)));
if (Settings.applyBlindEffect) target
.addPotionEffect(new PotionEffect(
PotionEffectType.BLINDNESS,
Settings.getRegistrationTimeout * 20, 2));
m._(target, "unregistered");
} else {
// Player isn't online, do nothing else
}
} else {
// Player isn't online, do nothing else
}
} else {
// Player does not exist, do nothing else
// Player does not exist, do nothing else
}
m._(sender, "unregistered");
ConsoleLogger.info(args[1] + " unregistered");
return true;
} else if (args[0].equalsIgnoreCase("purgelastpos")){
} else if (args[0].equalsIgnoreCase("purgelastpos")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme purgelastpos playername");
return true;
@ -490,8 +553,9 @@ public class AdminCommand implements CommandExecutor {
String name = args[1].toLowerCase();
PlayerAuth auth = database.getAuth(name);
if (auth == null) {
sender.sendMessage("The player " + name + " is not registered ");
return true;
sender.sendMessage("The player " + name
+ " is not registered ");
return true;
}
auth.setQuitLocX(0);
auth.setQuitLocY(0);
@ -500,44 +564,48 @@ public class AdminCommand implements CommandExecutor {
database.updateQuitLoc(auth);
sender.sendMessage(name + " 's last pos location is now reset");
} catch (Exception e) {
ConsoleLogger.showError("An error occured while trying to reset location or player do not exist, please see below: ");
ConsoleLogger.showError(e.getMessage());
if (sender instanceof Player)
sender.sendMessage("An error occured while trying to reset location or player do not exist, please see logs");
ConsoleLogger
.showError("An error occured while trying to reset location or player do not exist, please see below: ");
ConsoleLogger.showError(e.getMessage());
if (sender instanceof Player) sender
.sendMessage("An error occured while trying to reset location or player do not exist, please see logs");
}
return true;
} else if (args[0].equalsIgnoreCase("switchantibot")) {
if (args.length != 2) {
sender.sendMessage("Usage : /authme switchantibot on/off");
return true;
}
if (args[1].equalsIgnoreCase("on")) {
plugin.switchAntiBotMod(true);
sender.sendMessage("[AuthMe] AntiBotMod enabled");
return true;
}
if (args[1].equalsIgnoreCase("off")) {
plugin.switchAntiBotMod(false);
sender.sendMessage("[AuthMe] AntiBotMod disabled");
return true;
}
sender.sendMessage("Usage : /authme switchantibot on/off");
return true;
if (args.length != 2) {
sender.sendMessage("Usage : /authme switchantibot on/off");
return true;
}
if (args[1].equalsIgnoreCase("on")) {
plugin.switchAntiBotMod(true);
sender.sendMessage("[AuthMe] AntiBotMod enabled");
return true;
}
if (args[1].equalsIgnoreCase("off")) {
plugin.switchAntiBotMod(false);
sender.sendMessage("[AuthMe] AntiBotMod disabled");
return true;
}
sender.sendMessage("Usage : /authme switchantibot on/off");
return true;
} else if (args[0].equalsIgnoreCase("getip")) {
if (args.length < 2) {
sender.sendMessage("Usage : /authme getip onlinePlayerName");
return true;
}
if (Bukkit.getPlayer(args[1]) != null) {
Player player = Bukkit.getPlayer(args[1]);
sender.sendMessage(player.getName() + " actual ip is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort());
sender.sendMessage(player.getName() + " real ip is : " + plugin.getIP(player));
return true;
} else {
sender.sendMessage("This player is not actually online");
sender.sendMessage("Usage : /authme getip onlinePlayerName");
return true;
}
if (args.length < 2) {
sender.sendMessage("Usage : /authme getip onlinePlayerName");
return true;
}
if (Bukkit.getPlayer(args[1]) != null) {
Player player = Bukkit.getPlayer(args[1]);
sender.sendMessage(player.getName() + " actual ip is : "
+ player.getAddress().getAddress().getHostAddress()
+ ":" + player.getAddress().getPort());
sender.sendMessage(player.getName() + " real ip is : "
+ plugin.getIP(player));
return true;
} else {
sender.sendMessage("This player is not actually online");
sender.sendMessage("Usage : /authme getip onlinePlayerName");
return true;
}
} else if (args[0].equalsIgnoreCase("resetposition")) {
if (args.length < 2) {
sender.sendMessage("Usage : /authme resetPosition <playerName>");
@ -553,7 +621,8 @@ public class AdminCommand implements CommandExecutor {
auth.setQuitLocZ(0D);
auth.setWorld("world");
database.updateQuitLoc(auth);
sender.sendMessage("[AuthMe] Successfully reset position for " + auth.getNickname());
sender.sendMessage("[AuthMe] Successfully reset position for "
+ auth.getNickname());
return true;
} else {
sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername");

View File

@ -11,20 +11,19 @@ import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class CaptchaCommand implements CommandExecutor {
public AuthMe plugin;
public AuthMe plugin;
private Messages m = Messages.getInstance();
public static RandomString rdm = new RandomString(Settings.captchaLength);
public CaptchaCommand(AuthMe plugin) {
this.plugin = plugin;
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd,
String label, String[] args) {
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) {
return true;
@ -34,37 +33,38 @@ public class CaptchaCommand implements CommandExecutor {
String name = player.getName().toLowerCase();
if (args.length == 0) {
m._(player, "usage_captcha");
m._(player, "usage_captcha");
return true;
}
if (PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "logged_in");
m._(player, "logged_in");
return true;
}
if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
m._(player, "no_perm");
m._(player, "no_perm");
return true;
}
if (!Settings.useCaptcha) {
m._(player, "usage_log");
return true;
m._(player, "usage_log");
return true;
}
if(!plugin.cap.containsKey(name)) {
m._(player, "usage_log");
return true;
}
if (!plugin.cap.containsKey(name)) {
m._(player, "usage_log");
return true;
}
if(Settings.useCaptcha && !args[0].equals(plugin.cap.get(name))) {
plugin.cap.remove(name);
plugin.cap.put(name, rdm.nextString());
for (String s : m._("wrong_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)));
}
return true;
if (Settings.useCaptcha && !args[0].equals(plugin.cap.get(name))) {
plugin.cap.remove(name);
plugin.cap.put(name, rdm.nextString());
for (String s : m._("wrong_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA",
plugin.cap.get(name)));
}
return true;
}
try {
plugin.captcha.remove(name);
@ -74,6 +74,6 @@ public class CaptchaCommand implements CommandExecutor {
m._(player, "valid_captcha");
m._(player, "login_msg");
return true;
}
}
}

View File

@ -18,7 +18,6 @@ import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class ChangePasswordCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
@ -31,51 +30,56 @@ public class ChangePasswordCommand implements CommandExecutor {
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm");
m._(sender, "no_perm");
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "not_logged_in");
m._(player, "not_logged_in");
return true;
}
if (args.length != 2) {
m._(player, "usage_changepassword");
m._(player, "usage_changepassword");
return true;
}
try {
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, args[1], name);
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash,
args[1], name);
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
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 (PasswordSecurity.userSalt.containsKey(name)
&& PasswordSecurity.userSalt.get(name) != null) auth
.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt("");
if (!database.updatePassword(auth)) {
m._(player, "error");
m._(player, "error");
return true;
}
database.updateSalt(auth);
PlayerCache.getInstance().updatePlayer(auth);
m._(player, "pwd_changed");
ConsoleLogger.info(player.getName() + " changed his password");
if(plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " change his password!"));
if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName()
+ " change his password!"));
}
} else {
m._(player, "wrong_pwd");
m._(player, "wrong_pwd");
}
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());

View File

@ -18,7 +18,6 @@ import fr.xephi.authme.converter.xAuthConverter;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Messages;
public class ConverterCommand implements CommandExecutor {
private AuthMe plugin;
@ -26,12 +25,13 @@ public class ConverterCommand implements CommandExecutor {
private DataSource database;
public ConverterCommand(AuthMe plugin, DataSource database) {
this.plugin = plugin;
this.database = database;
this.plugin = plugin;
this.database = database;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, final String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
final String[] args) {
if (!(sender instanceof Player)) {
return true;
}
@ -45,7 +45,7 @@ public class ConverterCommand implements CommandExecutor {
sender.sendMessage("Usage : /converter flattosql | flattosqlite | xauth | crazylogin | rakamak | royalauth | vauth");
return true;
}
ConvertType type = ConvertType.valueOf(args[0]);
if (type == null) {
m._(sender, "error");
@ -53,7 +53,7 @@ public class ConverterCommand implements CommandExecutor {
}
Converter converter = null;
switch (type) {
case ftsql:
case ftsql:
converter = new FlatToSql();
break;
case ftsqlite:
@ -74,7 +74,8 @@ public class ConverterCommand implements CommandExecutor {
case vauth:
converter = new vAuthConverter(plugin, database, sender);
break;
default: break;
default:
break;
}
if (converter == null) {
m._(sender, "error");
@ -84,27 +85,23 @@ public class ConverterCommand implements CommandExecutor {
sender.sendMessage("[AuthMe] Successfully converted from " + args[0]);
return true;
}
public enum ConvertType {
ftsql("flattosql"),
ftsqlite("flattosqlite"),
xauth("xauth"),
crazylogin("crazylogin"),
rakamak("rakamak"),
royalauth("royalauth"),
vauth("vauth");
ftsql("flattosql"), ftsqlite("flattosqlite"), xauth("xauth"), crazylogin(
"crazylogin"), rakamak("rakamak"), royalauth("royalauth"), vauth(
"vauth");
String name;
ConvertType(String name) {
this.name = name;
}
String getName() {
return this.name;
}
ConvertType fromName(String name) {
return ConvertType.valueOf(name);
}

View File

@ -24,8 +24,8 @@ import fr.xephi.authme.settings.Settings;
*/
public class EmailCommand implements CommandExecutor {
public AuthMe plugin;
private DataSource data;
public AuthMe plugin;
private DataSource data;
private Messages m = Messages.getInstance();
public EmailCommand(AuthMe plugin, DataSource data) {
@ -34,44 +34,49 @@ public class EmailCommand implements CommandExecutor {
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm");
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm");
return true;
}
if (args.length == 0) {
m._(player, "usage_email_add");
m._(player, "usage_email_change");
m._(player, "usage_email_recovery");
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
if(args[0].equalsIgnoreCase("add")) {
if (args.length != 3) {
m._(player, "usage_email_add");
return true;
}
if(Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") && data.getAllAuthsByEmail(args[1]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return true;
}
}
if(args[1].equals(args[2]) && PlayerCache.getInstance().isAuthenticated(name)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
if (auth.getEmail() == null || (!auth.getEmail().equals("your@email.com") && !auth.getEmail().isEmpty())) {
m._(player, "usage_email_change");
return true;
if (args.length == 0) {
m._(player, "usage_email_add");
m._(player, "usage_email_change");
m._(player, "usage_email_recovery");
return true;
}
if (args[0].equalsIgnoreCase("add")) {
if (args.length != 3) {
m._(player, "usage_email_add");
return true;
}
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts")
&& data.getAllAuthsByEmail(args[1]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return true;
}
if(!Settings.isEmailCorrect(args[1])) {
}
if (args[1].equals(args[2])
&& PlayerCache.getInstance().isAuthenticated(name)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
if (auth.getEmail() == null
|| (!auth.getEmail().equals("your@email.com") && !auth
.getEmail().isEmpty())) {
m._(player, "usage_email_change");
return true;
}
if (!Settings.isEmailCorrect(args[1])) {
m._(player, "email_invalid");
return true;
}
@ -83,37 +88,40 @@ public class EmailCommand implements CommandExecutor {
PlayerCache.getInstance().updatePlayer(auth);
m._(player, "email_added");
player.sendMessage(auth.getEmail());
} else if (PlayerCache.getInstance().isAuthenticated(name)){
} else if (PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "email_confirm");
} else {
if (!data.isAuthAvailable(name)) {
m._(player, "login_msg");
} else {
m._(player, "reg_email_msg");
}
if (!data.isAuthAvailable(name)) {
m._(player, "login_msg");
} else {
m._(player, "reg_email_msg");
}
}
} else if(args[0].equalsIgnoreCase("change")) {
} else if (args[0].equalsIgnoreCase("change")) {
if (args.length != 3) {
m._(player, "usage_email_change");
return true;
}
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts")
&& data.getAllAuthsByEmail(args[2]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return true;
}
if(Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") && data.getAllAuthsByEmail(args[2]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return true;
}
}
if(PlayerCache.getInstance().isAuthenticated(name)) {
}
if (PlayerCache.getInstance().isAuthenticated(name)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
if (auth.getEmail() == null || auth.getEmail().equals("your@email.com") || auth.getEmail().isEmpty()) {
m._(player, "usage_email_add");
return true;
if (auth.getEmail() == null
|| auth.getEmail().equals("your@email.com")
|| auth.getEmail().isEmpty()) {
m._(player, "usage_email_add");
return true;
}
if (!args[1].equals(auth.getEmail())) {
m._(player, "old_email_invalid");
return true;
if (!args[1].equals(auth.getEmail())) {
m._(player, "old_email_invalid");
return true;
}
if(!Settings.isEmailCorrect(args[2])) {
if (!Settings.isEmailCorrect(args[2])) {
m._(player, "new_email_invalid");
return true;
}
@ -125,78 +133,85 @@ public class EmailCommand implements CommandExecutor {
PlayerCache.getInstance().updatePlayer(auth);
m._(player, "email_changed");
player.sendMessage(m._("email_defined") + auth.getEmail());
} else if (PlayerCache.getInstance().isAuthenticated(name)){
} else if (PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "email_confirm");
} else {
if (!data.isAuthAvailable(name)) {
m._(player, "login_msg");
} else {
m._(player, "reg_email_msg");
}
if (!data.isAuthAvailable(name)) {
m._(player, "login_msg");
} else {
m._(player, "reg_email_msg");
}
}
}
if(args[0].equalsIgnoreCase("recovery")) {
if (args.length != 2) {
m._(player, "usage_email_recovery");
return true;
}
if (plugin.mail == null) {
m._(player, "error");
return true;
}
if (data.isAuthAvailable(name)) {
if (PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "logged_in");
return true;
}
try {
RandomString rand = new RandomString(Settings.getRecoveryPassLength);
String thePass = rand.nextString();
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, name);
PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name);
} else if (data.isAuthAvailable(name)) {
auth = data.getAuth(name);
} else {
m._(player, "unknown_user");
return true;
}
if (Settings.getmailAccount.equals("") || Settings.getmailAccount.isEmpty()) {
m._(player, "error");
return true;
}
if (!args[1].equalsIgnoreCase(auth.getEmail()) || args[1].equalsIgnoreCase("your@email.com") || auth.getEmail().equalsIgnoreCase("your@email.com")) {
m._(player, "email_invalid");
return true;
}
final String finalhashnew = hashnew;
final PlayerAuth finalauth = auth;
if (data instanceof Thread) {
finalauth.setHash(hashnew);
data.updatePassword(auth);
} else {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
finalauth.setHash(finalhashnew);
data.updatePassword(finalauth);
}
});
}
plugin.mail.main(auth, thePass);
m._(player, "email_send");
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m._(sender, "error");
} catch (NoClassDefFoundError ncdfe) {
ConsoleLogger.showError(ncdfe.getMessage());
m._(sender, "error");
}
} else {
m._(player, "reg_email_msg");
}
if (args[0].equalsIgnoreCase("recovery")) {
if (args.length != 2) {
m._(player, "usage_email_recovery");
return true;
}
if (plugin.mail == null) {
m._(player, "error");
return true;
}
if (data.isAuthAvailable(name)) {
if (PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "logged_in");
return true;
}
try {
RandomString rand = new RandomString(
Settings.getRecoveryPassLength);
String thePass = rand.nextString();
String hashnew = PasswordSecurity.getHash(
Settings.getPasswordHash, thePass, name);
PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name);
} else if (data.isAuthAvailable(name)) {
auth = data.getAuth(name);
} else {
m._(player, "unknown_user");
return true;
}
if (Settings.getmailAccount.equals("")
|| Settings.getmailAccount.isEmpty()) {
m._(player, "error");
return true;
}
if (!args[1].equalsIgnoreCase(auth.getEmail())
|| args[1].equalsIgnoreCase("your@email.com")
|| auth.getEmail().equalsIgnoreCase(
"your@email.com")) {
m._(player, "email_invalid");
return true;
}
final String finalhashnew = hashnew;
final PlayerAuth finalauth = auth;
if (data instanceof Thread) {
finalauth.setHash(hashnew);
data.updatePassword(auth);
} else {
Bukkit.getScheduler().runTaskAsynchronously(plugin,
new Runnable() {
@Override
public void run() {
finalauth.setHash(finalhashnew);
data.updatePassword(finalauth);
}
});
}
plugin.mail.main(auth, thePass);
m._(player, "email_send");
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m._(sender, "error");
} catch (NoClassDefFoundError ncdfe) {
ConsoleLogger.showError(ncdfe.getMessage());
m._(sender, "error");
}
} else {
m._(player, "reg_email_msg");
}
}
return true;
}

View File

@ -8,18 +8,18 @@ import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.settings.Messages;
public class LoginCommand implements CommandExecutor {
private AuthMe plugin;
private Messages m = Messages.getInstance();
public LoginCommand(AuthMe plugin) {
this.plugin = plugin;
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, final String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
final String[] args) {
if (!(sender instanceof Player)) {
return true;
}
@ -27,15 +27,15 @@ public class LoginCommand implements CommandExecutor {
final Player player = (Player) sender;
if (args.length == 0) {
m._(player, "usage_log");
m._(player, "usage_log");
return true;
}
if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
m._(player, "no_perm");
m._(player, "no_perm");
return true;
}
plugin.management.performLogin(player, args[0], false);
plugin.management.performLogin(player, args[0], false);
return true;
}
}

View File

@ -27,7 +27,6 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class LogoutCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
@ -42,13 +41,14 @@ public class LogoutCommand implements CommandExecutor {
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm");
m._(sender, "no_perm");
return true;
}
@ -56,7 +56,7 @@ public class LogoutCommand implements CommandExecutor {
String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "not_logged_in");
m._(player, "not_logged_in");
return true;
}
@ -72,46 +72,55 @@ public class LogoutCommand implements CommandExecutor {
database.setUnlogged(name);
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawnLoc);
Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player,
spawnLoc);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if(!tpEvent.isCancelled()) {
if (tpEvent.getTo() != null)
player.teleport(tpEvent.getTo());
if (!tpEvent.isCancelled()) {
if (tpEvent.getTo() != null) player.teleport(tpEvent.getTo());
}
}
if (LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().deleteLimboPlayer(name);
if (LimboCache.getInstance().hasLimboPlayer(name)) LimboCache
.getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player);
utils.setGroup(player, groupType.NOTLOGGEDIN);
if(Settings.protectInventoryBeforeLogInEnabled) {
player.getInventory().clear();
// create cache file for handling lost of inventories on unlogged in status
DataFileCache playerData = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(),LimboCache.getInstance().getLimboPlayer(name).getArmour());
playerBackup.createCache(name, playerData, LimboCache.getInstance().getLimboPlayer(name).getGroup(),LimboCache.getInstance().getLimboPlayer(name).getOperator(),LimboCache.getInstance().getLimboPlayer(name).isFlying());
if (Settings.protectInventoryBeforeLogInEnabled) {
player.getInventory().clear();
// create cache file for handling lost of inventories on unlogged in
// status
DataFileCache playerData = new DataFileCache(LimboCache
.getInstance().getLimboPlayer(name).getInventory(),
LimboCache.getInstance().getLimboPlayer(name).getArmour());
playerBackup.createCache(name, playerData, LimboCache.getInstance()
.getLimboPlayer(name).getGroup(), LimboCache.getInstance()
.getLimboPlayer(name).getOperator(), LimboCache
.getInstance().getLimboPlayer(name).isFlying());
}
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(
plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), interval));
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(
plugin, name, m._("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
try {
if (player.isInsideVehicle())
player.getVehicle().eject();
if (player.isInsideVehicle()) player.getVehicle().eject();
} catch (NullPointerException npe) {
}
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
if (Settings.applyBlindEffect) player.addPotionEffect(new PotionEffect(
PotionEffectType.BLINDNESS,
Settings.getRegistrationTimeout * 20, 2));
m._(player, "logout");
ConsoleLogger.info(player.getDisplayName() + " logged out");
if(plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged out!"));
if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] "
+ player.getName() + " logged out!"));
}
return true;
}

View File

@ -10,7 +10,6 @@ import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Messages;
/**
*
* @author stefano
@ -18,34 +17,37 @@ import fr.xephi.authme.settings.Messages;
public class PasspartuCommand implements CommandExecutor {
private Utils utils = Utils.getInstance();
public AuthMe plugin;
private Messages m = Messages.getInstance();
private Messages m = Messages.getInstance();
public PasspartuCommand(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm");
m._(sender, "no_perm");
return true;
}
if (PlayerCache.getInstance().isAuthenticated(sender.getName().toLowerCase())) {
if (PlayerCache.getInstance().isAuthenticated(
sender.getName().toLowerCase())) {
return true;
}
if ((sender instanceof Player) && args.length == 1) {
if(utils.readToken(args[0])) {
//bypass login!
plugin.management.performLogin((Player) sender, "dontneed", true);
return true;
}
sender.sendMessage("Time is expired or Token is Wrong!");
return true;
}
sender.sendMessage("usage: /passpartu token");
return true;
if ((sender instanceof Player) && args.length == 1) {
if (utils.readToken(args[0])) {
// bypass login!
plugin.management.performLogin((Player) sender, "dontneed",
true);
return true;
}
sender.sendMessage("Time is expired or Token is Wrong!");
return true;
}
sender.sendMessage("usage: /passpartu token");
return true;
}
}

View File

@ -11,61 +11,62 @@ import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class RegisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
public PlayerAuth auth;
public AuthMe plugin;
public PlayerAuth auth;
public AuthMe plugin;
public RegisterCommand(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead");
return true;
sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead");
return true;
}
if (args.length == 0) {
m._(sender, "usage_reg");
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm");
m._(sender, "no_perm");
return true;
}
final Player player = (Player) sender;
if(Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
if(Settings.doubleEmailCheck) {
if(args.length < 2) {
if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
if (Settings.doubleEmailCheck) {
if (args.length < 2) {
m._(player, "usage_reg");
return true;
}
if(!args[0].equals(args[1])) {
}
if (!args[0].equals(args[1])) {
m._(player, "usage_reg");
return true;
}
}
}
}
final String email = args[0];
if(!Settings.isEmailCorrect(email)) {
if (!Settings.isEmailCorrect(email)) {
m._(player, "email_invalid");
return true;
}
RandomString rand = new RandomString(Settings.getRecoveryPassLength);
final String thePass = rand.nextString();
}
RandomString rand = new RandomString(Settings.getRecoveryPassLength);
final String thePass = rand.nextString();
plugin.management.performRegister(player, thePass, email);
return true;
}
if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
if (args.length == 0
|| (Settings.getEnablePasswordVerifier && args.length < 2)) {
m._(player, "usage_reg");
return true;
}
if (args.length > 1 && Settings.getEnablePasswordVerifier)
if(!args[0].equals(args[1])) {
m._(player, "password_error");
return true;
}
if (args.length > 1 && Settings.getEnablePasswordVerifier) if (!args[0]
.equals(args[1])) {
m._(player, "password_error");
return true;
}
plugin.management.performRegister(player, args[0], "");
return true;
}

View File

@ -29,7 +29,6 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class UnregisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
@ -43,13 +42,14 @@ public class UnregisterCommand implements CommandExecutor {
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm");
m._(sender, "no_perm");
return true;
}
@ -57,80 +57,109 @@ public class UnregisterCommand implements CommandExecutor {
String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "not_logged_in");
m._(player, "not_logged_in");
return true;
}
if (args.length != 1) {
m._(player, "usage_unreg");
m._(player, "usage_unreg");
return true;
}
try {
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache
.getInstance().getAuth(name).getHash(), player.getName())) {
if (!database.removeAuth(name)) {
player.sendMessage("error");
return true;
}
if(Settings.isForcedRegistrationEnabled) {
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()) {
player.teleport(tpEvent.getTo());
if (Settings.isForcedRegistrationEnabled) {
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()) {
player.teleport(tpEvent.getTo());
}
}
player.getInventory().setContents(new ItemStack[36]);
player.getInventory().setArmorContents(new ItemStack[4]);
player.saveData();
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
if (!Settings.getRegisteredGroup.isEmpty())
Utils.getInstance().setGroup(player, groupType.UNREGISTERED);
player.getInventory().setContents(new ItemStack[36]);
player.getInventory().setArmorContents(new ItemStack[4]);
player.saveData();
PlayerCache.getInstance().removePlayer(
player.getName().toLowerCase());
if (!Settings.getRegisteredGroup.isEmpty()) Utils
.getInstance().setGroup(player,
groupType.UNREGISTERED);
LimboCache.getInstance().addLimboPlayer(player);
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
int id = sched.scheduleSyncDelayedTask(plugin,
new TimeoutTask(plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name)
.setTimeoutTaskId(id);
}
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("reg_msg"), interval)));
LimboCache
.getInstance()
.getLimboPlayer(name)
.setMessageTaskId(
sched.scheduleSyncDelayedTask(
plugin,
new MessageTask(plugin, name, m
._("reg_msg"), interval)));
m._(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
if(plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " unregistered himself!"));
ConsoleLogger.info(player.getDisplayName()
+ " unregistered himself");
if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName()
+ " unregistered himself!"));
}
return true;
}
if(!Settings.unRegisteredGroup.isEmpty()){
Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED);
}
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
// check if Player cache File Exist and delete it, preventing duplication of items
if(playerCache.doesCacheExist(name)) {
playerCache.removeCache(name);
}
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
m._(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
if(plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " 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.getInstance().setGroup(player,
Utils.groupType.UNREGISTERED);
}
PlayerCache.getInstance().removePlayer(
player.getName().toLowerCase());
// check if Player cache File Exist and delete it, preventing
// duplication of items
if (playerCache.doesCacheExist(name)) {
playerCache.removeCache(name);
}
if (Settings.applyBlindEffect) player
.addPotionEffect(new PotionEffect(
PotionEffectType.BLINDNESS,
Settings.getRegistrationTimeout * 20, 2));
m._(player, "unregistered");
ConsoleLogger.info(player.getDisplayName()
+ " unregistered himself");
if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName()
+ " 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 true;
} else {
m._(player, "wrong_pwd");
m._(player, "wrong_pwd");
}
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());

View File

@ -14,65 +14,69 @@ import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Settings;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class CrazyLoginConverter implements Converter {
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public CrazyLoginConverter (AuthMe instance, DataSource database, CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public CrazyLoginConverter(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public CrazyLoginConverter getInstance() {
return this;
}
public CrazyLoginConverter getInstance() {
return this;
}
private static String fileName;
private static File source;
private static String fileName;
private static File source;
@Override
public void run() {
fileName = Settings.crazyloginFileName;
@Override
public void run() {
fileName = Settings.crazyloginFileName;
try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
source = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + fileName);
if (!source.exists()) {
sender.sendMessage("Error while trying to import datas, please put " + fileName + " in AuthMe folder!");
sender.sendMessage("Error while trying to import datas, please put "
+ fileName + " in AuthMe folder!");
return;
}
source.createNewFile();
BufferedReader users = null;
String line;
BufferedReader users = null;
String line;
users = new BufferedReader(new FileReader(source));
while ((line = users.readLine()) != null) {
if (line.contains("|")) {
String[] args = line.split("\\|");
if (args.length < 2)
continue;
if (args[0].equalsIgnoreCase("name"))
continue;
if (line.contains("|")) {
String[] args = line.split("\\|");
if (args.length < 2) continue;
if (args[0].equalsIgnoreCase("name")) continue;
String player = args[0].toLowerCase();
String psw = args[1];
try {
if (player != null && psw != null) {
PlayerAuth auth = new PlayerAuth(player, psw, "127.0.0.1", System.currentTimeMillis());
PlayerAuth auth = new PlayerAuth(player, psw,
"127.0.0.1", System.currentTimeMillis());
database.saveAuth(auth);
}
} catch (Exception e) {}
}
} catch (Exception e) {
}
}
}
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) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
}

View File

@ -12,11 +12,10 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class FlatToSql implements Converter {
private static String tableName;
@ -31,73 +30,103 @@ public class FlatToSql implements Converter {
private static String columnEmail;
private static String columnLogged;
private static String columnID;
private static File source;
private static File output;
private static File source;
private static File output;
public FlatToSql() {
tableName = Settings.getMySQLTablename;
columnName = Settings.getMySQLColumnName;
columnPassword = Settings.getMySQLColumnPassword;
columnIp = Settings.getMySQLColumnIp;
columnLastLogin = Settings.getMySQLColumnLastLogin;
lastlocX = Settings.getMySQLlastlocX;
lastlocY = Settings.getMySQLlastlocY;
lastlocZ = Settings.getMySQLlastlocZ;
lastlocWorld = Settings.getMySQLlastlocWorld;
columnEmail = Settings.getMySQLColumnEmail;
columnLogged = Settings.getMySQLColumnLogged;
columnID = Settings.getMySQLColumnId;
}
public FlatToSql() {
tableName = Settings.getMySQLTablename;
columnName = Settings.getMySQLColumnName;
columnPassword = Settings.getMySQLColumnPassword;
columnIp = Settings.getMySQLColumnIp;
columnLastLogin = Settings.getMySQLColumnLastLogin;
lastlocX = Settings.getMySQLlastlocX;
lastlocY = Settings.getMySQLlastlocY;
lastlocZ = Settings.getMySQLlastlocZ;
lastlocWorld = Settings.getMySQLlastlocWorld;
columnEmail = Settings.getMySQLColumnEmail;
columnLogged = Settings.getMySQLColumnLogged;
columnID = Settings.getMySQLColumnId;
}
@Override
public void run() {
@Override
public void run() {
try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
source = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + "auths.db");
source.createNewFile();
output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql");
BufferedReader br = null;
BufferedWriter sql = null;
output = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + "authme.sql");
BufferedReader br = null;
BufferedWriter sql = null;
br = new BufferedReader(new FileReader(source));
sql = new BufferedWriter(new FileWriter(output));
String createDB = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ 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) DEFAULT 'world',"
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com',"
+ columnLogged + " SMALLINT NOT NULL DEFAULT '0',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));";
+ 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) DEFAULT 'world'," + columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged
+ " SMALLINT NOT NULL DEFAULT '0',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "));";
sql.write(createDB);
String line;
String newline;
while ((line = br.readLine()) != null) {
sql.newLine();
sql.newLine();
String[] args = line.split(":");
if (args.length == 4)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0.0, 0.0, 0.0, 'world', 'your@email.com', 0);";
else if (args.length == 7)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", 'world', 'your@email.com', 0);";
else if (args.length == 8)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', 'your@email.com', 0);";
else if (args.length == 9)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', '" + args[8] + "', 0);";
else
newline = "";
if (newline != "")
sql.write(newline);
if (args.length == 4) newline = "INSERT INTO " + tableName
+ "(" + columnName + "," + columnPassword + ","
+ columnIp + "," + columnLastLogin + "," + lastlocX
+ "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
+ "," + columnEmail + "," + columnLogged
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
+ args[2] + "', " + args[3]
+ ", 0.0, 0.0, 0.0, 'world', 'your@email.com', 0);";
else if (args.length == 7) newline = "INSERT INTO " + tableName
+ "(" + columnName + "," + columnPassword + ","
+ columnIp + "," + columnLastLogin + "," + lastlocX
+ "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
+ "," + columnEmail + "," + columnLogged
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
+ args[2] + "', " + args[3] + ", " + args[4] + ", "
+ args[5] + ", " + args[6]
+ ", 'world', 'your@email.com', 0);";
else if (args.length == 8) newline = "INSERT INTO " + tableName
+ "(" + columnName + "," + columnPassword + ","
+ columnIp + "," + columnLastLogin + "," + lastlocX
+ "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
+ "," + columnEmail + "," + columnLogged
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
+ args[2] + "', " + args[3] + ", " + args[4] + ", "
+ args[5] + ", " + args[6] + ", '" + args[7]
+ "', 'your@email.com', 0);";
else if (args.length == 9) newline = "INSERT INTO " + tableName
+ "(" + columnName + "," + columnPassword + ","
+ columnIp + "," + columnLastLogin + "," + lastlocX
+ "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
+ "," + columnEmail + "," + columnLogged
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
+ args[2] + "', " + args[3] + ", " + args[4] + ", "
+ args[5] + ", " + args[6] + ", '" + args[7] + "', '"
+ args[8] + "', 0);";
else newline = "";
if (newline != "") sql.write(newline);
}
sql.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) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
}

View File

@ -18,9 +18,8 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
public class FlatToSqlite implements Converter {
public CommandSender sender;
public FlatToSqlite(CommandSender sender) {
@ -37,13 +36,13 @@ public class FlatToSqlite implements Converter {
private static String lastlocZ;
private static String lastlocWorld;
private static String columnEmail;
private static File source;
private static String database;
private static String columnID;
private static Connection con;
private static File source;
private static String database;
private static String columnID;
private static Connection con;
@Override
public void run() {
@Override
public void run() {
database = Settings.getMySQLDatabase;
tableName = Settings.getMySQLTablename;
columnName = Settings.getMySQLColumnName;
@ -56,60 +55,77 @@ public class FlatToSqlite implements Converter {
lastlocWorld = Settings.getMySQLlastlocWorld;
columnEmail = Settings.getMySQLColumnEmail;
columnID = Settings.getMySQLColumnId;
ConsoleLogger.info("Converting FlatFile to SQLite ...");
if (new File(AuthMe.getInstance().getDataFolder() + File.separator + database + ".db").exists()) {
sender.sendMessage("The Database " + database + ".db can't be created cause the file already exist");
return;
ConsoleLogger.info("Converting FlatFile to SQLite ...");
if (new File(AuthMe.getInstance().getDataFolder() + File.separator
+ database + ".db").exists()) {
sender.sendMessage("The Database " + database
+ ".db can't be created cause the file already exist");
return;
}
try {
connect();
setup();
} catch (Exception e) {
ConsoleLogger.showError("Problem while trying to convert to sqlite !");
sender.sendMessage("Problem while trying to convert to sqlite !");
return;
}
try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
source.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(source));
String line;
int i = 1;
String newline;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length == 4)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0, 0, 0, 'world', 'your@email.com');";
else if (args.length == 7)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", 'world', 'your@email.com');";
else if (args.length == 8)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', 'your@email.com');";
else if (args.length == 9)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', '" + args[8] + "');";
else
newline = "";
if (newline != "")
saveAuth(newline);
i = i + 1;
}
br.close();
ConsoleLogger.info("The FlatFile has been converted to " + database + ".db file");
close();
sender.sendMessage("The FlatFile has been converted to " + database + ".db file");
return;
} catch (FileNotFoundException ex) {
connect();
setup();
} catch (Exception e) {
ConsoleLogger
.showError("Problem while trying to convert to sqlite !");
sender.sendMessage("Problem while trying to convert to sqlite !");
return;
}
try {
source = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + "auths.db");
source.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(source));
String line;
int i = 1;
String newline;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length == 4) newline = "INSERT INTO " + tableName
+ " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
+ "', '" + args[2] + "', " + args[3]
+ ", 0, 0, 0, 'world', 'your@email.com');";
else if (args.length == 7) newline = "INSERT INTO " + tableName
+ " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
+ "', '" + args[2] + "', " + args[3] + ", " + args[4]
+ ", " + args[5] + ", " + args[6]
+ ", 'world', 'your@email.com');";
else if (args.length == 8) newline = "INSERT INTO " + tableName
+ " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
+ "', '" + args[2] + "', " + args[3] + ", " + args[4]
+ ", " + args[5] + ", " + args[6] + ", '" + args[7]
+ "', 'your@email.com');";
else if (args.length == 9) newline = "INSERT INTO " + tableName
+ " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
+ "', '" + args[2] + "', " + args[3] + ", " + args[4]
+ ", " + args[5] + ", " + args[6] + ", '" + args[7]
+ "', '" + args[8] + "');";
else newline = "";
if (newline != "") saveAuth(newline);
i = i + 1;
}
br.close();
ConsoleLogger.info("The FlatFile has been converted to " + database
+ ".db file");
close();
sender.sendMessage("The FlatFile has been converted to " + database
+ ".db file");
return;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
}
sender.sendMessage("Errors appears while trying to convert to SQLite");
return;
}
private synchronized static void connect() throws ClassNotFoundException, SQLException {
}
private synchronized static void connect() throws ClassNotFoundException,
SQLException {
Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded");
con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"+database+".db");
con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"
+ database + ".db");
}
private synchronized static void setup() throws SQLException {
@ -118,18 +134,19 @@ public class FlatToSqlite implements Converter {
try {
st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ columnID + " INTEGER AUTO_INCREMENT,"
+ columnName + " VARCHAR(255) NOT NULL UNIQUE,"
+ columnPassword + " VARCHAR(255) NOT NULL,"
+ columnIp + " VARCHAR(40) NOT NULL,"
+ columnLastLogin + " BIGINT,"
+ lastlocX + " smallint(6) DEFAULT '0',"
+ lastlocY + " smallint(6) DEFAULT '0',"
+ lastlocZ + " smallint(6) DEFAULT '0',"
+ lastlocWorld + " VARCHAR(255) DEFAULT 'world',"
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
+ columnID + " INTEGER AUTO_INCREMENT," + columnName
+ " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ " VARCHAR(255) NOT NULL," + columnIp
+ " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT,"
+ lastlocX + " smallint(6) DEFAULT '0'," + lastlocY
+ " smallint(6) DEFAULT '0'," + lastlocZ
+ " smallint(6) DEFAULT '0'," + lastlocWorld
+ " VARCHAR(255) DEFAULT 'world'," + columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "));");
rs = con.getMetaData().getColumns(null, null, tableName,
columnPassword);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnPassword + " VARCHAR(255) NOT NULL;");
@ -141,7 +158,8 @@ public class FlatToSqlite implements Converter {
+ columnIp + " VARCHAR(40) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
rs = con.getMetaData().getColumns(null, null, tableName,
columnLastLogin);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLastLogin + " BIGINT;");
@ -149,19 +167,29 @@ public class FlatToSqlite implements Converter {
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " smallint(6) NOT NULL DEFAULT '0'; "
+ "ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " smallint(6) NOT NULL DEFAULT '0'; "
+ "ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " smallint(6) NOT NULL DEFAULT '0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocX + " smallint(6) NOT NULL DEFAULT '0'; "
+ "ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocY + " smallint(6) NOT NULL DEFAULT '0'; "
+ "ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocZ + " smallint(6) NOT NULL DEFAULT '0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
rs = con.getMetaData().getColumns(null, null, tableName,
lastlocWorld);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER " + lastlocZ + ";");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER "
+ lastlocZ + ";");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
rs = con.getMetaData().getColumns(null, null, tableName,
columnEmail);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com';");
}
} finally {
close(rs);
@ -169,21 +197,21 @@ public class FlatToSqlite implements Converter {
}
ConsoleLogger.info("SQLite Setup finished");
}
private static synchronized boolean saveAuth(String s) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement(s);
pst.executeUpdate();
} catch (SQLException e) {
ConsoleLogger.showError(e.getMessage());
return false;
} finally {
close(pst);
}
return true;
PreparedStatement pst = null;
try {
pst = con.prepareStatement(s);
pst.executeUpdate();
} catch (SQLException e) {
ConsoleLogger.showError(e.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
private static void close(Statement st) {
if (st != null) {
try {
@ -203,7 +231,7 @@ public class FlatToSqlite implements Converter {
}
}
}
public synchronized static void close() {
try {
con.close();

View File

@ -20,86 +20,91 @@ import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class RakamakConverter implements Converter {
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public RakamakConverter (AuthMe instance, DataSource database, CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public RakamakConverter(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public RakamakConverter getInstance() {
return this;
}
public RakamakConverter getInstance() {
return this;
}
private static Boolean useIP;
private static String fileName;
private static String ipFileName;
private static File source;
private static File ipfiles;
private static Boolean useIP;
private static String fileName;
private static String ipFileName;
private static File source;
private static File ipfiles;
@Override
public void run() {
HashAlgorithm hash = Settings.getPasswordHash;
useIP = Settings.rakamakUseIp;
fileName = Settings.rakamakUsers;
ipFileName = Settings.rakamakUsersIp;
HashMap<String, String> playerIP = new HashMap<String, String>();
HashMap<String, String> playerPSW = new HashMap<String, String>();
@Override
public void run() {
HashAlgorithm hash = Settings.getPasswordHash;
useIP = Settings.rakamakUseIp;
fileName = Settings.rakamakUsers;
ipFileName = Settings.rakamakUsersIp;
HashMap<String, String> playerIP = new HashMap<String, String>();
HashMap<String, String> playerPSW = new HashMap<String, String>();
try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
ipfiles = new File(AuthMe.getInstance().getDataFolder() + File.separator + ipFileName);
source = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + fileName);
ipfiles = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + ipFileName);
source.createNewFile();
ipfiles.createNewFile();
BufferedReader users = null;
BufferedReader ipFile = null;
BufferedReader users = null;
BufferedReader ipFile = null;
ipFile = new BufferedReader(new FileReader(ipfiles));
String line;
String line;
if (useIP) {
String tempLine;
while ((tempLine = ipFile.readLine()) != null) {
if (tempLine.contains("=")) {
String[] args = tempLine.split("=");
playerIP.put(args[0], args[1]);
}
}
String tempLine;
while ((tempLine = ipFile.readLine()) != null) {
if (tempLine.contains("=")) {
String[] args = tempLine.split("=");
playerIP.put(args[0], args[1]);
}
}
}
ipFile.close();
users = new BufferedReader(new FileReader(source));
while ((line = users.readLine()) != null) {
if (line.contains("=")) {
String[] arguments = line.split("=");
try {
playerPSW.put(arguments[0],PasswordSecurity.getHash(hash, arguments[1], arguments[0]));
} catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
}
}
if (line.contains("=")) {
String[] arguments = line.split("=");
try {
playerPSW.put(arguments[0], PasswordSecurity.getHash(
hash, arguments[1], arguments[0]));
} catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
}
}
}
users.close();
for (Entry<String, String> m : playerPSW.entrySet()) {
String player = m.getKey();
String psw = playerPSW.get(player);
String ip;
if (useIP) {
ip = playerIP.get(player);
} else {
ip = "127.0.0.1";
}
PlayerAuth auth = new PlayerAuth(player, psw, ip, System.currentTimeMillis());
if (PasswordSecurity.userSalt.containsKey(player))
auth.setSalt(PasswordSecurity.userSalt.get(player));
database.saveAuth(auth);
}
ConsoleLogger.info("Rakamak database has been imported correctly");
sender.sendMessage("Rakamak database has been imported correctly");
for (Entry<String, String> m : playerPSW.entrySet()) {
String player = m.getKey();
String psw = playerPSW.get(player);
String ip;
if (useIP) {
ip = playerIP.get(player);
} else {
ip = "127.0.0.1";
}
PlayerAuth auth = new PlayerAuth(player, psw, ip,
System.currentTimeMillis());
if (PasswordSecurity.userSalt.containsKey(player)) auth
.setSalt(PasswordSecurity.userSalt.get(player));
database.saveAuth(auth);
}
ConsoleLogger.info("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");
@ -107,5 +112,5 @@ public class RakamakConverter implements Converter {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Error IOException");
}
}
}
}

View File

@ -10,14 +10,14 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
public class RoyalAuthConverter implements Converter {
public AuthMe plugin;
private DataSource data;
public RoyalAuthConverter(AuthMe plugin) {
this.plugin = plugin;
this.data = plugin.database;
}
public AuthMe plugin;
private DataSource data;
public RoyalAuthConverter(AuthMe plugin) {
this.plugin = plugin;
this.data = plugin.database;
}
@Override
public void run() {
@ -25,16 +25,19 @@ public class RoyalAuthConverter implements Converter {
try {
String name = o.getName().toLowerCase();
String separator = File.separator;
File file = new File("." + separator + "plugins" + separator + "RoyalAuth" + separator + "userdata" + separator + name + ".yml");
if (data.isAuthAvailable(name))
continue;
if (!file.exists())
continue;
File file = new File("." + separator + "plugins" + separator
+ "RoyalAuth" + separator + "userdata" + separator
+ name + ".yml");
if (data.isAuthAvailable(name)) continue;
if (!file.exists()) continue;
RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file);
PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com", o.getName());
PlayerAuth auth = new PlayerAuth(name, ra.getHash(),
"127.0.0.1", ra.getLastLogin(), "your@email.com",
o.getName());
data.saveAuth(auth);
} catch (Exception e) {
ConsoleLogger.showError("Error while trying to import "+ o.getName() + " RoyalAuth datas");
ConsoleLogger.showError("Error while trying to import "
+ o.getName() + " RoyalAuth datas");
}
}
}

View File

@ -6,17 +6,17 @@ import fr.xephi.authme.settings.CustomConfiguration;
public class RoyalAuthYamlReader extends CustomConfiguration {
public RoyalAuthYamlReader(File file) {
super(file);
public RoyalAuthYamlReader(File file) {
super(file);
load();
save();
}
}
public long getLastLogin() {
return getLong("timestamps.quit");
}
public String getHash() {
return getString("login.password");
}
public long getLastLogin() {
return getLong("timestamps.quit");
}
public String getHash() {
return getString("login.password");
}
}

View File

@ -21,59 +21,63 @@ import fr.xephi.authme.datasource.DataSource;
public class newxAuthToFlat {
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public newxAuthToFlat(AuthMe instance, DataSource database, CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public newxAuthToFlat(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public boolean convert() {
if (instance.getServer().getPluginManager().getPlugin("xAuth") == null) {
sender.sendMessage("[AuthMe] xAuth plugin not found");
return false;
}
if (!(new File("./plugins/xAuth/xAuth.h2.db").exists())) {
sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data...");
}
List<Integer> players = getXAuthPlayers();
if (players == null || players.isEmpty()) {
sender.sendMessage("[AuthMe] Error while import xAuthPlayers");
return false;
}
sender.sendMessage("[AuthMe] Starting import...");
try {
for (int id : players) {
String pl = getIdPlayer(id);
String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth);
}
}
sender.sendMessage("[AuthMe] Successfull convert from xAuth database");
} catch (Exception e) {
sender.sendMessage("[AuthMe] An error has been thrown while import xAuth database, the import hadn't fail but can be not complete ");
}
return true;
}
public boolean convert() {
if (instance.getServer().getPluginManager().getPlugin("xAuth") == null) {
sender.sendMessage("[AuthMe] xAuth plugin not found");
return false;
}
if (!(new File("./plugins/xAuth/xAuth.h2.db").exists())) {
sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data...");
}
List<Integer> players = getXAuthPlayers();
if (players == null || players.isEmpty()) {
sender.sendMessage("[AuthMe] Error while import xAuthPlayers");
return false;
}
sender.sendMessage("[AuthMe] Starting import...");
try {
for (int id : players) {
String pl = getIdPlayer(id);
String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0,
"your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth);
}
}
sender.sendMessage("[AuthMe] Successfull convert from xAuth database");
} catch (Exception e) {
sender.sendMessage("[AuthMe] An error has been thrown while import xAuth database, the import hadn't fail but can be not complete ");
}
return true;
}
public String getIdPlayer(int id) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
public String getIdPlayer(int id) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
String sql = String.format(
"SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
if (!rs.next())
return null;
if (!rs.next()) return null;
realPass = rs.getString("playername").toLowerCase();
} catch (SQLException e) {
xAuthLog.severe("Failed to retrieve name for account: " + id, e);
@ -81,20 +85,21 @@ public class newxAuthToFlat {
} finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);
}
return realPass;
}
return realPass;
}
public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT * FROM `%s`",
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin()
.getDatabaseController().getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
while (rs.next()) {
xP.add(rs.getInt("id"));
}
} catch (SQLException e) {
@ -103,29 +108,32 @@ public class newxAuthToFlat {
} finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);
}
return xP;
}
return xP;
}
public String getPassword(int accountId) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
public String getPassword(int accountId) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
String sql = String.format(
"SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql);
ps.setInt(1, accountId);
rs = ps.executeQuery();
if (!rs.next())
return null;
if (!rs.next()) return null;
realPass = rs.getString("password");
} catch (SQLException e) {
xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e);
xAuthLog.severe("Failed to retrieve password hash for account: "
+ accountId, e);
return null;
} finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);
}
return realPass;
}
return realPass;
}
}

View File

@ -19,66 +19,69 @@ import fr.xephi.authme.api.API;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class oldxAuthToFlat {
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public AuthMe instance;
public DataSource database;
public CommandSender sender;
public oldxAuthToFlat(AuthMe instance, DataSource database, CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public oldxAuthToFlat(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance;
this.database = database;
this.sender = sender;
}
public boolean convert() {
if (instance.getServer().getPluginManager().getPlugin("xAuth") == null) {
sender.sendMessage("[AuthMe] xAuth plugin not found");
return false;
}
if (!(new File("./plugins/xAuth/xAuth.h2.db").exists())) {
sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data...");
}
List<Integer> players = getXAuthPlayers();
if (players == null || players.isEmpty()) {
sender.sendMessage("[AuthMe] Error while import xAuthPlayers");
return false;
}
sender.sendMessage("[AuthMe] Starting import...");
try {
for (int id : players) {
String pl = getIdPlayer(id);
String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth);
}
}
sender.sendMessage("[AuthMe] Successfull convert from xAuth database");
} catch (Exception e) {
sender.sendMessage("[AuthMe] An error has been thrown while import xAuth database, the import hadn't fail but can be not complete ");
}
return true;
}
public boolean convert() {
if (instance.getServer().getPluginManager().getPlugin("xAuth") == null) {
sender.sendMessage("[AuthMe] xAuth plugin not found");
return false;
}
if (!(new File("./plugins/xAuth/xAuth.h2.db").exists())) {
sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data...");
}
List<Integer> players = getXAuthPlayers();
if (players == null || players.isEmpty()) {
sender.sendMessage("[AuthMe] Error while import xAuthPlayers");
return false;
}
sender.sendMessage("[AuthMe] Starting import...");
try {
for (int id : players) {
String pl = getIdPlayer(id);
String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0,
"your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth);
}
}
sender.sendMessage("[AuthMe] Successfull convert from xAuth database");
} catch (Exception e) {
sender.sendMessage("[AuthMe] An error has been thrown while import xAuth database, the import hadn't fail but can be not complete ");
}
return true;
}
public String getIdPlayer(int id) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
public String getIdPlayer(int id) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
String sql = String.format(
"SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
if (!rs.next())
return null;
if (!rs.next()) return null;
realPass = rs.getString("playername").toLowerCase();
} catch (SQLException e) {
xAuthLog.severe("Failed to retrieve name for account: " + id, e);
@ -86,20 +89,21 @@ public class oldxAuthToFlat {
} finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);
}
return realPass;
}
return realPass;
}
public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT * FROM `%s`",
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin()
.getDatabaseController().getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
while (rs.next()) {
xP.add(rs.getInt("id"));
}
} catch (SQLException e) {
@ -108,29 +112,32 @@ public class oldxAuthToFlat {
} finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);
}
return xP;
}
return xP;
}
public String getPassword(int accountId) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
public String getPassword(int accountId) {
String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
String sql = String.format(
"SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql);
ps.setInt(1, accountId);
rs = ps.executeQuery();
if (!rs.next())
return null;
if (!rs.next()) return null;
realPass = rs.getString("password");
} catch (SQLException e) {
xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e);
xAuthLog.severe("Failed to retrieve password hash for account: "
+ accountId, e);
return null;
} finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);
}
return realPass;
}
return realPass;
}
}

View File

@ -12,7 +12,8 @@ public class vAuthConverter implements Converter {
public DataSource database;
public CommandSender sender;
public vAuthConverter(AuthMe plugin, DataSource database, CommandSender sender) {
public vAuthConverter(AuthMe plugin, DataSource database,
CommandSender sender) {
this.plugin = plugin;
this.database = database;
this.sender = sender;

View File

@ -15,23 +15,25 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
public class vAuthFileReader {
public AuthMe plugin;
public DataSource database;
public CommandSender sender;
public vAuthFileReader(AuthMe plugin, DataSource database, CommandSender sender) {
public vAuthFileReader(AuthMe plugin, DataSource database,
CommandSender sender) {
this.plugin = plugin;
this.database = database;
this.sender = sender;
}
public void convert() throws IOException {
final File file = new File(plugin.getDataFolder().getParent() + "/vAuth/passwords.yml");
final File file = new File(plugin.getDataFolder().getParent()
+ "/vAuth/passwords.yml");
Scanner scanner = null;
try {
scanner = new Scanner(file);
while(scanner.hasNextLine()) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String name = line.split(": ")[0];
String password = line.split(": ")[1];
@ -39,29 +41,34 @@ public class vAuthFileReader {
if (isUUIDinstance(password)) {
String pname = null;
try {
pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName();
pname = Bukkit.getOfflinePlayer(UUID.fromString(name))
.getName();
} catch (Exception e) {
pname = getName(UUID.fromString(name));
} catch (NoSuchMethodError e) {
pname = getName(UUID.fromString(name));
}
if (pname == null) continue;
auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname);
auth = new PlayerAuth(pname.toLowerCase(), password,
"127.0.0.1", System.currentTimeMillis(),
"your@email.com", pname);
} else {
auth = new PlayerAuth(name, password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", API.getPlayerRealName(name));
auth = new PlayerAuth(name, password, "127.0.0.1",
System.currentTimeMillis(), "your@email.com",
API.getPlayerRealName(name));
}
if (auth != null) database.saveAuth(auth);
}
} catch (Exception e) {
}
}
private boolean isUUIDinstance(String s) {
if (String.valueOf(s.charAt(8)).equalsIgnoreCase("-")) return true;
return true;
}
private String getName(UUID uuid) {
try {
for (OfflinePlayer op : Bukkit.getOfflinePlayers()) {

View File

@ -10,8 +10,9 @@ public class xAuthConverter implements Converter {
public AuthMe plugin;
public DataSource database;
public CommandSender sender;
public xAuthConverter(AuthMe plugin, DataSource database, CommandSender sender) {
public xAuthConverter(AuthMe plugin, DataSource database,
CommandSender sender) {
this.plugin = plugin;
this.database = database;
this.sender = sender;
@ -21,12 +22,14 @@ public class xAuthConverter implements Converter {
public void run() {
try {
Class.forName("com.cypherx.xauth.xAuth");
oldxAuthToFlat converter = new oldxAuthToFlat(plugin, database, sender);
oldxAuthToFlat converter = new oldxAuthToFlat(plugin, database,
sender);
converter.convert();
} catch (ClassNotFoundException e) {
try {
Class.forName("de.luricos.bukkit.xAuth.xAuth");
newxAuthToFlat converter = new newxAuthToFlat(plugin, database, sender);
newxAuthToFlat converter = new newxAuthToFlat(plugin, database,
sender);
converter.convert();
} catch (ClassNotFoundException ce) {
sender.sendMessage("xAuth has not been found, please put xAuth.jar in your plugin folder and restart!");

View File

@ -9,7 +9,6 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
public class CacheDataSource implements DataSource {
private DataSource source;
@ -17,24 +16,23 @@ public class CacheDataSource implements DataSource {
private HashMap<String, PlayerAuth> cache = new HashMap<String, PlayerAuth>();
public CacheDataSource(AuthMe plugin, DataSource source) {
this.plugin = plugin;
this.plugin = plugin;
this.source = source;
}
@Override
public synchronized boolean isAuthAvailable(String user) {
if (cache.containsKey(user.toLowerCase())) return true;
return source.isAuthAvailable(user.toLowerCase());
if (cache.containsKey(user.toLowerCase())) return true;
return source.isAuthAvailable(user.toLowerCase());
}
@Override
public synchronized PlayerAuth getAuth(String user) {
if(cache.containsKey(user.toLowerCase())) {
if (cache.containsKey(user.toLowerCase())) {
return cache.get(user.toLowerCase());
} else {
PlayerAuth auth = source.getAuth(user.toLowerCase());
if (auth != null)
cache.put(user.toLowerCase(), auth);
if (auth != null) cache.put(user.toLowerCase(), auth);
return auth;
}
}
@ -51,8 +49,8 @@ public class CacheDataSource implements DataSource {
@Override
public synchronized boolean updatePassword(PlayerAuth auth) {
if (source.updatePassword(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase()))
cache.get(auth.getNickname()).setHash(auth.getHash());
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
auth.getNickname()).setHash(auth.getHash());
return true;
}
return false;
@ -61,10 +59,10 @@ public class CacheDataSource implements DataSource {
@Override
public boolean updateSession(PlayerAuth auth) {
if (source.updateSession(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setIp(auth.getIp());
cache.get(auth.getNickname()).setLastLogin(auth.getLastLogin());
}
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setIp(auth.getIp());
cache.get(auth.getNickname()).setLastLogin(auth.getLastLogin());
}
return true;
}
return false;
@ -73,12 +71,12 @@ public class CacheDataSource implements DataSource {
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
if (source.updateQuitLoc(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setQuitLocX(auth.getQuitLocX());
cache.get(auth.getNickname()).setQuitLocY(auth.getQuitLocY());
cache.get(auth.getNickname()).setQuitLocZ(auth.getQuitLocZ());
cache.get(auth.getNickname()).setWorld(auth.getWorld());
}
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setQuitLocX(auth.getQuitLocX());
cache.get(auth.getNickname()).setQuitLocY(auth.getQuitLocY());
cache.get(auth.getNickname()).setQuitLocZ(auth.getQuitLocZ());
cache.get(auth.getNickname()).setWorld(auth.getWorld());
}
return true;
}
return false;
@ -94,7 +92,7 @@ public class CacheDataSource implements DataSource {
int cleared = source.purgeDatabase(until);
if (cleared > 0) {
for (PlayerAuth auth : cache.values()) {
if(auth.getLastLogin() < until) {
if (auth.getLastLogin() < until) {
cache.remove(auth.getNickname());
}
}
@ -107,7 +105,7 @@ public class CacheDataSource implements DataSource {
List<String> cleared = source.autoPurgeDatabase(until);
if (cleared.size() > 0) {
for (PlayerAuth auth : cache.values()) {
if(auth.getLastLogin() < until) {
if (auth.getLastLogin() < until) {
cache.remove(auth.getNickname());
}
}
@ -131,88 +129,88 @@ public class CacheDataSource implements DataSource {
@Override
public void reload() {
cache.clear();
source.reload();
for (Player player : plugin.getServer().getOnlinePlayers()) {
String user = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(user)) {
try {
cache.clear();
source.reload();
for (Player player : plugin.getServer().getOnlinePlayers()) {
String user = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(user)) {
try {
PlayerAuth auth = source.getAuth(user);
cache.put(user, auth);
} catch (NullPointerException npe) {
}
} catch (NullPointerException npe) {
}
}
}
}
}
}
@Override
public synchronized boolean updateEmail(PlayerAuth auth) {
if(source.updateEmail(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase()))
cache.get(auth.getNickname()).setEmail(auth.getEmail());
return true;
}
return false;
}
@Override
public synchronized boolean updateEmail(PlayerAuth auth) {
if (source.updateEmail(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
auth.getNickname()).setEmail(auth.getEmail());
return true;
}
return false;
}
@Override
public synchronized boolean updateSalt(PlayerAuth auth) {
if(source.updateSalt(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase()))
cache.get(auth.getNickname()).setSalt(auth.getSalt());
return true;
}
return false;
}
@Override
public synchronized boolean updateSalt(PlayerAuth auth) {
if (source.updateSalt(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
auth.getNickname()).setSalt(auth.getSalt());
return true;
}
return false;
}
@Override
public synchronized List<String> getAllAuthsByName(PlayerAuth auth) {
return source.getAllAuthsByName(auth);
}
@Override
public synchronized List<String> getAllAuthsByName(PlayerAuth auth) {
return source.getAllAuthsByName(auth);
}
@Override
public synchronized List<String> getAllAuthsByIp(String ip) {
return source.getAllAuthsByIp(ip);
}
@Override
public synchronized List<String> getAllAuthsByIp(String ip) {
return source.getAllAuthsByIp(ip);
}
@Override
public synchronized List<String> getAllAuthsByEmail(String email) {
return source.getAllAuthsByEmail(email);
}
@Override
public synchronized List<String> getAllAuthsByEmail(String email) {
return source.getAllAuthsByEmail(email);
}
@Override
public synchronized void purgeBanned(List<String> banned) {
source.purgeBanned(banned);
for (PlayerAuth auth : cache.values()) {
if (banned.contains(auth.getNickname())) {
cache.remove(auth.getNickname());
}
}
}
@Override
public synchronized void purgeBanned(List<String> banned) {
source.purgeBanned(banned);
for (PlayerAuth auth : cache.values()) {
if (banned.contains(auth.getNickname())) {
cache.remove(auth.getNickname());
}
}
}
@Override
public DataSourceType getType() {
return source.getType();
}
@Override
public DataSourceType getType() {
return source.getType();
}
@Override
public boolean isLogged(String user) {
return source.isLogged(user);
}
@Override
public boolean isLogged(String user) {
return source.isLogged(user);
}
@Override
public void setLogged(String user) {
source.setLogged(user);
}
@Override
public void setLogged(String user) {
source.setLogged(user);
}
@Override
public void setUnlogged(String user) {
source.setUnlogged(user);
}
@Override
public void setUnlogged(String user) {
source.setUnlogged(user);
}
@Override
public void purgeLogged() {
source.purgeLogged();
}
@Override
public void purgeLogged() {
source.purgeLogged();
}
}

View File

@ -4,7 +4,6 @@ import java.util.List;
import fr.xephi.authme.cache.auth.PlayerAuth;
public interface DataSource {
public enum DataSourceType {
@ -23,7 +22,7 @@ public interface DataSource {
boolean updatePassword(PlayerAuth auth);
int purgeDatabase(long until);
List<String> autoPurgeDatabase(long until);
boolean removeAuth(String user);
@ -47,15 +46,15 @@ public interface DataSource {
void reload();
void purgeBanned(List<String> banned);
DataSourceType getType();
boolean isLogged(String user);
void setLogged(String user);
void setUnlogged(String user);
void purgeLogged();
}

View File

@ -17,36 +17,35 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.PlayersLogs;
import fr.xephi.authme.settings.Settings;
public class FlatFileThread extends Thread implements DataSource {
/* file layout:
*
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:LASTPOSWORLD:EMAIL
*
/*
* file layout:
*
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:
* LASTPOSWORLD:EMAIL
*
* Old but compatible:
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:LASTPOSWORLD
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS
* PLAYERNAME:HASHSUM:IP
* PLAYERNAME:HASHSUM
*
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY
* :LASTPOSZ:LASTPOSWORLD PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS
* PLAYERNAME:HASHSUM:IP PLAYERNAME:HASHSUM
*/
private File source;
public void run() {
source = new File(Settings.AUTH_FILE);
try {
source.createNewFile();
} catch (IOException e) {
source.createNewFile();
} catch (IOException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
.getPluginManager().disablePlugin(AuthMe.getInstance());
return;
}
}
}
@Override
@ -86,7 +85,11 @@ public class FlatFileThread extends Thread implements DataSource {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(source, true));
bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":" + auth.getWorld() + ":" + auth.getEmail() + "\n");
bw.write(auth.getNickname() + ":" + auth.getHash() + ":"
+ auth.getIp() + ":" + auth.getLastLogin() + ":"
+ auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":"
+ auth.getQuitLocZ() + ":" + auth.getWorld() + ":"
+ auth.getEmail() + "\n");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
@ -114,28 +117,51 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
}
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], 0, 0, 0, 0, "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
}
break;
}
}
@ -172,26 +198,49 @@ public class FlatFileThread extends Thread implements DataSource {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 4: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break;
}
}
break;
}
@ -215,9 +264,9 @@ public class FlatFileThread extends Thread implements DataSource {
return true;
}
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
@ -228,7 +277,11 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), auth.getEmail(), API.getPlayerRealName(args[0]));
newAuth = new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]), auth.getQuitLocX(),
auth.getQuitLocY(), auth.getQuitLocZ(),
auth.getWorld(), auth.getEmail(),
API.getPlayerRealName(args[0]));
break;
}
}
@ -278,7 +331,7 @@ public class FlatFileThread extends Thread implements DataSource {
} catch (IOException ex) {
}
}
}
}
}
@Override
@ -428,17 +481,40 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(user)) {
switch (args.length) {
case 2:
return new PlayerAuth(args[0], args[1], "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1],
"198.18.0.1", 0, "your@email.com",
API.getPlayerRealName(args[0]));
case 3:
return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2], 0,
"your@email.com",
API.getPlayerRealName(args[0]));
case 4:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]), "your@email.com",
API.getPlayerRealName(args[0]));
case 7:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "unavailableworld", "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]),
"unavailableworld", "your@email.com",
API.getPlayerRealName(args[0]));
case 8:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
case 9:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
}
}
}
@ -467,49 +543,54 @@ public class FlatFileThread extends Thread implements DataSource {
public void reload() {
}
@Override
public boolean updateEmail(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line = "";
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], auth.getEmail(), API.getPlayerRealName(args[0]));
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
removeAuth(auth.getNickname());
saveAuth(newAuth);
return true;
}
@Override
public boolean updateEmail(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line = "";
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
auth.getEmail(), API.getPlayerRealName(args[0]));
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
removeAuth(auth.getNickname());
saveAuth(newAuth);
return true;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
return false;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
return false;
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
BufferedReader br = null;
List<String> countIp = new ArrayList<String>();
try {
@ -535,11 +616,11 @@ public class FlatFileThread extends Thread implements DataSource {
} catch (IOException ex) {
}
}
}
}
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
@Override
public List<String> getAllAuthsByIp(String ip) {
BufferedReader br = null;
List<String> countIp = new ArrayList<String>();
try {
@ -566,10 +647,10 @@ public class FlatFileThread extends Thread implements DataSource {
}
}
}
}
}
@Override
public List<String> getAllAuthsByEmail(String email) {
@Override
public List<String> getAllAuthsByEmail(String email) {
BufferedReader br = null;
List<String> countEmail = new ArrayList<String>();
try {
@ -596,10 +677,10 @@ public class FlatFileThread extends Thread implements DataSource {
}
}
}
}
}
@Override
public void purgeBanned(List<String> banned) {
@Override
public void purgeBanned(List<String> banned) {
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> lines = new ArrayList<String>();
@ -609,11 +690,12 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
try {
if (banned.contains(args[0])) {
lines.add(line);
}
} catch (NullPointerException npe) {}
catch (ArrayIndexOutOfBoundsException aioobe) {}
if (banned.contains(args[0])) {
lines.add(line);
}
} catch (NullPointerException npe) {
} catch (ArrayIndexOutOfBoundsException aioobe) {
}
}
bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) {
@ -640,30 +722,30 @@ public class FlatFileThread extends Thread implements DataSource {
}
}
return;
}
}
@Override
public DataSourceType getType() {
return DataSourceType.FILE;
}
@Override
public DataSourceType getType() {
return DataSourceType.FILE;
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
}

View File

@ -1,12 +1,14 @@
// Copyright 2007-2013 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
// Copyright 2007-2013 Christian d'Heureuse, Inventec Informatik AG, Zurich,
// Switzerland
// www.source-code.biz, www.inventec.ch/chdh
//
// This module is multi-licensed and may be used under the terms
// of any of the following licenses:
//
// EPL, Eclipse Public License, http://www.eclipse.org/legal
// LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html
// MPL, Mozilla Public License 1.1, http://www.mozilla.org/MPL
// EPL, Eclipse Public License, http://www.eclipse.org/legal
// LGPL, GNU Lesser General Public License,
// http://www.gnu.org/licenses/lgpl.html
// MPL, Mozilla Public License 1.1, http://www.mozilla.org/MPL
//
// Please contact the author if you need another license.
// This module is provided "as is", without warranties of any kind.
@ -25,302 +27,406 @@ import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
/**
* A lightweight standalone JDBC connection pool manager.
*
* <p>The public methods of this class are thread-safe.
*
* <p>Home page: <a href="http://www.source-code.biz/miniconnectionpoolmanager">www.source-code.biz/miniconnectionpoolmanager</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL / LGPL / MPL.
*/
* A lightweight standalone JDBC connection pool manager.
*
* <p>
* The public methods of this class are thread-safe.
*
* <p>
* Home page: <a
* href="http://www.source-code.biz/miniconnectionpoolmanager">www.
* source-code.biz/miniconnectionpoolmanager</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL / LGPL / MPL.
*/
public class MiniConnectionPoolManager {
private ConnectionPoolDataSource dataSource;
private int maxConnections;
private long timeoutMs;
private PrintWriter logWriter;
private Semaphore semaphore;
private PoolConnectionEventListener poolConnectionEventListener;
private ConnectionPoolDataSource dataSource;
private int maxConnections;
private long timeoutMs;
private PrintWriter logWriter;
private Semaphore semaphore;
private PoolConnectionEventListener poolConnectionEventListener;
// The following variables must only be accessed within synchronized blocks.
// @GuardedBy("this") could by used in the future.
private LinkedList<PooledConnection> recycledConnections; // list of inactive PooledConnections
private int activeConnections; // number of active (open) connections of this pool
private boolean isDisposed; // true if this connection pool has been disposed
private boolean doPurgeConnection; // flag to purge the connection currently beeing closed instead of recycling it
private PooledConnection connectionInTransition; // a PooledConnection which is currently within a PooledConnection.getConnection() call, or null
// The following variables must only be accessed within synchronized blocks.
// @GuardedBy("this") could by used in the future.
private LinkedList<PooledConnection> recycledConnections; // list of
// inactive
// PooledConnections
private int activeConnections; // number of active (open) connections of
// this pool
private boolean isDisposed; // true if this connection pool has been
// disposed
private boolean doPurgeConnection; // flag to purge the connection currently
// beeing closed instead of recycling it
private PooledConnection connectionInTransition; // a PooledConnection which
// is currently within a
// PooledConnection.getConnection()
// call, or null
/**
* Thrown in {@link #getConnection()} or {@link #getValidConnection()} when no free connection becomes
* available within <code>timeout</code> seconds.
*/
public static class TimeoutException extends RuntimeException {
private static final long serialVersionUID = 1;
public TimeoutException () {
super("Timeout while waiting for a free database connection."); }
public TimeoutException (String msg) {
super(msg); }}
/**
* Thrown in {@link #getConnection()} or {@link #getValidConnection()} when
* no free connection becomes available within <code>timeout</code> seconds.
*/
public static class TimeoutException extends RuntimeException {
private static final long serialVersionUID = 1;
/**
* Constructs a MiniConnectionPoolManager object with a timeout of 60 seconds.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
*/
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections) {
this(dataSource, maxConnections, 60); }
public TimeoutException() {
super("Timeout while waiting for a free database connection.");
}
/**
* Constructs a MiniConnectionPoolManager object.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
* @param timeout
* the maximum time in seconds to wait for a free connection.
*/
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections, int timeout) {
this.dataSource = dataSource;
this.maxConnections = maxConnections;
this.timeoutMs = timeout * 1000L;
try {
logWriter = dataSource.getLogWriter(); }
catch (SQLException e) {}
if (maxConnections < 1) {
throw new IllegalArgumentException("Invalid maxConnections value."); }
semaphore = new Semaphore(maxConnections,true);
recycledConnections = new LinkedList<PooledConnection>();
poolConnectionEventListener = new PoolConnectionEventListener(); }
public TimeoutException(String msg) {
super(msg);
}
}
/**
* Closes all unused pooled connections.
*/
public synchronized void dispose() throws SQLException {
if (isDisposed) {
return; }
isDisposed = true;
SQLException e = null;
while (!recycledConnections.isEmpty()) {
PooledConnection pconn = recycledConnections.remove();
try {
pconn.close(); }
catch (SQLException e2) {
if (e == null) {
e = e2; }}}
if (e != null) {
throw e; }}
/**
* Constructs a MiniConnectionPoolManager object with a timeout of 60
* seconds.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
*/
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,
int maxConnections) {
this(dataSource, maxConnections, 60);
}
/**
* Retrieves a connection from the connection pool.
*
* <p>If <code>maxConnections</code> connections are already in use, the method
* waits until a connection becomes available or <code>timeout</code> seconds elapsed.
* When the application is finished using the connection, it must close it
* in order to return it to the pool.
*
* @return
* a new <code>Connection</code> object.
* @throws TimeoutException
* when no connection becomes available within <code>timeout</code> seconds.
*/
public Connection getConnection() throws SQLException {
return getConnection2(timeoutMs); }
/**
* Constructs a MiniConnectionPoolManager object.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
* @param timeout
* the maximum time in seconds to wait for a free connection.
*/
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,
int maxConnections, int timeout) {
this.dataSource = dataSource;
this.maxConnections = maxConnections;
this.timeoutMs = timeout * 1000L;
try {
logWriter = dataSource.getLogWriter();
} catch (SQLException e) {
}
if (maxConnections < 1) {
throw new IllegalArgumentException("Invalid maxConnections value.");
}
semaphore = new Semaphore(maxConnections, true);
recycledConnections = new LinkedList<PooledConnection>();
poolConnectionEventListener = new PoolConnectionEventListener();
}
private Connection getConnection2 (long timeoutMs) throws SQLException {
// This routine is unsynchronized, because semaphore.tryAcquire() may block.
synchronized (this) {
if (isDisposed) {
throw new IllegalStateException("Connection pool has been disposed."); }}
try {
if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
throw new TimeoutException(); }}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for a database connection.",e); }
boolean ok = false;
try {
Connection conn = getConnection3();
ok = true;
return conn; }
finally {
if (!ok) {
semaphore.release(); }}}
/**
* Closes all unused pooled connections.
*/
public synchronized void dispose() throws SQLException {
if (isDisposed) {
return;
}
isDisposed = true;
SQLException e = null;
while (!recycledConnections.isEmpty()) {
PooledConnection pconn = recycledConnections.remove();
try {
pconn.close();
} catch (SQLException e2) {
if (e == null) {
e = e2;
}
}
}
if (e != null) {
throw e;
}
}
private synchronized Connection getConnection3() throws SQLException {
if (isDisposed) {
throw new IllegalStateException("Connection pool has been disposed."); }
PooledConnection pconn;
if (!recycledConnections.isEmpty()) {
pconn = recycledConnections.remove(); }
else {
pconn = dataSource.getPooledConnection();
pconn.addConnectionEventListener(poolConnectionEventListener); }
Connection conn;
try {
// The JDBC driver may call ConnectionEventListener.connectionErrorOccurred()
// from within PooledConnection.getConnection(). To detect this within
// disposeConnection(), we temporarily set connectionInTransition.
connectionInTransition = pconn;
activeConnections++;
conn = pconn.getConnection(); }
finally {
connectionInTransition = null; }
assertInnerState();
return conn; }
/**
* Retrieves a connection from the connection pool.
*
* <p>
* If <code>maxConnections</code> connections are already in use, the method
* waits until a connection becomes available or <code>timeout</code>
* seconds elapsed. When the application is finished using the connection,
* it must close it in order to return it to the pool.
*
* @return a new <code>Connection</code> object.
* @throws TimeoutException
* when no connection becomes available within
* <code>timeout</code> seconds.
*/
public Connection getConnection() throws SQLException {
return getConnection2(timeoutMs);
}
/**
* Retrieves a connection from the connection pool and ensures that it is valid
* by calling {@link Connection#isValid(int)}.
*
* <p>If a connection is not valid, the method tries to get another connection
* until one is valid (or a timeout occurs).
*
* <p>Pooled connections may become invalid when e.g. the database server is
* restarted.
*
* <p>This method is slower than {@link #getConnection()} because the JDBC
* driver has to send an extra command to the database server to test the connection.
*
* <p>This method requires Java 1.6 or newer.
*
* @throws TimeoutException
* when no valid connection becomes available within <code>timeout</code> seconds.
*/
public Connection getValidConnection() {
long time = System.currentTimeMillis();
long timeoutTime = time + timeoutMs;
int triesWithoutDelay = getInactiveConnections() + 1;
while (true) {
Connection conn = getValidConnection2(time, timeoutTime);
if (conn != null) {
return conn; }
triesWithoutDelay--;
if (triesWithoutDelay <= 0) {
triesWithoutDelay = 0;
try {
Thread.sleep(250); }
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for a valid database connection.", e); }}
time = System.currentTimeMillis();
if (time >= timeoutTime) {
throw new TimeoutException("Timeout while waiting for a valid database connection."); }}}
private Connection getConnection2(long timeoutMs) throws SQLException {
// This routine is unsynchronized, because semaphore.tryAcquire() may
// block.
synchronized (this) {
if (isDisposed) {
throw new IllegalStateException(
"Connection pool has been disposed.");
}
}
try {
if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
throw new TimeoutException();
}
} catch (InterruptedException e) {
throw new RuntimeException(
"Interrupted while waiting for a database connection.", e);
}
boolean ok = false;
try {
Connection conn = getConnection3();
ok = true;
return conn;
} finally {
if (!ok) {
semaphore.release();
}
}
}
private Connection getValidConnection2 (long time, long timeoutTime) {
long rtime = Math.max(1, timeoutTime - time);
Connection conn;
try {
conn = getConnection2(rtime); }
catch (SQLException e) {
return null; }
rtime = timeoutTime - System.currentTimeMillis();
int rtimeSecs = Math.max(1, (int)((rtime+999)/1000));
try {
if (conn.isValid(rtimeSecs)) {
return conn; }}
catch (SQLException e) {}
// This Exception should never occur. If it nevertheless occurs, it's because of an error in the
// JDBC driver which we ignore and assume that the connection is not valid.
// When isValid() returns false, the JDBC driver should have already called connectionErrorOccurred()
// and the PooledConnection has been removed from the pool, i.e. the PooledConnection will
// not be added to recycledConnections when Connection.close() is called.
// But to be sure that this works even with a faulty JDBC driver, we call purgeConnection().
purgeConnection(conn);
return null; }
private synchronized Connection getConnection3() throws SQLException {
if (isDisposed) {
throw new IllegalStateException(
"Connection pool has been disposed.");
}
PooledConnection pconn;
if (!recycledConnections.isEmpty()) {
pconn = recycledConnections.remove();
} else {
pconn = dataSource.getPooledConnection();
pconn.addConnectionEventListener(poolConnectionEventListener);
}
Connection conn;
try {
// The JDBC driver may call
// ConnectionEventListener.connectionErrorOccurred()
// from within PooledConnection.getConnection(). To detect this
// within
// disposeConnection(), we temporarily set connectionInTransition.
connectionInTransition = pconn;
activeConnections++;
conn = pconn.getConnection();
} finally {
connectionInTransition = null;
}
assertInnerState();
return conn;
}
// Purges the PooledConnection associated with the passed Connection from the connection pool.
private synchronized void purgeConnection (Connection conn) {
try {
doPurgeConnection = true;
// (A potential problem of this program logic is that setting the doPurgeConnection flag
// has an effect only if the JDBC driver calls connectionClosed() synchronously within
// Connection.close().)
conn.close(); }
catch (SQLException e) {}
// ignore exception from close()
finally {
doPurgeConnection = false; }}
/**
* Retrieves a connection from the connection pool and ensures that it is
* valid by calling {@link Connection#isValid(int)}.
*
* <p>
* If a connection is not valid, the method tries to get another connection
* until one is valid (or a timeout occurs).
*
* <p>
* Pooled connections may become invalid when e.g. the database server is
* restarted.
*
* <p>
* This method is slower than {@link #getConnection()} because the JDBC
* driver has to send an extra command to the database server to test the
* connection.
*
* <p>
* This method requires Java 1.6 or newer.
*
* @throws TimeoutException
* when no valid connection becomes available within
* <code>timeout</code> seconds.
*/
public Connection getValidConnection() {
long time = System.currentTimeMillis();
long timeoutTime = time + timeoutMs;
int triesWithoutDelay = getInactiveConnections() + 1;
while (true) {
Connection conn = getValidConnection2(time, timeoutTime);
if (conn != null) {
return conn;
}
triesWithoutDelay--;
if (triesWithoutDelay <= 0) {
triesWithoutDelay = 0;
try {
Thread.sleep(250);
} catch (InterruptedException e) {
throw new RuntimeException(
"Interrupted while waiting for a valid database connection.",
e);
}
}
time = System.currentTimeMillis();
if (time >= timeoutTime) {
throw new TimeoutException(
"Timeout while waiting for a valid database connection.");
}
}
}
private synchronized void recycleConnection (PooledConnection pconn) {
if (isDisposed || doPurgeConnection) {
disposeConnection(pconn);
return; }
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError"); }
activeConnections--;
semaphore.release();
recycledConnections.add(pconn);
assertInnerState(); }
private Connection getValidConnection2(long time, long timeoutTime) {
long rtime = Math.max(1, timeoutTime - time);
Connection conn;
try {
conn = getConnection2(rtime);
} catch (SQLException e) {
return null;
}
rtime = timeoutTime - System.currentTimeMillis();
int rtimeSecs = Math.max(1, (int) ((rtime + 999) / 1000));
try {
if (conn.isValid(rtimeSecs)) {
return conn;
}
} catch (SQLException e) {
}
// This Exception should never occur. If it nevertheless occurs, it's
// because of an error in the
// JDBC driver which we ignore and assume that the connection is not
// valid.
// When isValid() returns false, the JDBC driver should have already
// called connectionErrorOccurred()
// and the PooledConnection has been removed from the pool, i.e. the
// PooledConnection will
// not be added to recycledConnections when Connection.close() is
// called.
// But to be sure that this works even with a faulty JDBC driver, we
// call purgeConnection().
purgeConnection(conn);
return null;
}
private synchronized void disposeConnection (PooledConnection pconn) {
pconn.removeConnectionEventListener(poolConnectionEventListener);
if (!recycledConnections.remove(pconn) && pconn != connectionInTransition) {
// If the PooledConnection is not in the recycledConnections list
// and is not currently within a PooledConnection.getConnection() call,
// we assume that the connection was active.
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError"); }
activeConnections--;
semaphore.release(); }
closeConnectionAndIgnoreException(pconn);
assertInnerState(); }
// Purges the PooledConnection associated with the passed Connection from
// the connection pool.
private synchronized void purgeConnection(Connection conn) {
try {
doPurgeConnection = true;
// (A potential problem of this program logic is that setting the
// doPurgeConnection flag
// has an effect only if the JDBC driver calls connectionClosed()
// synchronously within
// Connection.close().)
conn.close();
} catch (SQLException e) {
}
// ignore exception from close()
finally {
doPurgeConnection = false;
}
}
private void closeConnectionAndIgnoreException (PooledConnection pconn) {
try {
pconn.close(); }
catch (SQLException e) {
log("Error while closing database connection: "+e.toString()); }}
private synchronized void recycleConnection(PooledConnection pconn) {
if (isDisposed || doPurgeConnection) {
disposeConnection(pconn);
return;
}
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError");
}
activeConnections--;
semaphore.release();
recycledConnections.add(pconn);
assertInnerState();
}
private void log (String msg) {
String s = "MiniConnectionPoolManager: "+msg;
try {
if (logWriter == null) {
System.err.println(s); }
else {
logWriter.println(s); }}
catch (Exception e) {}}
private synchronized void disposeConnection(PooledConnection pconn) {
pconn.removeConnectionEventListener(poolConnectionEventListener);
if (!recycledConnections.remove(pconn)
&& pconn != connectionInTransition) {
// If the PooledConnection is not in the recycledConnections list
// and is not currently within a PooledConnection.getConnection()
// call,
// we assume that the connection was active.
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError");
}
activeConnections--;
semaphore.release();
}
closeConnectionAndIgnoreException(pconn);
assertInnerState();
}
private synchronized void assertInnerState() {
if (activeConnections < 0) {
throw new AssertionError("AuthMeDatabaseError"); }
if (activeConnections + recycledConnections.size() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError"); }
if (activeConnections + semaphore.availablePermits() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError"); }}
private void closeConnectionAndIgnoreException(PooledConnection pconn) {
try {
pconn.close();
} catch (SQLException e) {
log("Error while closing database connection: " + e.toString());
}
}
private class PoolConnectionEventListener implements ConnectionEventListener {
public void connectionClosed (ConnectionEvent event) {
PooledConnection pconn = (PooledConnection)event.getSource();
recycleConnection(pconn); }
public void connectionErrorOccurred (ConnectionEvent event) {
PooledConnection pconn = (PooledConnection)event.getSource();
disposeConnection(pconn); }}
private void log(String msg) {
String s = "MiniConnectionPoolManager: " + msg;
try {
if (logWriter == null) {
System.err.println(s);
} else {
logWriter.println(s);
}
} catch (Exception e) {
}
}
/**
* Returns the number of active (open) connections of this pool.
*
* <p>This is the number of <code>Connection</code> objects that have been
* issued by {@link #getConnection()}, for which <code>Connection.close()</code>
* has not yet been called.
*
* @return
* the number of active connections.
**/
public synchronized int getActiveConnections() {
return activeConnections; }
private synchronized void assertInnerState() {
if (activeConnections < 0) {
throw new AssertionError("AuthMeDatabaseError");
}
if (activeConnections + recycledConnections.size() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError");
}
if (activeConnections + semaphore.availablePermits() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError");
}
}
/**
* Returns the number of inactive (unused) connections in this pool.
*
* <p>This is the number of internally kept recycled connections,
* for which <code>Connection.close()</code> has been called and which
* have not yet been reused.
*
* @return
* the number of inactive connections.
**/
public synchronized int getInactiveConnections() {
return recycledConnections.size(); }
private class PoolConnectionEventListener implements
ConnectionEventListener {
public void connectionClosed(ConnectionEvent event) {
PooledConnection pconn = (PooledConnection) event.getSource();
recycleConnection(pconn);
}
} // end class MiniConnectionPoolManager
public void connectionErrorOccurred(ConnectionEvent event) {
PooledConnection pconn = (PooledConnection) event.getSource();
disposeConnection(pconn);
}
}
/**
* Returns the number of active (open) connections of this pool.
*
* <p>
* This is the number of <code>Connection</code> objects that have been
* issued by {@link #getConnection()}, for which
* <code>Connection.close()</code> has not yet been called.
*
* @return the number of active connections.
**/
public synchronized int getActiveConnections() {
return activeConnections;
}
/**
* Returns the number of inactive (unused) connections in this pool.
*
* <p>
* This is the number of internally kept recycled connections, for which
* <code>Connection.close()</code> has been called and which have not yet
* been reused.
*
* @return the number of inactive connections.
**/
public synchronized int getInactiveConnections() {
return recycledConnections.size();
}
} // end class MiniConnectionPoolManager

File diff suppressed because it is too large Load Diff

View File

@ -17,7 +17,6 @@ import fr.xephi.authme.datasource.MiniConnectionPoolManager.TimeoutException;
import fr.xephi.authme.settings.PlayersLogs;
import fr.xephi.authme.settings.Settings;
public class SQLiteThread extends Thread implements DataSource {
private String database;
@ -53,33 +52,35 @@ public class SQLiteThread extends Thread implements DataSource {
this.columnID = Settings.getMySQLColumnId;
try {
this.connect();
this.setup();
} catch (ClassNotFoundException e) {
this.connect();
this.setup();
} catch (ClassNotFoundException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
.getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} catch (SQLException e) {
} catch (SQLException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
.getPluginManager().disablePlugin(AuthMe.getInstance());
return;
}
}
}
private synchronized void connect() throws ClassNotFoundException, SQLException {
private synchronized void connect() throws ClassNotFoundException,
SQLException {
Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"+database+".db");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"
+ database + ".db");
}
@ -89,18 +90,19 @@ public class SQLiteThread extends Thread implements DataSource {
try {
st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ columnID + " INTEGER AUTO_INCREMENT,"
+ columnName + " VARCHAR(255) NOT NULL UNIQUE,"
+ columnPassword + " VARCHAR(255) NOT NULL,"
+ columnIp + " VARCHAR(40) NOT NULL,"
+ columnLastLogin + " BIGINT,"
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0',"
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0',"
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0',"
+ lastlocWorld + " VARCHAR(255) DEFAULT 'world',"
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
+ columnID + " INTEGER AUTO_INCREMENT," + columnName
+ " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ " VARCHAR(255) NOT NULL," + columnIp
+ " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT,"
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ
+ " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld
+ " VARCHAR(255) DEFAULT 'world'," + columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "));");
rs = con.getMetaData().getColumns(null, null, tableName,
columnPassword);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnPassword + " VARCHAR(255) NOT NULL;");
@ -112,7 +114,8 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnIp + " VARCHAR(40) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
rs = con.getMetaData().getColumns(null, null, tableName,
columnLastLogin);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLastLogin + " BIGINT;");
@ -120,19 +123,28 @@ public class SQLiteThread extends Thread implements DataSource {
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
rs = con.getMetaData().getColumns(null, null, tableName,
lastlocWorld);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
rs = con.getMetaData().getColumns(null, null, tableName,
columnEmail);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com';");
}
} finally {
close(rs);
@ -146,7 +158,8 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?");
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnName + "=?");
pst.setString(1, user);
rs = pst.executeQuery();
return rs.next();
@ -169,15 +182,38 @@ public class SQLiteThread extends Thread implements DataSource {
pst.setString(1, user);
rs = pst.executeQuery();
if (rs.next()) {
if (rs.getString(columnIp).isEmpty() ) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "198.18.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld) , rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName)));
if (rs.getString(columnIp).isEmpty()) {
return new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword), "198.18.0.1",
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld),
rs.getString(columnEmail), API.getPlayerRealName(rs
.getString(columnName)));
} else {
if(!columnSalt.isEmpty()){
return 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), API.getPlayerRealName(rs.getString(columnName)));
} else {
return 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), API.getPlayerRealName(rs.getString(columnName)));
}
}
if (!columnSalt.isEmpty()) {
return 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),
API.getPlayerRealName(rs.getString(columnName)));
} else {
return 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),
API.getPlayerRealName(rs.getString(columnName)));
}
}
} else {
return null;
}
@ -195,14 +231,19 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null;
try {
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + ") VALUES (?,?,?,?);");
pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + ") VALUES (?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin());
pst.executeUpdate();
} else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);");
pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + "," + columnSalt
+ ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
@ -223,7 +264,8 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean updatePassword(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
@ -240,7 +282,9 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateSession(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnIp + "=?, " + columnLastLogin + "=? WHERE "
+ columnName + "=?;");
pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getNickname());
@ -258,8 +302,9 @@ public class SQLiteThread extends Thread implements DataSource {
public int purgeDatabase(long until) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until);
return pst.executeUpdate();
} catch (SQLException ex) {
@ -276,18 +321,19 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null;
List<String> list = new ArrayList<String>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until);
rs = pst.executeQuery();
while (rs.next()) {
list.add(rs.getString(columnName));
list.add(rs.getString(columnName));
}
return list;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} finally {
close(rs);
close(rs);
close(pst);
}
}
@ -296,7 +342,8 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean removeAuth(String user) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnName + "=?;");
pst.setString(1, user);
pst.executeUpdate();
} catch (SQLException ex) {
@ -312,7 +359,9 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateQuitLoc(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, "+ lastlocY +"=?, "+ lastlocZ +"=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, "
+ lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ());
@ -332,30 +381,31 @@ public class SQLiteThread extends Thread implements DataSource {
public int getIps(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
int countIp=0;
int countIp = 0;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while(rs.next()) {
countIp++;
}
return countIp;
while (rs.next()) {
countIp++;
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
} finally {
close(rs);
close(pst);
}
}
}
@Override
public boolean updateEmail(PlayerAuth auth) {
@Override
public boolean updateEmail(PlayerAuth auth) {
PreparedStatement pst = null;
try {
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(2, auth.getNickname());
pst.executeUpdate();
@ -368,14 +418,15 @@ public class SQLiteThread extends Thread implements DataSource {
return true;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
if(columnSalt.isEmpty()) {
return false;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
if (columnSalt.isEmpty()) {
return false;
}
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnSalt + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
@ -421,8 +472,8 @@ public class SQLiteThread extends Thread implements DataSource {
}
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<String>();
@ -431,10 +482,10 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnIp + "=?;");
pst.setString(1, auth.getIp());
rs = pst.executeQuery();
while(rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
@ -442,15 +493,15 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} catch (NullPointerException npe) {
return new ArrayList<String>();
return new ArrayList<String>();
} finally {
close(rs);
close(pst);
}
}
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
@Override
public List<String> getAllAuthsByIp(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<String>();
@ -459,10 +510,10 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while(rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
@ -470,15 +521,15 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} catch (NullPointerException npe) {
return new ArrayList<String>();
return new ArrayList<String>();
} finally {
close(rs);
close(pst);
}
}
}
}
@Override
public List<String> getAllAuthsByEmail(String email) {
@Override
public List<String> getAllAuthsByEmail(String email) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countEmail = new ArrayList<String>();
@ -487,10 +538,10 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnEmail + "=?;");
pst.setString(1, email);
rs = pst.executeQuery();
while(rs.next()) {
countEmail.add(rs.getString(columnName));
}
return countEmail;
while (rs.next()) {
countEmail.add(rs.getString(columnName));
}
return countEmail;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
@ -498,51 +549,52 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} catch (NullPointerException npe) {
return new ArrayList<String>();
return new ArrayList<String>();
} finally {
close(rs);
close(pst);
}
}
}
}
@Override
public void purgeBanned(List<String> banned) {
@Override
public void purgeBanned(List<String> banned) {
PreparedStatement pst = null;
try {
for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, name);
pst.executeUpdate();
}
for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, name);
pst.executeUpdate();
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
}
}
}
@Override
public DataSourceType getType() {
return DataSourceType.SQLITE;
}
@Override
public DataSourceType getType() {
return DataSourceType.SQLITE;
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
}

View File

@ -4,31 +4,35 @@ import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class AuthMeTeleportEvent extends CustomEvent {
private Player player;
private Location to;
private Location from;
private Player player;
private Location to;
private Location from;
public AuthMeTeleportEvent(Player player, Location to) {
this.player = player;
this.from = player.getLocation();
this.to = to;
}
public Player getPlayer() {
return player;
}
public void setTo(Location to) {
this.to = to;
}
public Location getTo() {
return to;
}
public Location getFrom() {
return from;
}
public AuthMeTeleportEvent(Player player, Location to) {
this.player = player;
this.from = player.getLocation();
this.to = to;
}
public Player getPlayer() {
return player;
}
public void setTo(Location to) {
this.to = to;
}
public Location getTo() {
return to;
}
public Location getFrom() {
return from;
}
}

View File

@ -6,33 +6,33 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class CustomEvent extends Event implements Cancellable {
private boolean isCancelled;
private static final HandlerList handlers = new HandlerList();
private static Server s;
private boolean isCancelled;
private static final HandlerList handlers = new HandlerList();
private static Server s;
public HandlerList getHandlers() {
return handlers;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public boolean isCancelled() {
return this.isCancelled;
}
public boolean isCancelled() {
return this.isCancelled;
}
public void setCancelled(boolean cancelled) {
this.isCancelled = cancelled;
}
public void setCancelled(boolean cancelled) {
this.isCancelled = cancelled;
}
public static Server getServer() {
return s;
}
public static Server getServer() {
return s;
}
}

View File

@ -4,51 +4,52 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class ProtectInventoryEvent extends CustomEvent {
private ItemStack[] storedinventory;
private ItemStack[] storedarmor;
private ItemStack[] emptyInventory = null;
private ItemStack[] emptyArmor = null;
private Player player;
private ItemStack[] storedinventory;
private ItemStack[] storedarmor;
private ItemStack[] emptyInventory = null;
private ItemStack[] emptyArmor = null;
private Player player;
public ProtectInventoryEvent(Player player, ItemStack[] storedinventory, ItemStack[] storedarmor) {
this.player = player;
this.storedinventory = storedinventory;
this.storedarmor = storedarmor;
this.emptyInventory = new ItemStack[36];
this.emptyArmor = new ItemStack[4];
}
public ProtectInventoryEvent(Player player, ItemStack[] storedinventory,
ItemStack[] storedarmor) {
this.player = player;
this.storedinventory = storedinventory;
this.storedarmor = storedarmor;
this.emptyInventory = new ItemStack[36];
this.emptyArmor = new ItemStack[4];
}
public ItemStack[] getStoredInventory() {
return this.storedinventory;
}
public ItemStack[] getStoredInventory() {
return this.storedinventory;
}
public ItemStack[] getStoredArmor() {
return this.storedarmor;
}
public ItemStack[] getStoredArmor() {
return this.storedarmor;
}
public Player getPlayer() {
return this.player;
}
public Player getPlayer() {
return this.player;
}
public void setNewInventory(ItemStack[] emptyInventory) {
this.emptyInventory = emptyInventory;
}
public void setNewInventory(ItemStack[] emptyInventory) {
this.emptyInventory = emptyInventory;
}
public ItemStack[] getEmptyInventory() {
return this.emptyInventory;
}
public ItemStack[] getEmptyInventory() {
return this.emptyInventory;
}
public void setNewArmor(ItemStack[] emptyArmor) {
this.emptyArmor = emptyArmor;
}
public void setNewArmor(ItemStack[] emptyArmor) {
this.emptyArmor = emptyArmor;
}
public ItemStack[] getEmptyArmor() {
return this.emptyArmor;
}
public ItemStack[] getEmptyArmor() {
return this.emptyArmor;
}
}

View File

@ -4,31 +4,35 @@ import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class RegisterTeleportEvent extends CustomEvent {
private Player player;
private Location to;
private Location from;
private Player player;
private Location to;
private Location from;
public RegisterTeleportEvent(Player player, Location to) {
this.player = player;
this.from = player.getLocation();
this.to = to;
}
public Player getPlayer() {
return player;
}
public void setTo(Location to) {
this.to = to;
}
public Location getTo() {
return to;
}
public Location getFrom() {
return from;
}
public RegisterTeleportEvent(Player player, Location to) {
this.player = player;
this.from = player.getLocation();
this.to = to;
}
public Player getPlayer() {
return player;
}
public void setTo(Location to) {
this.to = to;
}
public Location getTo() {
return to;
}
public Location getFrom() {
return from;
}
}

View File

@ -3,23 +3,23 @@ package fr.xephi.authme.events;
import org.bukkit.entity.Player;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class ResetInventoryEvent extends CustomEvent {
private Player player;
private Player player;
public ResetInventoryEvent(Player player) {
this.player = player;
}
public ResetInventoryEvent(Player player) {
this.player = player;
}
public Player getPlayer() {
return this.player;
}
public Player getPlayer() {
return this.player;
}
public void setPlayer(Player player) {
this.player = player;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -4,43 +4,44 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class RestoreInventoryEvent extends CustomEvent {
private ItemStack[] inventory;
private ItemStack[] armor;
private Player player;
private ItemStack[] inventory;
private ItemStack[] armor;
private Player player;
public RestoreInventoryEvent(Player player, ItemStack[] inventory, ItemStack[] armor) {
this.player = player;
this.inventory = inventory;
this.armor = armor;
}
public RestoreInventoryEvent(Player player, ItemStack[] inventory,
ItemStack[] armor) {
this.player = player;
this.inventory = inventory;
this.armor = armor;
}
public ItemStack[] getInventory() {
return this.inventory;
}
public ItemStack[] getInventory() {
return this.inventory;
}
public void setInventory(ItemStack[] inventory) {
this.inventory = inventory;
}
public void setInventory(ItemStack[] inventory) {
this.inventory = inventory;
}
public ItemStack[] getArmor() {
return this.armor;
}
public ItemStack[] getArmor() {
return this.armor;
}
public void setArmor(ItemStack[] armor) {
this.armor = armor;
}
public void setArmor(ItemStack[] armor) {
this.armor = armor;
}
public Player getPlayer() {
return this.player;
}
public Player getPlayer() {
return this.player;
}
public void setPlayer(Player player) {
this.player = player;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -3,29 +3,29 @@ package fr.xephi.authme.events;
import fr.xephi.authme.cache.auth.PlayerAuth;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class SessionEvent extends CustomEvent {
private PlayerAuth player;
private boolean isLogin;
private PlayerAuth player;
private boolean isLogin;
public SessionEvent(PlayerAuth auth, boolean isLogin) {
this.player = auth;
this.isLogin = isLogin;
}
public SessionEvent(PlayerAuth auth, boolean isLogin) {
this.player = auth;
this.isLogin = isLogin;
}
public PlayerAuth getPlayerAuth() {
return this.player;
}
public PlayerAuth getPlayerAuth() {
return this.player;
}
public void setPlayer(PlayerAuth player) {
this.player = player;
}
public void setPlayer(PlayerAuth player) {
this.player = player;
}
public boolean isLogin() {
return isLogin;
}
public boolean isLogin() {
return isLogin;
}
}

View File

@ -4,36 +4,42 @@ import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class SpawnTeleportEvent extends CustomEvent {
private Player player;
private Location to;
private Location from;
private boolean isAuthenticated;
private Player player;
private Location to;
private Location from;
private boolean isAuthenticated;
public SpawnTeleportEvent(Player player, Location from, Location to, boolean isAuthenticated) {
this.player = player;
this.from = from;
this.to = to;
this.isAuthenticated = isAuthenticated;
}
public Player getPlayer() {
return player;
}
public void setTo(Location to) {
this.to = to;
}
public Location getTo() {
return to;
}
public Location getFrom() {
return from;
}
public boolean isAuthenticated() {
return isAuthenticated;
}
public SpawnTeleportEvent(Player player, Location from, Location to,
boolean isAuthenticated) {
this.player = player;
this.from = from;
this.to = to;
this.isAuthenticated = isAuthenticated;
}
public Player getPlayer() {
return player;
}
public void setTo(Location to) {
this.to = to;
}
public Location getTo() {
return to;
}
public Location getFrom() {
return from;
}
public boolean isAuthenticated() {
return isAuthenticated;
}
}

View File

@ -5,51 +5,52 @@ import org.bukkit.inventory.ItemStack;
import fr.xephi.authme.cache.backup.FileCache;
/**
*
* @author Xephi59
*/
*
* @author Xephi59
*/
public class StoreInventoryEvent extends CustomEvent {
private ItemStack[] inventory;
private ItemStack[] armor;
private Player player;
private ItemStack[] inventory;
private ItemStack[] armor;
private Player player;
public StoreInventoryEvent(Player player) {
this.player = player;
this.inventory = player.getInventory().getContents();
this.armor = player.getInventory().getArmorContents();
}
public StoreInventoryEvent(Player player) {
this.player = player;
this.inventory = player.getInventory().getContents();
this.armor = player.getInventory().getArmorContents();
}
public StoreInventoryEvent(Player player, FileCache fileCache) {
this.player = player;
this.inventory = fileCache.readCache(player.getName().toLowerCase()).getInventory();
this.armor = fileCache.readCache(player.getName().toLowerCase()).getArmour();
}
public StoreInventoryEvent(Player player, FileCache fileCache) {
this.player = player;
this.inventory = fileCache.readCache(player.getName().toLowerCase())
.getInventory();
this.armor = fileCache.readCache(player.getName().toLowerCase())
.getArmour();
}
public ItemStack[] getInventory() {
return this.inventory;
}
public ItemStack[] getInventory() {
return this.inventory;
}
public void setInventory(ItemStack[] inventory) {
this.inventory = inventory;
}
public void setInventory(ItemStack[] inventory) {
this.inventory = inventory;
}
public ItemStack[] getArmor() {
return this.armor;
}
public ItemStack[] getArmor() {
return this.armor;
}
public void setArmor(ItemStack[] armor) {
this.armor = armor;
}
public void setArmor(ItemStack[] armor) {
this.armor = armor;
}
public Player getPlayer() {
return this.player;
}
public Player getPlayer() {
return this.player;
}
public void setPlayer(Player player) {
this.player = player;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -3,5 +3,5 @@ package fr.xephi.authme.gui;
import org.getspout.spoutapi.event.screen.ButtonClickEvent;
public interface Clickable {
public void handleClick(ButtonClickEvent event);
public void handleClick(ButtonClickEvent event);
}

View File

@ -3,26 +3,21 @@ package fr.xephi.authme.gui;
import org.getspout.spoutapi.event.screen.ButtonClickEvent;
import org.getspout.spoutapi.gui.GenericButton;
public class CustomButton extends GenericButton
{
public Clickable handleRef = null;
public class CustomButton extends GenericButton {
public Clickable handleRef = null;
public CustomButton(Clickable c) {
handleRef = c;
}
public CustomButton(Clickable c) {
handleRef = c;
}
@Override
public void onButtonClick(ButtonClickEvent event) {
handleRef.handleClick(event);
}
@Override
public void onButtonClick(ButtonClickEvent event) {
handleRef.handleClick(event);
}
public CustomButton setMidPos(int x, int y)
{
this.setX(x)
.setY(y)
.shiftXPos(-(width / 2))
.shiftYPos(-(height / 2));
return this;
}
public CustomButton setMidPos(int x, int y) {
this.setX(x).setY(y).shiftXPos(-(width / 2)).shiftYPos(-(height / 2));
return this;
}
}

View File

@ -20,112 +20,86 @@ import fr.xephi.authme.gui.Clickable;
import fr.xephi.authme.gui.CustomButton;
import fr.xephi.authme.settings.SpoutCfg;
public class LoginScreen extends GenericPopup implements Clickable {
public class LoginScreen extends GenericPopup implements Clickable{
public AuthMe plugin = AuthMe.getInstance();
private SpoutCfg spoutCfg = SpoutCfg.getInstance();
private CustomButton exitBtn;
private CustomButton loginBtn;
private GenericTextField passBox;
private GenericLabel titleLbl;
private GenericLabel textLbl;
private GenericLabel errorLbl;
public AuthMe plugin = AuthMe.getInstance();
private SpoutCfg spoutCfg = SpoutCfg.getInstance();
private CustomButton exitBtn;
private CustomButton loginBtn;
private GenericTextField passBox;
private GenericLabel titleLbl;
private GenericLabel textLbl;
private GenericLabel errorLbl;
String exitTxt = spoutCfg.getString("LoginScreen.exit button");
String loginTxt = spoutCfg.getString("LoginScreen.login button");
String exitMsg = spoutCfg.getString("LoginScreen.exit message");
String title = spoutCfg.getString("LoginScreen.title");
@SuppressWarnings("unchecked")
List<String> textlines = (List<String>) spoutCfg.getList("LoginScreen.text");
public SpoutPlayer splayer;
String exitTxt = spoutCfg.getString("LoginScreen.exit button");
String loginTxt = spoutCfg.getString("LoginScreen.login button");
String exitMsg = spoutCfg.getString("LoginScreen.exit message");
String title = spoutCfg.getString("LoginScreen.title");
@SuppressWarnings("unchecked")
List<String> textlines = (List<String>) spoutCfg
.getList("LoginScreen.text");
public SpoutPlayer splayer;
public LoginScreen(SpoutPlayer player) {
this.splayer = player;
createScreen();
}
public LoginScreen(SpoutPlayer player) {
this.splayer = player;
createScreen();
}
private void createScreen() {
int objects = textlines.size() + 4;
int part = !(textlines.size() <= 5) ? 195 / objects : 20;
int h = 3*part/4, w = 8*part;
titleLbl = new GenericLabel();
titleLbl
.setText(title)
.setTextColor(new Color(1.0F, 0, 0, 1.0F))
.setAlign(WidgetAnchor.TOP_CENTER)
.setHeight(h)
.setWidth(w)
.setX(maxWidth / 2 )
.setY(25);
this.attachWidget(plugin, titleLbl);
int ystart = 25 + h + part/2;
for (int x=0; x<textlines.size();x++)
{
textLbl = new GenericLabel();
textLbl
.setText(textlines.get(x))
.setAlign(WidgetAnchor.TOP_CENTER)
.setHeight(h)
.setWidth(w)
.setX(maxWidth / 2)
.setY(ystart + x*part);
this.attachWidget(plugin, textLbl);
}
passBox = new GenericTextField();
passBox
.setMaximumCharacters(18)
.setMaximumLines(1)
.setHeight(h-2)
.setWidth(w-2)
.setY(220-h - 2*part);
passBox.setPasswordField(true);
setXToMid(passBox);
this.attachWidget(plugin, passBox);
errorLbl = new GenericLabel();
errorLbl
.setText("")
.setTextColor(new Color(1.0F, 0, 0, 1.0F))
.setHeight(h)
.setWidth(w)
.setX(passBox.getX() + passBox.getWidth() + 2)
.setY(passBox.getY());
this.attachWidget(plugin, errorLbl);
loginBtn = new CustomButton(this);
loginBtn
.setText(loginTxt)
.setHeight(h)
.setWidth(w)
.setY(220-h-part);
setXToMid(loginBtn);
this.attachWidget(plugin, loginBtn);
exitBtn = new CustomButton(this);
exitBtn
.setText(exitTxt)
.setHeight(h)
.setWidth(w)
.setY(220-h);
setXToMid(exitBtn);
this.attachWidget(plugin, exitBtn);
this.setPriority(RenderPriority.Highest);
}
private void createScreen() {
int objects = textlines.size() + 4;
int part = !(textlines.size() <= 5) ? 195 / objects : 20;
int h = 3 * part / 4, w = 8 * part;
titleLbl = new GenericLabel();
titleLbl.setText(title).setTextColor(new Color(1.0F, 0, 0, 1.0F))
.setAlign(WidgetAnchor.TOP_CENTER).setHeight(h).setWidth(w)
.setX(maxWidth / 2).setY(25);
this.attachWidget(plugin, titleLbl);
int ystart = 25 + h + part / 2;
for (int x = 0; x < textlines.size(); x++) {
textLbl = new GenericLabel();
textLbl.setText(textlines.get(x)).setAlign(WidgetAnchor.TOP_CENTER)
.setHeight(h).setWidth(w).setX(maxWidth / 2)
.setY(ystart + x * part);
this.attachWidget(plugin, textLbl);
}
passBox = new GenericTextField();
passBox.setMaximumCharacters(18).setMaximumLines(1).setHeight(h - 2)
.setWidth(w - 2).setY(220 - h - 2 * part);
passBox.setPasswordField(true);
setXToMid(passBox);
this.attachWidget(plugin, passBox);
errorLbl = new GenericLabel();
errorLbl.setText("").setTextColor(new Color(1.0F, 0, 0, 1.0F))
.setHeight(h).setWidth(w)
.setX(passBox.getX() + passBox.getWidth() + 2)
.setY(passBox.getY());
this.attachWidget(plugin, errorLbl);
loginBtn = new CustomButton(this);
loginBtn.setText(loginTxt).setHeight(h).setWidth(w)
.setY(220 - h - part);
setXToMid(loginBtn);
this.attachWidget(plugin, loginBtn);
exitBtn = new CustomButton(this);
exitBtn.setText(exitTxt).setHeight(h).setWidth(w).setY(220 - h);
setXToMid(exitBtn);
this.attachWidget(plugin, exitBtn);
this.setPriority(RenderPriority.Highest);
}
@EventHandler (priority = EventPriority.HIGHEST)
public void handleClick(ButtonClickEvent event) {
Button b = event.getButton();
SpoutPlayer player = event.getPlayer();
if (event.isCancelled() || event == null || event.getPlayer() == null) return;
if (b.equals(loginBtn))
{
plugin.management.performLogin(player, passBox.getText(), false);
}else if(b.equals(exitBtn))
{
event.getPlayer().kickPlayer(exitMsg);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void handleClick(ButtonClickEvent event) {
Button b = event.getButton();
SpoutPlayer player = event.getPlayer();
if (event.isCancelled() || event == null || event.getPlayer() == null) return;
if (b.equals(loginBtn)) {
plugin.management.performLogin(player, passBox.getText(), false);
} else if (b.equals(exitBtn)) {
event.getPlayer().kickPlayer(exitMsg);
}
}
private void setXToMid(Widget w) {
w.setX( (maxWidth - w.getWidth()) / 2);
}
private void setXToMid(Widget w) {
w.setX((maxWidth - w.getWidth()) / 2);
}
}

View File

@ -12,7 +12,6 @@ import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Settings;
public class AuthMeBlockListener implements Listener {
private DataSource data;
@ -32,7 +31,7 @@ public class AuthMeBlockListener implements Listener {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(Utils.getInstance().isUnrestricted(player)) {
if (Utils.getInstance().isUnrestricted(player)) {
return;
}
@ -57,11 +56,12 @@ public class AuthMeBlockListener implements Listener {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(Utils.getInstance().isUnrestricted(player)) {
if (Utils.getInstance().isUnrestricted(player)) {
return;
}
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return;
}

View File

@ -14,16 +14,15 @@ import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Settings;
public class AuthMeChestShopListener implements Listener {
public DataSource database;
public AuthMe plugin;
public DataSource database;
public AuthMe plugin;
public AuthMeChestShopListener(DataSource database, AuthMe plugin) {
this.database = database;
this.plugin = plugin;
}
public AuthMeChestShopListener(DataSource database, AuthMe plugin) {
this.database = database;
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPreTransaction(PreTransactionEvent event) {

View File

@ -18,8 +18,7 @@ import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.settings.Settings;
public class AuthMeEntityListener implements Listener{
public class AuthMeEntityListener implements Listener {
private DataSource data;
public AuthMe instance;
@ -35,23 +34,21 @@ public class AuthMeEntityListener implements Listener{
return;
}
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
if(Utils.getInstance().isUnrestricted((Player)entity)) {
if (Utils.getInstance().isUnrestricted((Player) entity)) {
return;
}
if(instance.citizens.isNPC(entity, instance))
return;
if (instance.citizens.isNPC(entity, instance)) return;
Player player = (Player) entity;
String name = player.getName().toLowerCase();
if(CombatTagComunicator.isNPC(player))
return;
if (CombatTagComunicator.isNPC(player)) return;
if (PlayerCache.getInstance().isAuthenticated(name)) {
return;
@ -76,9 +73,8 @@ public class AuthMeEntityListener implements Listener{
if (!(entity instanceof Player)) {
return;
}
if(instance.citizens.isNPC(entity, instance))
return;
if (instance.citizens.isNPC(entity, instance)) return;
Player player = (Player) entity;
String name = player.getName().toLowerCase();
@ -106,9 +102,8 @@ public class AuthMeEntityListener implements Listener{
if (!(entity instanceof Player)) {
return;
}
if(instance.citizens.isNPC(entity, instance))
return;
if (instance.citizens.isNPC(entity, instance)) return;
Player player = (Player) entity;
String name = player.getName().toLowerCase();
@ -126,7 +121,7 @@ public class AuthMeEntityListener implements Listener{
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
public void EntityRegainHealthEvent(EntityRegainHealthEvent event) {
if (event.isCancelled()) {
@ -137,9 +132,8 @@ public class AuthMeEntityListener implements Listener{
if (!(entity instanceof Player)) {
return;
}
if(instance.citizens.isNPC(entity, instance))
return;
if (instance.citizens.isNPC(entity, instance)) return;
Player player = (Player) entity;
String name = player.getName().toLowerCase();
@ -154,30 +148,31 @@ public class AuthMeEntityListener implements Listener{
}
}
event.setCancelled(true);
event.setCancelled(true);
}
@EventHandler (priority = EventPriority.MONITOR)
public void onEntityInteract(EntityInteractEvent event) {
if (event.isCancelled() || event == null) {
return;
}
if (!(event.getEntity() instanceof Player)) {
return;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityInteract(EntityInteractEvent event) {
if (event.isCancelled() || event == null) {
return;
}
if (!(event.getEntity() instanceof Player)) {
return;
}
Player player = (Player) event.getEntity();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
if (Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return;
}
if(instance.citizens.isNPC(player, instance))
return;
if (instance.citizens.isNPC(player, instance)) return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return;
}
@ -189,27 +184,28 @@ public class AuthMeEntityListener implements Listener{
event.setCancelled(true);
}
@EventHandler (priority = EventPriority.LOWEST)
@EventHandler(priority = EventPriority.LOWEST)
public void onLowestEntityInteract(EntityInteractEvent event) {
if (event.isCancelled() || event == null) {
return;
}
if (event.isCancelled() || event == null) {
return;
}
if (!(event.getEntity() instanceof Player)) {
return;
}
if (!(event.getEntity() instanceof Player)) {
return;
}
Player player = (Player) event.getEntity();
String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
if (Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return;
}
if(instance.citizens.isNPC(player, instance))
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
if (instance.citizens.isNPC(player, instance)) return;
if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return;
}

View File

@ -18,80 +18,80 @@ public class AuthMeServerListener implements Listener {
private Messages m = Messages.getInstance();
public AuthMeServerListener(AuthMe plugin) {
this.plugin = plugin;
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onServerPing(ServerListPingEvent event) {
if (!Settings.enableProtection) return;
if (Settings.countries.isEmpty()) return;
if (!Settings.countriesBlacklist.isEmpty()) {
if(Settings.countriesBlacklist.contains(plugin.getCountryCode(event.getAddress().getHostAddress())))
event.setMotd(m._("country_banned")[0]);
}
if(Settings.countries.contains(plugin.getCountryCode(event.getAddress().getHostAddress()))) {
event.setMotd(plugin.getServer().getMotd());
} else {
event.setMotd(m._("country_banned")[0]);
}
if (!Settings.enableProtection) return;
if (Settings.countries.isEmpty()) return;
if (!Settings.countriesBlacklist.isEmpty()) {
if (Settings.countriesBlacklist.contains(plugin
.getCountryCode(event.getAddress().getHostAddress()))) event
.setMotd(m._("country_banned")[0]);
}
if (Settings.countries.contains(plugin.getCountryCode(event
.getAddress().getHostAddress()))) {
event.setMotd(plugin.getServer().getMotd());
} else {
event.setMotd(m._("country_banned")[0]);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPluginDisable(PluginDisableEvent event) {
String pluginName = event.getPlugin().getName();
if(pluginName.equalsIgnoreCase("Essentials")) {
plugin.ess = null;
ConsoleLogger.info("Essentials has been disabled, unhook!");
return;
}
if(pluginName.equalsIgnoreCase("EssentialsSpawn")) {
plugin.essentialsSpawn = null;
ConsoleLogger.info("EssentialsSpawn has been disabled, unhook!");
return;
}
if(pluginName.equalsIgnoreCase("Multiverse-Core")) {
plugin.multiverse = null;
ConsoleLogger.info("Multiverse-Core has been disabled, unhook!");
return;
}
if(pluginName.equalsIgnoreCase("Notifications")) {
plugin.notifications = null;
ConsoleLogger.info("Notifications has been disabled, unhook!");
}
if(pluginName.equalsIgnoreCase("ChestShop")) {
plugin.ChestShop = 0;
ConsoleLogger.info("ChestShop has been disabled, unhook!");
}
if(pluginName.equalsIgnoreCase("CombatTag")) {
plugin.CombatTag = 0;
ConsoleLogger.info("CombatTag has been disabled, unhook!");
}
if(pluginName.equalsIgnoreCase("Citizens")) {
plugin.CitizensVersion = 0;
ConsoleLogger.info("Citizens has been disabled, unhook!");
}
if(pluginName.equalsIgnoreCase("Vault")) {
plugin.permission = null;
ConsoleLogger.showError("Vault has been disabled, unhook permissions!");
}
String pluginName = event.getPlugin().getName();
if (pluginName.equalsIgnoreCase("Essentials")) {
plugin.ess = null;
ConsoleLogger.info("Essentials has been disabled, unhook!");
return;
}
if (pluginName.equalsIgnoreCase("EssentialsSpawn")) {
plugin.essentialsSpawn = null;
ConsoleLogger.info("EssentialsSpawn has been disabled, unhook!");
return;
}
if (pluginName.equalsIgnoreCase("Multiverse-Core")) {
plugin.multiverse = null;
ConsoleLogger.info("Multiverse-Core has been disabled, unhook!");
return;
}
if (pluginName.equalsIgnoreCase("Notifications")) {
plugin.notifications = null;
ConsoleLogger.info("Notifications has been disabled, unhook!");
}
if (pluginName.equalsIgnoreCase("ChestShop")) {
plugin.ChestShop = 0;
ConsoleLogger.info("ChestShop has been disabled, unhook!");
}
if (pluginName.equalsIgnoreCase("CombatTag")) {
plugin.CombatTag = 0;
ConsoleLogger.info("CombatTag has been disabled, unhook!");
}
if (pluginName.equalsIgnoreCase("Citizens")) {
plugin.CitizensVersion = 0;
ConsoleLogger.info("Citizens has been disabled, unhook!");
}
if (pluginName.equalsIgnoreCase("Vault")) {
plugin.permission = null;
ConsoleLogger
.showError("Vault has been disabled, unhook permissions!");
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPluginEnable(PluginEnableEvent event) {
String pluginName = event.getPlugin().getName();
if(pluginName.equalsIgnoreCase("Essentials") || pluginName.equalsIgnoreCase("EssentialsSpawn"))
plugin.checkEssentials();
if(pluginName.equalsIgnoreCase("Multiverse-Core"))
plugin.checkMultiverse();
if(pluginName.equalsIgnoreCase("Notifications"))
plugin.checkNotifications();
if(pluginName.equalsIgnoreCase("ChestShop"))
plugin.checkChestShop();
if(pluginName.equalsIgnoreCase("CombatTag"))
plugin.combatTag();
if(pluginName.equalsIgnoreCase("Citizens"))
plugin.citizensVersion();
if(pluginName.equalsIgnoreCase("Vault"))
plugin.checkVault();
String pluginName = event.getPlugin().getName();
if (pluginName.equalsIgnoreCase("Essentials")
|| pluginName.equalsIgnoreCase("EssentialsSpawn")) plugin
.checkEssentials();
if (pluginName.equalsIgnoreCase("Multiverse-Core")) plugin
.checkMultiverse();
if (pluginName.equalsIgnoreCase("Notifications")) plugin
.checkNotifications();
if (pluginName.equalsIgnoreCase("ChestShop")) plugin.checkChestShop();
if (pluginName.equalsIgnoreCase("CombatTag")) plugin.combatTag();
if (pluginName.equalsIgnoreCase("Citizens")) plugin.citizensVersion();
if (pluginName.equalsIgnoreCase("Vault")) plugin.checkVault();
}
}

View File

@ -10,18 +10,21 @@ import fr.xephi.authme.gui.screens.LoginScreen;
import fr.xephi.authme.settings.SpoutCfg;
public class AuthMeSpoutListener implements Listener {
private DataSource data;
private DataSource data;
public AuthMeSpoutListener(DataSource data) {
this.data = data;
this.data = data;
}
@EventHandler
public void onSpoutCraftEnable(final SpoutCraftEnableEvent event) {
if(SpoutCfg.getInstance().getBoolean("LoginScreen.enabled")) {
if (data.isAuthAvailable(event.getPlayer().getName().toLowerCase()) && !PlayerCache.getInstance().isAuthenticated(event.getPlayer().getName().toLowerCase()) ) {
event.getPlayer().getMainScreen().attachPopupScreen(new LoginScreen(event.getPlayer()));
}
}
}
@EventHandler
public void onSpoutCraftEnable(final SpoutCraftEnableEvent event) {
if (SpoutCfg.getInstance().getBoolean("LoginScreen.enabled")) {
if (data.isAuthAvailable(event.getPlayer().getName().toLowerCase())
&& !PlayerCache.getInstance().isAuthenticated(
event.getPlayer().getName().toLowerCase())) {
event.getPlayer().getMainScreen()
.attachPopupScreen(new LoginScreen(event.getPlayer()));
}
}
}
}

View File

@ -13,25 +13,27 @@ public class BungeeCordMessage implements PluginMessageListener {
public AuthMe plugin;
public BungeeCordMessage(AuthMe plugin)
{
public BungeeCordMessage(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
public void onPluginMessageReceived(String channel, Player player,
byte[] message) {
if (!channel.equals("BungeeCord")) {
return;
}
try {
final DataInputStream in = new DataInputStream(new ByteArrayInputStream(message));
final DataInputStream in = new DataInputStream(
new ByteArrayInputStream(message));
String subchannel = in.readUTF();
if (subchannel.equals("IP")) { //We need only the IP channel
String ip = in.readUTF();
plugin.realIp.put(player.getName().toLowerCase(), ip); //Put the IP (only the ip not the port) in the hashmap
if (subchannel.equals("IP")) { // We need only the IP channel
String ip = in.readUTF();
plugin.realIp.put(player.getName().toLowerCase(), ip);
// Put the IP (only the ip not the port) in the hashmap
}
} catch (IOException ex) {
}
}
}
}

View File

@ -12,22 +12,22 @@ public class CitizensCommunicator {
public AuthMe instance;
public CitizensCommunicator(AuthMe instance) {
this.instance = instance;
this.instance = instance;
}
public boolean isNPC(final Entity player, AuthMe instance) {
try {
if (instance.CitizensVersion == 1) {
return CitizensManager.isNPC(player);
} else if (instance.CitizensVersion == 2) {
return CitizensAPI.getNPCRegistry().isNPC(player);
} else {
return false;
}
} catch (NoClassDefFoundError ncdfe) {
return false;
} catch (Exception npe) {
return false;
}
try {
if (instance.CitizensVersion == 1) {
return CitizensManager.isNPC(player);
} else if (instance.CitizensVersion == 2) {
return CitizensAPI.getNPCRegistry().isNPC(player);
} else {
return false;
}
} catch (NoClassDefFoundError ncdfe) {
return false;
} catch (Exception npe) {
return false;
}
}
}

View File

@ -12,13 +12,15 @@ public abstract class CombatTagComunicator {
/**
* Returns if the entity is an NPC
*
* @param player
* @return true if the player is an NPC
*/
public static boolean isNPC(Entity player) {
try {
if(Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null){
combatApi = new CombatTagApi((CombatTag) Bukkit.getServer().getPluginManager().getPlugin("CombatTag"));
if (Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null) {
combatApi = new CombatTagApi((CombatTag) Bukkit.getServer()
.getPluginManager().getPlugin("CombatTag"));
try {
combatApi.getClass().getMethod("isNPC");
} catch (Exception e) {

View File

@ -9,32 +9,39 @@ import fr.xephi.authme.settings.CustomConfiguration;
public class EssSpawn extends CustomConfiguration {
private static EssSpawn spawn;
private static EssSpawn spawn;
public EssSpawn() {
super(new File("./plugins/Essentials/spawn.yml"));
spawn = this;
load();
}
public EssSpawn() {
super(new File("./plugins/Essentials/spawn.yml"));
spawn = this;
load();
}
public static EssSpawn getInstance() {
public static EssSpawn getInstance() {
if (spawn == null) {
spawn = new EssSpawn();
}
}
return spawn;
}
public Location getLocation() {
try {
if (!this.contains("spawns.default.world")) return null;
if (this.getString("spawns.default.world").isEmpty() || this.getString("spawns.default.world") == "") return null;
Location location = new Location(Bukkit.getWorld(this.getString("spawns.default.world")), this.getDouble("spawns.default.x"), this.getDouble("spawns.default.y"), this.getDouble("spawns.default.z"), Float.parseFloat(this.getString("spawns.default.yaw")), Float.parseFloat(this.getString("spawns.default.pitch")));
return location;
} catch (NullPointerException npe) {
return null;
} catch (NumberFormatException nfe) {
return null;
}
}
public Location getLocation() {
try {
if (!this.contains("spawns.default.world")) return null;
if (this.getString("spawns.default.world").isEmpty()
|| this.getString("spawns.default.world") == "") return null;
Location location = new Location(Bukkit.getWorld(this
.getString("spawns.default.world")),
this.getDouble("spawns.default.x"),
this.getDouble("spawns.default.y"),
this.getDouble("spawns.default.z"), Float.parseFloat(this
.getString("spawns.default.yaw")),
Float.parseFloat(this.getString("spawns.default.pitch")));
return location;
} catch (NullPointerException npe) {
return null;
} catch (NumberFormatException nfe) {
return null;
}
}
}

View File

@ -12,7 +12,8 @@ import fr.xephi.authme.settings.Settings;
/**
*
* @authors Xephi59, <a href="http://dev.bukkit.org/profiles/Possible/">Possible</a>
* @authors Xephi59, <a
* href="http://dev.bukkit.org/profiles/Possible/">Possible</a>
*
*/
public class Management extends Thread {
@ -30,11 +31,15 @@ public class Management extends Thread {
public void run() {
}
public void performLogin(final Player player, final String password, final boolean forceLogin) {
new AsyncronousLogin(player, password, forceLogin, plugin, database).process();
public void performLogin(final Player player, final String password,
final boolean forceLogin) {
new AsyncronousLogin(player, password, forceLogin, plugin, database)
.process();
}
public void performRegister(final Player player, final String password, final String email) {
new AsyncronousRegister(player, password, email, plugin, database).process();
public void performRegister(final Player player, final String password,
final String email) {
new AsyncronousRegister(player, password, email, plugin, database)
.process();
}
}

View File

@ -32,7 +32,8 @@ public class AsyncronousLogin {
private static RandomString rdm = new RandomString(Settings.captchaLength);
private Messages m = Messages.getInstance();
public AsyncronousLogin(Player player, String password, boolean forceLogin, AuthMe plugin, DataSource data) {
public AsyncronousLogin(Player player, String password, boolean forceLogin,
AuthMe plugin, DataSource data) {
this.player = player;
this.password = password;
name = player.getName().toLowerCase();
@ -43,8 +44,9 @@ public class AsyncronousLogin {
}
protected String getIP() {
return plugin.getIP(player);
return plugin.getIP(player);
}
protected boolean needsCaptcha() {
if (Settings.useCaptcha) {
if (!plugin.captcha.containsKey(name)) {
@ -54,13 +56,17 @@ public class AsyncronousLogin {
plugin.captcha.remove(name);
plugin.captcha.put(name, i);
}
if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
if (plugin.captcha.containsKey(name)
&& plugin.captcha.get(name) >= Settings.maxLoginTry) {
plugin.cap.put(name, rdm.nextString());
for (String s : m._("usage_captcha")) {
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;
} else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
} else if (plugin.captcha.containsKey(name)
&& plugin.captcha.get(name) >= Settings.maxLoginTry) {
try {
plugin.captcha.remove(name);
plugin.cap.remove(name);
@ -72,41 +78,52 @@ public class AsyncronousLogin {
}
/**
* Checks the precondition for authentication (like user known) and returns the playerAuth-State
* Checks the precondition for authentication (like user known) and returns
* the playerAuth-State
*/
protected PlayerAuth preAuth() {
if (PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "logged_in");
m._(player, "logged_in");
return null;
}
if (!database.isAuthAvailable(name)) {
m._(player, "user_unknown");
if(LimboCache.getInstance().hasLimboPlayer(name)) {
Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId());
String[] msg;
if(Settings.emailRegistration) {
msg = m._("reg_email_msg");
m._(player, "user_unknown");
if (LimboCache.getInstance().hasLimboPlayer(name)) {
Bukkit.getScheduler().cancelTask(
LimboCache.getInstance().getLimboPlayer(name)
.getMessageTaskId());
String[] msg;
if (Settings.emailRegistration) {
msg = m._("reg_email_msg");
} else {
msg = m._("reg_msg");
msg = m._("reg_msg");
}
int msgT = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, msg, Settings.getWarnMessageInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
}
int msgT = Bukkit.getScheduler().scheduleSyncDelayedTask(
plugin,
new MessageTask(plugin, name, msg,
Settings.getWarnMessageInterval));
LimboCache.getInstance().getLimboPlayer(name)
.setMessageTaskId(msgT);
}
return null;
}
if (Settings.getMaxLoginPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !getIP().equalsIgnoreCase("127.0.0.1") && !getIP().equalsIgnoreCase("localhost")) {
if (plugin.isLoggedIp(realName, getIP())) {
m._(player, "logged_in");
return null;
}
if (Settings.getMaxLoginPerIp > 0
&& !plugin.authmePermissible(player, "authme.allow2accounts")
&& !getIP().equalsIgnoreCase("127.0.0.1")
&& !getIP().equalsIgnoreCase("localhost")) {
if (plugin.isLoggedIp(realName, getIP())) {
m._(player, "logged_in");
return null;
}
}
PlayerAuth pAuth = database.getAuth(name);
if (pAuth == null) {
m._(player, "user_unknown");
m._(player, "user_unknown");
return null;
}
if (!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) {
m._(player, "vb_nonActiv");
if (!Settings.getMySQLColumnGroup.isEmpty()
&& pAuth.getGroupId() == Settings.getNonActivatedGroup) {
m._(player, "vb_nonActiv");
return null;
}
return pAuth;
@ -114,22 +131,22 @@ public class AsyncronousLogin {
public void process() {
PlayerAuth pAuth = preAuth();
if (pAuth == null || needsCaptcha())
return;
if (pAuth == null || needsCaptcha()) return;
String hash = pAuth.getHash();
String email = pAuth.getEmail();
boolean passwordVerified = true;
if (!forceLogin)
try {
passwordVerified = PasswordSecurity.comparePasswordWithHash(password, hash, realName);
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
m._(player, "error");
return;
}
if (!forceLogin) try {
passwordVerified = PasswordSecurity.comparePasswordWithHash(
password, hash, realName);
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
m._(player, "error");
return;
}
if (passwordVerified && player.isOnline()) {
PlayerAuth auth = new PlayerAuth(name, hash, getIP(), new Date().getTime(), email, realName);
PlayerAuth auth = new PlayerAuth(name, hash, getIP(),
new Date().getTime(), email, realName);
database.updateSession(auth);
if (Settings.useCaptcha) {
@ -146,11 +163,12 @@ public class AsyncronousLogin {
displayOtherAccounts(auth, player);
if (!Settings.noConsoleSpam)
ConsoleLogger.info(player.getName() + " logged in!");
if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
+ " logged in!");
if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged in!"));
plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName() + " logged in!"));
}
// makes player isLoggedin via API
@ -158,36 +176,53 @@ public class AsyncronousLogin {
database.setLogged(name);
plugin.otherAccounts.addPlayer(player.getUniqueId());
// As the scheduling executes the Task most likely after the current task, we schedule it in the end
// so that we can be sure, and have not to care if it might be processed in other order.
ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin(player, plugin, database);
// As the scheduling executes the Task most likely after the current
// task, we schedule it in the end
// so that we can be sure, and have not to care if it might be
// processed in other order.
ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin(
player, plugin, database);
if (syncronousPlayerLogin.getLimbo() != null) {
player.getServer().getScheduler().cancelTask(syncronousPlayerLogin.getLimbo().getTimeoutTaskId());
player.getServer().getScheduler().cancelTask(syncronousPlayerLogin.getLimbo().getMessageTaskId());
player.getServer()
.getScheduler()
.cancelTask(
syncronousPlayerLogin.getLimbo()
.getTimeoutTaskId());
player.getServer()
.getScheduler()
.cancelTask(
syncronousPlayerLogin.getLimbo()
.getMessageTaskId());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, syncronousPlayerLogin);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
syncronousPlayerLogin);
} else if (player.isOnline()) {
if (!Settings.noConsoleSpam)
ConsoleLogger.info(player.getName() + " used the wrong password");
if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
+ " used the wrong password");
if (Settings.isKickOnWrongPasswordEnabled) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (AuthMePlayerListener.gameMode != null && AuthMePlayerListener.gameMode.containsKey(name)) {
player.setGameMode(AuthMePlayerListener.gameMode.get(name));
}
player.kickPlayer(m._("wrong_pwd")[0]);
}
});
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
if (AuthMePlayerListener.gameMode != null
&& AuthMePlayerListener.gameMode
.containsKey(name)) {
player.setGameMode(AuthMePlayerListener.gameMode
.get(name));
}
player.kickPlayer(m._("wrong_pwd")[0]);
}
});
} else {
m._(player, "wrong_pwd");
m._(player, "wrong_pwd");
return;
}
} else {
ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... ");
ConsoleLogger.showError("Player " + name
+ " wasn't online during login process, aborted... ");
}
}
public void displayOtherAccounts(PlayerAuth auth, Player p) {
if (!Settings.displayOtherAccounts) {
return;
@ -196,7 +231,8 @@ public class AsyncronousLogin {
return;
}
List<String> auths = this.database.getAllAuthsByName(auth);
//List<String> uuidlist = plugin.otherAccounts.getAllPlayersByUUID(player.getUniqueId());
// List<String> uuidlist =
// plugin.otherAccounts.getAllPlayersByUUID(player.getUniqueId());
if (auths.isEmpty() || auths == null) {
return;
}
@ -204,7 +240,8 @@ public class AsyncronousLogin {
return;
}
String message = "[AuthMe] ";
//String uuidaccounts = "[AuthMe] PlayerNames has %size% links to this UUID : ";
// String uuidaccounts =
// "[AuthMe] PlayerNames has %size% links to this UUID : ";
int i = 0;
for (String account : auths) {
i++;
@ -215,23 +252,19 @@ public class AsyncronousLogin {
message = message + ".";
}
}
/*TODO: Active uuid system
i = 0;
for (String account : uuidlist) {
i++;
uuidaccounts = uuidaccounts + account;
if (i != auths.size()) {
uuidaccounts = uuidaccounts + ", ";
} else {
uuidaccounts = uuidaccounts + ".";
}
}*/
/*
* TODO: Active uuid system i = 0; for (String account : uuidlist) {
* i++; uuidaccounts = uuidaccounts + account; if (i != auths.size()) {
* uuidaccounts = uuidaccounts + ", "; } else { uuidaccounts =
* uuidaccounts + "."; } }
*/
for (Player player : plugin.getServer().getOnlinePlayers()) {
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(uuidaccounts.replace("%size%", ""+uuidlist.size()));
// player.sendMessage(uuidaccounts.replace("%size%",
// ""+uuidlist.size()));
}
}
}

View File

@ -33,10 +33,11 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
private PluginManager pm;
private FileCache playerCache = new FileCache();
public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin, DataSource data) {
this.plugin = plugin;
this.database = data;
this.pm = plugin.getServer().getPluginManager();
public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin,
DataSource data) {
this.plugin = plugin;
this.database = data;
this.pm = plugin.getServer().getPluginManager();
this.player = player;
this.name = player.getName().toLowerCase();
this.limbo = LimboCache.getInstance().getLimboPlayer(name);
@ -49,18 +50,21 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
protected void restoreOpState() {
player.setOp(limbo.getOperator());
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
if (player.getGameMode() != GameMode.CREATIVE
&& !Settings.isMovementAllowed) {
player.setAllowFlight(limbo.isFlying());
player.setFlying(limbo.isFlying());
}
}
protected void packQuitLocation() {
Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player);
Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(),
auth.getQuitLocZ(), auth.getWorld(), player);
}
protected void teleportBackFromSpawn() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc());
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player,
limbo.getLoc());
pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo();
@ -73,7 +77,8 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
protected void teleportToSpawn() {
Location spawnL = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnL, true);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player,
player.getLocation(), spawnL, true);
pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo();
@ -85,49 +90,57 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
}
protected void restoreInventory() {
RestoreInventoryEvent event = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour());
RestoreInventoryEvent event = new RestoreInventoryEvent(player,
limbo.getInventory(), limbo.getArmour());
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
API.setPlayerInventory(player, event.getInventory(), event.getArmor());
API.setPlayerInventory(player, event.getInventory(),
event.getArmor());
}
}
protected void forceCommands() {
for (String command : Settings.forceCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) {}
}
for (String command : Settings.forceCommandsAsConsole) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%p", player.getName()));
}
for (String command : Settings.forceCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) {
}
}
for (String command : Settings.forceCommandsAsConsole) {
Bukkit.getServer().dispatchCommand(
Bukkit.getServer().getConsoleSender(),
command.replace("%p", player.getName()));
}
}
@Override
public void run() {
// Limbo contains the State of the Player before /login
// Limbo contains the State of the Player before /login
if (limbo != null) {
// Op & Flying
restoreOpState();
/*
* Restore Inventories and GameMode
* We need to restore them before teleport the player
* Cause in AuthMePlayerListener, we call ProtectInventoryEvent after Teleporting
* Also it's the current world inventory !
* Restore Inventories and GameMode We need to restore them before
* teleport the player Cause in AuthMePlayerListener, we call
* ProtectInventoryEvent after Teleporting Also it's the current
* world inventory !
*/
if (!Settings.forceOnlyAfterLogin) {
player.setGameMode(limbo.getGameMode());
// Inventory - Make it after restore GameMode , cause we need to restore the
player.setGameMode(limbo.getGameMode());
// Inventory - Make it after restore GameMode , cause we need to
// restore the
// right inventory in the right gamemode
if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
if (Settings.protectInventoryBeforeLogInEnabled
&& player.hasPlayedBefore()) {
restoreInventory();
}
}
else {
// Inventory - Make it before force the survival GameMode to cancel all
// inventory problem
if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
} else {
// Inventory - Make it before force the survival GameMode to
// cancel all
// inventory problem
if (Settings.protectInventoryBeforeLogInEnabled
&& player.hasPlayedBefore()) {
restoreInventory();
}
player.setGameMode(GameMode.SURVIVAL);
@ -135,25 +148,32 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
if (!Settings.noTeleport) {
// Teleport
if (Settings.isTeleportToSpawnEnabled && !Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) {
if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) {
if (Settings.isTeleportToSpawnEnabled
&& !Settings.isForceSpawnLocOnJoinEnabled
&& Settings.getForcedWorlds.contains(player.getWorld()
.getName())) {
if (Settings.isSaveQuitLocationEnabled
&& auth.getQuitLocY() != 0) {
packQuitLocation();
} else {
teleportBackFromSpawn();
}
} else if (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) {
} else if (Settings.isForceSpawnLocOnJoinEnabled
&& Settings.getForcedWorlds.contains(player.getWorld()
.getName())) {
teleportToSpawn();
} else if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) {
} else if (Settings.isSaveQuitLocationEnabled
&& auth.getQuitLocY() != 0) {
packQuitLocation();
} else {
teleportBackFromSpawn();
}
}
// Re-Force Survival GameMode if we need due to world change specification
if (Settings.isForceSurvivalModeEnabled)
Utils.forceGM(player);
// Re-Force Survival GameMode if we need due to world change
// specification
if (Settings.isForceSurvivalModeEnabled) Utils.forceGM(player);
// Restore Permission Group
Utils.getInstance().setGroup(player, groupType.LOGGEDIN);
@ -165,32 +185,35 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
}
// We can now display the join message
if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (p.isOnline())
p.sendMessage(AuthMePlayerListener.joinMessage.get(name));
}
AuthMePlayerListener.joinMessage.remove(name);
if (AuthMePlayerListener.joinMessage.containsKey(name)
&& AuthMePlayerListener.joinMessage.get(name) != null
&& !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (p.isOnline()) p
.sendMessage(AuthMePlayerListener.joinMessage.get(name));
}
AuthMePlayerListener.joinMessage.remove(name);
}
if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS);
if (Settings.applyBlindEffect) player
.removePotionEffect(PotionEffectType.BLINDNESS);
// 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));
player.saveData();
// Login is finish, display welcome message
if(Settings.useWelcomeMessage)
if(Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
player.sendMessage(plugin.replaceAllInfos(s, player));
}
if (Settings.useWelcomeMessage) if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(
plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
player.sendMessage(plugin.replaceAllInfos(s, player));
}
}
// Login is now finish , we can force all commands
forceCommands();

View File

@ -26,7 +26,8 @@ public class AsyncronousRegister {
private DataSource database;
private Messages m = Messages.getInstance();
public AsyncronousRegister(Player player, String password, String email, AuthMe plugin, DataSource data) {
public AsyncronousRegister(Player player, String password, String email,
AuthMe plugin, DataSource data) {
this.player = player;
this.password = password;
name = player.getName().toLowerCase();
@ -38,11 +39,11 @@ public class AsyncronousRegister {
}
protected String getIp() {
return plugin.getIP(player);
return plugin.getIP(player);
}
protected void preRegister() {
if (PlayerCache.getInstance().isAuthenticated(name)) {
if (PlayerCache.getInstance().isAuthenticated(name)) {
m._(player, "logged_in");
allowRegister = false;
}
@ -54,8 +55,9 @@ public class AsyncronousRegister {
String lowpass = password.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.contains("insert") || lowpass.contains("modify")
|| lowpass.contains("from") || lowpass.contains("select")
|| lowpass.contains(";") || lowpass.contains("null"))
|| !lowpass.matches(Settings.getPassRegex)) {
m._(player, "password_error");
allowRegister = false;
@ -63,102 +65,122 @@ public class AsyncronousRegister {
if (database.isAuthAvailable(player.getName().toLowerCase())) {
m._(player, "user_regged");
if (plugin.pllog.getStringList("players").contains(player.getName())) {
plugin.pllog.getStringList("players").remove(player.getName());
if (plugin.pllog.getStringList("players")
.contains(player.getName())) {
plugin.pllog.getStringList("players").remove(player.getName());
}
allowRegister = false;
}
if(Settings.getmaxRegPerIp > 0 ){
if(!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp && !getIp().equalsIgnoreCase("127.0.0.1") && !getIp().equalsIgnoreCase("localhost")) {
m._(player, "max_reg");
allowRegister = false;
}
if (Settings.getmaxRegPerIp > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts")
&& database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp
&& !getIp().equalsIgnoreCase("127.0.0.1")
&& !getIp().equalsIgnoreCase("localhost")) {
m._(player, "max_reg");
allowRegister = false;
}
}
}
public void process() {
preRegister();
if(!allowRegister) return;
if(!email.isEmpty() && email != "") {
if(Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return;
}
}
emailRegister();
return;
}
passwordRegister();
preRegister();
if (!allowRegister) return;
if (!email.isEmpty() && email != "") {
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts")
&& database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return;
}
}
emailRegister();
return;
}
passwordRegister();
}
protected void emailRegister() {
if(Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return;
}
}
PlayerAuth auth = null;
try {
final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
auth = new PlayerAuth(name, hashnew, getIp(), new Date().getTime(), (int) player.getLocation().getX() , (int) player.getLocation().getY(), (int) player.getLocation().getZ(), player.getLocation().getWorld().getName(), email, realName);
} catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
m._(player, "error");
return;
}
if (PasswordSecurity.userSalt.containsKey(name)) {
auth.setSalt(PasswordSecurity.userSalt.get(name));
}
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts")
&& database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg");
return;
}
}
PlayerAuth auth = null;
try {
final String hashnew = PasswordSecurity.getHash(
Settings.getPasswordHash, password, name);
auth = new PlayerAuth(name, hashnew, getIp(), new Date().getTime(),
(int) player.getLocation().getX(), (int) player
.getLocation().getY(), (int) player.getLocation()
.getZ(), player.getLocation().getWorld().getName(),
email, realName);
} catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
m._(player, "error");
return;
}
if (PasswordSecurity.userSalt.containsKey(name)) {
auth.setSalt(PasswordSecurity.userSalt.get(name));
}
database.saveAuth(auth);
database.updateEmail(auth);
database.updateSession(auth);
plugin.mail.main(auth, password);
ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
return;
database.updateEmail(auth);
database.updateSession(auth);
plugin.mail.main(auth, password);
ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(
player, plugin);
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, syncronous);
return;
}
protected void passwordRegister() {
if(password.length() < Settings.getPasswordMinLen || password.length() > Settings.passwordMaxLength) {
m._(player, "pass_len");
if (password.length() < Settings.getPasswordMinLen
|| password.length() > Settings.passwordMaxLength) {
m._(player, "pass_len");
return;
}
if(!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(password.toLowerCase())) {
m._(player, "password_error");
return;
}
if (!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(password.toLowerCase())) {
m._(player, "password_error");
return;
}
}
PlayerAuth auth = null;
String hash = "";
try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
} catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
m._(player, "error");
return;
}
if (Settings.getMySQLColumnSalt.isEmpty() && !PasswordSecurity.userSalt.containsKey(name))
{
auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(), "your@email.com", player.getName());
try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, password,
name);
} catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
m._(player, "error");
return;
}
if (Settings.getMySQLColumnSalt.isEmpty()
&& !PasswordSecurity.userSalt.containsKey(name)) {
auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(),
"your@email.com", player.getName());
} else {
auth = new PlayerAuth(name, hash, PasswordSecurity.userSalt.get(name), getIp(), new Date().getTime(), player.getName());
auth = new PlayerAuth(name, hash,
PasswordSecurity.userSalt.get(name), getIp(),
new Date().getTime(), player.getName());
}
if (!database.saveAuth(auth)) {
m._(player, "error");
m._(player, "error");
return;
}
if (!Settings.forceRegLogin) {
PlayerCache.getInstance().addPlayer(auth);
database.setLogged(name);
database.setLogged(name);
}
plugin.otherAccounts.addPlayer(player.getUniqueId());
ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(
player, plugin);
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, syncronous);
return;
}
}

View File

@ -20,56 +20,69 @@ import fr.xephi.authme.task.TimeoutTask;
public class ProcessSyncronousEmailRegister implements Runnable {
protected Player player;
protected String name;
private AuthMe plugin;
private Messages m = Messages.getInstance();
public ProcessSyncronousEmailRegister(Player player, AuthMe plugin) {
this.player = player;
this.name = player.getName().toLowerCase();
this.plugin = plugin;
}
@Override
public void run() {
if(!Settings.getRegisteredGroup.isEmpty()){
protected Player player;
protected String name;
private AuthMe plugin;
private Messages m = Messages.getInstance();
public ProcessSyncronousEmailRegister(Player player, AuthMe plugin) {
this.player = player;
this.name = player.getName().toLowerCase();
this.plugin = plugin;
}
@Override
public void run() {
if (!Settings.getRegisteredGroup.isEmpty()) {
Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
}
m._(player, "vb_nonActiv");
int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval;
int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval;
if (time != 0) {
Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getTimeoutTaskId());
int id = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), time);
Bukkit.getScheduler().cancelTask(
LimboCache.getInstance().getLimboPlayer(name)
.getTimeoutTaskId());
int id = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new TimeoutTask(plugin, name), time);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId());
int nwMsg = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), msgInterval));
Bukkit.getScheduler().cancelTask(
LimboCache.getInstance().getLimboPlayer(name)
.getMessageTaskId());
int nwMsg = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new MessageTask(plugin, name, m._("login_msg"), msgInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(nwMsg);
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, loca);
Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player,
loca);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if(!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
}
player.teleport(tpEvent.getTo());
if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.load();
}
player.teleport(tpEvent.getTo());
}
}
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
if (player.getGameMode() != GameMode.CREATIVE
&& !Settings.isMovementAllowed) {
player.setAllowFlight(false);
player.setFlying(false);
}
if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS);
if (Settings.applyBlindEffect) player
.removePotionEffect(PotionEffectType.BLINDNESS);
player.saveData();
if (!Settings.noConsoleSpam)
ConsoleLogger.info(player.getName() + " registered "+plugin.getIP(player));
if(plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " has registered by email!"));
if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
+ " registered " + plugin.getIP(player));
if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] "
+ player.getName() + " has registered by email!"));
}
}
}
}

View File

@ -24,125 +24,138 @@ import fr.xephi.authme.task.TimeoutTask;
public class ProcessSyncronousPasswordRegister implements Runnable {
protected Player player;
protected String name;
private AuthMe plugin;
private Messages m = Messages.getInstance();
public ProcessSyncronousPasswordRegister(Player player, AuthMe plugin) {
this.player = player;
this.name = player.getName().toLowerCase();
this.plugin = plugin;
}
protected void forceCommands(Player player) {
for (String command : Settings.forceCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) {}
}
protected Player player;
protected String name;
private AuthMe plugin;
private Messages m = Messages.getInstance();
public ProcessSyncronousPasswordRegister(Player player, AuthMe plugin) {
this.player = player;
this.name = player.getName().toLowerCase();
this.plugin = plugin;
}
protected void forceLogin(Player player) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawnLoc);
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());
protected void forceCommands(Player player) {
for (String command : Settings.forceCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) {
}
}
if (LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().deleteLimboPlayer(name);
}
protected void forceLogin(Player player) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player,
spawnLoc);
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 (LimboCache.getInstance().hasLimboPlayer(name)) LimboCache
.getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player);
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = plugin.getServer().getScheduler();
if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(
plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), interval));
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(
plugin, name, m._("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
try {
plugin.pllog.removePlayer(name);
if (player.isInsideVehicle())
player.getVehicle().eject();
plugin.pllog.removePlayer(name);
if (player.isInsideVehicle()) player.getVehicle().eject();
} catch (NullPointerException npe) {
}
}
@Override
public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (limbo != null) {
player.setGameMode(limbo.getGameMode());
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, loca);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if(!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
}
player.teleport(tpEvent.getTo());
}
}
plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId());
plugin.getServer().getScheduler().cancelTask(limbo.getMessageTaskId());
LimboCache.getInstance().deleteLimboPlayer(name);
}
}
if(!Settings.getRegisteredGroup.isEmpty()){
Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
}
m._(player, "registered");
if (!Settings.getmailAccount.isEmpty())
m._(player, "add_email");
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
player.setAllowFlight(false);
player.setFlying(false);
}
if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS);
// The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
player.saveData();
if (!Settings.noConsoleSpam)
ConsoleLogger.info(player.getName() + " registered "+plugin.getIP(player));
if(plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " has registered!"));
}
@Override
public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (limbo != null) {
player.setGameMode(limbo.getGameMode());
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(
player, loca);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.load();
}
player.teleport(tpEvent.getTo());
}
}
plugin.getServer().getScheduler()
.cancelTask(limbo.getTimeoutTaskId());
plugin.getServer().getScheduler()
.cancelTask(limbo.getMessageTaskId());
LimboCache.getInstance().deleteLimboPlayer(name);
}
// Kick Player after Registration is enabled, kick the player
if (Settings.forceRegKick) {
player.kickPlayer(m._("registered")[0]);
return;
}
if (!Settings.getRegisteredGroup.isEmpty()) {
Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
}
m._(player, "registered");
if (!Settings.getmailAccount.isEmpty()) m._(player, "add_email");
if (player.getGameMode() != GameMode.CREATIVE
&& !Settings.isMovementAllowed) {
player.setAllowFlight(false);
player.setFlying(false);
}
if (Settings.applyBlindEffect) player
.removePotionEffect(PotionEffectType.BLINDNESS);
// The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager()
.callEvent(new LoginEvent(player, true));
player.saveData();
// Request Login after Registation
if (Settings.forceRegLogin) {
forceLogin(player);
return;
}
if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
+ " registered " + plugin.getIP(player));
if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] "
+ player.getName() + " has registered!"));
}
// Register is finish and player is logged, display welcome message
if(Settings.useWelcomeMessage)
if(Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
player.sendMessage(plugin.replaceAllInfos(s, player));
}
}
// Kick Player after Registration is enabled, kick the player
if (Settings.forceRegKick) {
player.kickPlayer(m._("registered")[0]);
return;
}
// Register is now finish , we can force all commands
forceCommands(player);
// Request Login after Registation
if (Settings.forceRegLogin) {
forceLogin(player);
return;
}
}
// Register is finish and player is logged, display welcome message
if (Settings.useWelcomeMessage) if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(
plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
player.sendMessage(plugin.replaceAllInfos(s, player));
}
}
// Register is now finish , we can force all commands
forceCommands(player);
}
}

View File

@ -15,7 +15,6 @@ import fr.xephi.authme.security.crypts.BCRYPT;
import fr.xephi.authme.security.crypts.EncryptionMethod;
import fr.xephi.authme.settings.Settings;
public class PasswordSecurity {
private static SecureRandom rnd = new SecureRandom();
@ -27,145 +26,157 @@ public class PasswordSecurity {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset();
byte[] digest = sha1.digest(msg);
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)).substring(0, length);
return String.format("%0" + (digest.length << 1) + "x",
new BigInteger(1, digest)).substring(0, length);
}
public static String getHash(HashAlgorithm alg, String password, String playerName) throws NoSuchAlgorithmException {
EncryptionMethod method;
try {
if (alg != HashAlgorithm.CUSTOM)
method = (EncryptionMethod) alg.getclass().newInstance();
else method = null;
} catch (InstantiationException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
} catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
}
String salt = "";
switch (alg) {
case SHA256:
salt = createSalt(16);
break;
case MD5VB:
salt = createSalt(16);
break;
case XAUTH:
salt = createSalt(12);
break;
case MYBB:
salt = createSalt(8);
userSalt.put(playerName, salt);
break;
case IPB3:
salt = createSalt(5);
userSalt.put(playerName, salt);
break;
case PHPFUSION:
salt = createSalt(12);
userSalt.put(playerName, salt);
break;
case SALTED2MD5:
salt = createSalt(Settings.saltLength);
userSalt.put(playerName, salt);
break;
case JOOMLA:
salt = createSalt(32);
userSalt.put(playerName, salt);
break;
case BCRYPT:
salt = BCRYPT.gensalt(Settings.bCryptLog2Rounds);
userSalt.put(playerName, salt);
break;
case WBB3:
salt = createSalt(40);
userSalt.put(playerName, salt);
break;
case WBB4:
salt = BCRYPT.gensalt(8);
userSalt.put(playerName, salt);
break;
case PBKDF2:
salt = createSalt(12);
userSalt.put(playerName, salt);
break;
case SMF:
return method.getHash(password, null, playerName);
case PHPBB:
salt = createSalt(16);
userSalt.put(playerName, salt);
break;
case MD5:
case SHA1:
case WHIRLPOOL:
case PLAINTEXT:
case XENFORO:
case SHA512:
case ROYALAUTH:
case CRAZYCRYPT1:
case DOUBLEMD5:
case WORDPRESS:
case CUSTOM:
break;
default:
throw new NoSuchAlgorithmException("Unknown hash algorithm");
public static String getHash(HashAlgorithm alg, String password,
String playerName) throws NoSuchAlgorithmException {
EncryptionMethod method;
try {
if (alg != HashAlgorithm.CUSTOM) method = (EncryptionMethod) alg
.getclass().newInstance();
else method = null;
} catch (InstantiationException e) {
throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
} catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
}
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
String salt = "";
switch (alg) {
case SHA256:
salt = createSalt(16);
break;
case MD5VB:
salt = createSalt(16);
break;
case XAUTH:
salt = createSalt(12);
break;
case MYBB:
salt = createSalt(8);
userSalt.put(playerName, salt);
break;
case IPB3:
salt = createSalt(5);
userSalt.put(playerName, salt);
break;
case PHPFUSION:
salt = createSalt(12);
userSalt.put(playerName, salt);
break;
case SALTED2MD5:
salt = createSalt(Settings.saltLength);
userSalt.put(playerName, salt);
break;
case JOOMLA:
salt = createSalt(32);
userSalt.put(playerName, salt);
break;
case BCRYPT:
salt = BCRYPT.gensalt(Settings.bCryptLog2Rounds);
userSalt.put(playerName, salt);
break;
case WBB3:
salt = createSalt(40);
userSalt.put(playerName, salt);
break;
case WBB4:
salt = BCRYPT.gensalt(8);
userSalt.put(playerName, salt);
break;
case PBKDF2:
salt = createSalt(12);
userSalt.put(playerName, salt);
break;
case SMF:
return method.getHash(password, null, playerName);
case PHPBB:
salt = createSalt(16);
userSalt.put(playerName, salt);
break;
case MD5:
case SHA1:
case WHIRLPOOL:
case PLAINTEXT:
case XENFORO:
case SHA512:
case ROYALAUTH:
case CRAZYCRYPT1:
case DOUBLEMD5:
case WORDPRESS:
case CUSTOM:
break;
default:
throw new NoSuchAlgorithmException("Unknown hash algorithm");
}
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method,
playerName);
Bukkit.getPluginManager().callEvent(event);
method = event.getMethod();
if (method == null)
throw new NoSuchAlgorithmException("Unknown hash algorithm");
if (method == null) throw new NoSuchAlgorithmException(
"Unknown hash algorithm");
return method.getHash(password, salt, playerName);
}
public static boolean comparePasswordWithHash(String password, String hash, String playerName) throws NoSuchAlgorithmException {
HashAlgorithm algo = Settings.getPasswordHash;
EncryptionMethod method;
try {
if (algo != HashAlgorithm.CUSTOM)
method = (EncryptionMethod) algo.getclass().newInstance();
else method = null;
} catch (InstantiationException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
} catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
}
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
public static boolean comparePasswordWithHash(String password, String hash,
String playerName) throws NoSuchAlgorithmException {
HashAlgorithm algo = Settings.getPasswordHash;
EncryptionMethod method;
try {
if (algo != HashAlgorithm.CUSTOM) method = (EncryptionMethod) algo
.getclass().newInstance();
else method = null;
} catch (InstantiationException e) {
throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
} catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
}
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method,
playerName);
Bukkit.getPluginManager().callEvent(event);
method = event.getMethod();
if (method == null)
throw new NoSuchAlgorithmException("Unknown hash algorithm");
if (method == null) throw new NoSuchAlgorithmException(
"Unknown hash algorithm");
try {
if (method.comparePassword(hash, password, playerName))
return true;
if (method.comparePassword(hash, password, playerName)) return true;
} catch (Exception e) {
}
if (Settings.supportOldPassword) {
try {
if (compareWithAllEncryptionMethod(password, hash, playerName))
return true;
} catch (Exception e) {}
try {
if (compareWithAllEncryptionMethod(password, hash, playerName)) return true;
} catch (Exception e) {
}
}
return false;
}
private static boolean compareWithAllEncryptionMethod(String password, String hash, String playerName) throws NoSuchAlgorithmException {
for (HashAlgorithm algo : HashAlgorithm.values()) {
if (algo != HashAlgorithm.CUSTOM)
try {
EncryptionMethod method = (EncryptionMethod) algo.getclass().newInstance();
if (method.comparePassword(hash, password, playerName)) {
PlayerAuth nAuth = AuthMe.getInstance().database.getAuth(playerName);
if (nAuth != null) {
nAuth.setHash(getHash(Settings.getPasswordHash, password, playerName));
nAuth.setSalt(userSalt.get(playerName));
AuthMe.getInstance().database.updatePassword(nAuth);
AuthMe.getInstance().database.updateSalt(nAuth);
}
return true;
}
} catch (Exception e) {}
}
return false;
private static boolean compareWithAllEncryptionMethod(String password,
String hash, String playerName) throws NoSuchAlgorithmException {
for (HashAlgorithm algo : HashAlgorithm.values()) {
if (algo != HashAlgorithm.CUSTOM) try {
EncryptionMethod method = (EncryptionMethod) algo.getclass()
.newInstance();
if (method.comparePassword(hash, password, playerName)) {
PlayerAuth nAuth = AuthMe.getInstance().database
.getAuth(playerName);
if (nAuth != null) {
nAuth.setHash(getHash(Settings.getPasswordHash,
password, playerName));
nAuth.setSalt(userSalt.get(playerName));
AuthMe.getInstance().database.updatePassword(nAuth);
AuthMe.getInstance().database.updateSalt(nAuth);
}
return true;
}
} catch (Exception e) {
}
}
return false;
}
}

View File

@ -3,37 +3,34 @@ package fr.xephi.authme.security;
import java.util.Random;
/**
*
* @author Xephi59
*/
public class RandomString
{
*
* @author Xephi59
*/
public class RandomString {
private static final char[] chars = new char[36];
private static final char[] chars = new char[36];
static {
for (int idx = 0; idx < 10; ++idx)
chars[idx] = (char) ('0' + idx);
for (int idx = 10; idx < 36; ++idx)
chars[idx] = (char) ('a' + idx - 10);
}
static {
for (int idx = 0; idx < 10; ++idx)
chars[idx] = (char) ('0' + idx);
for (int idx = 10; idx < 36; ++idx)
chars[idx] = (char) ('a' + idx - 10);
}
private final Random random = new Random();
private final Random random = new Random();
private final char[] buf;
private final char[] buf;
public RandomString(int length)
{
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
}
public RandomString(int length) {
if (length < 1) throw new IllegalArgumentException("length < 1: "
+ length);
buf = new char[length];
}
public String nextString()
{
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = chars[random.nextInt(chars.length)];
return new String(buf);
}
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = chars[random.nextInt(chars.length)];
return new String(buf);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -7,12 +7,14 @@ import java.security.NoSuchAlgorithmException;
public class CRAZYCRYPT1 implements EncryptionMethod {
protected final Charset charset = Charset.forName("UTF-8");
private static final char[] CRYPTCHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] CRYPTCHARS = new char[] { '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
final String text = "ÜÄaeut//&/=I " + password + "7421€547" + name + "__+IÄIH§%NK " + password;
final String text = "ÜÄaeut//&/=I " + password + "7421€547" + name
+ "__+IÄIH§%NK " + password;
try {
final MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(text.getBytes(charset), 0, text.length());
@ -27,7 +29,7 @@ public class CRAZYCRYPT1 implements EncryptionMethod {
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, null, playerName));
}
public static String byteArrayToHexString(final byte... args) {
final char[] chars = new char[args.length * 2];
for (int i = 0; i < args.length; i++) {
@ -36,4 +38,4 @@ public class CRAZYCRYPT1 implements EncryptionMethod {
}
return new String(chars);
}
}
}

View File

@ -5,28 +5,29 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.security.pbkdf2.PBKDF2Engine;
import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters;
public class CryptPBKDF2 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
String result = "pbkdf2_sha256$10000$"+salt+"$";
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000);
PBKDF2Engine engine = new PBKDF2Engine(params);
return result + engine.deriveKey(password,64).toString();
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
String result = "pbkdf2_sha256$10000$" + salt + "$";
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII",
salt.getBytes(), 10000);
PBKDF2Engine engine = new PBKDF2Engine(params);
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
String salt = line[2];
String derivedKey = line[3];
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000, derivedKey.getBytes());
PBKDF2Engine engine = new PBKDF2Engine(params);
return engine.verifyKey(password);
}
return result + engine.deriveKey(password, 64).toString();
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
String salt = line[2];
String derivedKey = line[3];
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII",
salt.getBytes(), 10000, derivedKey.getBytes());
PBKDF2Engine engine = new PBKDF2Engine(params);
return engine.verifyKey(password);
}
}

View File

@ -6,24 +6,26 @@ import java.security.NoSuchAlgorithmException;
public class DOUBLEMD5 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(password));
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(password));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
private static String getMD5(String message) throws NoSuchAlgorithmException {
private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -3,28 +3,38 @@ package fr.xephi.authme.security.crypts;
import java.security.NoSuchAlgorithmException;
/**
* <p>Public interface for Custom Password encryption method</p>
* <p>The getHash function is called when we need to crypt the password (/register usually)</p>
* <p>The comparePassword is called when we need to match password (/login usually)</p>
* <p>
* Public interface for Custom Password encryption method
* </p>
* <p>
* The getHash function is called when we need to crypt the password (/register
* usually)
* </p>
* <p>
* The comparePassword is called when we need to match password (/login usually)
* </p>
*/
public interface EncryptionMethod {
/**
* @param password
* @param salt (can be an other data like playerName;salt , playerName, etc...
* for customs methods)
* @return Hashing password
* @throws NoSuchAlgorithmException
*/
String getHash(String password, String salt, String name) throws NoSuchAlgorithmException;
/**
* @param password
* @param salt
* (can be an other data like playerName;salt , playerName,
* etc... for customs methods)
* @return Hashing password
* @throws NoSuchAlgorithmException
*/
String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException;
/**
* @param hash
* @param password
* @param playerName
* @return true if password match, false else
* @throws NoSuchAlgorithmException
*/
boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException;
/**
* @param hash
* @param password
* @param playerName
* @return true if password match, false else
* @throws NoSuchAlgorithmException
*/
boolean comparePassword(String hash, String password, String playerName)
throws NoSuchAlgorithmException;
}

View File

@ -6,27 +6,29 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe;
public class IPB3 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(salt) + getMD5(password));
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(salt) + getMD5(password));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
return hash.equals(getHash(password, salt, playerName));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, playerName));
}
private static String getMD5(String message) throws NoSuchAlgorithmException {
private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,24 +6,26 @@ import java.security.NoSuchAlgorithmException;
public class JOOMLA implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(password + salt) + ":" + salt;
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(password + salt) + ":" + salt;
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = hash.split(":")[1];
return hash.equals(getMD5(password + salt) + ":" + salt);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = hash.split(":")[1];
return hash.equals(getMD5(password + salt) + ":" + salt);
}
private static String getMD5(String message) throws NoSuchAlgorithmException {
private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,21 +6,25 @@ import java.security.NoSuchAlgorithmException;
public class MD5 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(password);
}
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
private static String getMD5(String message) throws NoSuchAlgorithmException {
private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,25 +6,27 @@ import java.security.NoSuchAlgorithmException;
public class MD5VB implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return "$MD5vb$" + salt + "$" + getMD5(getMD5(password) + salt);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return "$MD5vb$" + salt + "$" + getMD5(getMD5(password) + salt);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
return hash.equals(getHash(password, line[2], ""));
}
private static String getMD5(String message) throws NoSuchAlgorithmException {
}
private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,27 +6,29 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe;
public class MYBB implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(salt)+ getMD5(password));
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(salt) + getMD5(password));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
return hash.equals(getHash(password, salt, playerName));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, playerName));
}
private static String getMD5(String message) throws NoSuchAlgorithmException {
private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -1,6 +1,6 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
package fr.xephi.authme.security.crypts;
@ -14,151 +14,138 @@ import java.security.NoSuchAlgorithmException;
* @author stefano
*/
public class PHPBB implements EncryptionMethod {
private static final int PHP_VERSION = 4;
private String itoa64 =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final int PHP_VERSION = 4;
private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public String phpbb_hash(String password, String salt) {
String random_state = salt;
String random = "";
int count = 6;
if (random.length() < count) {
random = "";
for (int i = 0; i < count; i += 16) {
random_state = md5(salt + random_state);
random += pack(md5(random_state));
}
random = random.substring(0, count);
public String phpbb_hash(String password, String salt) {
String random_state = salt;
String random = "";
int count = 6;
if (random.length() < count) {
random = "";
for (int i = 0; i < count; i += 16) {
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));
if (hash.length() == 34) return hash;
return md5(password);
}
String hash = _hash_crypt_private(
password, _hash_gensalt_private(random, itoa64));
if (hash.length() == 34)
return hash;
return md5(password);
}
private String _hash_gensalt_private(String input, String itoa64) {
return _hash_gensalt_private(input, itoa64, 6);
}
@SuppressWarnings("unused")
private String _hash_gensalt_private(
String input, String itoa64, int iteration_count_log2) {
if (iteration_count_log2 < 4 || iteration_count_log2 > 31) {
iteration_count_log2 = 8;
private String _hash_gensalt_private(String input, String itoa64) {
return _hash_gensalt_private(input, itoa64, 6);
}
String output = "$H$";
output += itoa64.charAt(
Math.min(iteration_count_log2 +
((PHP_VERSION >= 5) ? 5 : 3), 30));
output += _hash_encode64(input, 6);
return output;
}
/**
* Encode hash
*/
private String _hash_encode64(String input, int count) {
String output = "";
int i = 0;
do {
int value = input.charAt(i++);
output += itoa64.charAt(value & 0x3f);
if (i < count)
value |= input.charAt(i) << 8;
output += itoa64.charAt((value >> 6) & 0x3f);
if (i++ >= count)
break;
if (i < count)
value |= input.charAt(i) << 16;
output += itoa64.charAt((value >> 12) & 0x3f);
if (i++ >= count)
break;
output += itoa64.charAt((value >> 18) & 0x3f);
} while (i < count);
return output;
}
String _hash_crypt_private(String password, String setting) {
String output = "*";
if (!setting.substring(0, 3).equals("$H$"))
@SuppressWarnings("unused")
private String _hash_gensalt_private(String input, String itoa64,
int iteration_count_log2) {
if (iteration_count_log2 < 4 || iteration_count_log2 > 31) {
iteration_count_log2 = 8;
}
String output = "$H$";
output += itoa64.charAt(Math.min(iteration_count_log2
+ ((PHP_VERSION >= 5) ? 5 : 3), 30));
output += _hash_encode64(input, 6);
return output;
int count_log2 = itoa64.indexOf(setting.charAt(3));
if (count_log2 < 7 || count_log2 > 30)
}
/**
* Encode hash
*/
private String _hash_encode64(String input, int count) {
String output = "";
int i = 0;
do {
int value = input.charAt(i++);
output += itoa64.charAt(value & 0x3f);
if (i < count) value |= input.charAt(i) << 8;
output += itoa64.charAt((value >> 6) & 0x3f);
if (i++ >= count) break;
if (i < count) value |= input.charAt(i) << 16;
output += itoa64.charAt((value >> 12) & 0x3f);
if (i++ >= count) break;
output += itoa64.charAt((value >> 18) & 0x3f);
} while (i < count);
return output;
int count = 1 << count_log2;
String salt = setting.substring(4, 12);
if (salt.length() != 8)
}
String _hash_crypt_private(String password, String setting) {
String output = "*";
if (!setting.substring(0, 3).equals("$H$")) return output;
int count_log2 = itoa64.indexOf(setting.charAt(3));
if (count_log2 < 7 || count_log2 > 30) return output;
int count = 1 << count_log2;
String salt = setting.substring(4, 12);
if (salt.length() != 8) return output;
String m1 = md5(salt + password);
String hash = pack(m1);
do {
hash = pack(md5(hash + password));
} while (--count > 0);
output = setting.substring(0, 12);
output += _hash_encode64(hash, 16);
return output;
String m1 = md5(salt + password);
String hash = pack(m1);
do {
hash = pack(md5(hash + password));
} while (--count > 0);
output = setting.substring(0, 12);
output += _hash_encode64(hash, 16);
return output;
}
public boolean phpbb_check_hash( String password, String hash) {
if (hash.length() == 34)
return _hash_crypt_private(password, hash).equals(hash);
else
return md5(password).equals(hash);
}
public static String md5(String data) {
try {
byte[] bytes = data.getBytes("ISO-8859-1");
MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] hash = md5er.digest(bytes);
return bytes2hex(hash);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
static int hexToInt(char ch) {
if(ch >= '0' && ch <= '9')
return ch - '0';
ch = Character.toUpperCase(ch);
if(ch >= 'A' && ch <= 'F')
return ch - 'A' + 0xA;
throw new IllegalArgumentException("Not a hex character: " + ch);
}
private static String bytes2hex(byte[] bytes) {
StringBuffer r = new StringBuffer(32);
for (int i = 0; i < bytes.length; i++) {
String x = Integer.toHexString(bytes[i] & 0xff);
if (x.length() < 2)
r.append("0");
r.append(x);
public boolean phpbb_check_hash(String password, String hash) {
if (hash.length() == 34) return _hash_crypt_private(password, hash)
.equals(hash);
else return md5(password).equals(hash);
}
return r.toString();
}
static String pack(String hex) {
StringBuffer buf = new StringBuffer();
for(int i = 0; i < hex.length(); i += 2) {
char c1 = hex.charAt(i);
char c2 = hex.charAt(i+1);
char packed = (char) (hexToInt(c1) * 16 + hexToInt(c2));
buf.append(packed);
public static String md5(String data) {
try {
byte[] bytes = data.getBytes("ISO-8859-1");
MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] hash = md5er.digest(bytes);
return bytes2hex(hash);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return buf.toString();
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return phpbb_hash(password, salt);
}
static int hexToInt(char ch) {
if (ch >= '0' && ch <= '9') return ch - '0';
ch = Character.toUpperCase(ch);
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 0xA;
throw new IllegalArgumentException("Not a hex character: " + ch);
}
@Override
public boolean comparePassword(String hash, String password, String playerName)
throws NoSuchAlgorithmException {
return phpbb_check_hash(password, hash);
}
private static String bytes2hex(byte[] bytes) {
StringBuffer r = new StringBuffer(32);
for (int i = 0; i < bytes.length; i++) {
String x = Integer.toHexString(bytes[i] & 0xff);
if (x.length() < 2) r.append("0");
r.append(x);
}
return r.toString();
}
static String pack(String hex) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < hex.length(); i += 2) {
char c1 = hex.charAt(i);
char c2 = hex.charAt(i + 1);
char packed = (char) (hexToInt(c1) * 16 + hexToInt(c2));
buf.append(packed);
}
return buf.toString();
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return phpbb_hash(password, salt);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return phpbb_check_hash(password, hash);
}
}

View File

@ -11,49 +11,52 @@ import javax.crypto.spec.SecretKeySpec;
import fr.xephi.authme.AuthMe;
public class PHPFUSION implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
String digest = null;
String algo = "HmacSHA256";
String keyString = getSHA1(salt);
try {
SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);
Mac mac = Mac.getInstance(algo);
mac.init(key);
byte[] bytes = mac.doFinal(password.getBytes("ASCII"));
StringBuffer hash = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hash.append('0');
SecretKeySpec key = new SecretKeySpec(
(keyString).getBytes("UTF-8"), algo);
Mac mac = Mac.getInstance(algo);
mac.init(key);
byte[] bytes = mac.doFinal(password.getBytes("ASCII"));
StringBuffer hash = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
hash.append(hex);
}
digest = hash.toString();
digest = hash.toString();
} catch (UnsupportedEncodingException e) {
} catch (InvalidKeyException e) {
} catch (NoSuchAlgorithmException e) {
}
return digest;
}
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
return hash.equals(getHash(password, salt, ""));
}
private static String getSHA1(String message) throws NoSuchAlgorithmException {
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, ""));
}
private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset();
sha1.update(message.getBytes());
byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -4,16 +4,16 @@ import java.security.NoSuchAlgorithmException;
public class PLAINTEXT implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return password;
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return password;
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(password);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(password);
}
}

View File

@ -5,26 +5,30 @@ import java.security.NoSuchAlgorithmException;
public class ROYALAUTH implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
for (int i = 0; i < 25; i++)
password = hash(password, salt);
return password;
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
for (int i = 0; i < 25; i++)
password = hash(password, salt);
return password;
}
public String hash(String password, String salt) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(password.getBytes());
byte byteData[] = md.digest();
StringBuilder sb = new StringBuilder();
for (byte aByteData : byteData)
sb.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1));
return sb.toString();
}
public String hash(String password, String salt)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(password.getBytes());
byte byteData[] = md.digest();
StringBuilder sb = new StringBuilder();
for (byte aByteData : byteData)
sb.append(Integer.toString((aByteData & 0xff) + 0x100, 16)
.substring(1));
return sb.toString();
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
return hash.equalsIgnoreCase(getHash(password, "", ""));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equalsIgnoreCase(getHash(password, "", ""));
}
}

View File

@ -6,27 +6,29 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe;
public class SALTED2MD5 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(password) + salt);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(getMD5(password) + salt);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
return hash.equals(getMD5(getMD5(password) + salt));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getMD5(getMD5(password) + salt));
}
private static String getMD5(String message) throws NoSuchAlgorithmException {
private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,23 +6,26 @@ import java.security.NoSuchAlgorithmException;
public class SHA1 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return getSHA1(password);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA1(password);
}
@Override
public boolean comparePassword(String hash, String password, String playerName)
throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
private static String getSHA1(String message) throws NoSuchAlgorithmException {
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset();
sha1.update(message.getBytes());
byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,24 +6,27 @@ import java.security.NoSuchAlgorithmException;
public class SHA256 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return "$SHA$" + salt + "$" + getSHA256(getSHA256(password) + salt);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return "$SHA$" + salt + "$" + getSHA256(getSHA256(password) + salt);
}
@Override
public boolean comparePassword(String hash, String password, String playerName)
throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
return hash.equals(getHash(password, line[2], ""));
}
private static String getSHA256(String message) throws NoSuchAlgorithmException {
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
return hash.equals(getHash(password, line[2], ""));
}
private static String getSHA256(String message)
throws NoSuchAlgorithmException {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
sha256.reset();
sha256.update(message.getBytes());
byte[] digest = sha256.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,23 +6,25 @@ import java.security.NoSuchAlgorithmException;
public class SHA512 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA512(password);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA512(password);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
private static String getSHA512(String message) throws NoSuchAlgorithmException {
private static String getSHA512(String message)
throws NoSuchAlgorithmException {
MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
sha512.reset();
sha512.update(message.getBytes());
byte[] digest = sha512.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,23 +6,25 @@ import java.security.NoSuchAlgorithmException;
public class SMF implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA1(name.toLowerCase() + password);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA1(name.toLowerCase() + password);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, null, playerName));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, null, playerName));
}
private static String getSHA1(String message) throws NoSuchAlgorithmException {
private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset();
sha1.update(message.getBytes());
byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -6,27 +6,29 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe;
public class WBB3 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA1(salt.concat(getSHA1(salt.concat(getSHA1(password)))));
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA1(salt.concat(getSHA1(salt.concat(getSHA1(password)))));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
return hash.equals(getHash(password, salt, ""));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, ""));
}
private static String getSHA1(String message) throws NoSuchAlgorithmException {
private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset();
sha1.update(message.getBytes());
byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest));
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
}
}

View File

@ -4,16 +4,16 @@ import java.security.NoSuchAlgorithmException;
public class WBB4 implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return BCRYPT.getDoubleHash(password, salt);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return BCRYPT.getDoubleHash(password, salt);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return BCRYPT.checkpw(password, hash, 2);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return BCRYPT.checkpw(password, hash, 2);
}
}

View File

@ -7,53 +7,57 @@ package fr.xephi.authme.security.crypts;
* <b>References</b>
*
* <P>
* The Whirlpool algorithm was developed by
* <a href="mailto:pbarreto@scopus.com.br">Paulo S. L. M. Barreto</a> and
* <a href="mailto:vincent.rijmen@cryptomathic.com">Vincent Rijmen</a>.
* The Whirlpool algorithm was developed by <a
* href="mailto:pbarreto@scopus.com.br">Paulo S. L. M. Barreto</a> and <a
* href="mailto:vincent.rijmen@cryptomathic.com">Vincent Rijmen</a>.
*
* See
* P.S.L.M. Barreto, V. Rijmen,
* ``The Whirlpool hashing function,''
* First NESSIE workshop, 2000 (tweaked version, 2003),
* <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip>
* See P.S.L.M. Barreto, V. Rijmen, ``The Whirlpool hashing function,'' First
* NESSIE workshop, 2000 (tweaked version, 2003),
* <https://www.cosic.esat.kuleuven
* .ac.be/nessie/workshop/submissions/whirlpool.zip>
*
* @author Paulo S.L.M. Barreto
* @author Vincent Rijmen.
* @author Paulo S.L.M. Barreto
* @author Vincent Rijmen.
*
* @version 3.0 (2003.03.12)
*
* =============================================================================
* ====================================================================
* =========
*
* Differences from version 2.1:
* Differences from version 2.1:
*
* - Suboptimal diffusion matrix replaced by cir(1, 1, 4, 1, 8, 5, 2, 9).
* - Suboptimal diffusion matrix replaced by cir(1, 1, 4, 1, 8, 5, 2,
* 9).
*
* =============================================================================
* ====================================================================
* =========
*
* Differences from version 2.0:
* Differences from version 2.0:
*
* - Generation of ISO/IEC 10118-3 test vectors.
* - Bug fix: nonzero carry was ignored when tallying the data length
* (this bug apparently only manifested itself when feeding data
* in pieces rather than in a single chunk at once).
* - Generation of ISO/IEC 10118-3 test vectors. - Bug fix: nonzero
* carry was ignored when tallying the data length (this bug apparently
* only manifested itself when feeding data in pieces rather than in a
* single chunk at once).
*
* Differences from version 1.0:
* Differences from version 1.0:
*
* - Original S-box replaced by the tweaked, hardware-efficient version.
* - Original S-box replaced by the tweaked, hardware-efficient
* version.
*
* =============================================================================
* ====================================================================
* =========
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
@ -80,30 +84,29 @@ public class WHIRLPOOL implements EncryptionMethod {
/**
* The substitution box.
*/
private static final String sbox =
"\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152" +
"\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57" +
"\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85" +
"\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8" +
"\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333" +
"\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0" +
"\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE" +
"\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d" +
"\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF" +
"\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A" +
"\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c" +
"\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04" +
"\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB" +
"\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9" +
"\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1" +
"\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886";
private static final String sbox = "\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152"
+ "\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57"
+ "\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85"
+ "\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8"
+ "\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333"
+ "\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0"
+ "\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE"
+ "\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d"
+ "\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF"
+ "\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A"
+ "\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c"
+ "\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04"
+ "\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB"
+ "\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9"
+ "\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1"
+ "\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886";
private static long[][] C = new long[8][256];
private static long[] rc = new long[R + 1];
private static long[] rc = new long[R + 1];
static {
for (int x = 0; x < 256; x++) {
char c = sbox.charAt(x/2);
char c = sbox.charAt(x / 2);
long v1 = ((x & 1) == 0) ? c >>> 8 : c & 0xff;
long v2 = v1 << 1;
if (v2 >= 0x100L) {
@ -120,11 +123,11 @@ public class WHIRLPOOL implements EncryptionMethod {
}
long v9 = v8 ^ v1;
/*
* build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2, 9]:
* build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2,
* 9]:
*/
C[0][x] =
(v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32) |
(v8 << 24) | (v5 << 16) | (v2 << 8) | (v9 );
C[0][x] = (v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32)
| (v8 << 24) | (v5 << 16) | (v2 << 8) | (v9);
/*
* build the remaining circulant tables C[t][x] = C[0][x] rotr t
*/
@ -135,18 +138,20 @@ public class WHIRLPOOL implements EncryptionMethod {
/*
* build the round constants:
*/
rc[0] = 0L; /* not used (assigment kept only to properly initialize all variables) */
rc[0] = 0L; /*
* not used (assigment kept only to properly initialize all
* variables)
*/
for (int r = 1; r <= R; r++) {
int i = 8*(r - 1);
rc[r] =
(C[0][i ] & 0xff00000000000000L) ^
(C[1][i + 1] & 0x00ff000000000000L) ^
(C[2][i + 2] & 0x0000ff0000000000L) ^
(C[3][i + 3] & 0x000000ff00000000L) ^
(C[4][i + 4] & 0x00000000ff000000L) ^
(C[5][i + 5] & 0x0000000000ff0000L) ^
(C[6][i + 6] & 0x000000000000ff00L) ^
(C[7][i + 7] & 0x00000000000000ffL);
int i = 8 * (r - 1);
rc[r] = (C[0][i] & 0xff00000000000000L)
^ (C[1][i + 1] & 0x00ff000000000000L)
^ (C[2][i + 2] & 0x0000ff0000000000L)
^ (C[3][i + 3] & 0x000000ff00000000L)
^ (C[4][i + 4] & 0x00000000ff000000L)
^ (C[5][i + 5] & 0x0000000000ff0000L)
^ (C[6][i + 6] & 0x000000000000ff00L)
^ (C[7][i + 7] & 0x00000000000000ffL);
}
}
@ -173,9 +178,9 @@ public class WHIRLPOOL implements EncryptionMethod {
/**
* The hashing state.
*/
protected long[] hash = new long[8];
protected long[] K = new long[8];
protected long[] L = new long[8];
protected long[] hash = new long[8];
protected long[] K = new long[8];
protected long[] L = new long[8];
protected long[] block = new long[8];
protected long[] state = new long[8];
@ -190,15 +195,14 @@ public class WHIRLPOOL implements EncryptionMethod {
* map the buffer to a block:
*/
for (int i = 0, j = 0; i < 8; i++, j += 8) {
block[i] =
(((long)buffer[j ] ) << 56) ^
(((long)buffer[j + 1] & 0xffL) << 48) ^
(((long)buffer[j + 2] & 0xffL) << 40) ^
(((long)buffer[j + 3] & 0xffL) << 32) ^
(((long)buffer[j + 4] & 0xffL) << 24) ^
(((long)buffer[j + 5] & 0xffL) << 16) ^
(((long)buffer[j + 6] & 0xffL) << 8) ^
(((long)buffer[j + 7] & 0xffL) );
block[i] = (((long) buffer[j]) << 56)
^ (((long) buffer[j + 1] & 0xffL) << 48)
^ (((long) buffer[j + 2] & 0xffL) << 40)
^ (((long) buffer[j + 3] & 0xffL) << 32)
^ (((long) buffer[j + 4] & 0xffL) << 24)
^ (((long) buffer[j + 5] & 0xffL) << 16)
^ (((long) buffer[j + 6] & 0xffL) << 8)
^ (((long) buffer[j + 7] & 0xffL));
}
/*
* compute and apply K^0 to the cipher state:
@ -216,7 +220,7 @@ public class WHIRLPOOL implements EncryptionMethod {
for (int i = 0; i < 8; i++) {
L[i] = 0L;
for (int t = 0, s = 56; t < 8; t++, s -= 8) {
L[i] ^= C[t][(int)(K[(i - t) & 7] >>> s) & 0xff];
L[i] ^= C[t][(int) (K[(i - t) & 7] >>> s) & 0xff];
}
}
for (int i = 0; i < 8; i++) {
@ -229,7 +233,7 @@ public class WHIRLPOOL implements EncryptionMethod {
for (int i = 0; i < 8; i++) {
L[i] = K[i];
for (int t = 0, s = 56; t < 8; t++, s -= 8) {
L[i] ^= C[t][(int)(state[(i - t) & 7] >>> s) & 0xff];
L[i] ^= C[t][(int) (state[(i - t) & 7] >>> s) & 0xff];
}
}
for (int i = 0; i < 8; i++) {
@ -248,7 +252,7 @@ public class WHIRLPOOL implements EncryptionMethod {
* Initialize the hashing state.
*/
public void NESSIEinit() {
Arrays.fill(bitLength, (byte)0);
Arrays.fill(bitLength, (byte) 0);
bufferBits = bufferPos = 0;
buffer[0] = 0;
Arrays.fill(hash, 0L);
@ -257,41 +261,41 @@ public class WHIRLPOOL implements EncryptionMethod {
/**
* Delivers input data to the hashing algorithm.
*
* @param source plaintext data to hash.
* @param sourceBits how many bits of plaintext to process.
* @param source
* plaintext data to hash.
* @param sourceBits
* how many bits of plaintext to process.
*
* This method maintains the invariant: bufferBits < 512
* This method maintains the invariant: bufferBits < 512
*/
public void NESSIEadd(byte[] source, long sourceBits) {
/*
sourcePos
|
+-------+-------+-------
||||||||||||||||||||| source
+-------+-------+-------
+-------+-------+-------+-------+-------+-------
|||||||||||||||||||||| buffer
+-------+-------+-------+-------+-------+-------
|
bufferPos
*/
int sourcePos = 0; // index of leftmost source byte containing data (1 to 8 bits).
int sourceGap = (8 - ((int)sourceBits & 7)) & 7; // space on source[sourcePos].
* sourcePos | +-------+-------+------- ||||||||||||||||||||| source
* +-------+-------+-------
* +-------+-------+-------+-------+-------+-------
* |||||||||||||||||||||| buffer
* +-------+-------+-------+-------+-------+------- | bufferPos
*/
int sourcePos = 0; // index of leftmost source byte containing data (1
// to 8 bits).
int sourceGap = (8 - ((int) sourceBits & 7)) & 7; // space on
// source[sourcePos].
int bufferRem = bufferBits & 7; // occupied bits on buffer[bufferPos].
int b;
// tally the length of the added data:
long value = sourceBits;
for (int i = 31, carry = 0; i >= 0; i--) {
carry += (bitLength[i] & 0xff) + ((int)value & 0xff);
bitLength[i] = (byte)carry;
carry += (bitLength[i] & 0xff) + ((int) value & 0xff);
bitLength[i] = (byte) carry;
carry >>>= 8;
value >>>= 8;
}
// process data in chunks of 8 bits:
while (sourceBits > 8) { // at least source[sourcePos] and source[sourcePos+1] contain data.
while (sourceBits > 8) { // at least source[sourcePos] and
// source[sourcePos+1] contain data.
// take a byte from the source:
b = ((source[sourcePos] << sourceGap) & 0xff) |
((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap));
b = ((source[sourcePos] << sourceGap) & 0xff)
| ((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap));
if (b < 0 || b >= 256) {
throw new RuntimeException("LOGIC ERROR");
}
@ -304,7 +308,7 @@ public class WHIRLPOOL implements EncryptionMethod {
// reset buffer:
bufferBits = bufferPos = 0;
}
buffer[bufferPos] = (byte)((b << (8 - bufferRem)) & 0xff);
buffer[bufferPos] = (byte) ((b << (8 - bufferRem)) & 0xff);
bufferBits += bufferRem;
// proceed to remaining data:
sourceBits -= 8;
@ -313,29 +317,32 @@ public class WHIRLPOOL implements EncryptionMethod {
// now 0 <= sourceBits <= 8;
// furthermore, all data (if any is left) is in source[sourcePos].
if (sourceBits > 0) {
b = (source[sourcePos] << sourceGap) & 0xff; // bits are left-justified on b.
b = (source[sourcePos] << sourceGap) & 0xff; // bits are
// left-justified on b.
// process the remaining bits:
buffer[bufferPos] |= b >>> bufferRem;
} else {
b = 0;
}
if (bufferRem + sourceBits < 8) {
// all remaining data fits on buffer[bufferPos], and there still remains some space.
// all remaining data fits on buffer[bufferPos], and there still
// remains some space.
bufferBits += sourceBits;
} else {
// buffer[bufferPos] is full:
bufferPos++;
bufferBits += 8 - bufferRem; // bufferBits = 8*bufferPos;
sourceBits -= 8 - bufferRem;
// now 0 <= sourceBits < 8; furthermore, all data is in source[sourcePos].
// now 0 <= sourceBits < 8; furthermore, all data is in
// source[sourcePos].
if (bufferBits == 512) {
// process data block:
processBuffer();
// reset buffer:
bufferBits = bufferPos = 0;
}
buffer[bufferPos] = (byte)((b << (8 - bufferRem)) & 0xff);
bufferBits += (int)sourceBits;
buffer[bufferPos] = (byte) ((b << (8 - bufferRem)) & 0xff);
bufferBits += (int) sourceBits;
}
}
@ -368,58 +375,59 @@ public class WHIRLPOOL implements EncryptionMethod {
// return the completed message digest:
for (int i = 0, j = 0; i < 8; i++, j += 8) {
long h = hash[i];
digest[j ] = (byte)(h >>> 56);
digest[j + 1] = (byte)(h >>> 48);
digest[j + 2] = (byte)(h >>> 40);
digest[j + 3] = (byte)(h >>> 32);
digest[j + 4] = (byte)(h >>> 24);
digest[j + 5] = (byte)(h >>> 16);
digest[j + 6] = (byte)(h >>> 8);
digest[j + 7] = (byte)(h );
digest[j] = (byte) (h >>> 56);
digest[j + 1] = (byte) (h >>> 48);
digest[j + 2] = (byte) (h >>> 40);
digest[j + 3] = (byte) (h >>> 32);
digest[j + 4] = (byte) (h >>> 24);
digest[j + 5] = (byte) (h >>> 16);
digest[j + 6] = (byte) (h >>> 8);
digest[j + 7] = (byte) (h);
}
}
/**
* Delivers string input data to the hashing algorithm.
*
* @param source plaintext data to hash (ASCII text string).
* @param source
* plaintext data to hash (ASCII text string).
*
* This method maintains the invariant: bufferBits < 512
* This method maintains the invariant: bufferBits < 512
*/
public void NESSIEadd(String source) {
if (source.length() > 0) {
byte[] data = new byte[source.length()];
for (int i = 0; i < source.length(); i++) {
data[i] = (byte)source.charAt(i);
data[i] = (byte) source.charAt(i);
}
NESSIEadd(data, 8*data.length);
NESSIEadd(data, 8 * data.length);
}
}
protected static String display(byte[] array) {
char[] val = new char[2*array.length];
char[] val = new char[2 * array.length];
String hex = "0123456789ABCDEF";
for (int i = 0; i < array.length; i++) {
int b = array[i] & 0xff;
val[2*i] = hex.charAt(b >>> 4);
val[2*i + 1] = hex.charAt(b & 15);
val[2 * i] = hex.charAt(b >>> 4);
val[2 * i + 1] = hex.charAt(b & 15);
}
return String.valueOf(val);
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
byte[] digest = new byte[DIGESTBYTES];
NESSIEinit();
NESSIEadd(password);
NESSIEfinalize(digest);
return display(digest);
}
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
}

View File

@ -47,7 +47,8 @@ public class WORDPRESS implements EncryptionMethod {
private String crypt(String password, String setting) {
String output = "*0";
if (((setting.length() < 2) ? setting : setting.substring(0, 2)).equalsIgnoreCase(output)) {
if (((setting.length() < 2) ? setting : setting.substring(0, 2))
.equalsIgnoreCase(output)) {
output = "*1";
}
String id = (setting.length() < 3) ? setting : setting.substring(0, 3);
@ -94,22 +95,24 @@ public class WORDPRESS implements EncryptionMethod {
try {
return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException("This system doesn't support UTF-8!", e);
throw new UnsupportedOperationException(
"This system doesn't support UTF-8!", e);
}
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
byte random[] = new byte[6];
this.randomGen.nextBytes(random);
return crypt(password, gensaltPrivate(stringToUtf8(new String(random))));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String comparedHash = crypt(password, hash);
return comparedHash.equals(hash);
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String comparedHash = crypt(password, hash);
return comparedHash.equals(hash);
}
}

View File

@ -4,29 +4,31 @@ import java.security.NoSuchAlgorithmException;
public class XAUTH implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
String hash = getWhirlpool(salt + password).toLowerCase();
int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length());
int saltPos = (password.length() >= hash.length() ? hash.length() - 1
: password.length());
return hash.substring(0, saltPos) + salt + hash.substring(saltPos);
}
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length());
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
int saltPos = (password.length() >= hash.length() ? hash.length() - 1
: password.length());
String salt = hash.substring(saltPos, saltPos + 12);
return hash.equals(getHash(password, salt, ""));
}
}
public static String getWhirlpool(String message) {
public static String getWhirlpool(String message) {
WHIRLPOOL w = new WHIRLPOOL();
byte[] digest = new byte[WHIRLPOOL.DIGESTBYTES];
w.NESSIEinit();
w.NESSIEadd(message);
w.NESSIEfinalize(digest);
return WHIRLPOOL.display(digest);
}
}
}

View File

@ -9,51 +9,48 @@ import java.util.regex.Pattern;
import fr.xephi.authme.AuthMe;
public class XF implements EncryptionMethod {
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA256(getSHA256(password) + regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", salt));
}
@Override
public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA256(getSHA256(password)
+ regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", salt));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
return hash.equals(regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", salt));
}
@Override
public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash
.equals(regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", salt));
}
public String getSHA256(String password) throws NoSuchAlgorithmException
{
public String getSHA256(String password) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes());
byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer();
for (byte element : byteData)
{
sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1));
for (byte element : byteData) {
sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(
1));
}
StringBuffer hexString = new StringBuffer();
for (byte element : byteData)
{
for (byte element : byteData) {
String hex = Integer.toHexString(0xff & element);
if (hex.length() == 1)
{
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
public String regmatch(String pattern, String line)
{
public String regmatch(String pattern, String line) {
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile(pattern).matcher(line);
while (m.find())
{
while (m.find()) {
allMatches.add(m.group(1));
}
return allMatches.get(0);

View File

@ -23,14 +23,14 @@ package fr.xephi.authme.security.pbkdf2;
* </p>
* <p>
* For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p>
*
* @author Matthias G&auml;rtner
* @version 1.0
*/
public class BinTools
{
public class BinTools {
public static final String hex = "0123456789ABCDEF";
/**
@ -41,15 +41,12 @@ public class BinTools
* @return Hexadecimal representation of b. Uppercase A-F, two characters
* per byte. Empty string on <code>null</code> input.
*/
public static String bin2hex(final byte[] b)
{
if (b == null)
{
public static String bin2hex(final byte[] b) {
if (b == null) {
return "";
}
StringBuffer sb = new StringBuffer(2 * b.length);
for (int i = 0; i < b.length; i++)
{
for (int i = 0; i < b.length; i++) {
int v = (256 + b[i]) % 256;
sb.append(hex.charAt((v / 16) & 15));
sb.append(hex.charAt((v % 16) & 15));
@ -61,28 +58,23 @@ public class BinTools
* Convert hex string to array of bytes.
*
* @param s
* String containing hexadecimal digits. May be <code>null</code>.
* On odd length leading zero will be assumed.
* String containing hexadecimal digits. May be <code>null</code>
* . On odd length leading zero will be assumed.
* @return Array on bytes, non-<code>null</code>.
* @throws IllegalArgumentException
* when string contains non-hex character
*/
public static byte[] hex2bin(final String s)
{
public static byte[] hex2bin(final String s) {
String m = s;
if (s == null)
{
if (s == null) {
// Allow empty input string.
m = "";
}
else if (s.length() % 2 != 0)
{
} else if (s.length() % 2 != 0) {
// Assume leading zero for odd string length
m = "0" + s;
}
byte r[] = new byte[m.length() / 2];
for (int i = 0, n = 0; i < m.length(); n++)
{
for (int i = 0, n = 0; i < m.length(); n++) {
char h = m.charAt(i++);
char l = m.charAt(i++);
r[n] = (byte) (hex2bin(h) * 16 + hex2bin(l));
@ -99,18 +91,14 @@ public class BinTools
* @throws IllegalArgumentException
* on non-hex character
*/
public static int hex2bin(char c)
{
if (c >= '0' && c <= '9')
{
public static int hex2bin(char c) {
if (c >= '0' && c <= '9') {
return (c - '0');
}
if (c >= 'A' && c <= 'F')
{
if (c >= 'A' && c <= 'F') {
return (c - 'A' + 10);
}
if (c >= 'a' && c <= 'f')
{
if (c >= 'a' && c <= 'f') {
return (c - 'a' + 10);
}
throw new IllegalArgumentException(
@ -118,19 +106,16 @@ public class BinTools
+ "'");
}
public static void main(String[] args)
{
public static void main(String[] args) {
byte b[] = new byte[256];
byte bb = 0;
for (int i = 0; i < 256; i++)
{
for (int i = 0; i < 256; i++) {
b[i] = bb++;
}
String s = bin2hex(b);
byte c[] = hex2bin(s);
String t = bin2hex(c);
if (!s.equals(t))
{
if (!s.equals(t)) {
throw new AssertionError("Mismatch");
}
}

View File

@ -34,14 +34,14 @@ import javax.crypto.spec.SecretKeySpec;
* </p>
* <p>
* For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p>
*
* @author Matthias G&auml;rtner
* @version 1.0
*/
public class MacBasedPRF implements PRF
{
public class MacBasedPRF implements PRF {
protected Mac mac;
protected int hLen;
@ -54,57 +54,41 @@ public class MacBasedPRF implements PRF
* @param macAlgorithm
* Mac algorithm to use, i.e. HMacSHA1 or HMacMD5.
*/
public MacBasedPRF(String macAlgorithm)
{
public MacBasedPRF(String macAlgorithm) {
this.macAlgorithm = macAlgorithm;
try
{
try {
mac = Mac.getInstance(macAlgorithm);
hLen = mac.getMacLength();
}
catch (NoSuchAlgorithmException e)
{
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public MacBasedPRF(String macAlgorithm, String provider)
{
public MacBasedPRF(String macAlgorithm, String provider) {
this.macAlgorithm = macAlgorithm;
try
{
try {
mac = Mac.getInstance(macAlgorithm, provider);
hLen = mac.getMacLength();
}
catch (NoSuchAlgorithmException e)
{
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
catch (NoSuchProviderException e)
{
} catch (NoSuchProviderException e) {
throw new RuntimeException(e);
}
}
public byte[] doFinal(byte[] M)
{
public byte[] doFinal(byte[] M) {
byte[] r = mac.doFinal(M);
return r;
}
public int getHLen()
{
public int getHLen() {
return hLen;
}
public void init(byte[] P)
{
try
{
public void init(byte[] P) {
try {
mac.init(new SecretKeySpec(P, macAlgorithm));
}
catch (InvalidKeyException e)
{
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
}

View File

@ -24,14 +24,14 @@ package fr.xephi.authme.security.pbkdf2;
* </p>
* <p>
* For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p>
*
* @author Matthias G&auml;rtner
* @version 1.0
*/
public interface PBKDF2
{
public interface PBKDF2 {
/**
* Convert String-based input to internal byte array, then invoke PBKDF2.
* Desired key length defaults to Pseudo Random Function block size.
@ -60,8 +60,8 @@ public interface PBKDF2
*
* @param inputPassword
* Candidate password to compute the derived key for.
* @return <code>true</code> password match; <code>false</code>
* incorrect password
* @return <code>true</code> password match; <code>false</code> incorrect
* password
*/
public abstract boolean verifyKey(String inputPassword);

Some files were not shown because too many files have changed in this diff Show More