Replace all '/' in path to File.separator - Code Refactor

This commit is contained in:
Xephi 2014-08-25 03:12:28 +02:00
parent 12795436a0
commit d7cb60c1fe
104 changed files with 2470 additions and 3690 deletions

View File

@ -12,105 +12,125 @@ import com.google.common.base.Preconditions;
/** /**
* Store meta-data in an ItemStack as attributes. * Store meta-data in an ItemStack as attributes.
*
* @author Kristian * @author Kristian
*/ */
public class AttributeStorage { public class AttributeStorage {
private ItemStack target; private ItemStack target;
private final UUID uniqueKey; private final UUID uniqueKey;
private AttributeStorage(ItemStack target, UUID uniqueKey) { private AttributeStorage(ItemStack target, UUID uniqueKey) {
this.target = Preconditions.checkNotNull(target, "target cannot be NULL"); this.target = Preconditions.checkNotNull(target, "target cannot be NULL");
this.uniqueKey = Preconditions.checkNotNull(uniqueKey, "uniqueKey cannot be NULL"); this.uniqueKey = Preconditions.checkNotNull(uniqueKey, "uniqueKey cannot be NULL");
} }
/** /**
* Construct a new attribute storage system. * Construct a new attribute storage system.
* <p> * <p>
* The key must be the same in order to retrieve the same data. * The key must be the same in order to retrieve the same data.
* @param target - the item stack where the data will be stored. *
* @param uniqueKey - the unique key used to retrieve the correct data. * @param target
* - the item stack where the data will be stored.
* @param uniqueKey
* - the unique key used to retrieve the correct data.
*/ */
public static AttributeStorage newTarget(ItemStack target, UUID uniqueKey) { public static AttributeStorage newTarget(ItemStack target, UUID uniqueKey) {
return new AttributeStorage(target, uniqueKey); return new AttributeStorage(target, uniqueKey);
} }
/** /**
* Retrieve the data stored in the item's attribute. * Retrieve the data stored in the item's attribute.
* @param defaultValue - the default value to return if no data can be found. *
* @param defaultValue
* - the default value to return if no data can be found.
* @return The stored data, or defaultValue if not found. * @return The stored data, or defaultValue if not found.
*/ */
public String getData(String defaultValue) { public String getData(String defaultValue) {
Attribute current = getAttribute(new Attributes(target), uniqueKey); Attribute current = getAttribute(new Attributes(target), uniqueKey);
return current != null ? current.getName() : defaultValue; return current != null ? current.getName() : defaultValue;
} }
/** /**
* Determine if we are storing any data. * Determine if we are storing any data.
*
* @return TRUE if we are, FALSE otherwise. * @return TRUE if we are, FALSE otherwise.
*/ */
public boolean hasData() { public boolean hasData() {
return getAttribute(new Attributes(target), uniqueKey) != null; return getAttribute(new Attributes(target), uniqueKey) != null;
} }
/** /**
* Set the data stored in the attributes. * Set the data stored in the attributes.
* @param data - the data. *
* @param data
* - the data.
*/ */
public void setData(String data) { public void setData(String data) {
Attributes attributes = new Attributes(target); Attributes attributes = new Attributes(target);
Attribute current = getAttribute(attributes, uniqueKey); Attribute current = getAttribute(attributes, uniqueKey);
if (current == null) { if (current == null) {
attributes.add( attributes.add(Attribute.newBuilder().name(data).amount(getBaseDamage(target)).uuid(uniqueKey).operation(Operation.ADD_NUMBER).type(AttributeType.GENERIC_ATTACK_DAMAGE).build());
Attribute.newBuilder().
name(data).
amount(getBaseDamage(target)).
uuid(uniqueKey).
operation(Operation.ADD_NUMBER).
type(AttributeType.GENERIC_ATTACK_DAMAGE).
build()
);
} else { } else {
current.setName(data); current.setName(data);
} }
this.target = attributes.getStack(); this.target = attributes.getStack();
} }
/** /**
* Retrieve the base damage of the given item. * Retrieve the base damage of the given item.
* @param stack - the stack. *
* @param stack
* - the stack.
* @return The base damage. * @return The base damage.
*/ */
private int getBaseDamage(ItemStack stack) { private int getBaseDamage(ItemStack stack) {
// Yes - we have to hard code these values. Cannot use Operation.ADD_PERCENTAGE either. // Yes - we have to hard code these values. Cannot use
switch (stack.getType()) { // Operation.ADD_PERCENTAGE either.
case WOOD_SWORD: return 4; switch (stack.getType()) {
case GOLD_SWORD: return 4; case WOOD_SWORD:
case STONE_SWORD: return 5; return 4;
case IRON_SWORD: return 6; case GOLD_SWORD:
case DIAMOND_SWORD: return 7; return 4;
case STONE_SWORD:
case WOOD_AXE: return 3; return 5;
case GOLD_AXE: return 3; case IRON_SWORD:
case STONE_AXE: return 4; return 6;
case IRON_AXE: return 5; case DIAMOND_SWORD:
case DIAMOND_AXE: return 6; return 7;
default: return 0;
} case WOOD_AXE:
return 3;
case GOLD_AXE:
return 3;
case STONE_AXE:
return 4;
case IRON_AXE:
return 5;
case DIAMOND_AXE:
return 6;
default:
return 0;
}
} }
/** /**
* Retrieve the target stack. May have been changed. * Retrieve the target stack. May have been changed.
*
* @return The target stack. * @return The target stack.
*/ */
public ItemStack getTarget() { public ItemStack getTarget() {
return target; return target;
} }
/** /**
* Retrieve an attribute by UUID. * Retrieve an attribute by UUID.
* @param attributes - the attribute. *
* @param id - the UUID to search for. * @param attributes
* - the attribute.
* @param id
* - the UUID to search for.
* @return The first attribute associated with this UUID, or NULL. * @return The first attribute associated with this UUID, or NULL.
*/ */
private Attribute getAttribute(Attributes attributes, UUID id) { private Attribute getAttribute(Attributes attributes, UUID id) {
@ -121,4 +141,4 @@ public class AttributeStorage {
} }
return null; return null;
} }
} }

View File

@ -19,20 +19,22 @@ import com.google.common.collect.Iterators;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
public class Attributes { public class Attributes {
public enum Operation { public enum Operation {
ADD_NUMBER(0), ADD_NUMBER(0),
MULTIPLY_PERCENTAGE(1), MULTIPLY_PERCENTAGE(1),
ADD_PERCENTAGE(2); ADD_PERCENTAGE(2);
private int id; private int id;
private Operation(int id) { private Operation(int id) {
this.id = id; this.id = id;
} }
public int getId() { public int getId() {
return id; return id;
} }
public static Operation fromId(int id) { public static Operation fromId(int id) {
// Linear scan is very fast for small N // Linear scan is very fast for small N
for (Operation op : values()) { for (Operation op : values()) {
@ -43,56 +45,64 @@ public class Attributes {
throw new IllegalArgumentException("Corrupt operation ID " + id + " detected."); throw new IllegalArgumentException("Corrupt operation ID " + id + " detected.");
} }
} }
public static class AttributeType { public static class AttributeType {
private static ConcurrentMap<String, AttributeType> LOOKUP = Maps.newConcurrentMap(); private static ConcurrentMap<String, AttributeType> LOOKUP = Maps.newConcurrentMap();
public static final AttributeType GENERIC_MAX_HEALTH = new AttributeType("generic.maxHealth").register(); public static final AttributeType GENERIC_MAX_HEALTH = new AttributeType("generic.maxHealth").register();
public static final AttributeType GENERIC_FOLLOW_RANGE = new AttributeType("generic.followRange").register(); public static final AttributeType GENERIC_FOLLOW_RANGE = new AttributeType("generic.followRange").register();
public static final AttributeType GENERIC_ATTACK_DAMAGE = new AttributeType("generic.attackDamage").register(); public static final AttributeType GENERIC_ATTACK_DAMAGE = new AttributeType("generic.attackDamage").register();
public static final AttributeType GENERIC_MOVEMENT_SPEED = new AttributeType("generic.movementSpeed").register(); public static final AttributeType GENERIC_MOVEMENT_SPEED = new AttributeType("generic.movementSpeed").register();
public static final AttributeType GENERIC_KNOCKBACK_RESISTANCE = new AttributeType("generic.knockbackResistance").register(); public static final AttributeType GENERIC_KNOCKBACK_RESISTANCE = new AttributeType("generic.knockbackResistance").register();
private final String minecraftId; private final String minecraftId;
/** /**
* Construct a new attribute type. * Construct a new attribute type.
* <p> * <p>
* Remember to {@link #register()} the type. * Remember to {@link #register()} the type.
* @param minecraftId - the ID of the type. *
* @param minecraftId
* - the ID of the type.
*/ */
public AttributeType(String minecraftId) { public AttributeType(String minecraftId) {
this.minecraftId = minecraftId; this.minecraftId = minecraftId;
} }
/** /**
* Retrieve the associated minecraft ID. * Retrieve the associated minecraft ID.
*
* @return The associated ID. * @return The associated ID.
*/ */
public String getMinecraftId() { public String getMinecraftId() {
return minecraftId; return minecraftId;
} }
/** /**
* Register the type in the central registry. * Register the type in the central registry.
*
* @return The registered type. * @return The registered type.
*/ */
// Constructors should have no side-effects! // Constructors should have no side-effects!
public AttributeType register() { public AttributeType register() {
AttributeType old = LOOKUP.putIfAbsent(minecraftId, this); AttributeType old = LOOKUP.putIfAbsent(minecraftId, this);
return old != null ? old : this; return old != null ? old : this;
} }
/** /**
* Retrieve the attribute type associated with a given ID. * Retrieve the attribute type associated with a given ID.
* @param minecraftId The ID to search for. *
* @param minecraftId
* The ID to search for.
* @return The attribute type, or NULL if not found. * @return The attribute type, or NULL if not found.
*/ */
public static AttributeType fromId(String minecraftId) { public static AttributeType fromId(String minecraftId) {
return LOOKUP.get(minecraftId); return LOOKUP.get(minecraftId);
} }
/** /**
* Retrieve every registered attribute type. * Retrieve every registered attribute type.
*
* @return Every type. * @return Every type.
*/ */
public static Iterable<AttributeType> values() { public static Iterable<AttributeType> values() {
@ -101,6 +111,7 @@ public class Attributes {
} }
public static class Attribute { public static class Attribute {
private NbtCompound data; private NbtCompound data;
public Attribute(Builder builder) { public Attribute(Builder builder) {
@ -111,11 +122,11 @@ public class Attributes {
setName(builder.name); setName(builder.name);
setUUID(builder.uuid); setUUID(builder.uuid);
} }
private Attribute(NbtCompound data) { private Attribute(NbtCompound data) {
this.data = data; this.data = data;
} }
public double getAmount() { public double getAmount() {
return data.getDouble("Amount", 0.0); return data.getDouble("Amount", 0.0);
} }
@ -162,15 +173,18 @@ public class Attributes {
} }
/** /**
* Construct a new attribute builder with a random UUID and default operation of adding numbers. * Construct a new attribute builder with a random UUID and default
* operation of adding numbers.
*
* @return The attribute builder. * @return The attribute builder.
*/ */
public static Builder newBuilder() { public static Builder newBuilder() {
return new Builder().uuid(UUID.randomUUID()).operation(Operation.ADD_NUMBER); return new Builder().uuid(UUID.randomUUID()).operation(Operation.ADD_NUMBER);
} }
// Makes it easier to construct an attribute // Makes it easier to construct an attribute
public static class Builder { public static class Builder {
private double amount; private double amount;
private Operation operation = Operation.ADD_NUMBER; private Operation operation = Operation.ADD_NUMBER;
private AttributeType type; private AttributeType type;
@ -181,7 +195,8 @@ public class Attributes {
// Don't make this accessible // Don't make this accessible
} }
public Builder(double amount, Operation operation, AttributeType type, String name, UUID uuid) { public Builder(double amount, Operation operation,
AttributeType type, String name, UUID uuid) {
this.amount = amount; this.amount = amount;
this.operation = operation; this.operation = operation;
this.type = type; this.type = type;
@ -193,139 +208,156 @@ public class Attributes {
this.amount = amount; this.amount = amount;
return this; return this;
} }
public Builder operation(Operation operation) { public Builder operation(Operation operation) {
this.operation = operation; this.operation = operation;
return this; return this;
} }
public Builder type(AttributeType type) { public Builder type(AttributeType type) {
this.type = type; this.type = type;
return this; return this;
} }
public Builder name(String name) { public Builder name(String name) {
this.name = name; this.name = name;
return this; return this;
} }
public Builder uuid(UUID uuid) { public Builder uuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
return this; return this;
} }
public Attribute build() { public Attribute build() {
return new Attribute(this); return new Attribute(this);
} }
} }
} }
// This may be modified // This may be modified
public ItemStack stack; public ItemStack stack;
private NbtList attributes; private NbtList attributes;
public Attributes(ItemStack stack) { public Attributes(ItemStack stack) {
// Create a CraftItemStack (under the hood) // Create a CraftItemStack (under the hood)
this.stack = NbtFactory.getCraftItemStack(stack); this.stack = NbtFactory.getCraftItemStack(stack);
loadAttributes(false); loadAttributes(false);
} }
/** /**
* Load the NBT list from the TAG compound. * Load the NBT list from the TAG compound.
* @param createIfMissing - create the list if its missing. *
* @param createIfMissing
* - create the list if its missing.
*/ */
private void loadAttributes(boolean createIfMissing) { private void loadAttributes(boolean createIfMissing) {
if (this.attributes == null) { if (this.attributes == null) {
NbtCompound nbt = NbtFactory.fromItemTag(this.stack); NbtCompound nbt = NbtFactory.fromItemTag(this.stack);
this.attributes = nbt.getList("AttributeModifiers", createIfMissing); this.attributes = nbt.getList("AttributeModifiers", createIfMissing);
} }
} }
/** /**
* Remove the NBT list from the TAG compound. * Remove the NBT list from the TAG compound.
*/ */
private void removeAttributes() { private void removeAttributes() {
NbtCompound nbt = NbtFactory.fromItemTag(this.stack); NbtCompound nbt = NbtFactory.fromItemTag(this.stack);
nbt.remove("AttributeModifiers"); nbt.remove("AttributeModifiers");
this.attributes = null; this.attributes = null;
} }
/** /**
* Retrieve the modified item stack. * Retrieve the modified item stack.
*
* @return The modified item stack. * @return The modified item stack.
*/ */
public ItemStack getStack() { public ItemStack getStack() {
return stack; return stack;
} }
/** /**
* Retrieve the number of attributes. * Retrieve the number of attributes.
*
* @return Number of attributes. * @return Number of attributes.
*/ */
public int size() { public int size() {
return attributes != null ? attributes.size() : 0; return attributes != null ? attributes.size() : 0;
} }
/** /**
* Add a new attribute to the list. * Add a new attribute to the list.
* @param attribute - the new attribute. *
* @param attribute
* - the new attribute.
*/ */
public void add(Attribute attribute) { public void add(Attribute attribute) {
Preconditions.checkNotNull(attribute.getName(), "must specify an attribute name."); Preconditions.checkNotNull(attribute.getName(), "must specify an attribute name.");
loadAttributes(true); loadAttributes(true);
attributes.add(attribute.data); attributes.add(attribute.data);
} }
/** /**
* Remove the first instance of the given attribute. * Remove the first instance of the given attribute.
* <p> * <p>
* The attribute will be removed using its UUID. * The attribute will be removed using its UUID.
* @param attribute - the attribute to remove. *
* @param attribute
* - the attribute to remove.
* @return TRUE if the attribute was removed, FALSE otherwise. * @return TRUE if the attribute was removed, FALSE otherwise.
*/ */
public boolean remove(Attribute attribute) { public boolean remove(Attribute attribute) {
if (attributes == null) if (attributes == null)
return false; return false;
UUID uuid = attribute.getUUID(); UUID uuid = attribute.getUUID();
for (Iterator<Attribute> it = values().iterator(); it.hasNext(); ) { for (Iterator<Attribute> it = values().iterator(); it.hasNext();) {
if (Objects.equal(it.next().getUUID(), uuid)) { if (Objects.equal(it.next().getUUID(), uuid)) {
it.remove(); it.remove();
// Last removed attribute? // Last removed attribute?
if (size() == 0) { if (size() == 0) {
removeAttributes(); removeAttributes();
} }
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Remove every attribute. * Remove every attribute.
*/ */
public void clear() { public void clear() {
removeAttributes(); removeAttributes();
} }
/** /**
* Retrieve the attribute at a given index. * Retrieve the attribute at a given index.
* @param index - the index to look up. *
* @param index
* - the index to look up.
* @return The attribute at that index. * @return The attribute at that index.
*/ */
public Attribute get(int index) { public Attribute get(int index) {
if (size() == 0) if (size() == 0)
throw new IllegalStateException("Attribute list is empty."); throw new IllegalStateException("Attribute list is empty.");
return new Attribute((NbtCompound) attributes.get(index)); return new Attribute((NbtCompound) attributes.get(index));
} }
// We can't make Attributes itself iterable without splitting it up into separate classes // We can't make Attributes itself iterable without splitting it up into
public Iterable<Attribute> values() { // separate classes
public Iterable<Attribute> values() {
return new Iterable<Attribute>() { return new Iterable<Attribute>() {
@Override @Override
public Iterator<Attribute> iterator() { public Iterator<Attribute> iterator() {
// Handle the empty case // Handle the empty case
if (size() == 0) if (size() == 0)
return Collections.<Attribute>emptyList().iterator(); return Collections.<Attribute> emptyList().iterator();
return Iterators.transform(attributes.iterator(), return Iterators.transform(attributes.iterator(), new Function<Object, Attribute>() {
new Function<Object, Attribute>() {
@Override @Override
public Attribute apply(@Nullable Object element) { public Attribute apply(@Nullable Object element) {
return new Attribute((NbtCompound) element); return new Attribute((NbtCompound) element);

File diff suppressed because it is too large Load Diff

View File

@ -126,6 +126,7 @@ public class AuthMe extends JavaPlugin {
if (Settings.enableAntiBot) { if (Settings.enableAntiBot) {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override @Override
public void run() { public void run() {
delayedAntiBot = false; delayedAntiBot = false;
@ -155,18 +156,15 @@ public class AuthMe extends JavaPlugin {
Class.forName("org.apache.logging.log4j.core.Filter"); Class.forName("org.apache.logging.log4j.core.Filter");
setLog4JFilter(); setLog4JFilter();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
ConsoleLogger ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support is disabled");
.info("You're using Minecraft 1.6.x or older, Log4J support is disabled");
} catch (NoClassDefFoundError e) { } catch (NoClassDefFoundError e) {
ConsoleLogger ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support is disabled");
.info("You're using Minecraft 1.6.x or older, Log4J support is disabled");
} }
} }
// Load MailApi // Load MailApi
if (!Settings.getmailAccount.isEmpty() if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty())
&& !Settings.getmailPassword.isEmpty()) mail = new SendMailSSL( mail = new SendMailSSL(this);
this);
// Check Citizens Version // Check Citizens Version
citizensVersion(); citizensVersion();
@ -191,7 +189,8 @@ public class AuthMe extends JavaPlugin {
*/ */
if (Settings.isBackupActivated && Settings.isBackupOnStart) { if (Settings.isBackupActivated && Settings.isBackupOnStart) {
Boolean Backup = new PerformBackup(this).DoBackup(); Boolean Backup = new PerformBackup(this).DoBackup();
if (Backup) ConsoleLogger.info("Backup Complete"); if (Backup)
ConsoleLogger.info("Backup Complete");
else ConsoleLogger.showError("Error while making Backup"); else ConsoleLogger.showError("Error while making Backup");
} }
@ -240,10 +239,8 @@ public class AuthMe extends JavaPlugin {
PluginManager pm = getServer().getPluginManager(); PluginManager pm = getServer().getPluginManager();
if (Settings.bungee) { if (Settings.bungee) {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
"BungeeCord"); Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this));
Bukkit.getMessenger().registerIncomingPluginChannel(this,
"BungeeCord", new BungeeCordMessage(this));
} }
if (pm.isPluginEnabled("Spout")) { if (pm.isPluginEnabled("Spout")) {
pm.registerEvents(new AuthMeSpoutListener(database), this); pm.registerEvents(new AuthMeSpoutListener(database), this);
@ -261,35 +258,32 @@ public class AuthMe extends JavaPlugin {
this.getCommand("authme").setExecutor(new AdminCommand(this, database)); this.getCommand("authme").setExecutor(new AdminCommand(this, database));
this.getCommand("register").setExecutor(new RegisterCommand(this)); this.getCommand("register").setExecutor(new RegisterCommand(this));
this.getCommand("login").setExecutor(new LoginCommand(this)); this.getCommand("login").setExecutor(new LoginCommand(this));
this.getCommand("changepassword").setExecutor( this.getCommand("changepassword").setExecutor(new ChangePasswordCommand(database, this));
new ChangePasswordCommand(database, this)); this.getCommand("logout").setExecutor(new LogoutCommand(this, database));
this.getCommand("logout") this.getCommand("unregister").setExecutor(new UnregisterCommand(this, database));
.setExecutor(new LogoutCommand(this, database));
this.getCommand("unregister").setExecutor(
new UnregisterCommand(this, database));
this.getCommand("passpartu").setExecutor(new PasspartuCommand(this)); this.getCommand("passpartu").setExecutor(new PasspartuCommand(this));
this.getCommand("email").setExecutor(new EmailCommand(this, database)); this.getCommand("email").setExecutor(new EmailCommand(this, database));
this.getCommand("captcha").setExecutor(new CaptchaCommand(this)); this.getCommand("captcha").setExecutor(new CaptchaCommand(this));
this.getCommand("converter").setExecutor( this.getCommand("converter").setExecutor(new ConverterCommand(this, database));
new ConverterCommand(this, database));
if (!Settings.isForceSingleSessionEnabled) { if (!Settings.isForceSingleSessionEnabled) {
ConsoleLogger ConsoleLogger.showError("ATTENTION by disabling ForceSingleSession, your server protection is set to low");
.showError("ATTENTION by disabling ForceSingleSession, your server protection is set to low");
} }
if (Settings.reloadSupport) try { if (Settings.reloadSupport)
onReload(); try {
if (server.getOnlinePlayers().length < 1) { onReload();
try { if (server.getOnlinePlayers().length < 1) {
database.purgeLogged(); try {
} catch (NullPointerException npe) { database.purgeLogged();
} catch (NullPointerException npe) {
}
} }
} catch (NullPointerException ex) {
} }
} catch (NullPointerException ex) {
}
if (Settings.usePurge) autoPurge(); if (Settings.usePurge)
autoPurge();
// Download GeoIp.dat file // Download GeoIp.dat file
downloadGeoIp(); downloadGeoIp();
@ -300,35 +294,28 @@ public class AuthMe extends JavaPlugin {
dataManager = new DataManager(this, database); dataManager = new DataManager(this, database);
dataManager.start(); dataManager.start();
ConsoleLogger.info("Authme " + this.getDescription().getVersion() ConsoleLogger.info("Authme " + this.getDescription().getVersion() + " enabled");
+ " enabled");
} }
private void setLog4JFilter() { private void setLog4JFilter() {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override @Override
public void run() { public void run() {
org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
.getRootLogger();
coreLogger.addFilter(new Log4JFilter()); coreLogger.addFilter(new Log4JFilter());
} }
}); });
} }
public void checkVault() { public void checkVault() {
if (this.getServer().getPluginManager().getPlugin("Vault") != null if (this.getServer().getPluginManager().getPlugin("Vault") != null && this.getServer().getPluginManager().getPlugin("Vault").isEnabled()) {
&& this.getServer().getPluginManager().getPlugin("Vault") RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
.isEnabled()) {
RegisteredServiceProvider<Permission> permissionProvider = getServer()
.getServicesManager().getRegistration(
net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) { if (permissionProvider != null) {
permission = permissionProvider.getProvider(); permission = permissionProvider.getProvider();
ConsoleLogger.info("Vault plugin detected, hook with " ConsoleLogger.info("Vault plugin detected, hook with " + permission.getName() + " system");
+ permission.getName() + " system");
} else { } else {
ConsoleLogger ConsoleLogger.showError("Vault plugin is detected but not the permissions plugin!");
.showError("Vault plugin is detected but not the permissions plugin!");
} }
} else { } else {
permission = null; permission = null;
@ -340,9 +327,7 @@ public class AuthMe extends JavaPlugin {
this.ChestShop = 0; this.ChestShop = 0;
return; return;
} }
if (this.getServer().getPluginManager().getPlugin("ChestShop") != null if (this.getServer().getPluginManager().getPlugin("ChestShop") != null && this.getServer().getPluginManager().getPlugin("ChestShop").isEnabled()) {
&& this.getServer().getPluginManager().getPlugin("ChestShop")
.isEnabled()) {
try { try {
String ver = com.Acrobot.ChestShop.ChestShop.getVersion(); String ver = com.Acrobot.ChestShop.ChestShop.getVersion();
try { try {
@ -350,8 +335,7 @@ public class AuthMe extends JavaPlugin {
if (version >= 3.50) { if (version >= 3.50) {
this.ChestShop = version; this.ChestShop = version;
} else { } else {
ConsoleLogger ConsoleLogger.showError("Please Update your ChestShop version!");
.showError("Please Update your ChestShop version!");
} }
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
try { try {
@ -359,8 +343,7 @@ public class AuthMe extends JavaPlugin {
if (version >= 3.50) { if (version >= 3.50) {
this.ChestShop = version; this.ChestShop = version;
} else { } else {
ConsoleLogger ConsoleLogger.showError("Please Update your ChestShop version!");
.showError("Please Update your ChestShop version!");
} }
} catch (NumberFormatException nfee) { } catch (NumberFormatException nfee) {
} }
@ -377,14 +360,10 @@ public class AuthMe extends JavaPlugin {
multiverse = null; multiverse = null;
return; return;
} }
if (this.getServer().getPluginManager().getPlugin("Multiverse-Core") != null if (this.getServer().getPluginManager().getPlugin("Multiverse-Core") != null && this.getServer().getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
&& this.getServer().getPluginManager()
.getPlugin("Multiverse-Core").isEnabled()) {
try { try {
multiverse = (MultiverseCore) this.getServer() multiverse = (MultiverseCore) this.getServer().getPluginManager().getPlugin("Multiverse-Core");
.getPluginManager().getPlugin("Multiverse-Core"); ConsoleLogger.info("Hook with Multiverse-Core for SpawnLocations");
ConsoleLogger
.info("Hook with Multiverse-Core for SpawnLocations");
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
multiverse = null; multiverse = null;
} catch (ClassCastException cce) { } catch (ClassCastException cce) {
@ -398,12 +377,9 @@ public class AuthMe extends JavaPlugin {
} }
public void checkEssentials() { public void checkEssentials() {
if (this.getServer().getPluginManager().getPlugin("Essentials") != null if (this.getServer().getPluginManager().getPlugin("Essentials") != null && this.getServer().getPluginManager().getPlugin("Essentials").isEnabled()) {
&& this.getServer().getPluginManager().getPlugin("Essentials")
.isEnabled()) {
try { try {
ess = (Essentials) this.getServer().getPluginManager() ess = (Essentials) this.getServer().getPluginManager().getPlugin("Essentials");
.getPlugin("Essentials");
ConsoleLogger.info("Hook with Essentials plugin"); ConsoleLogger.info("Hook with Essentials plugin");
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
ess = null; ess = null;
@ -415,16 +391,13 @@ public class AuthMe extends JavaPlugin {
} else { } else {
ess = null; ess = null;
} }
if (this.getServer().getPluginManager().getPlugin("EssentialsSpawn") != null if (this.getServer().getPluginManager().getPlugin("EssentialsSpawn") != null && this.getServer().getPluginManager().getPlugin("EssentialsSpawn").isEnabled()) {
&& this.getServer().getPluginManager()
.getPlugin("EssentialsSpawn").isEnabled()) {
try { try {
essentialsSpawn = new EssSpawn().getLocation(); essentialsSpawn = new EssSpawn().getLocation();
ConsoleLogger.info("Hook with EssentialsSpawn plugin"); ConsoleLogger.info("Hook with EssentialsSpawn plugin");
} catch (Exception e) { } catch (Exception e) {
essentialsSpawn = null; essentialsSpawn = null;
ConsoleLogger ConsoleLogger.showError("Error while reading /plugins/Essentials/spawn.yml file ");
.showError("Error while reading /plugins/Essentials/spawn.yml file ");
} }
} else { } else {
ess = null; ess = null;
@ -436,11 +409,8 @@ public class AuthMe extends JavaPlugin {
this.notifications = null; this.notifications = null;
return; return;
} }
if (this.getServer().getPluginManager().getPlugin("Notifications") != null if (this.getServer().getPluginManager().getPlugin("Notifications") != null && this.getServer().getPluginManager().getPlugin("Notifications").isEnabled()) {
&& this.getServer().getPluginManager() this.notifications = (Notifications) this.getServer().getPluginManager().getPlugin("Notifications");
.getPlugin("Notifications").isEnabled()) {
this.notifications = (Notifications) this.getServer()
.getPluginManager().getPlugin("Notifications");
ConsoleLogger.info("Successfully hook with Notifications"); ConsoleLogger.info("Successfully hook with Notifications");
} else { } else {
this.notifications = null; this.notifications = null;
@ -448,9 +418,7 @@ public class AuthMe extends JavaPlugin {
} }
public void combatTag() { public void combatTag() {
if (this.getServer().getPluginManager().getPlugin("CombatTag") != null if (this.getServer().getPluginManager().getPlugin("CombatTag") != null && this.getServer().getPluginManager().getPlugin("CombatTag").isEnabled()) {
&& this.getServer().getPluginManager().getPlugin("CombatTag")
.isEnabled()) {
this.CombatTag = 1; this.CombatTag = 1;
} else { } else {
this.CombatTag = 0; this.CombatTag = 0;
@ -458,11 +426,8 @@ public class AuthMe extends JavaPlugin {
} }
public void citizensVersion() { public void citizensVersion() {
if (this.getServer().getPluginManager().getPlugin("Citizens") != null if (this.getServer().getPluginManager().getPlugin("Citizens") != null && this.getServer().getPluginManager().getPlugin("Citizens").isEnabled()) {
&& this.getServer().getPluginManager().getPlugin("Citizens") Citizens cit = (Citizens) this.getServer().getPluginManager().getPlugin("Citizens");
.isEnabled()) {
Citizens cit = (Citizens) this.getServer().getPluginManager()
.getPlugin("Citizens");
String ver = cit.getDescription().getVersion(); String ver = cit.getDescription().getVersion();
String[] args = ver.split("\\."); String[] args = ver.split("\\.");
if (args[0].contains("1")) { if (args[0].contains("1")) {
@ -477,30 +442,32 @@ public class AuthMe extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
if (Bukkit.getOnlinePlayers().length != 0) for (Player player : Bukkit if (Bukkit.getOnlinePlayers().length != 0)
.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
this.savePlayer(player); this.savePlayer(player);
} }
if (database != null) { if (database != null) {
database.close(); database.close();
} }
if (databaseThread != null) { if (databaseThread != null) {
if (databaseThread.isAlive()) databaseThread.interrupt(); if (databaseThread.isAlive())
databaseThread.interrupt();
} }
if (dataManager != null) { if (dataManager != null) {
if (dataManager.isAlive()) dataManager.interrupt(); if (dataManager.isAlive())
dataManager.interrupt();
} }
if (Settings.isBackupActivated && Settings.isBackupOnStop) { if (Settings.isBackupActivated && Settings.isBackupOnStop) {
Boolean Backup = new PerformBackup(this).DoBackup(); Boolean Backup = new PerformBackup(this).DoBackup();
if (Backup) ConsoleLogger.info("Backup Complete"); if (Backup)
ConsoleLogger.info("Backup Complete");
else ConsoleLogger.showError("Error while making Backup"); else ConsoleLogger.showError("Error while making Backup");
} }
ConsoleLogger.info("Authme " + this.getDescription().getVersion() ConsoleLogger.info("Authme " + this.getDescription().getVersion() + " disabled");
+ " disabled");
} }
private void onReload() { private void onReload() {
@ -510,10 +477,9 @@ public class AuthMe extends JavaPlugin {
if (database.isLogged(player.getName().toLowerCase())) { if (database.isLogged(player.getName().toLowerCase())) {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
PlayerAuth pAuth = database.getAuth(name); PlayerAuth pAuth = database.getAuth(name);
if (pAuth == null) break; if (pAuth == null)
PlayerAuth auth = new PlayerAuth(name, pAuth.getHash(), break;
pAuth.getIp(), new Date().getTime(), PlayerAuth auth = new PlayerAuth(name, pAuth.getHash(), pAuth.getIp(), new Date().getTime(), pAuth.getEmail(), player.getName());
pAuth.getEmail(), player.getName());
database.updateSession(auth); database.updateSession(auth);
PlayerCache.getInstance().addPlayer(auth); PlayerCache.getInstance().addPlayer(auth);
} }
@ -532,35 +498,28 @@ public class AuthMe extends JavaPlugin {
public void savePlayer(Player player) throws IllegalStateException, public void savePlayer(Player player) throws IllegalStateException,
NullPointerException { NullPointerException {
try { try {
if ((citizens.isNPC(player, this)) if ((citizens.isNPC(player, this)) || (Utils.getInstance().isUnrestricted(player)) || (CombatTagComunicator.isNPC(player))) {
|| (Utils.getInstance().isUnrestricted(player))
|| (CombatTagComunicator.isNPC(player))) {
return; return;
} }
} catch (Exception e) { } catch (Exception e) {
} }
try { try {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name) if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
&& !player.isDead() && Settings.isSaveQuitLocationEnabled) { final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName());
final PlayerAuth auth = new PlayerAuth(player.getName()
.toLowerCase(), player.getLocation().getX(), player
.getLocation().getY(), player.getLocation().getZ(),
player.getWorld().getName());
database.updateQuitLoc(auth); database.updateQuitLoc(auth);
} }
if (LimboCache.getInstance().hasLimboPlayer(name)) { if (LimboCache.getInstance().hasLimboPlayer(name)) {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer( LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
name);
if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) { if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) {
player.getInventory().setArmorContents(limbo.getArmour()); player.getInventory().setArmorContents(limbo.getArmour());
player.getInventory().setContents(limbo.getInventory()); player.getInventory().setContents(limbo.getInventory());
} }
if (!Settings.noTeleport) player.teleport(limbo.getLoc()); if (!Settings.noTeleport)
player.teleport(limbo.getLoc());
this.utils.addNormal(player, limbo.getGroup()); this.utils.addNormal(player, limbo.getGroup());
player.setOp(limbo.getOperator()); player.setOp(limbo.getOperator());
this.plugin.getServer().getScheduler() this.plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId());
.cancelTask(limbo.getTimeoutTaskId());
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
if (this.playerBackup.doesCacheExist(player)) { if (this.playerBackup.doesCacheExist(player)) {
this.playerBackup.removeCache(player); this.playerBackup.removeCache(player);
@ -608,7 +567,8 @@ public class AuthMe extends JavaPlugin {
} }
public boolean authmePermissible(Player player, String perm) { public boolean authmePermissible(Player player, String perm) {
if (player.hasPermission(perm)) return true; if (player.hasPermission(perm))
return true;
else if (permission != null) { else if (permission != null) {
return permission.playerHas(player, perm); return permission.playerHas(player, perm);
} }
@ -616,7 +576,8 @@ public class AuthMe extends JavaPlugin {
} }
public boolean authmePermissible(CommandSender sender, String perm) { public boolean authmePermissible(CommandSender sender, String perm) {
if (sender.hasPermission(perm)) return true; if (sender.hasPermission(perm))
return true;
else if (permission != null) { else if (permission != null) {
return permission.has(sender, perm); return permission.has(sender, perm);
} }
@ -631,23 +592,24 @@ public class AuthMe extends JavaPlugin {
calendar.add(Calendar.DATE, -(Settings.purgeDelay)); calendar.add(Calendar.DATE, -(Settings.purgeDelay));
long until = calendar.getTimeInMillis(); long until = calendar.getTimeInMillis();
List<String> cleared = this.database.autoPurgeDatabase(until); List<String> cleared = this.database.autoPurgeDatabase(until);
ConsoleLogger.info("AutoPurgeDatabase : " + cleared.size() ConsoleLogger.info("AutoPurgeDatabase : " + cleared.size() + " accounts removed.");
+ " accounts removed."); if (cleared.isEmpty())
if (cleared.isEmpty()) return; return;
if (Settings.purgeEssentialsFile && this.ess != null) dataManager if (Settings.purgeEssentialsFile && this.ess != null)
.purgeEssentials(cleared); dataManager.purgeEssentials(cleared);
if (Settings.purgePlayerDat) dataManager.purgeDat(cleared); if (Settings.purgePlayerDat)
if (Settings.purgeLimitedCreative) dataManager dataManager.purgeDat(cleared);
.purgeLimitedCreative(cleared); if (Settings.purgeLimitedCreative)
if (Settings.purgeAntiXray) dataManager.purgeAntiXray(cleared); dataManager.purgeLimitedCreative(cleared);
if (Settings.purgeAntiXray)
dataManager.purgeAntiXray(cleared);
} }
public Location getSpawnLocation(Player player) { public Location getSpawnLocation(Player player) {
World world = player.getWorld(); World world = player.getWorld();
String[] spawnPriority = Settings.spawnPriority.split(","); String[] spawnPriority = Settings.spawnPriority.split(",");
if (spawnPriority.length < 4) { if (spawnPriority.length < 4) {
ConsoleLogger ConsoleLogger.showError("Check your config for spawnPriority, you need to put all of 4 spawn priorities");
.showError("Check your config for spawnPriority, you need to put all of 4 spawn priorities");
ConsoleLogger.showError("Defaulting Spawn to world's one"); ConsoleLogger.showError("Defaulting Spawn to world's one");
return world.getSpawnLocation(); return world.getSpawnLocation();
} }
@ -655,14 +617,17 @@ public class AuthMe extends JavaPlugin {
int i = 3; int i = 3;
for (i = 3; i >= 0; i--) { for (i = 3; i >= 0; i--) {
String s = spawnPriority[i]; String s = spawnPriority[i];
if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) spawnLoc = getDefaultSpawn(world); if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null)
if (s.equalsIgnoreCase("multiverse") spawnLoc = getDefaultSpawn(world);
&& getMultiverseSpawn(world) != null) spawnLoc = getMultiverseSpawn(world); if (s.equalsIgnoreCase("multiverse") && getMultiverseSpawn(world) != null)
if (s.equalsIgnoreCase("essentials") spawnLoc = getMultiverseSpawn(world);
&& getEssentialsSpawn() != null) spawnLoc = getEssentialsSpawn(); if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null)
if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null) spawnLoc = getAuthMeSpawn(player); spawnLoc = getEssentialsSpawn();
if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null)
spawnLoc = getAuthMeSpawn(player);
} }
if (spawnLoc == null) spawnLoc = world.getSpawnLocation(); if (spawnLoc == null)
spawnLoc = world.getSpawnLocation();
return spawnLoc; return spawnLoc;
} }
@ -673,8 +638,7 @@ public class AuthMe extends JavaPlugin {
private Location getMultiverseSpawn(World world) { private Location getMultiverseSpawn(World world) {
if (multiverse != null && Settings.multiverse) { if (multiverse != null && Settings.multiverse) {
try { try {
return multiverse.getMVWorldManager().getMVWorld(world) return multiverse.getMVWorldManager().getMVWorld(world).getSpawnLocation();
.getSpawnLocation();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
} catch (ClassCastException cce) { } catch (ClassCastException cce) {
} catch (NoClassDefFoundError ncdfe) { } catch (NoClassDefFoundError ncdfe) {
@ -684,23 +648,21 @@ public class AuthMe extends JavaPlugin {
} }
private Location getEssentialsSpawn() { private Location getEssentialsSpawn() {
if (essentialsSpawn != null) return essentialsSpawn; if (essentialsSpawn != null)
return essentialsSpawn;
return null; return null;
} }
private Location getAuthMeSpawn(Player player) { private Location getAuthMeSpawn(Player player) {
if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null))
.hasPlayedBefore()) return Spawn.getInstance().getFirstSpawn();
&& (Spawn.getInstance().getFirstSpawn() != null)) return Spawn if (Spawn.getInstance().getSpawn() != null)
.getInstance().getFirstSpawn(); return Spawn.getInstance().getSpawn();
if (Spawn.getInstance().getSpawn() != null) return Spawn.getInstance()
.getSpawn();
return null; return null;
} }
public void downloadGeoIp() { public void downloadGeoIp() {
ConsoleLogger ConsoleLogger.info("LICENSE : This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com");
.info("LICENSE : This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com");
File file = new File(getDataFolder(), "GeoIP.dat"); File file = new File(getDataFolder(), "GeoIP.dat");
if (!file.exists()) { if (!file.exists()) {
try { try {
@ -710,7 +672,8 @@ public class AuthMe extends JavaPlugin {
conn.setConnectTimeout(10000); conn.setConnectTimeout(10000);
conn.connect(); conn.connect();
InputStream input = conn.getInputStream(); InputStream input = conn.getInputStream();
if (url.endsWith(".gz")) input = new GZIPInputStream(input); if (url.endsWith(".gz"))
input = new GZIPInputStream(input);
OutputStream output = new FileOutputStream(file); OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
int length = input.read(buffer); int length = input.read(buffer);
@ -727,10 +690,11 @@ public class AuthMe extends JavaPlugin {
public String getCountryCode(String ip) { public String getCountryCode(String ip) {
try { try {
if (ls == null) ls = new LookupService(new File(getDataFolder(), if (ls == null)
"GeoIP.dat")); ls = new LookupService(new File(getDataFolder(), "GeoIP.dat"));
String code = ls.getCountry(ip).getCode(); String code = ls.getCountry(ip).getCode();
if (code != null && !code.isEmpty()) return code; if (code != null && !code.isEmpty())
return code;
} catch (Exception e) { } catch (Exception e) {
} }
return null; return null;
@ -738,10 +702,11 @@ public class AuthMe extends JavaPlugin {
public String getCountryName(String ip) { public String getCountryName(String ip) {
try { try {
if (ls == null) ls = new LookupService(new File(getDataFolder(), if (ls == null)
"GeoIP.dat")); ls = new LookupService(new File(getDataFolder(), "GeoIP.dat"));
String code = ls.getCountry(ip).getName(); String code = ls.getCountry(ip).getName();
if (code != null && !code.isEmpty()) return code; if (code != null && !code.isEmpty())
return code;
} catch (Exception e) { } catch (Exception e) {
} }
return null; return null;
@ -753,20 +718,21 @@ public class AuthMe extends JavaPlugin {
} }
private void recallEmail() { private void recallEmail() {
if (!Settings.recallEmail) return; if (!Settings.recallEmail)
return;
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override @Override
public void run() { public void run() {
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
if (player.isOnline()) { if (player.isOnline()) {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (database.isAuthAvailable(name)) if (PlayerCache if (database.isAuthAvailable(name))
.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
String email = database.getAuth(name).getEmail(); String email = database.getAuth(name).getEmail();
if (email == null || email.isEmpty() if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com"))
|| email.equalsIgnoreCase("your@email.com")) m m._(player, "add_email");
._(player, "add_email"); }
}
} }
} }
} }
@ -777,20 +743,14 @@ public class AuthMe extends JavaPlugin {
try { try {
message = message.replace("&", "\u00a7"); message = message.replace("&", "\u00a7");
message = message.replace("{PLAYER}", player.getName()); message = message.replace("{PLAYER}", player.getName());
message = message.replace("{ONLINE}", "" message = message.replace("{ONLINE}", "" + this.getServer().getOnlinePlayers().length);
+ this.getServer().getOnlinePlayers().length); message = message.replace("{MAXPLAYERS}", "" + this.getServer().getMaxPlayers());
message = message.replace("{MAXPLAYERS}", ""
+ this.getServer().getMaxPlayers());
message = message.replace("{IP}", getIP(player)); message = message.replace("{IP}", getIP(player));
message = message.replace("{LOGINS}", "" message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged());
+ PlayerCache.getInstance().getLogged());
message = message.replace("{WORLD}", player.getWorld().getName()); message = message.replace("{WORLD}", player.getWorld().getName());
message = message.replace("{SERVER}", this.getServer() message = message.replace("{SERVER}", this.getServer().getServerName());
.getServerName()); message = message.replace("{VERSION}", this.getServer().getBukkitVersion());
message = message.replace("{VERSION}", this.getServer() message = message.replace("{COUNTRY}", this.getCountryName(getIP(player)));
.getBukkitVersion());
message = message.replace("{COUNTRY}",
this.getCountryName(getIP(player)));
} catch (Exception e) { } catch (Exception e) {
} }
return message; return message;
@ -800,30 +760,34 @@ public class AuthMe extends JavaPlugin {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
String ip = player.getAddress().getAddress().getHostAddress(); String ip = player.getAddress().getAddress().getHostAddress();
if (Settings.bungee) { if (Settings.bungee) {
if (realIp.containsKey(name)) ip = realIp.get(name); if (realIp.containsKey(name))
ip = realIp.get(name);
} }
if (Settings.checkVeryGames) if (getVeryGamesIP(player) != null) ip = getVeryGamesIP(player); if (Settings.checkVeryGames)
if (getVeryGamesIP(player) != null)
ip = getVeryGamesIP(player);
return ip; return ip;
} }
public boolean isLoggedIp(String name, String ip) { public boolean isLoggedIp(String name, String ip) {
int count = 0; int count = 0;
for (Player player : this.getServer().getOnlinePlayers()) { for (Player player : this.getServer().getOnlinePlayers()) {
if (ip.equalsIgnoreCase(getIP(player)) if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name))
&& database.isLogged(player.getName().toLowerCase()) count++;
&& !player.getName().equalsIgnoreCase(name)) count++;
} }
if (count >= Settings.getMaxLoginPerIp) return true; if (count >= Settings.getMaxLoginPerIp)
return true;
return false; return false;
} }
public boolean hasJoinedIp(String name, String ip) { public boolean hasJoinedIp(String name, String ip) {
int count = 0; int count = 0;
for (Player player : this.getServer().getOnlinePlayers()) { for (Player player : this.getServer().getOnlinePlayers()) {
if (ip.equalsIgnoreCase(getIP(player)) if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name))
&& !player.getName().equalsIgnoreCase(name)) count++; count++;
} }
if (count >= Settings.getMaxJoinPerIp) return true; if (count >= Settings.getMaxJoinPerIp)
return true;
return false; return false;
} }
@ -836,17 +800,13 @@ public class AuthMe extends JavaPlugin {
public String getVeryGamesIP(Player player) { public String getVeryGamesIP(Player player) {
String realIP = null; String realIP = null;
String sUrl = vgUrl; String sUrl = vgUrl;
sUrl = sUrl.replace("%IP%", sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort());
player.getAddress().getAddress().getHostAddress()).replace(
"%PORT%", "" + player.getAddress().getPort());
try { try {
URL url = new URL(sUrl); URL url = new URL(sUrl);
URLConnection urlc = url.openConnection(); URLConnection urlc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader( BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
urlc.getInputStream()));
String inputLine = in.readLine(); String inputLine = in.readLine();
if (inputLine != null && !inputLine.isEmpty() if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error")) {
&& !inputLine.equalsIgnoreCase("error")) {
realIP = inputLine; realIP = inputLine;
} }
} catch (Exception e) { } catch (Exception e) {

View File

@ -15,18 +15,13 @@ public class ConsoleFilter implements Filter {
@Override @Override
public boolean isLoggable(LogRecord record) { public boolean isLoggable(LogRecord record) {
try { try {
if (record == null || record.getMessage() == null) return true; if (record == null || record.getMessage() == null)
return true;
String logM = record.getMessage().toLowerCase(); String logM = record.getMessage().toLowerCase();
if (!logM.contains("issued server command:")) return true; if (!logM.contains("issued server command:"))
if (!logM.contains("/login ") && !logM.contains("/l ") return true;
&& !logM.contains("/reg ") 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 "))
&& !logM.contains("/changepassword ") return true;
&& !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]; String playername = record.getMessage().split(" ")[0];
record.setMessage(playername + " issued an AuthMe command!"); record.setMessage(playername + " issued an AuthMe command!");
return true; return true;

View File

@ -21,18 +21,13 @@ public class ConsoleLogger {
log.info("[AuthMe] " + message); log.info("[AuthMe] " + message);
if (Settings.useLogging) { if (Settings.useLogging) {
Calendar date = Calendar.getInstance(); Calendar date = Calendar.getInstance();
final String actually = "[" final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] " + message;
+ DateFormat.getDateInstance().format(date.getTime()) Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
+ ", " + date.get(Calendar.HOUR_OF_DAY) + ":" @Override
+ date.get(Calendar.MINUTE) + ":" public void run() {
+ date.get(Calendar.SECOND) + "] " + message; writeLog(actually);
Bukkit.getScheduler().runTaskAsynchronously( }
AuthMe.getInstance(), new Runnable() { });
@Override
public void run() {
writeLog(actually);
}
});
} }
} }
} }
@ -42,26 +37,20 @@ public class ConsoleLogger {
log.warning("[AuthMe] ERROR: " + message); log.warning("[AuthMe] ERROR: " + message);
if (Settings.useLogging) { if (Settings.useLogging) {
Calendar date = Calendar.getInstance(); Calendar date = Calendar.getInstance();
final String 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;
+ DateFormat.getDateInstance().format(date.getTime()) Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
+ ", " + date.get(Calendar.HOUR_OF_DAY) + ":" @Override
+ date.get(Calendar.MINUTE) + ":" public void run() {
+ date.get(Calendar.SECOND) + "] ERROR : " + message; writeLog(actually);
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 { try {
FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder() FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder() + File.separator + "authme.log", true);
+ File.separator + "authme.log", true);
BufferedWriter w = new BufferedWriter(fw); BufferedWriter w = new BufferedWriter(fw);
w.write(string); w.write(string);
w.newLine(); w.newLine();

View File

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

View File

@ -18,19 +18,13 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
@Override @Override
public Result filter(LogEvent record) { public Result filter(LogEvent record) {
try { try {
if (record == null || record.getMessage() == null) return Result.NEUTRAL; if (record == null || record.getMessage() == null)
String logM = record.getMessage().getFormattedMessage() return Result.NEUTRAL;
.toLowerCase(); String logM = record.getMessage().getFormattedMessage().toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:"))
if (!logM.contains("/login ") && !logM.contains("/l ") return Result.NEUTRAL;
&& !logM.contains("/reg ") 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 "))
&& !logM.contains("/changepassword ") return Result.NEUTRAL;
&& !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; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;
@ -41,18 +35,13 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
public Result filter(Logger arg0, Level arg1, Marker arg2, String message, public Result filter(Logger arg0, Level arg1, Marker arg2, String message,
Object... arg4) { Object... arg4) {
try { try {
if (message == null) return Result.NEUTRAL; if (message == null)
return Result.NEUTRAL;
String logM = message.toLowerCase(); String logM = message.toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:"))
if (!logM.contains("/login ") && !logM.contains("/l ") return Result.NEUTRAL;
&& !logM.contains("/reg ") 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 "))
&& !logM.contains("/changepassword ") return Result.NEUTRAL;
&& !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; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;
@ -63,18 +52,13 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
public Result filter(Logger arg0, Level arg1, Marker arg2, Object message, public Result filter(Logger arg0, Level arg1, Marker arg2, Object message,
Throwable arg4) { Throwable arg4) {
try { try {
if (message == null) return Result.NEUTRAL; if (message == null)
return Result.NEUTRAL;
String logM = message.toString().toLowerCase(); String logM = message.toString().toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:"))
if (!logM.contains("/login ") && !logM.contains("/l ") return Result.NEUTRAL;
&& !logM.contains("/reg ") 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 "))
&& !logM.contains("/changepassword ") return Result.NEUTRAL;
&& !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; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;
@ -85,18 +69,13 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
public Result filter(Logger arg0, Level arg1, Marker arg2, Message message, public Result filter(Logger arg0, Level arg1, Marker arg2, Message message,
Throwable arg4) { Throwable arg4) {
try { try {
if (message == null) return Result.NEUTRAL; if (message == null)
return Result.NEUTRAL;
String logM = message.getFormattedMessage().toLowerCase(); String logM = message.getFormattedMessage().toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:"))
if (!logM.contains("/login ") && !logM.contains("/l ") return Result.NEUTRAL;
&& !logM.contains("/reg ") 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 "))
&& !logM.contains("/changepassword ") return Result.NEUTRAL;
&& !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; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;

View File

@ -23,8 +23,7 @@ public class PerformBackup {
private String tblname = Settings.getMySQLTablename; private String tblname = Settings.getMySQLTablename;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
String dateString = format.format(new Date()); String dateString = format.format(new Date());
private String path = AuthMe.getInstance().getDataFolder() private String path = AuthMe.getInstance().getDataFolder() + File.separator + "backups" + File.separator + "backup" + dateString;
+ "/backups/backup" + dateString;
private AuthMe instance; private AuthMe instance;
public PerformBackup(AuthMe instance) { public PerformBackup(AuthMe instance) {
@ -49,15 +48,12 @@ public class PerformBackup {
} }
private boolean MySqlBackup() { private boolean MySqlBackup() {
File dirBackup = new File(AuthMe.getInstance().getDataFolder() File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");
+ "/backups");
if (!dirBackup.exists()) dirBackup.mkdir(); if (!dirBackup.exists())
dirBackup.mkdir();
if (checkWindows(Settings.backupWindowsPath)) { if (checkWindows(Settings.backupWindowsPath)) {
String executeCmd = Settings.backupWindowsPath String executeCmd = Settings.backupWindowsPath + "\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
+ "\\bin\\mysqldump.exe -u " + dbUserName + " -p"
+ dbPassword + " " + dbName + " --tables " + tblname
+ " -r " + path + ".sql";
Process runtimeProcess; Process runtimeProcess;
try { try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd); runtimeProcess = Runtime.getRuntime().exec(executeCmd);
@ -72,9 +68,7 @@ public class PerformBackup {
ex.printStackTrace(); ex.printStackTrace();
} }
} else { } else {
String executeCmd = "mysqldump -u " + dbUserName + " -p" String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
+ dbPassword + " " + dbName + " --tables " + tblname
+ " -r " + path + ".sql";
Process runtimeProcess; Process runtimeProcess;
try { try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd); runtimeProcess = Runtime.getRuntime().exec(executeCmd);
@ -93,13 +87,13 @@ public class PerformBackup {
} }
private boolean FileBackup(String backend) { private boolean FileBackup(String backend) {
File dirBackup = new File(AuthMe.getInstance().getDataFolder() File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");
+ "/backups");
if (!dirBackup.exists()) dirBackup.mkdir(); if (!dirBackup.exists())
dirBackup.mkdir();
try { try {
copy(new File("plugins/AuthMe/" + backend), new File(path + ".db")); copy(new File("plugins" + File.separator + "AuthMe" + File.separator + backend), new File(path + ".db"));
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
@ -118,8 +112,7 @@ public class PerformBackup {
if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) { if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) {
return true; return true;
} else { } else {
ConsoleLogger ConsoleLogger.showError("Mysql Windows Path is incorrect please check it");
.showError("Mysql Windows Path is incorrect please check it");
return true; return true;
} }
} else return false; } else return false;

View File

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

View File

@ -19,6 +19,7 @@ import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class Utils { public class Utils {
private String currentGroup; private String currentGroup;
private static Utils singleton; private static Utils singleton;
int id; int id;
@ -33,16 +34,15 @@ public class Utils {
} }
public void setGroup(String player, groupType group) { public void setGroup(String player, groupType group) {
if (!Settings.isPermissionCheckEnabled) return; if (!Settings.isPermissionCheckEnabled)
if (plugin.permission == null) return; return;
if (plugin.permission == null)
return;
try { try {
World world = null; World world = null;
currentGroup = plugin.permission.getPrimaryGroup(world, player); currentGroup = plugin.permission.getPrimaryGroup(world, player);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
ConsoleLogger ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null; plugin.permission = null;
return; return;
} }
@ -51,28 +51,27 @@ public class Utils {
switch (group) { switch (group) {
case UNREGISTERED: { case UNREGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, plugin.permission.playerAddGroup(world, name, Settings.unRegisteredGroup);
Settings.unRegisteredGroup);
break; break;
} }
case REGISTERED: { case REGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, plugin.permission.playerAddGroup(world, name, Settings.getRegisteredGroup);
Settings.getRegisteredGroup);
break; break;
} }
case NOTLOGGEDIN: { case NOTLOGGEDIN: {
if (!useGroupSystem()) break; if (!useGroupSystem())
break;
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, plugin.permission.playerAddGroup(world, name, Settings.getUnloggedinGroup);
Settings.getUnloggedinGroup);
break; break;
} }
case LOGGEDIN: { case LOGGEDIN: {
if (!useGroupSystem()) break; if (!useGroupSystem())
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer( break;
name.toLowerCase()); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name.toLowerCase());
if (limbo == null) break; if (limbo == null)
break;
String realGroup = limbo.getGroup(); String realGroup = limbo.getGroup();
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, realGroup); plugin.permission.playerAddGroup(world, name, realGroup);
@ -86,20 +85,15 @@ public class Utils {
if (!useGroupSystem()) { if (!useGroupSystem()) {
return false; return false;
} }
if (plugin.permission == null) return false; if (plugin.permission == null)
return false;
World world = null; World world = null;
try { try {
if (plugin.permission.playerRemoveGroup(world, player.getName() if (plugin.permission.playerRemoveGroup(world, player.getName().toString(), Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(world, player.getName().toString(), group)) {
.toString(), Settings.getUnloggedinGroup)
&& plugin.permission.playerAddGroup(world, player.getName()
.toString(), group)) {
return true; return true;
} }
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
ConsoleLogger ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null; plugin.permission = null;
return false; return false;
} }
@ -107,7 +101,8 @@ public class Utils {
} }
public void hasPermOnJoin(Player player) { public void hasPermOnJoin(Player player) {
if (plugin.permission == null) return; if (plugin.permission == null)
return;
Iterator<String> iter = Settings.getJoinPermissions.iterator(); Iterator<String> iter = Settings.getJoinPermissions.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
String permission = iter.next(); String permission = iter.next();
@ -118,10 +113,12 @@ public class Utils {
} }
public boolean isUnrestricted(Player player) { public boolean isUnrestricted(Player player) {
if (!Settings.isAllowRestrictedIp) return false; if (!Settings.isAllowRestrictedIp)
if (Settings.getUnrestrictedName.isEmpty() return false;
|| Settings.getUnrestrictedName == null) return false; if (Settings.getUnrestrictedName.isEmpty() || Settings.getUnrestrictedName == null)
if (Settings.getUnrestrictedName.contains(player.getName())) return true; return false;
if (Settings.getUnrestrictedName.contains(player.getName()))
return true;
return false; return false;
} }
@ -131,8 +128,8 @@ public class Utils {
} }
private boolean useGroupSystem() { private boolean useGroupSystem() {
if (Settings.isPermissionCheckEnabled if (Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty())
&& !Settings.getUnloggedinGroup.isEmpty()) return true; return true;
return false; return false;
} }
@ -144,18 +141,20 @@ public class Utils {
} else { } else {
theWorld = Bukkit.getWorld(w); theWorld = Bukkit.getWorld(w);
} }
if (theWorld == null) theWorld = pl.getWorld(); if (theWorld == null)
theWorld = pl.getWorld();
final World world = theWorld; final World world = theWorld;
final Location locat = new Location(world, x, y, z); final Location locat = new Location(world, x, y, z);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getChunk().isLoaded()) tpEvent.getTo() if (!tpEvent.getTo().getChunk().isLoaded())
.getChunk().load(); tpEvent.getTo().getChunk().load();
pl.teleport(tpEvent.getTo()); pl.teleport(tpEvent.getTo());
} }
} }
@ -166,16 +165,16 @@ public class Utils {
* Random Token for passpartu * Random Token for passpartu
*/ */
public boolean obtainToken() { public boolean obtainToken() {
File file = new File("plugins/AuthMe/passpartu.token"); File file = new File("plugins" + File.separator + "AuthMe" + File.separator + "passpartu.token");
if (file.exists()) file.delete(); if (file.exists())
file.delete();
FileWriter writer = null; FileWriter writer = null;
try { try {
file.createNewFile(); file.createNewFile();
writer = new FileWriter(file); writer = new FileWriter(file);
String token = generateToken(); String token = generateToken();
writer.write(token + ":" + System.currentTimeMillis() / 1000 writer.write(token + ":" + System.currentTimeMillis() / 1000 + API.newline);
+ API.newline);
writer.flush(); writer.flush();
ConsoleLogger.info("[AuthMe] Security passpartu token: " + token); ConsoleLogger.info("[AuthMe] Security passpartu token: " + token);
writer.close(); writer.close();
@ -190,11 +189,13 @@ public class Utils {
* Read Token * Read Token
*/ */
public boolean readToken(String inputToken) { public boolean readToken(String inputToken) {
File file = new File("plugins/AuthMe/passpartu.token"); File file = new File("plugins" + File.separator + "AuthMe" + File.separator + "passpartu.token");
if (!file.exists()) return false; if (!file.exists())
return false;
if (inputToken.isEmpty()) return false; if (inputToken.isEmpty())
return false;
Scanner reader = null; Scanner reader = null;
try { try {
reader = new Scanner(file); reader = new Scanner(file);
@ -202,9 +203,7 @@ public class Utils {
final String line = reader.nextLine(); final String line = reader.nextLine();
if (line.contains(":")) { if (line.contains(":")) {
String[] tokenInfo = line.split(":"); String[] tokenInfo = line.split(":");
if (tokenInfo[0].equals(inputToken) if (tokenInfo[0].equals(inputToken) && System.currentTimeMillis() / 1000 - 30 <= Integer.parseInt(tokenInfo[1])) {
&& System.currentTimeMillis() / 1000 - 30 <= Integer
.parseInt(tokenInfo[1])) {
file.delete(); file.delete();
reader.close(); reader.close();
return true; return true;
@ -236,13 +235,15 @@ public class Utils {
* Used for force player GameMode * Used for force player GameMode
*/ */
public static void forceGM(Player player) { public static void forceGM(Player player) {
if (!AuthMe.getInstance().authmePermissible(player, if (!AuthMe.getInstance().authmePermissible(player, "authme.bypassforcesurvival"))
"authme.bypassforcesurvival")) player player.setGameMode(GameMode.SURVIVAL);
.setGameMode(GameMode.SURVIVAL);
} }
public enum groupType { public enum groupType {
UNREGISTERED, REGISTERED, NOTLOGGEDIN, LOGGEDIN UNREGISTERED,
REGISTERED,
NOTLOGGEDIN,
LOGGEDIN
} }
} }

View File

@ -32,8 +32,7 @@ public class API {
* @return AuthMe instance * @return AuthMe instance
*/ */
public static AuthMe hookAuthMe() { public static AuthMe hookAuthMe() {
Plugin plugin = Bukkit.getServer().getPluginManager() Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
.getPlugin("AuthMe");
if (plugin == null || !(plugin instanceof AuthMe)) { if (plugin == null || !(plugin instanceof AuthMe)) {
return null; return null;
} }
@ -50,8 +49,7 @@ public class API {
* @return true if player is authenticate * @return true if player is authenticate
*/ */
public static boolean isAuthenticated(Player player) { public static boolean isAuthenticated(Player player) {
return PlayerCache.getInstance().isAuthenticated( return PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase());
player.getName().toLowerCase());
} }
/** /**
@ -61,7 +59,8 @@ public class API {
*/ */
@Deprecated @Deprecated
public boolean isaNPC(Player player) { public boolean isaNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player, instance)) return true; if (instance.getCitizensCommunicator().isNPC(player, instance))
return true;
return CombatTagComunicator.isNPC(player); return CombatTagComunicator.isNPC(player);
} }
@ -71,7 +70,8 @@ public class API {
* @return true if player is a npc * @return true if player is a npc
*/ */
public boolean isNPC(Player player) { public boolean isNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player, instance)) return true; if (instance.getCitizensCommunicator().isNPC(player, instance))
return true;
return CombatTagComunicator.isNPC(player); return CombatTagComunicator.isNPC(player);
} }
@ -86,13 +86,10 @@ public class API {
public static Location getLastLocation(Player player) { public static Location getLastLocation(Player player) {
try { try {
PlayerAuth auth = PlayerCache.getInstance().getAuth( PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
player.getName().toLowerCase());
if (auth != null) { if (auth != null) {
Location loc = new Location(Bukkit.getWorld(auth.getWorld()), Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
auth.getQuitLocX(), auth.getQuitLocY(),
auth.getQuitLocZ());
return loc; return loc;
} else { } else {
return null; return null;
@ -129,12 +126,12 @@ public class API {
*/ */
public static boolean checkPassword(String playerName, public static boolean checkPassword(String playerName,
String passwordToCheck) { String passwordToCheck) {
if (!isRegistered(playerName)) return false; if (!isRegistered(playerName))
return false;
String player = playerName.toLowerCase(); String player = playerName.toLowerCase();
PlayerAuth auth = database.getAuth(player); PlayerAuth auth = database.getAuth(player);
try { try {
return PasswordSecurity.comparePasswordWithHash(passwordToCheck, return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
auth.getHash(), playerName);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
return false; return false;
} }
@ -150,13 +147,11 @@ public class API {
public static boolean registerPlayer(String playerName, String password) { public static boolean registerPlayer(String playerName, String password) {
try { try {
String name = playerName.toLowerCase(); String name = playerName.toLowerCase();
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
password, name);
if (isRegistered(name)) { if (isRegistered(name)) {
return false; return false;
} }
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com", getPlayerRealName(name));
"your@email.com", getPlayerRealName(name));
if (!database.saveAuth(auth)) { if (!database.saveAuth(auth)) {
return false; return false;
} }
@ -174,9 +169,9 @@ public class API {
*/ */
public static String getPlayerRealName(String nickname) { public static String getPlayerRealName(String nickname) {
try { try {
String realName = instance.dataManager.getOfflinePlayer(nickname) String realName = instance.dataManager.getOfflinePlayer(nickname).getName();
.getName(); if (realName != null && !realName.isEmpty())
if (realName != null && !realName.isEmpty()) return realName; return realName;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
} }
return nickname; return nickname;

View File

@ -129,7 +129,8 @@ public class PlayerAuth {
} }
public String getIp() { public String getIp() {
if (ip == null || ip.isEmpty()) ip = "127.0.0.1"; if (ip == null || ip.isEmpty())
ip = "127.0.0.1";
return ip; return ip;
} }
@ -139,8 +140,7 @@ public class PlayerAuth {
public String getHash() { public String getHash() {
if (Settings.getPasswordHash == HashAlgorithm.MD5VB) { if (Settings.getPasswordHash == HashAlgorithm.MD5VB) {
if (salt != null && !salt.isEmpty() if (salt != null && !salt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.MD5VB) {
&& Settings.getPasswordHash == HashAlgorithm.MD5VB) {
vBhash = "$MD5vb$" + salt + "$" + hash; vBhash = "$MD5vb$" + salt + "$" + hash;
return vBhash; return vBhash;
} }
@ -186,7 +186,8 @@ public class PlayerAuth {
public long getLastLogin() { public long getLastLogin() {
try { try {
if (Long.valueOf(lastLogin) == null) lastLogin = 0L; if (Long.valueOf(lastLogin) == null)
lastLogin = 0L;
} catch (NullPointerException e) { } catch (NullPointerException e) {
lastLogin = 0L; lastLogin = 0L;
} }
@ -219,15 +220,13 @@ public class PlayerAuth {
return false; return false;
} }
PlayerAuth other = (PlayerAuth) obj; PlayerAuth other = (PlayerAuth) obj;
return other.getIp().equals(this.ip) return other.getIp().equals(this.ip) && other.getNickname().equals(this.nickname);
&& other.getNickname().equals(this.nickname);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int hashCode = 7; int hashCode = 7;
hashCode = 71 * hashCode hashCode = 71 * hashCode + (this.nickname != null ? this.nickname.hashCode() : 0);
+ (this.nickname != null ? this.nickname.hashCode() : 0);
hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0); hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0);
return hashCode; return hashCode;
} }
@ -242,10 +241,7 @@ public class PlayerAuth {
@Override @Override
public String toString() { public String toString() {
String s = "Player : " + nickname + " ! IP : " + ip + " ! LastLogin : " String s = "Player : " + nickname + " ! IP : " + ip + " ! LastLogin : " + lastLogin + " ! LastPosition : " + x + "," + y + "," + z + "," + world + " ! Email : " + email + " ! Hash : " + hash + " ! Salt : " + salt + " ! RealName : " + realName;
+ lastLogin + " ! LastPosition : " + x + "," + y + "," + z
+ "," + world + " ! Email : " + email + " ! Hash : " + hash
+ " ! Salt : " + salt + " ! RealName : " + realName;
return s; return s;
} }

View File

@ -29,9 +29,9 @@ public class FileCache {
public FileCache(AuthMe plugin) { public FileCache(AuthMe plugin) {
this.plugin = plugin; this.plugin = plugin;
final File file = new File(plugin.getDataFolder() + File.separator final File file = new File(plugin.getDataFolder() + File.separator + "cache");
+ "cache"); if (!file.exists())
if (!file.exists()) file.mkdir(); file.mkdir();
} }
public void createCache(Player player, DataFileCache playerData, public void createCache(Player player, DataFileCache playerData,
@ -44,8 +44,7 @@ public class FileCache {
} catch (Error e) { } catch (Error e) {
path = player.getName(); path = player.getName();
} }
File file = new File(plugin.getDataFolder() + File.separator + "cache" File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
+ File.separator + path + File.separator + "playerdatas.cache");
if (file.exists()) { if (file.exists()) {
return; return;
@ -61,16 +60,13 @@ public class FileCache {
writer.write(String.valueOf(flying) + API.newline); writer.write(String.valueOf(flying) + API.newline);
writer.close(); writer.close();
file = new File(plugin.getDataFolder() + File.separator + "cache" file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory");
+ File.separator + path + File.separator + "inventory");
file.mkdir(); file.mkdir();
ItemStack[] inv = playerData.getInventory(); ItemStack[] inv = playerData.getInventory();
for (int i = 0; i < inv.length; i++) { for (int i = 0; i < inv.length; i++) {
ItemStack item = inv[i]; ItemStack item = inv[i];
file = new File(plugin.getDataFolder() + File.separator file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache");
+ "cache" + File.separator + path + File.separator
+ "inventory" + File.separator + i + ".cache");
writer = new FileWriter(file); writer = new FileWriter(file);
writer.write(item.getType().name() + API.newline); writer.write(item.getType().name() + API.newline);
writer.write(item.getDurability() + API.newline); writer.write(item.getDurability() + API.newline);
@ -78,8 +74,8 @@ public class FileCache {
writer.flush(); writer.flush();
if (item.hasItemMeta()) { if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName()) writer.write("name=" if (meta.hasDisplayName())
+ meta.getDisplayName() + API.newline); writer.write("name=" + meta.getDisplayName() + API.newline);
if (meta.hasLore()) { if (meta.hasLore()) {
String lores = ""; String lores = "";
for (String lore : meta.getLore()) for (String lore : meta.getLore())
@ -88,40 +84,33 @@ public class FileCache {
} }
if (meta.hasEnchants()) { if (meta.hasEnchants()) {
for (Enchantment ench : meta.getEnchants().keySet()) { for (Enchantment ench : meta.getEnchants().keySet()) {
writer.write("metaenchant=" + ench.getName() + ":" writer.write("metaenchant=" + ench.getName() + ":" + meta.getEnchants().get(ench) + API.newline);
+ meta.getEnchants().get(ench)
+ API.newline);
} }
} }
writer.flush(); writer.flush();
} }
for (Enchantment ench : item.getEnchantments().keySet()) { for (Enchantment ench : item.getEnchantments().keySet()) {
writer.write("enchant=" + ench.getName() + ":" writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
+ item.getEnchantments().get(ench) + API.newline);
} }
Attributes attributes = new Attributes(item); Attributes attributes = new Attributes(item);
if (attributes != null) if (attributes != null)
while (attributes.values().iterator().hasNext()) { while (attributes.values().iterator().hasNext()) {
Attribute a = attributes.values().iterator().next(); Attribute a = attributes.values().iterator().next();
if (a != null) { if (a != null) {
writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
+ ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
} }
} }
writer.close(); writer.close();
} }
file = new File(plugin.getDataFolder() + File.separator + "cache" file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours");
+ File.separator + path + File.separator + "armours");
file.mkdir(); file.mkdir();
ItemStack[] armors = playerData.getArmour(); ItemStack[] armors = playerData.getArmour();
for (int i = 0; i < armors.length; i++) { for (int i = 0; i < armors.length; i++) {
ItemStack item = armors[i]; ItemStack item = armors[i];
file = new File(plugin.getDataFolder() + File.separator file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache");
+ "cache" + File.separator + path + File.separator
+ "armours" + File.separator + i + ".cache");
writer = new FileWriter(file); writer = new FileWriter(file);
if (item != null) { if (item != null) {
writer.write(item.getType().name() + API.newline); writer.write(item.getType().name() + API.newline);
@ -130,8 +119,8 @@ public class FileCache {
writer.flush(); writer.flush();
if (item.hasItemMeta()) { if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName()) writer.write("name=" if (meta.hasDisplayName())
+ meta.getDisplayName() + API.newline); writer.write("name=" + meta.getDisplayName() + API.newline);
if (meta.hasLore()) { if (meta.hasLore()) {
String lores = ""; String lores = "";
for (String lore : meta.getLore()) for (String lore : meta.getLore())
@ -141,17 +130,14 @@ public class FileCache {
writer.flush(); writer.flush();
} }
for (Enchantment ench : item.getEnchantments().keySet()) { for (Enchantment ench : item.getEnchantments().keySet()) {
writer.write("enchant=" + ench.getName() + ":" writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
+ item.getEnchantments().get(ench)
+ API.newline);
} }
Attributes attributes = new Attributes(item); Attributes attributes = new Attributes(item);
if (attributes != null) if (attributes != null)
while (attributes.values().iterator().hasNext()) { while (attributes.values().iterator().hasNext()) {
Attribute a = attributes.values().iterator().next(); Attribute a = attributes.values().iterator().next();
if (a != null) { if (a != null) {
writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
+ ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
} }
} }
} else { } else {
@ -197,7 +183,8 @@ public class FileCache {
String line = reader.nextLine(); String line = reader.nextLine();
if (!line.contains(":")) { if (!line.contains(":")) {
// the fist line represent the player group, operator status // the fist line represent the player group, operator
// status
// and flying status // and flying status
final String[] playerInfo = line.split(";"); final String[] playerInfo = line.split(";");
group = playerInfo[0]; group = playerInfo[0];
@ -206,7 +193,8 @@ public class FileCache {
op = true; op = true;
} else op = false; } else op = false;
if (playerInfo.length > 2) { if (playerInfo.length > 2) {
if (Integer.parseInt(playerInfo[2]) == 1) flying = true; if (Integer.parseInt(playerInfo[2]) == 1)
flying = true;
else flying = false; else flying = false;
} }
@ -227,22 +215,19 @@ public class FileCache {
line = line.split(";")[0]; line = line.split(";")[0];
} }
final String[] in = line.split(":"); final String[] in = line.split(":");
// can enchant item? size ofstring in file - 4 all / 2 = number // can enchant item? size ofstring in file - 4 all / 2 =
// number
// of enchant // of enchant
if (in[0].equals("i")) { if (in[0].equals("i")) {
stacki[i] = new ItemStack(Material.getMaterial(in[1]), stacki[i] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
Integer.parseInt(in[2]), Short.parseShort((in[3])));
if (in.length > 4 && !in[4].isEmpty()) { if (in.length > 4 && !in[4].isEmpty()) {
for (int k = 4; k < in.length - 1; k++) { for (int k = 4; k < in.length - 1; k++) {
stacki[i].addUnsafeEnchantment( stacki[i].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
Enchantment.getByName(in[k]),
Integer.parseInt(in[k + 1]));
k++; k++;
} }
} }
try { try {
ItemMeta meta = plugin.getServer().getItemFactory() ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacki[i].getType());
.getItemMeta(stacki[i].getType());
if (!name.isEmpty()) { if (!name.isEmpty()) {
meta.setDisplayName(name); meta.setDisplayName(name);
} }
@ -253,25 +238,23 @@ public class FileCache {
} }
meta.setLore(loreList); meta.setLore(loreList);
} }
if (meta != null) stacki[i].setItemMeta(meta); if (meta != null)
stacki[i].setItemMeta(meta);
} catch (Exception e) { } catch (Exception e) {
} }
i++; i++;
} else { } else {
stacka[a] = new ItemStack(Material.getMaterial(in[1]), stacka[a] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
Integer.parseInt(in[2]), Short.parseShort((in[3])));
if (in.length > 4 && !in[4].isEmpty()) { if (in.length > 4 && !in[4].isEmpty()) {
for (int k = 4; k < in.length - 1; k++) { for (int k = 4; k < in.length - 1; k++) {
stacka[a].addUnsafeEnchantment( stacka[a].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
Enchantment.getByName(in[k]),
Integer.parseInt(in[k + 1]));
k++; k++;
} }
} }
try { try {
ItemMeta meta = plugin.getServer().getItemFactory() ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacka[a].getType());
.getItemMeta(stacka[a].getType()); if (!name.isEmpty())
if (!name.isEmpty()) meta.setDisplayName(name); meta.setDisplayName(name);
if (!lores.isEmpty()) { if (!lores.isEmpty()) {
List<String> loreList = new ArrayList<String>(); List<String> loreList = new ArrayList<String>();
for (String s : lores.split("%newline%")) { for (String s : lores.split("%newline%")) {
@ -279,7 +262,8 @@ public class FileCache {
} }
meta.setLore(loreList); meta.setLore(loreList);
} }
if (meta != null) stacki[i].setItemMeta(meta); if (meta != null)
stacki[i].setItemMeta(meta);
} catch (Exception e) { } catch (Exception e) {
} }
a++; a++;
@ -325,9 +309,8 @@ public class FileCache {
} }
if (reader != null) if (reader != null)
reader.close(); reader.close();
for (int i = 0 ; i < inv.length; i++) { for (int i = 0; i < inv.length; i++) {
reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache"));
+ File.separator + "inventory" + File.separator + i + ".cache"));
ItemStack item = new ItemStack(Material.AIR); ItemStack item = new ItemStack(Material.AIR);
ItemMeta meta = null; ItemMeta meta = null;
Attributes attributes = new Attributes(item); Attributes attributes = new Attributes(item);
@ -350,7 +333,8 @@ public class FileCache {
case 4: case 4:
meta = Bukkit.getItemFactory().getItemMeta(item.getType()); meta = Bukkit.getItemFactory().getItemMeta(item.getType());
break; break;
default: break; default:
break;
} }
if (line.startsWith("name=")) { if (line.startsWith("name=")) {
line = line.substring(5); line = line.substring(5);
@ -375,7 +359,8 @@ public class FileCache {
try { try {
line = line.substring(10); line = line.substring(10);
String[] args = line.split(";"); String[] args = line.split(";");
if (args.length != 5) continue; if (args.length != 5)
continue;
String name = args[0]; String name = args[0];
AttributeType type = AttributeType.fromId(args[1]); AttributeType type = AttributeType.fromId(args[1]);
double amount = Double.parseDouble(args[2]); double amount = Double.parseDouble(args[2]);
@ -383,7 +368,8 @@ public class FileCache {
UUID uuid = UUID.fromString(args[4]); UUID uuid = UUID.fromString(args[4]);
Attribute attribute = new Attribute(new Builder(amount, operation, type, name, uuid)); Attribute attribute = new Attribute(new Builder(amount, operation, type, name, uuid));
attributes.add(attribute); attributes.add(attribute);
} catch (Exception e) {} } catch (Exception e) {
}
} }
count++; count++;
} }
@ -391,9 +377,8 @@ public class FileCache {
reader.close(); reader.close();
inv[i] = attributes.getStack(); inv[i] = attributes.getStack();
} }
for (int i = 0 ; i < armours.length; i++) { for (int i = 0; i < armours.length; i++) {
reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache"));
+ File.separator + "armours" + File.separator + i + ".cache"));
ItemStack item = new ItemStack(Material.AIR); ItemStack item = new ItemStack(Material.AIR);
ItemMeta meta = null; ItemMeta meta = null;
Attributes attributes = new Attributes(item); Attributes attributes = new Attributes(item);
@ -416,7 +401,8 @@ public class FileCache {
case 4: case 4:
meta = Bukkit.getItemFactory().getItemMeta(item.getType()); meta = Bukkit.getItemFactory().getItemMeta(item.getType());
break; break;
default: break; default:
break;
} }
if (line.startsWith("name=")) { if (line.startsWith("name=")) {
line = line.substring(5); line = line.substring(5);
@ -441,7 +427,8 @@ public class FileCache {
try { try {
line = line.substring(10); line = line.substring(10);
String[] args = line.split(";"); String[] args = line.split(";");
if (args.length != 5) continue; if (args.length != 5)
continue;
String name = args[0]; String name = args[0];
AttributeType type = AttributeType.fromId(args[1]); AttributeType type = AttributeType.fromId(args[1]);
double amount = Double.parseDouble(args[2]); double amount = Double.parseDouble(args[2]);
@ -449,7 +436,8 @@ public class FileCache {
UUID uuid = UUID.fromString(args[4]); UUID uuid = UUID.fromString(args[4]);
Attribute attribute = new Attribute(new Builder(amount, operation, type, name, uuid)); Attribute attribute = new Attribute(new Builder(amount, operation, type, name, uuid));
attributes.add(attribute); attributes.add(attribute);
} catch (Exception e) {} } catch (Exception e) {
}
} }
count++; count++;
} }
@ -478,18 +466,17 @@ public class FileCache {
} catch (Error e) { } catch (Error e) {
path = player.getName(); path = player.getName();
} }
File file = new File(plugin.getDataFolder() + File.separator + "cache" File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path);
+ File.separator + path);
if (!file.exists()) { if (!file.exists()) {
file = new File("cache/" + player.getName().toLowerCase() file = new File("cache/" + player.getName().toLowerCase() + ".cache");
+ ".cache");
} }
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) { if (file.isDirectory()) {
for (File f : file.listFiles()) for (File f : file.listFiles())
if (f.isDirectory()) for (File a : f.listFiles()) if (f.isDirectory())
a.delete(); for (File a : f.listFiles())
a.delete();
else f.delete(); else f.delete();
} else file.delete(); } else file.delete();
} }
@ -504,11 +491,9 @@ public class FileCache {
} catch (Error e) { } catch (Error e) {
path = player.getName(); path = player.getName();
} }
File file = new File(plugin.getDataFolder() + File.separator + "cache" File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path);
+ File.separator + path);
if (!file.exists()) { if (!file.exists()) {
file = new File("cache/" + player.getName().toLowerCase() file = new File("cache/" + player.getName().toLowerCase() + ".cache");
+ ".cache");
} }
if (file.exists()) { if (file.exists()) {

View File

@ -39,11 +39,9 @@ public class LimboCache {
boolean flying; boolean flying;
if (playerData.doesCacheExist(player)) { if (playerData.doesCacheExist(player)) {
StoreInventoryEvent event = new StoreInventoryEvent(player, StoreInventoryEvent event = new StoreInventoryEvent(player, playerData);
playerData);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
&& event.getArmor() != null) {
inv = event.getInventory(); inv = event.getInventory();
arm = event.getArmor(); arm = event.getArmor();
} else { } else {
@ -56,34 +54,31 @@ public class LimboCache {
} else { } else {
StoreInventoryEvent event = new StoreInventoryEvent(player); StoreInventoryEvent event = new StoreInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
&& event.getArmor() != null) {
inv = event.getInventory(); inv = event.getInventory();
arm = event.getArmor(); arm = event.getArmor();
} else { } else {
inv = null; inv = null;
arm = null; arm = null;
} }
if (player.isOp()) operator = true; if (player.isOp())
operator = true;
else operator = false; else operator = false;
if (player.isFlying()) flying = true; if (player.isFlying())
flying = true;
else flying = false; else flying = false;
if (plugin.permission != null) { if (plugin.permission != null) {
try { try {
playerGroup = plugin.permission.getPrimaryGroup(player); playerGroup = plugin.permission.getPrimaryGroup(player);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
ConsoleLogger ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null; plugin.permission = null;
} }
} }
} }
if (Settings.isForceSurvivalModeEnabled) { if (Settings.isForceSurvivalModeEnabled) {
if (Settings.isResetInventoryIfCreative if (Settings.isResetInventoryIfCreative && player.getGameMode() == GameMode.CREATIVE) {
&& player.getGameMode() == GameMode.CREATIVE) {
ResetInventoryEvent event = new ResetInventoryEvent(player); ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
@ -96,13 +91,11 @@ public class LimboCache {
if (player.isDead()) { if (player.isDead()) {
loc = plugin.getSpawnLocation(player); loc = plugin.getSpawnLocation(player);
} }
cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc, cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup, flying));
inv, arm, gameMode, operator, playerGroup, flying));
} }
public void addLimboPlayer(Player player, String group) { public void addLimboPlayer(Player player, String group) {
cache.put(player.getName().toLowerCase(), new LimboPlayer(player cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group));
.getName().toLowerCase(), group));
} }
public void deleteLimboPlayer(String name) { public void deleteLimboPlayer(String name) {

View File

@ -76,32 +76,26 @@ public class AdminCommand implements CommandExecutor {
return true; return true;
} }
if (!plugin.authmePermissible(sender, if (!plugin.authmePermissible(sender, "authme.admin." + args[0].toLowerCase())) {
"authme.admin." + args[0].toLowerCase())) {
m._(sender, "no_perm"); m._(sender, "no_perm");
return true; return true;
} }
if ((sender instanceof ConsoleCommandSender) if ((sender instanceof ConsoleCommandSender) && args[0].equalsIgnoreCase("passpartuToken")) {
&& args[0].equalsIgnoreCase("passpartuToken")) {
if (args.length > 1) { if (args.length > 1) {
System.out System.out.println("[AuthMe] command usage: /authme passpartuToken");
.println("[AuthMe] command usage: /authme passpartuToken");
return true; return true;
} }
if (Utils.getInstance().obtainToken()) { if (Utils.getInstance().obtainToken()) {
System.out System.out.println("[AuthMe] You have 30s for insert this token ingame with /passpartu [token]");
.println("[AuthMe] You have 30s for insert this token ingame with /passpartu [token]");
} else { } else {
System.out System.out.println("[AuthMe] Security error on passpartu token, redo it. ");
.println("[AuthMe] Security error on passpartu token, redo it. ");
} }
return true; return true;
} }
if (args[0].equalsIgnoreCase("version")) { if (args[0].equalsIgnoreCase("version")) {
sender.sendMessage("AuthMe Version: " sender.sendMessage("AuthMe Version: " + AuthMe.getInstance().getDescription().getVersion());
+ AuthMe.getInstance().getDescription().getVersion());
return true; return true;
} }
@ -115,16 +109,15 @@ public class AdminCommand implements CommandExecutor {
calendar.add(Calendar.DATE, -(Integer.parseInt(args[1]))); calendar.add(Calendar.DATE, -(Integer.parseInt(args[1])));
long until = calendar.getTimeInMillis(); long until = calendar.getTimeInMillis();
List<String> purged = database.autoPurgeDatabase(until); List<String> purged = database.autoPurgeDatabase(until);
sender.sendMessage("Deleted " + purged.size() sender.sendMessage("Deleted " + purged.size() + " user accounts");
+ " user accounts"); if (Settings.purgeEssentialsFile && plugin.ess != null)
if (Settings.purgeEssentialsFile && plugin.ess != null) plugin.dataManager plugin.dataManager.purgeEssentials(purged);
.purgeEssentials(purged); if (Settings.purgePlayerDat)
if (Settings.purgePlayerDat) plugin.dataManager plugin.dataManager.purgeDat(purged);
.purgeDat(purged); if (Settings.purgeLimitedCreative)
if (Settings.purgeLimitedCreative) plugin.dataManager plugin.dataManager.purgeLimitedCreative(purged);
.purgeLimitedCreative(purged); if (Settings.purgeAntiXray)
if (Settings.purgeAntiXray) plugin.dataManager plugin.dataManager.purgeAntiXray(purged);
.purgeAntiXray(purged);
return true; return true;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
sender.sendMessage("Usage: /authme purge <DAYS>"); sender.sendMessage("Usage: /authme purge <DAYS>");
@ -132,9 +125,9 @@ public class AdminCommand implements CommandExecutor {
} }
} else if (args[0].equalsIgnoreCase("reload")) { } else if (args[0].equalsIgnoreCase("reload")) {
database.reload(); database.reload();
File newConfigFile = new File("plugins/AuthMe", "config.yml"); File newConfigFile = new File("plugins" + File.separator + "AuthMe", "config.yml");
if (!newConfigFile.exists()) { if (!newConfigFile.exists()) {
InputStream fis = getClass().getResourceAsStream("/config.yml"); InputStream fis = getClass().getResourceAsStream("" + File.separator + "config.yml");
FileOutputStream fos = null; FileOutputStream fos = null;
try { try {
fos = new FileOutputStream(newConfigFile); fos = new FileOutputStream(newConfigFile);
@ -145,8 +138,7 @@ public class AdminCommand implements CommandExecutor {
fos.write(buf, 0, i); fos.write(buf, 0, i);
} }
} catch (Exception e) { } catch (Exception e) {
Logger.getLogger(JavaPlugin.class.getName()).log( Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR");
Level.SEVERE, "Failed to load config from JAR");
} finally { } finally {
try { try {
if (fis != null) { if (fis != null) {
@ -159,8 +151,7 @@ public class AdminCommand implements CommandExecutor {
} }
} }
} }
YamlConfiguration newConfig = YamlConfiguration YamlConfiguration newConfig = YamlConfiguration.loadConfiguration(newConfigFile);
.loadConfiguration(newConfigFile);
Settings.reloadConfigOptions(newConfig); Settings.reloadConfigOptions(newConfig);
m.reLoad(); m.reLoad();
s.reLoad(); s.reLoad();
@ -176,16 +167,10 @@ public class AdminCommand implements CommandExecutor {
long lastLogin = player.getLastLogin(); long lastLogin = player.getLastLogin();
Date d = new Date(lastLogin); Date d = new Date(lastLogin);
final long diff = System.currentTimeMillis() - lastLogin; final long diff = System.currentTimeMillis() - lastLogin;
final String msg = (int) (diff / 86400000) + " days " final String msg = (int) (diff / 86400000) + " days " + (int) (diff / 3600000 % 24) + " hours " + (int) (diff / 60000 % 60) + " mins " + (int) (diff / 1000 % 60) + " secs.";
+ (int) (diff / 3600000 % 24) + " hours "
+ (int) (diff / 60000 % 60) + " mins "
+ (int) (diff / 1000 % 60) + " secs.";
String lastIP = player.getIp(); String lastIP = player.getIp();
sender.sendMessage("[AuthMe] " + args[1].toLowerCase() sender.sendMessage("[AuthMe] " + args[1].toLowerCase() + " lastlogin : " + d.toString());
+ " lastlogin : " + d.toString()); sender.sendMessage("[AuthMe] The player : " + player.getNickname() + " is unlogged since " + msg);
sender.sendMessage("[AuthMe] The player : "
+ player.getNickname() + " is unlogged since "
+ msg);
sender.sendMessage("[AuthMe] LastPlayer IP : " + lastIP); sender.sendMessage("[AuthMe] LastPlayer IP : " + lastIP);
} else { } else {
m._(sender, "unknown_user"); m._(sender, "unknown_user");
@ -204,104 +189,86 @@ public class AdminCommand implements CommandExecutor {
if (!args[1].contains(".")) { if (!args[1].contains(".")) {
final CommandSender fSender = sender; final CommandSender fSender = sender;
final String[] arguments = args; final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
new Runnable() {
@Override @Override
public void run() { public void run() {
PlayerAuth pAuth = null; PlayerAuth pAuth = null;
String message = "[AuthMe] "; String message = "[AuthMe] ";
try { try {
pAuth = database.getAuth(arguments[1] pAuth = database.getAuth(arguments[1].toLowerCase());
.toLowerCase()); } catch (NullPointerException npe) {
} catch (NullPointerException npe) { fSender.sendMessage("[AuthMe] This player is unknown");
fSender.sendMessage("[AuthMe] This player is unknown"); return;
return; }
} if (pAuth != null) {
if (pAuth != null) { List<String> accountList = database.getAllAuthsByName(pAuth);
List<String> accountList = database if (accountList.isEmpty() || accountList == null) {
.getAllAuthsByName(pAuth); fSender.sendMessage("[AuthMe] This player is unknown");
if (accountList.isEmpty() return;
|| accountList == null) { }
fSender.sendMessage("[AuthMe] This player is unknown"); if (accountList.size() == 1) {
return; fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
} return;
if (accountList.size() == 1) { }
fSender.sendMessage("[AuthMe] " int i = 0;
+ arguments[1] for (String account : accountList) {
+ " is a single account player"); i++;
return; message = message + account;
} if (i != accountList.size()) {
int i = 0; message = message + ", ";
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 { } else {
fSender.sendMessage("[AuthMe] This player is unknown"); message = message + ".";
return;
} }
} }
}); 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; return true;
} else { } else {
final CommandSender fSender = sender; final CommandSender fSender = sender;
final String[] arguments = args; final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
new Runnable() {
@Override @Override
public void run() { public void run() {
String message = "[AuthMe] "; String message = "[AuthMe] ";
if (arguments[1] != null) { if (arguments[1] != null) {
List<String> accountList = database List<String> accountList = database.getAllAuthsByIp(arguments[1]);
.getAllAuthsByIp(arguments[1]); if (accountList.isEmpty() || accountList == null) {
if (accountList.isEmpty() fSender.sendMessage("[AuthMe] Please put a valid IP");
|| accountList == null) { return;
fSender.sendMessage("[AuthMe] Please put a valid IP"); }
return; if (accountList.size() == 1) {
} fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
if (accountList.size() == 1) { return;
fSender.sendMessage("[AuthMe] " }
+ arguments[1] int i = 0;
+ " is a single account player"); for (String account : accountList) {
return; i++;
} message = message + account;
int i = 0; if (i != accountList.size()) {
for (String account : accountList) { message = message + ", ";
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 { } else {
fSender.sendMessage("[AuthMe] Please put a valid IP"); message = message + ".";
return;
} }
} }
}); 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; return true;
} }
} else if (args[0].equalsIgnoreCase("register") } else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
|| args[0].equalsIgnoreCase("reg")) {
if (args.length != 3) { if (args.length != 3) {
sender.sendMessage("Usage: /authme register playername password"); sender.sendMessage("Usage: /authme register playername password");
return true; return true;
@ -312,13 +279,10 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "user_regged"); m._(sender, "user_regged");
return true; return true;
} }
String hash = PasswordSecurity.getHash( String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name);
Settings.getPasswordHash, args[2], name); PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0L, "your@email.com", API.getPlayerRealName(name));
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0L, if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
"your@email.com", API.getPlayerRealName(name)); auth.setSalt(PasswordSecurity.userSalt.get(name));
if (PasswordSecurity.userSalt.containsKey(name)
&& PasswordSecurity.userSalt.get(name) != null) auth
.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt(""); else auth.setSalt("");
if (!database.saveAuth(auth)) { if (!database.saveAuth(auth)) {
m._(sender, "error"); m._(sender, "error");
@ -342,8 +306,7 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "unknown_user"); m._(sender, "unknown_user");
return true; return true;
} }
sender.sendMessage("[AuthMe] " + args[1] + " email : " sender.sendMessage("[AuthMe] " + args[1] + " email : " + getAuth.getEmail());
+ getAuth.getEmail());
return true; return true;
} else if (args[0].equalsIgnoreCase("chgemail")) { } else if (args[0].equalsIgnoreCase("chgemail")) {
if (args.length != 3) { if (args.length != 3) {
@ -361,17 +324,15 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "error"); m._(sender, "error");
return true; return true;
} }
if (PlayerCache.getInstance().getAuth(playername) != null) PlayerCache if (PlayerCache.getInstance().getAuth(playername) != null)
.getInstance().updatePlayer(getAuth); PlayerCache.getInstance().updatePlayer(getAuth);
return true; return true;
} else if (args[0].equalsIgnoreCase("setspawn")) { } else if (args[0].equalsIgnoreCase("setspawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().setSpawn( if (Spawn.getInstance().setSpawn(((Player) sender).getLocation()))
((Player) sender).getLocation())) sender sender.sendMessage("[AuthMe] Correctly define new spawn");
.sendMessage("[AuthMe] Correctly define new spawn"); else sender.sendMessage("[AuthMe] SetSpawn fail , please retry");
else sender
.sendMessage("[AuthMe] SetSpawn fail , please retry");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -382,11 +343,9 @@ public class AdminCommand implements CommandExecutor {
} else if (args[0].equalsIgnoreCase("setfirstspawn")) { } else if (args[0].equalsIgnoreCase("setfirstspawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().setFirstSpawn( if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation()))
((Player) sender).getLocation())) sender sender.sendMessage("[AuthMe] Correctly define new first spawn");
.sendMessage("[AuthMe] Correctly define new first spawn"); else sender.sendMessage("[AuthMe] SetFirstSpawn fail , please retry");
else sender
.sendMessage("[AuthMe] SetFirstSpawn fail , please retry");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -399,34 +358,22 @@ public class AdminCommand implements CommandExecutor {
for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) { for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) {
bannedPlayers.add(off.getName().toLowerCase()); bannedPlayers.add(off.getName().toLowerCase());
} }
final List<String> bP = bannedPlayers; database.purgeBanned(bannedPlayers);
if (database instanceof Thread) { if (Settings.purgeEssentialsFile && plugin.ess != null)
database.purgeBanned(bP); plugin.dataManager.purgeEssentials(bannedPlayers);
} else { if (Settings.purgePlayerDat)
Bukkit.getScheduler().runTaskAsynchronously(plugin, plugin.dataManager.purgeDat(bannedPlayers);
new Runnable() { if (Settings.purgeLimitedCreative)
@Override plugin.dataManager.purgeLimitedCreative(bannedPlayers);
public void run() { if (Settings.purgeAntiXray)
database.purgeBanned(bP); plugin.dataManager.purgeAntiXray(bannedPlayers);
}
});
}
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; return true;
} else if (args[0].equalsIgnoreCase("spawn")) { } else if (args[0].equalsIgnoreCase("spawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().getSpawn() != null) ((Player) sender) if (Spawn.getInstance().getSpawn() != null)
.teleport(Spawn.getInstance().getSpawn()); ((Player) sender).teleport(Spawn.getInstance().getSpawn());
else sender else sender.sendMessage("[AuthMe] Spawn fail , please try to define the spawn");
.sendMessage("[AuthMe] Spawn fail , please try to define the spawn");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -437,10 +384,9 @@ public class AdminCommand implements CommandExecutor {
} else if (args[0].equalsIgnoreCase("firstspawn")) { } else if (args[0].equalsIgnoreCase("firstspawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().getFirstSpawn() != null) ((Player) sender) if (Spawn.getInstance().getFirstSpawn() != null)
.teleport(Spawn.getInstance().getFirstSpawn()); ((Player) sender).teleport(Spawn.getInstance().getFirstSpawn());
else sender else sender.sendMessage("[AuthMe] Spawn fail , please try to define the first spawn");
.sendMessage("[AuthMe] Spawn fail , please try to define the first spawn");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -448,16 +394,14 @@ public class AdminCommand implements CommandExecutor {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} }
return true; return true;
} else if (args[0].equalsIgnoreCase("changepassword") } else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
|| args[0].equalsIgnoreCase("cp")) {
if (args.length != 3) { if (args.length != 3) {
sender.sendMessage("Usage: /authme changepassword playername newpassword"); sender.sendMessage("Usage: /authme changepassword playername newpassword");
return true; return true;
} }
try { try {
String name = args[1].toLowerCase(); String name = args[1].toLowerCase();
String hash = PasswordSecurity.getHash( String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name);
Settings.getPasswordHash, args[2], name);
PlayerAuth auth = null; PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name); auth = PlayerCache.getInstance().getAuth(name);
@ -484,9 +428,7 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "error"); m._(sender, "error");
} }
return true; return true;
} else if (args[0].equalsIgnoreCase("unregister") } else if (args[0].equalsIgnoreCase("unregister") || args[0].equalsIgnoreCase("unreg") || args[0].equalsIgnoreCase("del")) {
|| args[0].equalsIgnoreCase("unreg")
|| args[0].equalsIgnoreCase("del")) {
if (args.length != 2) { if (args.length != 2) {
sender.sendMessage("Usage: /authme unregister playername"); sender.sendMessage("Usage: /authme unregister playername");
return true; return true;
@ -505,13 +447,10 @@ public class AdminCommand implements CommandExecutor {
Utils.getInstance().setGroup(name, groupType.UNREGISTERED); Utils.getInstance().setGroup(name, groupType.UNREGISTERED);
if (target != null) { if (target != null) {
if (target.isOnline()) { if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
&& !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(target); Location spawn = plugin.getSpawnLocation(target);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent( SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(target, target.getLocation(), spawn, false);
target, target.getLocation(), spawn, false); plugin.getServer().getPluginManager().callEvent(tpEvent);
plugin.getServer().getPluginManager()
.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
target.teleport(tpEvent.getTo()); target.teleport(tpEvent.getTo());
} }
@ -521,23 +460,12 @@ public class AdminCommand implements CommandExecutor {
int interval = Settings.getWarnMessageInterval; int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler(); BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) { if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
new TimeoutTask(plugin, name), delay); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
LimboCache.getInstance().getLimboPlayer(name)
.setTimeoutTaskId(id);
} }
LimboCache LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("reg_msg"), interval)));
.getInstance() if (Settings.applyBlindEffect)
.getLimboPlayer(name) target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
.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"); m._(target, "unregistered");
} else { } else {
// Player isn't online, do nothing else // Player isn't online, do nothing else
@ -557,8 +485,7 @@ public class AdminCommand implements CommandExecutor {
String name = args[1].toLowerCase(); String name = args[1].toLowerCase();
PlayerAuth auth = database.getAuth(name); PlayerAuth auth = database.getAuth(name);
if (auth == null) { if (auth == null) {
sender.sendMessage("The player " + name sender.sendMessage("The player " + name + " is not registered ");
+ " is not registered ");
return true; return true;
} }
auth.setQuitLocX(0); auth.setQuitLocX(0);
@ -568,11 +495,10 @@ public class AdminCommand implements CommandExecutor {
database.updateQuitLoc(auth); database.updateQuitLoc(auth);
sender.sendMessage(name + " 's last pos location is now reset"); sender.sendMessage(name + " 's last pos location is now reset");
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger ConsoleLogger.showError("An error occured while trying to reset location or player do not exist, please see below: ");
.showError("An error occured while trying to reset location or player do not exist, please see below: ");
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (sender instanceof Player) sender if (sender instanceof Player)
.sendMessage("An error occured while trying to reset location or player do not exist, please see logs"); sender.sendMessage("An error occured while trying to reset location or player do not exist, please see logs");
} }
return true; return true;
} else if (args[0].equalsIgnoreCase("switchantibot")) { } else if (args[0].equalsIgnoreCase("switchantibot")) {
@ -599,11 +525,8 @@ public class AdminCommand implements CommandExecutor {
} }
if (Bukkit.getPlayer(args[1]) != null) { if (Bukkit.getPlayer(args[1]) != null) {
Player player = Bukkit.getPlayer(args[1]); Player player = Bukkit.getPlayer(args[1]);
sender.sendMessage(player.getName() + " actual ip is : " sender.sendMessage(player.getName() + " actual ip is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort());
+ player.getAddress().getAddress().getHostAddress() sender.sendMessage(player.getName() + " real ip is : " + plugin.getIP(player));
+ ":" + player.getAddress().getPort());
sender.sendMessage(player.getName() + " real ip is : "
+ plugin.getIP(player));
return true; return true;
} else { } else {
sender.sendMessage("This player is not actually online"); sender.sendMessage("This player is not actually online");
@ -625,8 +548,7 @@ public class AdminCommand implements CommandExecutor {
auth.setQuitLocZ(0D); auth.setQuitLocZ(0D);
auth.setWorld("world"); auth.setWorld("world");
database.updateQuitLoc(auth); database.updateQuitLoc(auth);
sender.sendMessage("[AuthMe] Successfully reset position for " sender.sendMessage("[AuthMe] Successfully reset position for " + auth.getNickname());
+ auth.getNickname());
return true; return true;
} else { } else {
sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername"); sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername");

View File

@ -61,8 +61,7 @@ public class CaptchaCommand implements CommandExecutor {
plugin.cap.remove(name); plugin.cap.remove(name);
plugin.cap.put(name, rdm.nextString()); plugin.cap.put(name, rdm.nextString());
for (String s : m._("wrong_captcha")) { for (String s : m._("wrong_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)));
plugin.cap.get(name)));
} }
return true; return true;
} }

View File

@ -54,16 +54,13 @@ public class ChangePasswordCommand implements CommandExecutor {
} }
try { try {
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, args[1], name);
args[1], name);
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
.getInstance().getAuth(name).getHash(), player.getName())) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name); PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
auth.setHash(hashnew); auth.setHash(hashnew);
if (PasswordSecurity.userSalt.containsKey(name) if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
&& PasswordSecurity.userSalt.get(name) != null) auth auth.setSalt(PasswordSecurity.userSalt.get(name));
.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt(""); else auth.setSalt("");
if (!database.updatePassword(auth)) { if (!database.updatePassword(auth)) {
m._(player, "error"); m._(player, "error");
@ -74,9 +71,7 @@ public class ChangePasswordCommand implements CommandExecutor {
m._(player, "pwd_changed"); m._(player, "pwd_changed");
ConsoleLogger.info(player.getName() + " changed his password"); ConsoleLogger.info(player.getName() + " changed his password");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification( plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " change his password!"));
"[AuthMe] " + player.getName()
+ " change his password!"));
} }
} else { } else {
m._(player, "wrong_pwd"); m._(player, "wrong_pwd");

View File

@ -88,9 +88,13 @@ public class ConverterCommand implements CommandExecutor {
public enum ConvertType { public enum ConvertType {
ftsql("flattosql"), ftsqlite("flattosqlite"), xauth("xauth"), crazylogin( ftsql("flattosql"),
"crazylogin"), rakamak("rakamak"), royalauth("royalauth"), vauth( ftsqlite("flattosqlite"),
"vauth"); xauth("xauth"),
crazylogin("crazylogin"),
rakamak("rakamak"),
royalauth("royalauth"),
vauth("vauth");
String name; String name;

View File

@ -61,18 +61,14 @@ public class EmailCommand implements CommandExecutor {
return true; return true;
} }
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") if (!plugin.authmePermissible(sender, "authme.allow2accounts") && data.getAllAuthsByEmail(args[1]).size() >= Settings.getmaxRegPerEmail) {
&& data.getAllAuthsByEmail(args[1]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return true; return true;
} }
} }
if (args[1].equals(args[2]) if (args[1].equals(args[2]) && PlayerCache.getInstance().isAuthenticated(name)) {
&& PlayerCache.getInstance().isAuthenticated(name)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name); PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
if (auth.getEmail() == null if (auth.getEmail() == null || (!auth.getEmail().equals("your@email.com") && !auth.getEmail().isEmpty())) {
|| (!auth.getEmail().equals("your@email.com") && !auth
.getEmail().isEmpty())) {
m._(player, "usage_email_change"); m._(player, "usage_email_change");
return true; return true;
} }
@ -103,17 +99,14 @@ public class EmailCommand implements CommandExecutor {
return true; return true;
} }
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") if (!plugin.authmePermissible(sender, "authme.allow2accounts") && data.getAllAuthsByEmail(args[2]).size() >= Settings.getmaxRegPerEmail) {
&& data.getAllAuthsByEmail(args[2]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return true; return true;
} }
} }
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name); PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
if (auth.getEmail() == null if (auth.getEmail() == null || auth.getEmail().equals("your@email.com") || auth.getEmail().isEmpty()) {
|| auth.getEmail().equals("your@email.com")
|| auth.getEmail().isEmpty()) {
m._(player, "usage_email_add"); m._(player, "usage_email_add");
return true; return true;
} }
@ -158,11 +151,9 @@ public class EmailCommand implements CommandExecutor {
return true; return true;
} }
try { try {
RandomString rand = new RandomString( RandomString rand = new RandomString(Settings.getRecoveryPassLength);
Settings.getRecoveryPassLength);
String thePass = rand.nextString(); String thePass = rand.nextString();
String hashnew = PasswordSecurity.getHash( String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, name);
Settings.getPasswordHash, thePass, name);
PlayerAuth auth = null; PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name); auth = PlayerCache.getInstance().getAuth(name);
@ -172,16 +163,12 @@ public class EmailCommand implements CommandExecutor {
m._(player, "unknown_user"); m._(player, "unknown_user");
return true; return true;
} }
if (Settings.getmailAccount.equals("") if (Settings.getmailAccount.equals("") || Settings.getmailAccount.isEmpty()) {
|| Settings.getmailAccount.isEmpty()) {
m._(player, "error"); m._(player, "error");
return true; return true;
} }
if (!args[1].equalsIgnoreCase(auth.getEmail()) if (!args[1].equalsIgnoreCase(auth.getEmail()) || args[1].equalsIgnoreCase("your@email.com") || auth.getEmail().equalsIgnoreCase("your@email.com")) {
|| args[1].equalsIgnoreCase("your@email.com")
|| auth.getEmail().equalsIgnoreCase(
"your@email.com")) {
m._(player, "email_invalid"); m._(player, "email_invalid");
return true; return true;
} }
@ -191,14 +178,14 @@ public class EmailCommand implements CommandExecutor {
finalauth.setHash(hashnew); finalauth.setHash(hashnew);
data.updatePassword(auth); data.updatePassword(auth);
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(plugin, Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
new Runnable() {
@Override @Override
public void run() { public void run() {
finalauth.setHash(finalhashnew); finalauth.setHash(finalhashnew);
data.updatePassword(finalauth); data.updatePassword(finalauth);
} }
}); });
} }
plugin.mail.main(auth, thePass); plugin.mail.main(auth, thePass);
m._(player, "email_send"); m._(player, "email_send");

View File

@ -74,54 +74,46 @@ public class LogoutCommand implements CommandExecutor {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(player); Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawnLoc);
spawnLoc);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (tpEvent.getTo() != null) player.teleport(tpEvent.getTo()); if (tpEvent.getTo() != null)
player.teleport(tpEvent.getTo());
} }
} }
if (LimboCache.getInstance().hasLimboPlayer(name)) LimboCache if (LimboCache.getInstance().hasLimboPlayer(name))
.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
utils.setGroup(player, groupType.NOTLOGGEDIN); utils.setGroup(player, groupType.NOTLOGGEDIN);
if (Settings.protectInventoryBeforeLogInEnabled) { if (Settings.protectInventoryBeforeLogInEnabled) {
player.getInventory().clear(); player.getInventory().clear();
// create cache file for handling lost of inventories on unlogged in // create cache file for handling lost of inventories on unlogged in
// status // status
DataFileCache playerData = new DataFileCache(LimboCache DataFileCache playerData = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour());
.getInstance().getLimboPlayer(name).getInventory(), playerBackup.createCache(player, playerData, LimboCache.getInstance().getLimboPlayer(name).getGroup(), LimboCache.getInstance().getLimboPlayer(name).getOperator(), LimboCache.getInstance().getLimboPlayer(name).isFlying());
LimboCache.getInstance().getLimboPlayer(name).getArmour());
playerBackup.createCache(player, playerData, LimboCache.getInstance()
.getLimboPlayer(name).getGroup(), LimboCache.getInstance()
.getLimboPlayer(name).getOperator(), LimboCache
.getInstance().getLimboPlayer(name).isFlying());
} }
int delay = Settings.getRegistrationTimeout * 20; int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval; int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler(); BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) { if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask( int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
} }
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask( int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), interval));
plugin, name, m._("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
try { try {
if (player.isInsideVehicle()) player.getVehicle().eject(); if (player.isInsideVehicle())
player.getVehicle().eject();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
} }
if (Settings.applyBlindEffect) player.addPotionEffect(new PotionEffect( if (Settings.applyBlindEffect)
PotionEffectType.BLINDNESS, player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
Settings.getRegistrationTimeout * 20, 2));
m._(player, "logout"); m._(player, "logout");
ConsoleLogger.info(player.getDisplayName() + " logged out"); ConsoleLogger.info(player.getDisplayName() + " logged out");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged out!"));
+ player.getName() + " logged out!"));
} }
return true; return true;
} }

View File

@ -15,6 +15,7 @@ import fr.xephi.authme.settings.Messages;
* @author stefano * @author stefano
*/ */
public class PasspartuCommand implements CommandExecutor { public class PasspartuCommand implements CommandExecutor {
private Utils utils = Utils.getInstance(); private Utils utils = Utils.getInstance();
public AuthMe plugin; public AuthMe plugin;
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
@ -32,16 +33,14 @@ public class PasspartuCommand implements CommandExecutor {
return true; return true;
} }
if (PlayerCache.getInstance().isAuthenticated( if (PlayerCache.getInstance().isAuthenticated(sender.getName().toLowerCase())) {
sender.getName().toLowerCase())) {
return true; return true;
} }
if ((sender instanceof Player) && args.length == 1) { if ((sender instanceof Player) && args.length == 1) {
if (utils.readToken(args[0])) { if (utils.readToken(args[0])) {
// bypass login! // bypass login!
plugin.management.performLogin((Player) sender, "dontneed", plugin.management.performLogin((Player) sender, "dontneed", true);
true);
return true; return true;
} }
sender.sendMessage("Time is expired or Token is Wrong!"); sender.sendMessage("Time is expired or Token is Wrong!");

View File

@ -57,16 +57,15 @@ public class RegisterCommand implements CommandExecutor {
plugin.management.performRegister(player, thePass, email); plugin.management.performRegister(player, thePass, email);
return true; return true;
} }
if (args.length == 0 if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
|| (Settings.getEnablePasswordVerifier && args.length < 2)) {
m._(player, "usage_reg"); m._(player, "usage_reg");
return true; return true;
} }
if (args.length > 1 && Settings.getEnablePasswordVerifier) if (!args[0] if (args.length > 1 && Settings.getEnablePasswordVerifier)
.equals(args[1])) { if (!args[0].equals(args[1])) {
m._(player, "password_error"); m._(player, "password_error");
return true; return true;
} }
plugin.management.performRegister(player, args[0], ""); plugin.management.performRegister(player, args[0], "");
return true; return true;
} }

View File

@ -67,20 +67,16 @@ public class UnregisterCommand implements CommandExecutor {
return true; return true;
} }
try { try {
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
.getInstance().getAuth(name).getHash(), player.getName())) {
if (!database.removeAuth(name)) { if (!database.removeAuth(name)) {
player.sendMessage("error"); player.sendMessage("error");
return true; return true;
} }
if (Settings.isForcedRegistrationEnabled) { if (Settings.isForcedRegistrationEnabled) {
if (Settings.isTeleportToSpawnEnabled if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
&& !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player); Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent( SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
player, player.getLocation(), spawn, false); plugin.getServer().getPluginManager().callEvent(tpEvent);
plugin.getServer().getPluginManager()
.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
@ -88,72 +84,48 @@ public class UnregisterCommand implements CommandExecutor {
player.getInventory().setContents(new ItemStack[36]); player.getInventory().setContents(new ItemStack[36]);
player.getInventory().setArmorContents(new ItemStack[4]); player.getInventory().setArmorContents(new ItemStack[4]);
player.saveData(); player.saveData();
PlayerCache.getInstance().removePlayer( PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
player.getName().toLowerCase()); if (!Settings.getRegisteredGroup.isEmpty())
if (!Settings.getRegisteredGroup.isEmpty()) Utils Utils.getInstance().setGroup(player, groupType.UNREGISTERED);
.getInstance().setGroup(player,
groupType.UNREGISTERED);
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
int delay = Settings.getRegistrationTimeout * 20; int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval; int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler(); BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) { if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
new TimeoutTask(plugin, name), delay); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
LimboCache.getInstance().getLimboPlayer(name)
.setTimeoutTaskId(id);
} }
LimboCache LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("reg_msg"), interval)));
.getInstance()
.getLimboPlayer(name)
.setMessageTaskId(
sched.scheduleSyncDelayedTask(
plugin,
new MessageTask(plugin, name, m
._("reg_msg"), interval)));
m._(player, "unregistered"); m._(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
+ " unregistered himself");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification( plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " unregistered himself!"));
"[AuthMe] " + player.getName()
+ " unregistered himself!"));
} }
return true; return true;
} }
if (!Settings.unRegisteredGroup.isEmpty()) { if (!Settings.unRegisteredGroup.isEmpty()) {
Utils.getInstance().setGroup(player, Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED);
Utils.groupType.UNREGISTERED);
} }
PlayerCache.getInstance().removePlayer( PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
player.getName().toLowerCase());
// check if Player cache File Exist and delete it, preventing // check if Player cache File Exist and delete it, preventing
// duplication of items // duplication of items
if (playerCache.doesCacheExist(player)) { if (playerCache.doesCacheExist(player)) {
playerCache.removeCache(player); playerCache.removeCache(player);
} }
if (Settings.applyBlindEffect) player if (Settings.applyBlindEffect)
.addPotionEffect(new PotionEffect( player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
PotionEffectType.BLINDNESS,
Settings.getRegistrationTimeout * 20, 2));
m._(player, "unregistered"); m._(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
+ " unregistered himself");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification( plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " unregistered himself!"));
"[AuthMe] " + player.getName()
+ " unregistered himself!"));
} }
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player); Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
player.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld() if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
.getChunkAt(tpEvent.getTo()).isLoaded()) { tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
tpEvent.getTo().getWorld()
.getChunkAt(tpEvent.getTo()).load();
} }
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }

View File

@ -41,11 +41,9 @@ public class CrazyLoginConverter implements Converter {
public void run() { public void run() {
fileName = Settings.crazyloginFileName; fileName = Settings.crazyloginFileName;
try { try {
source = new File(AuthMe.getInstance().getDataFolder() source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
+ File.separator + fileName);
if (!source.exists()) { if (!source.exists()) {
sender.sendMessage("Error while trying to import datas, please put " sender.sendMessage("Error while trying to import datas, please put " + fileName + " in AuthMe folder!");
+ fileName + " in AuthMe folder!");
return; return;
} }
source.createNewFile(); source.createNewFile();
@ -55,14 +53,15 @@ public class CrazyLoginConverter implements Converter {
while ((line = users.readLine()) != null) { while ((line = users.readLine()) != null) {
if (line.contains("|")) { if (line.contains("|")) {
String[] args = line.split("\\|"); String[] args = line.split("\\|");
if (args.length < 2) continue; if (args.length < 2)
if (args[0].equalsIgnoreCase("name")) continue; continue;
if (args[0].equalsIgnoreCase("name"))
continue;
String player = args[0].toLowerCase(); String player = args[0].toLowerCase();
String psw = args[1]; String psw = args[1];
try { try {
if (player != null && psw != null) { if (player != null && psw != null) {
PlayerAuth auth = new PlayerAuth(player, psw, PlayerAuth auth = new PlayerAuth(player, psw, "127.0.0.1", System.currentTimeMillis());
"127.0.0.1", System.currentTimeMillis());
database.saveAuth(auth); database.saveAuth(auth);
} }
} catch (Exception e) { } catch (Exception e) {
@ -70,8 +69,7 @@ public class CrazyLoginConverter implements Converter {
} }
} }
users.close(); users.close();
ConsoleLogger ConsoleLogger.info("CrazyLogin database has been imported correctly");
.info("CrazyLogin database has been imported correctly");
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) { } catch (IOException ex) {

View File

@ -51,78 +51,35 @@ public class FlatToSql implements Converter {
@Override @Override
public void run() { public void run() {
try { try {
source = new File(AuthMe.getInstance().getDataFolder() source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
+ File.separator + "auths.db");
source.createNewFile(); source.createNewFile();
output = new File(AuthMe.getInstance().getDataFolder() output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql");
+ File.separator + "authme.sql");
BufferedReader br = null; BufferedReader br = null;
BufferedWriter sql = null; BufferedWriter sql = null;
br = new BufferedReader(new FileReader(source)); br = new BufferedReader(new FileReader(source));
sql = new BufferedWriter(new FileWriter(output)); sql = new BufferedWriter(new FileWriter(output));
String createDB = "CREATE TABLE IF NOT EXISTS " + tableName + " (" 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); sql.write(createDB);
String line; String line;
String newline; String newline;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
sql.newLine(); sql.newLine();
String[] args = line.split(":"); String[] args = line.split(":");
if (args.length == 4) newline = "INSERT INTO " + tableName if (args.length == 4)
+ "(" + columnName + "," + columnPassword + "," 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);";
+ columnIp + "," + columnLastLogin + "," + lastlocX else if (args.length == 7)
+ "," + lastlocY + "," + lastlocZ + "," + lastlocWorld 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);";
+ "," + columnEmail + "," + columnLogged else if (args.length == 8)
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '" 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);";
+ args[2] + "', " + args[3] else if (args.length == 9)
+ ", 0.0, 0.0, 0.0, 'world', 'your@email.com', 0);"; 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 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 = ""; else newline = "";
if (newline != "") sql.write(newline); if (newline != "")
sql.write(newline);
} }
sql.close(); sql.close();
br.close(); br.close();
ConsoleLogger ConsoleLogger.info("The FlatFile has been converted to authme.sql file");
.info("The FlatFile has been converted to authme.sql file");
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) { } catch (IOException ex) {

View File

@ -56,24 +56,20 @@ public class FlatToSqlite implements Converter {
columnEmail = Settings.getMySQLColumnEmail; columnEmail = Settings.getMySQLColumnEmail;
columnID = Settings.getMySQLColumnId; columnID = Settings.getMySQLColumnId;
ConsoleLogger.info("Converting FlatFile to SQLite ..."); ConsoleLogger.info("Converting FlatFile to SQLite ...");
if (new File(AuthMe.getInstance().getDataFolder() + File.separator if (new File(AuthMe.getInstance().getDataFolder() + File.separator + database + ".db").exists()) {
+ database + ".db").exists()) { sender.sendMessage("The Database " + database + ".db can't be created cause the file already exist");
sender.sendMessage("The Database " + database
+ ".db can't be created cause the file already exist");
return; return;
} }
try { try {
connect(); connect();
setup(); setup();
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger ConsoleLogger.showError("Problem while trying to convert to sqlite !");
.showError("Problem while trying to convert to sqlite !");
sender.sendMessage("Problem while trying to convert to sqlite !"); sender.sendMessage("Problem while trying to convert to sqlite !");
return; return;
} }
try { try {
source = new File(AuthMe.getInstance().getDataFolder() source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
+ File.separator + "auths.db");
source.createNewFile(); source.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(source)); BufferedReader br = new BufferedReader(new FileReader(source));
String line; String line;
@ -81,35 +77,23 @@ public class FlatToSqlite implements Converter {
String newline; String newline;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args.length == 4) newline = "INSERT INTO " + tableName if (args.length == 4)
+ " VALUES (" + i + ", '" + args[0] + "', '" + args[1] newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0, 0, 0, 'world', 'your@email.com');";
+ "', '" + args[2] + "', " + args[3] else if (args.length == 7)
+ ", 0, 0, 0, 'world', 'your@email.com');"; 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 == 7) newline = "INSERT INTO " + tableName else if (args.length == 8)
+ " VALUES (" + i + ", '" + args[0] + "', '" + args[1] 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');";
+ "', '" + args[2] + "', " + args[3] + ", " + args[4] else if (args.length == 9)
+ ", " + args[5] + ", " + args[6] newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', '" + args[8] + "');";
+ ", '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 = ""; else newline = "";
if (newline != "") saveAuth(newline); if (newline != "")
saveAuth(newline);
i = i + 1; i = i + 1;
} }
br.close(); br.close();
ConsoleLogger.info("The FlatFile has been converted to " + database ConsoleLogger.info("The FlatFile has been converted to " + database + ".db file");
+ ".db file");
close(); close();
sender.sendMessage("The FlatFile has been converted to " + database sender.sendMessage("The FlatFile has been converted to " + database + ".db file");
+ ".db file");
return; return;
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
@ -124,8 +108,7 @@ public class FlatToSqlite implements Converter {
SQLException { SQLException {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded"); ConsoleLogger.info("SQLite driver loaded");
con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
+ database + ".db");
} }
private synchronized static void setup() throws SQLException { private synchronized static void setup() throws SQLException {
@ -133,63 +116,35 @@ public class FlatToSqlite implements Converter {
ResultSet rs = null; ResultSet rs = null;
try { try {
st = con.createStatement(); st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" 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 + "));");
+ columnID + " INTEGER AUTO_INCREMENT," + columnName rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
+ " 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()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;");
+ columnPassword + " VARCHAR(255) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnIp); rs = con.getMetaData().getColumns(null, null, tableName, columnIp);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;");
+ columnIp + " VARCHAR(40) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
columnLastLogin);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT;");
+ columnLastLogin + " BIGINT;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " 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';");
+ 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.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
lastlocWorld);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER " + lastlocZ + ";");
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER "
+ lastlocZ + ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
columnEmail);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com';");
} }
} finally { } finally {
close(rs); close(rs);

View File

@ -55,10 +55,8 @@ public class RakamakConverter implements Converter {
HashMap<String, String> playerIP = new HashMap<String, String>(); HashMap<String, String> playerIP = new HashMap<String, String>();
HashMap<String, String> playerPSW = new HashMap<String, String>(); HashMap<String, String> playerPSW = new HashMap<String, String>();
try { try {
source = new File(AuthMe.getInstance().getDataFolder() source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
+ File.separator + fileName); ipfiles = new File(AuthMe.getInstance().getDataFolder() + File.separator + ipFileName);
ipfiles = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + ipFileName);
source.createNewFile(); source.createNewFile();
ipfiles.createNewFile(); ipfiles.createNewFile();
BufferedReader users = null; BufferedReader users = null;
@ -80,8 +78,7 @@ public class RakamakConverter implements Converter {
if (line.contains("=")) { if (line.contains("=")) {
String[] arguments = line.split("="); String[] arguments = line.split("=");
try { try {
playerPSW.put(arguments[0], PasswordSecurity.getHash( playerPSW.put(arguments[0], PasswordSecurity.getHash(hash, arguments[1], arguments[0]));
hash, arguments[1], arguments[0]));
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
} }
@ -97,10 +94,9 @@ public class RakamakConverter implements Converter {
} else { } else {
ip = "127.0.0.1"; ip = "127.0.0.1";
} }
PlayerAuth auth = new PlayerAuth(player, psw, ip, PlayerAuth auth = new PlayerAuth(player, psw, ip, System.currentTimeMillis());
System.currentTimeMillis()); if (PasswordSecurity.userSalt.containsKey(player))
if (PasswordSecurity.userSalt.containsKey(player)) auth auth.setSalt(PasswordSecurity.userSalt.get(player));
.setSalt(PasswordSecurity.userSalt.get(player));
database.saveAuth(auth); database.saveAuth(auth);
} }
ConsoleLogger.info("Rakamak database has been imported correctly"); ConsoleLogger.info("Rakamak database has been imported correctly");

View File

@ -25,19 +25,16 @@ public class RoyalAuthConverter implements Converter {
try { try {
String name = o.getName().toLowerCase(); String name = o.getName().toLowerCase();
String separator = File.separator; String separator = File.separator;
File file = new File("." + separator + "plugins" + separator File file = new File("." + separator + "plugins" + separator + "RoyalAuth" + separator + "userdata" + separator + name + ".yml");
+ "RoyalAuth" + separator + "userdata" + separator if (data.isAuthAvailable(name))
+ name + ".yml"); continue;
if (data.isAuthAvailable(name)) continue; if (!file.exists())
if (!file.exists()) continue; continue;
RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file); RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file);
PlayerAuth auth = new PlayerAuth(name, ra.getHash(), PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com", o.getName());
"127.0.0.1", ra.getLastLogin(), "your@email.com",
o.getName());
data.saveAuth(auth); data.saveAuth(auth);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError("Error while trying to import " ConsoleLogger.showError("Error while trying to import " + o.getName() + " RoyalAuth datas");
+ o.getName() + " RoyalAuth datas");
} }
} }
} }

View File

@ -37,7 +37,7 @@ public class newxAuthToFlat {
sender.sendMessage("[AuthMe] xAuth plugin not found"); sender.sendMessage("[AuthMe] xAuth plugin not found");
return false; return false;
} }
if (!(new File("./plugins/xAuth/xAuth.h2.db").exists())) { if (!(new File(instance.getDataFolder().getParent() + File.separator + "xAuth" + File.separator + "xAuth.h2.db").exists())) {
sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data..."); sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data...");
} }
List<Integer> players = getXAuthPlayers(); List<Integer> players = getXAuthPlayers();
@ -51,8 +51,7 @@ public class newxAuthToFlat {
String pl = getIdPlayer(id); String pl = getIdPlayer(id);
String psw = getPassword(id); String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) { if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(pl));
"your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth); database.saveAuth(auth);
} }
} }
@ -65,19 +64,16 @@ public class newxAuthToFlat {
public String getIdPlayer(int id) { public String getIdPlayer(int id) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController() Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format( String sql = String.format("SELECT `playername` FROM `%s` WHERE `id` = ?", xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
"SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, id); ps.setInt(1, id);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) return null; if (!rs.next())
return null;
realPass = rs.getString("playername").toLowerCase(); realPass = rs.getString("playername").toLowerCase();
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve name for account: " + id, e); xAuthLog.severe("Failed to retrieve name for account: " + id, e);
@ -90,13 +86,11 @@ public class newxAuthToFlat {
public List<Integer> getXAuthPlayers() { public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>(); List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController() Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin() String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
.getDatabaseController().getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
rs = ps.executeQuery(); rs = ps.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -113,23 +107,19 @@ public class newxAuthToFlat {
public String getPassword(int accountId) { public String getPassword(int accountId) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController() Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format( String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?", xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
"SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, accountId); ps.setInt(1, accountId);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) return null; if (!rs.next())
return null;
realPass = rs.getString("password"); realPass = rs.getString("password");
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve password hash for account: " xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e);
+ accountId, e);
return null; return null;
} finally { } finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);

View File

@ -41,7 +41,7 @@ public class oldxAuthToFlat {
sender.sendMessage("[AuthMe] xAuth plugin not found"); sender.sendMessage("[AuthMe] xAuth plugin not found");
return false; return false;
} }
if (!(new File("./plugins/xAuth/xAuth.h2.db").exists())) { if (!(new File(instance.getDataFolder().getParent() + File.separator + "xAuth" + File.separator + "xAuth.h2.db").exists())) {
sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data..."); sender.sendMessage("[AuthMe] xAuth H2 database not found, checking for MySQL or SQLite data...");
} }
List<Integer> players = getXAuthPlayers(); List<Integer> players = getXAuthPlayers();
@ -55,8 +55,7 @@ public class oldxAuthToFlat {
String pl = getIdPlayer(id); String pl = getIdPlayer(id);
String psw = getPassword(id); String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) { if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(pl));
"your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth); database.saveAuth(auth);
} }
} }
@ -69,19 +68,16 @@ public class oldxAuthToFlat {
public String getIdPlayer(int id) { public String getIdPlayer(int id) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController() Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format( String sql = String.format("SELECT `playername` FROM `%s` WHERE `id` = ?", xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
"SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, id); ps.setInt(1, id);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) return null; if (!rs.next())
return null;
realPass = rs.getString("playername").toLowerCase(); realPass = rs.getString("playername").toLowerCase();
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve name for account: " + id, e); xAuthLog.severe("Failed to retrieve name for account: " + id, e);
@ -94,13 +90,11 @@ public class oldxAuthToFlat {
public List<Integer> getXAuthPlayers() { public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>(); List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController() Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin() String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
.getDatabaseController().getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
rs = ps.executeQuery(); rs = ps.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -117,23 +111,19 @@ public class oldxAuthToFlat {
public String getPassword(int accountId) { public String getPassword(int accountId) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController() Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format( String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?", xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT));
"SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, accountId); ps.setInt(1, accountId);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) return null; if (!rs.next())
return null;
realPass = rs.getString("password"); realPass = rs.getString("password");
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve password hash for account: " xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e);
+ accountId, e);
return null; return null;
} finally { } finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);

View File

@ -28,8 +28,7 @@ public class vAuthFileReader {
} }
public void convert() throws IOException { public void convert() throws IOException {
final File file = new File(plugin.getDataFolder().getParent() final File file = new File(plugin.getDataFolder().getParent() + "" + File.separator + "vAuth" + File.separator + "passwords.yml");
+ "/vAuth/passwords.yml");
Scanner scanner = null; Scanner scanner = null;
try { try {
scanner = new Scanner(file); scanner = new Scanner(file);
@ -41,23 +40,20 @@ public class vAuthFileReader {
if (isUUIDinstance(password)) { if (isUUIDinstance(password)) {
String pname = null; String pname = null;
try { try {
pname = Bukkit.getOfflinePlayer(UUID.fromString(name)) pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName();
.getName();
} catch (Exception e) { } catch (Exception e) {
pname = getName(UUID.fromString(name)); pname = getName(UUID.fromString(name));
} catch (NoSuchMethodError e) { } catch (NoSuchMethodError e) {
pname = getName(UUID.fromString(name)); pname = getName(UUID.fromString(name));
} }
if (pname == null) continue; if (pname == null)
auth = new PlayerAuth(pname.toLowerCase(), password, continue;
"127.0.0.1", System.currentTimeMillis(), auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname);
"your@email.com", pname);
} else { } else {
auth = new PlayerAuth(name, password, "127.0.0.1", auth = new PlayerAuth(name, password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", API.getPlayerRealName(name));
System.currentTimeMillis(), "your@email.com",
API.getPlayerRealName(name));
} }
if (auth != null) database.saveAuth(auth); if (auth != null)
database.saveAuth(auth);
} }
} catch (Exception e) { } catch (Exception e) {
} }
@ -65,14 +61,16 @@ public class vAuthFileReader {
} }
private boolean isUUIDinstance(String s) { private boolean isUUIDinstance(String s) {
if (String.valueOf(s.charAt(8)).equalsIgnoreCase("-")) return true; if (String.valueOf(s.charAt(8)).equalsIgnoreCase("-"))
return true;
return true; return true;
} }
private String getName(UUID uuid) { private String getName(UUID uuid) {
try { try {
for (OfflinePlayer op : Bukkit.getOfflinePlayers()) { for (OfflinePlayer op : Bukkit.getOfflinePlayers()) {
if (op.getUniqueId().compareTo(uuid) == 0) return op.getName(); if (op.getUniqueId().compareTo(uuid) == 0)
return op.getName();
} }
} catch (Exception e) { } catch (Exception e) {
} }

View File

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

View File

@ -22,7 +22,8 @@ public class CacheDataSource implements DataSource {
@Override @Override
public synchronized boolean isAuthAvailable(String user) { public synchronized boolean isAuthAvailable(String user) {
if (cache.containsKey(user.toLowerCase())) return true; if (cache.containsKey(user.toLowerCase()))
return true;
return source.isAuthAvailable(user.toLowerCase()); return source.isAuthAvailable(user.toLowerCase());
} }
@ -32,7 +33,8 @@ public class CacheDataSource implements DataSource {
return cache.get(user.toLowerCase()); return cache.get(user.toLowerCase());
} else { } else {
PlayerAuth auth = source.getAuth(user.toLowerCase()); PlayerAuth auth = source.getAuth(user.toLowerCase());
if (auth != null) cache.put(user.toLowerCase(), auth); if (auth != null)
cache.put(user.toLowerCase(), auth);
return auth; return auth;
} }
} }
@ -49,8 +51,8 @@ public class CacheDataSource implements DataSource {
@Override @Override
public synchronized boolean updatePassword(PlayerAuth auth) { public synchronized boolean updatePassword(PlayerAuth auth) {
if (source.updatePassword(auth)) { if (source.updatePassword(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get( if (cache.containsKey(auth.getNickname().toLowerCase()))
auth.getNickname()).setHash(auth.getHash()); cache.get(auth.getNickname()).setHash(auth.getHash());
return true; return true;
} }
return false; return false;
@ -147,8 +149,8 @@ public class CacheDataSource implements DataSource {
@Override @Override
public synchronized boolean updateEmail(PlayerAuth auth) { public synchronized boolean updateEmail(PlayerAuth auth) {
if (source.updateEmail(auth)) { if (source.updateEmail(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get( if (cache.containsKey(auth.getNickname().toLowerCase()))
auth.getNickname()).setEmail(auth.getEmail()); cache.get(auth.getNickname()).setEmail(auth.getEmail());
return true; return true;
} }
return false; return false;
@ -157,8 +159,8 @@ public class CacheDataSource implements DataSource {
@Override @Override
public synchronized boolean updateSalt(PlayerAuth auth) { public synchronized boolean updateSalt(PlayerAuth auth) {
if (source.updateSalt(auth)) { if (source.updateSalt(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get( if (cache.containsKey(auth.getNickname().toLowerCase()))
auth.getNickname()).setSalt(auth.getSalt()); cache.get(auth.getNickname()).setSalt(auth.getSalt());
return true; return true;
} }
return false; return false;

View File

@ -8,7 +8,9 @@ public interface DataSource {
public enum DataSourceType { public enum DataSourceType {
MYSQL, FILE, SQLITE MYSQL,
FILE,
SQLITE
} }
boolean isAuthAvailable(String user); boolean isAuthAvailable(String user);

View File

@ -42,8 +42,8 @@ public class FlatFileThread extends Thread implements DataSource {
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN..."); ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} }
} }
@ -85,11 +85,7 @@ public class FlatFileThread extends Thread implements DataSource {
BufferedWriter bw = null; BufferedWriter bw = null;
try { try {
bw = new BufferedWriter(new FileWriter(source, true)); bw = new BufferedWriter(new FileWriter(source, true));
bw.write(auth.getNickname() + ":" + auth.getHash() + ":" bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":" + auth.getWorld() + ":" + auth.getEmail() + "\n");
+ auth.getIp() + ":" + auth.getLastLogin() + ":"
+ auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":"
+ auth.getQuitLocZ() + ":" + auth.getWorld() + ":"
+ auth.getEmail() + "\n");
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
@ -119,46 +115,23 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
switch (args.length) { switch (args.length) {
case 4: { case 4: {
newAuth = new PlayerAuth(args[0], auth.getHash(), newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
args[2], Long.parseLong(args[3]), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 7: { case 7: {
newAuth = new PlayerAuth(args[0], auth.getHash(), 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]));
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; break;
} }
case 8: { case 8: {
newAuth = new PlayerAuth(args[0], auth.getHash(), 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]));
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; break;
} }
case 9: { case 9: {
newAuth = new PlayerAuth(args[0], auth.getHash(), 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]));
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; break;
} }
default: { default: {
newAuth = new PlayerAuth(args[0], auth.getHash(), newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
args[2], 0, 0, 0, 0, "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
} }
@ -199,46 +172,23 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
switch (args.length) { switch (args.length) {
case 4: { case 4: {
newAuth = new PlayerAuth(args[0], args[1], newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 7: { case 7: {
newAuth = new PlayerAuth(args[0], args[1], 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]));
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; break;
} }
case 8: { case 8: {
newAuth = new PlayerAuth(args[0], args[1], 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]));
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; break;
} }
case 9: { case 9: {
newAuth = new PlayerAuth(args[0], args[1], 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]));
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; break;
} }
default: { default: {
newAuth = new PlayerAuth(args[0], args[1], newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
} }
@ -277,11 +227,7 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], 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]));
Long.parseLong(args[3]), auth.getQuitLocX(),
auth.getQuitLocY(), auth.getQuitLocZ(),
auth.getWorld(), auth.getEmail(),
API.getPlayerRealName(args[0]));
break; break;
} }
} }
@ -481,40 +427,17 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(user)) { if (args[0].equals(user)) {
switch (args.length) { switch (args.length) {
case 2: case 2:
return new PlayerAuth(args[0], args[1], return new PlayerAuth(args[0], args[1], "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(args[0]));
"198.18.0.1", 0, "your@email.com",
API.getPlayerRealName(args[0]));
case 3: case 3:
return new PlayerAuth(args[0], args[1], args[2], 0, return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", API.getPlayerRealName(args[0]));
"your@email.com",
API.getPlayerRealName(args[0]));
case 4: case 4:
return new PlayerAuth(args[0], args[1], args[2], return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", API.getPlayerRealName(args[0]));
Long.parseLong(args[3]), "your@email.com",
API.getPlayerRealName(args[0]));
case 7: case 7:
return new PlayerAuth(args[0], args[1], args[2], 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]));
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: case 8:
return new PlayerAuth(args[0], args[1], args[2], 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]));
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: case 9:
return new PlayerAuth(args[0], args[1], args[2], 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]));
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
} }
} }
} }
@ -556,12 +479,7 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], 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]));
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; break;
} }
} }

View File

@ -69,6 +69,7 @@ public class MiniConnectionPoolManager {
* no free connection becomes available within <code>timeout</code> seconds. * no free connection becomes available within <code>timeout</code> seconds.
*/ */
public static class TimeoutException extends RuntimeException { public static class TimeoutException extends RuntimeException {
private static final long serialVersionUID = 1; private static final long serialVersionUID = 1;
public TimeoutException() { public TimeoutException() {
@ -168,8 +169,7 @@ public class MiniConnectionPoolManager {
// block. // block.
synchronized (this) { synchronized (this) {
if (isDisposed) { if (isDisposed) {
throw new IllegalStateException( throw new IllegalStateException("Connection pool has been disposed.");
"Connection pool has been disposed.");
} }
} }
try { try {
@ -177,8 +177,7 @@ public class MiniConnectionPoolManager {
throw new TimeoutException(); throw new TimeoutException();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException( throw new RuntimeException("Interrupted while waiting for a database connection.", e);
"Interrupted while waiting for a database connection.", e);
} }
boolean ok = false; boolean ok = false;
try { try {
@ -194,8 +193,7 @@ public class MiniConnectionPoolManager {
private synchronized Connection getConnection3() throws SQLException { private synchronized Connection getConnection3() throws SQLException {
if (isDisposed) { if (isDisposed) {
throw new IllegalStateException( throw new IllegalStateException("Connection pool has been disposed.");
"Connection pool has been disposed.");
} }
PooledConnection pconn; PooledConnection pconn;
if (!recycledConnections.isEmpty()) { if (!recycledConnections.isEmpty()) {
@ -260,15 +258,12 @@ public class MiniConnectionPoolManager {
try { try {
Thread.sleep(250); Thread.sleep(250);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException( throw new RuntimeException("Interrupted while waiting for a valid database connection.", e);
"Interrupted while waiting for a valid database connection.",
e);
} }
} }
time = System.currentTimeMillis(); time = System.currentTimeMillis();
if (time >= timeoutTime) { if (time >= timeoutTime) {
throw new TimeoutException( throw new TimeoutException("Timeout while waiting for a valid database connection.");
"Timeout while waiting for a valid database connection.");
} }
} }
} }
@ -340,8 +335,7 @@ public class MiniConnectionPoolManager {
private synchronized void disposeConnection(PooledConnection pconn) { private synchronized void disposeConnection(PooledConnection pconn) {
pconn.removeConnectionEventListener(poolConnectionEventListener); pconn.removeConnectionEventListener(poolConnectionEventListener);
if (!recycledConnections.remove(pconn) if (!recycledConnections.remove(pconn) && pconn != connectionInTransition) {
&& pconn != connectionInTransition) {
// If the PooledConnection is not in the recycledConnections list // If the PooledConnection is not in the recycledConnections list
// and is not currently within a PooledConnection.getConnection() // and is not currently within a PooledConnection.getConnection()
// call, // call,
@ -390,6 +384,7 @@ public class MiniConnectionPoolManager {
private class PoolConnectionEventListener implements private class PoolConnectionEventListener implements
ConnectionEventListener { ConnectionEventListener {
public void connectionClosed(ConnectionEvent event) { public void connectionClosed(ConnectionEvent event) {
PooledConnection pconn = (PooledConnection) event.getSource(); PooledConnection pconn = (PooledConnection) event.getSource();
recycleConnection(pconn); recycleConnection(pconn);

View File

@ -70,32 +70,29 @@ public class MySQLThread extends Thread implements DataSource {
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} catch (TimeoutException e) { } catch (TimeoutException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} }
} }
@ -121,85 +118,45 @@ public class MySQLThread extends Thread implements DataSource {
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
st = con.createStatement(); st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword + " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) 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 rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
+ " 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
+ "));");
rs = con.getMetaData().getColumns(null, null, tableName,
columnPassword);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;");
+ columnPassword + " VARCHAR(255) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnIp); rs = con.getMetaData().getColumns(null, null, tableName, columnIp);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;");
+ columnIp + " VARCHAR(40) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
columnLastLogin);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT;");
+ columnLastLogin + " BIGINT;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + columnLastLogin + " , ADD " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocX + " , ADD " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocY + ";");
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0' AFTER "
+ columnLastLogin + " , ADD " + lastlocY
+ " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocX
+ " , ADD " + lastlocZ
+ " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocY
+ ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
lastlocWorld);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER " + lastlocZ + ";");
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER "
+ lastlocZ + ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
columnEmail);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com' AFTER " + lastlocWorld + ";");
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com' AFTER "
+ lastlocWorld + ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, columnLogged);
columnLogged);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLogged + " SMALLINT NOT NULL DEFAULT '0' AFTER " + columnEmail + ";");
+ columnLogged
+ " SMALLINT NOT NULL DEFAULT '0' AFTER " + columnEmail
+ ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (rs.next()) { if (rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " MODIFY " st.executeUpdate("ALTER TABLE " + tableName + " MODIFY " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY "
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY "
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
} }
} finally { } finally {
close(rs); close(rs);
@ -215,8 +172,7 @@ public class MySQLThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
@ -243,61 +199,25 @@ public class MySQLThread extends Thread implements DataSource {
int id = -1; int id = -1;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
if (rs.getString(columnIp).isEmpty() if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) {
&& rs.getString(columnIp) != null) { pAuth = 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)));
pAuth = 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 { } else {
if (!columnSalt.isEmpty()) { if (!columnSalt.isEmpty()) {
if (!columnGroup.isEmpty()) pAuth = new PlayerAuth( if (!columnGroup.isEmpty())
rs.getString(columnName), pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName)));
rs.getString(columnPassword), else pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName)));
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 pAuth = new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword),
rs.getString(columnSalt),
rs.getString(columnIp),
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ),
rs.getString(lastlocWorld),
rs.getString(columnEmail),
API.getPlayerRealName(rs.getString(columnName)));
} else { } else {
pAuth = new PlayerAuth(rs.getString(columnName), pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), API.getPlayerRealName(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 (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
rs.close(); rs.close();
pst = con pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;");
.prepareStatement("SELECT * FROM xf_user_authenticate WHERE "
+ columnID + "=?;");
pst.setInt(1, id); pst.setInt(1, id);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
@ -329,21 +249,15 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
if ((columnSalt == null || columnSalt.isEmpty()) if ((columnSalt == null || columnSalt.isEmpty()) || (auth.getSalt() == null || auth.getSalt().isEmpty())) {
|| (auth.getSalt() == null || 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(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin()); pst.setLong(4, auth.getLastLogin());
pst.executeUpdate(); pst.executeUpdate();
} else { } else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);");
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + "," + columnSalt
+ ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
@ -353,8 +267,7 @@ public class MySQLThread extends Thread implements DataSource {
} }
if (!columnOthers.isEmpty()) { if (!columnOthers.isEmpty()) {
for (String column : columnOthers) { for (String column : columnOthers) {
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + column + "=? WHERE " + columnName + "=?;");
+ column + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getRealname()); pst.setString(1, auth.getRealname());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -363,42 +276,32 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.PHPBB) { if (Settings.getPasswordHash == HashAlgorithm.PHPBB) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Insert player in phpbb_user_group // Insert player in phpbb_user_group
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getPhpbbPrefix + "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getPhpbbPrefix
+ "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);");
pst.setInt(1, Settings.getPhpbbGroup); pst.setInt(1, Settings.getPhpbbGroup);
pst.setInt(2, id); pst.setInt(2, id);
pst.setInt(3, 0); pst.setInt(3, 0);
pst.setInt(4, 0); pst.setInt(4, 0);
pst.executeUpdate(); pst.executeUpdate();
// Update player group in phpbb_users // Update player group in phpbb_users
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".group_id=? WHERE " + columnName + "=?;");
+ tableName + ".group_id=? WHERE " + columnName
+ "=?;");
pst.setInt(1, Settings.getPhpbbGroup); pst.setInt(1, Settings.getPhpbbGroup);
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
// Get current time without ms // Get current time without ms
long time = System.currentTimeMillis() / 1000; long time = System.currentTimeMillis() / 1000;
// Update user_regdate // Update user_regdate
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".user_regdate=? WHERE " + columnName + "=?;");
+ tableName + ".user_regdate=? WHERE " + columnName
+ "=?;");
pst.setLong(1, time); pst.setLong(1, time);
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
// Update user_lastvisit // Update user_lastvisit
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".user_lastvisit=? WHERE " + columnName + "=?;");
+ tableName + ".user_lastvisit=? WHERE "
+ columnName + "=?;");
pst.setLong(1, time); pst.setLong(1, time);
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -407,116 +310,79 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) { if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// First Name // First Name
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "first_name"); pst.setString(2, "first_name");
pst.setString(3, ""); pst.setString(3, "");
pst.executeUpdate(); pst.executeUpdate();
// Last Name // Last Name
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "last_name"); pst.setString(2, "last_name");
pst.setString(3, ""); pst.setString(3, "");
pst.executeUpdate(); pst.executeUpdate();
// Nick Name // Nick Name
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "nickname"); pst.setString(2, "nickname");
pst.setString(3, auth.getNickname()); pst.setString(3, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
// Description // Description
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "description"); pst.setString(2, "description");
pst.setString(3, ""); pst.setString(3, "");
pst.executeUpdate(); pst.executeUpdate();
// Rich_Editing // Rich_Editing
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "rich_editing"); pst.setString(2, "rich_editing");
pst.setString(3, "true"); pst.setString(3, "true");
pst.executeUpdate(); pst.executeUpdate();
// Comments_Shortcuts // Comments_Shortcuts
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "comment_shortcuts"); pst.setString(2, "comment_shortcuts");
pst.setString(3, "false"); pst.setString(3, "false");
pst.executeUpdate(); pst.executeUpdate();
// admin_color // admin_color
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "admin_color"); pst.setString(2, "admin_color");
pst.setString(3, "fresh"); pst.setString(3, "fresh");
pst.executeUpdate(); pst.executeUpdate();
// use_ssl // use_ssl
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "use_ssl"); pst.setString(2, "use_ssl");
pst.setString(3, "0"); pst.setString(3, "0");
pst.executeUpdate(); pst.executeUpdate();
// show_admin_bar_front // show_admin_bar_front
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "show_admin_bar_front"); pst.setString(2, "show_admin_bar_front");
pst.setString(3, "true"); pst.setString(3, "true");
pst.executeUpdate(); pst.executeUpdate();
// wp_capabilities // wp_capabilities
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "wp_capabilities"); pst.setString(2, "wp_capabilities");
pst.setString(3, "a:1:{s:10:\"subscriber\";b:1;}"); pst.setString(3, "a:1:{s:10:\"subscriber\";b:1;}");
pst.executeUpdate(); pst.executeUpdate();
// wp_user_level // wp_user_level
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "wp_user_level"); pst.setString(2, "wp_user_level");
pst.setString(3, "0"); pst.setString(3, "0");
pst.executeUpdate(); pst.executeUpdate();
// default_password_nag // default_password_nag
pst = con pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "default_password_nag"); pst.setString(2, "default_password_nag");
pst.setString(3, ""); pst.setString(3, "");
@ -526,15 +392,13 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Insert password in the correct table // Insert password in the correct table
pst = con pst = con.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);");
.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "XenForo_Authentication_Core12"); pst.setString(2, "XenForo_Authentication_Core12");
byte[] bytes = auth.getHash().getBytes(); byte[] bytes = auth.getHash().getBytes();
@ -563,33 +427,27 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;");
+ columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash()); pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Insert password in the correct table // Insert password in the correct table
pst = con pst = con.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE " + columnID + "=?;");
.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE "
+ columnID + "=?;");
byte[] bytes = auth.getHash().getBytes(); byte[] bytes = auth.getHash().getBytes();
Blob blob = con.createBlob(); Blob blob = con.createBlob();
blob.setBytes(1, bytes); blob.setBytes(1, bytes);
pst.setBlob(1, blob); pst.setBlob(1, blob);
pst.setInt(2, id); pst.setInt(2, id);
pst.executeUpdate(); pst.executeUpdate();
pst = con pst = con.prepareStatement("UPDATE xf_user_authenticate SET scheme_class=? WHERE " + columnID + "=?;");
.prepareStatement("UPDATE xf_user_authenticate SET scheme_class=? WHERE "
+ columnID + "=?;");
pst.setString(1, "XenForo_Authentication_Core12"); pst.setString(1, "XenForo_Authentication_Core12");
pst.setInt(2, id); pst.setInt(2, id);
pst.executeUpdate(); pst.executeUpdate();
@ -614,9 +472,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;");
+ columnIp + "=?, " + columnLastLogin + "=? WHERE "
+ columnName + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin()); pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getNickname()); pst.setString(3, auth.getNickname());
@ -640,8 +496,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
return pst.executeUpdate(); return pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -664,15 +519,13 @@ public class MySQLThread extends Thread implements DataSource {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
list.add(rs.getString(columnName)); list.add(rs.getString(columnName));
} }
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
pst.executeUpdate(); pst.executeUpdate();
return list; return list;
@ -698,21 +551,17 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ " WHERE " + columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Remove data // Remove data
pst = con pst = con.prepareStatement("DELETE FROM xf_user_authenticate WHERE " + columnID + "=?;");
.prepareStatement("DELETE FROM xf_user_authenticate WHERE "
+ columnID + "=?;");
pst.setInt(1, id); pst.setInt(1, id);
} }
} }
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -734,9 +583,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
+ lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ
+ "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX()); pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY()); pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ()); pst.setDouble(3, auth.getQuitLocZ());
@ -764,8 +611,7 @@ public class MySQLThread extends Thread implements DataSource {
int countIp = 0; int countIp = 0;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
+ columnIp + "=?;");
pst.setString(1, ip); pst.setString(1, ip);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -791,8 +637,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + " =? WHERE " + columnName + "=?;");
+ columnEmail + " =? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail()); pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -818,8 +663,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + " =? WHERE " + columnName + "=?;");
+ columnSalt + " =? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt()); pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -852,12 +696,11 @@ public class MySQLThread extends Thread implements DataSource {
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
} }
} }
@ -899,8 +742,7 @@ public class MySQLThread extends Thread implements DataSource {
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<String>();
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
+ columnIp + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -928,8 +770,7 @@ public class MySQLThread extends Thread implements DataSource {
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<String>();
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
+ columnIp + "=?;");
pst.setString(1, ip); pst.setString(1, ip);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -957,8 +798,7 @@ public class MySQLThread extends Thread implements DataSource {
List<String> countEmail = new ArrayList<String>(); List<String> countEmail = new ArrayList<String>();
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
+ columnEmail + "=?;");
pst.setString(1, email); pst.setString(1, email);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -985,8 +825,7 @@ public class MySQLThread extends Thread implements DataSource {
try { try {
for (String name : banned) { for (String name : banned) {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("DELETE FROM " + tableName pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
+ " WHERE " + columnName + "=?;");
pst.setString(1, name); pst.setString(1, name);
pst.executeUpdate(); pst.executeUpdate();
} }
@ -1009,33 +848,32 @@ public class MySQLThread extends Thread implements DataSource {
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
} }
} catch (AssertionError ae) { } catch (AssertionError ae) {
// Make sure assertionerror is caused by the connectionpoolmanager, // Make sure assertionerror is caused by the connectionpoolmanager,
// else re-throw it // else re-throw it
if (!ae.getMessage().equalsIgnoreCase("AuthMeDatabaseError")) throw new AssertionError( if (!ae.getMessage().equalsIgnoreCase("AuthMeDatabaseError"))
ae.getMessage()); throw new AssertionError(ae.getMessage());
try { try {
con = null; con = null;
reconnect(false); reconnect(false);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
} }
} }
if (con == null) con = conPool.getValidConnection(); if (con == null)
con = conPool.getValidConnection();
return con; return con;
} }
@ -1050,8 +888,8 @@ public class MySQLThread extends Thread implements DataSource {
dataSource.setUser(username); dataSource.setUser(username);
dataSource.setPassword(password); dataSource.setPassword(password);
conPool = new MiniConnectionPoolManager(dataSource, 10); conPool = new MiniConnectionPoolManager(dataSource, 10);
if (!reload) ConsoleLogger if (!reload)
.info("ConnectionPool was unavailable... Reconnected!"); ConsoleLogger.info("ConnectionPool was unavailable... Reconnected!");
} }
@Override @Override
@ -1066,11 +904,11 @@ public class MySQLThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) return (rs.getInt(columnLogged) == 1); if (rs.next())
return (rs.getInt(columnLogged) == 1);
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
@ -1091,8 +929,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnName + "=?;");
+ columnLogged + "=? WHERE " + columnName + "=?;");
pst.setInt(1, 1); pst.setInt(1, 1);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
@ -1115,8 +952,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnName + "=?;");
+ columnLogged + "=? WHERE " + columnName + "=?;");
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
@ -1139,8 +975,7 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;");
+ columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setInt(2, 1); pst.setInt(2, 1);
pst.executeUpdate(); pst.executeUpdate();

View File

@ -60,8 +60,8 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN..."); ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
@ -69,8 +69,8 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN..."); ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer() if (!Settings.isStopEnabled)
.getPluginManager().disablePlugin(AuthMe.getInstance()); AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} }
} }
@ -79,8 +79,7 @@ public class SQLiteThread extends Thread implements DataSource {
SQLException { SQLException {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded"); ConsoleLogger.info("SQLite driver loaded");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
+ database + ".db");
} }
@ -89,62 +88,37 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
try { try {
st = con.createStatement(); st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" 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 + "));");
+ columnID + " INTEGER AUTO_INCREMENT," + columnName rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
+ " 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()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;");
+ columnPassword + " VARCHAR(255) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnIp); rs = con.getMetaData().getColumns(null, null, tableName, columnIp);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;");
+ columnIp + " VARCHAR(40) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
columnLastLogin);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT;");
+ columnLastLogin + " BIGINT;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
+ 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 " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
lastlocWorld);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';");
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world';");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
columnEmail);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com';");
} }
} finally { } finally {
close(rs); close(rs);
@ -158,8 +132,7 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?");
+ columnName + "=?");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
return rs.next(); return rs.next();
@ -177,41 +150,17 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
if (rs.getString(columnIp).isEmpty()) { if (rs.getString(columnIp).isEmpty()) {
return new PlayerAuth(rs.getString(columnName), 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)));
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 { } else {
if (!columnSalt.isEmpty()) { if (!columnSalt.isEmpty()) {
return new PlayerAuth(rs.getString(columnName), 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)));
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 { } else {
return new PlayerAuth(rs.getString(columnName), 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)));
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 { } else {
@ -231,19 +180,14 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) { if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + ") VALUES (?,?,?,?);");
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + ") VALUES (?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin()); pst.setLong(4, auth.getLastLogin());
pst.executeUpdate(); pst.executeUpdate();
} else { } else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);");
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + "," + columnSalt
+ ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
@ -264,8 +208,7 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean updatePassword(PlayerAuth auth) { public synchronized boolean updatePassword(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;");
+ columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash()); pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -282,9 +225,7 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateSession(PlayerAuth auth) { public boolean updateSession(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;");
+ columnIp + "=?, " + columnLastLogin + "=? WHERE "
+ columnName + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin()); pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getNickname()); pst.setString(3, auth.getNickname());
@ -303,8 +244,7 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
return pst.executeUpdate(); return pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -321,8 +261,7 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -342,8 +281,7 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean removeAuth(String user) { public synchronized boolean removeAuth(String user) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -359,9 +297,7 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateQuitLoc(PlayerAuth auth) { public boolean updateQuitLoc(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
+ lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, "
+ lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX()); pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY()); pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ()); pst.setDouble(3, auth.getQuitLocZ());
@ -383,8 +319,7 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
int countIp = 0; int countIp = 0;
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
+ columnIp + "=?;");
pst.setString(1, ip); pst.setString(1, ip);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -404,8 +339,7 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateEmail(PlayerAuth auth) { public boolean updateEmail(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;");
+ columnEmail + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail()); pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -425,8 +359,7 @@ public class SQLiteThread extends Thread implements DataSource {
} }
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + "=? WHERE " + columnName + "=?;");
+ columnSalt + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt()); pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -478,8 +411,7 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<String>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
+ columnIp + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -506,8 +438,7 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
List<String> countIp = new ArrayList<String>(); List<String> countIp = new ArrayList<String>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
+ columnIp + "=?;");
pst.setString(1, ip); pst.setString(1, ip);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -534,8 +465,7 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
List<String> countEmail = new ArrayList<String>(); List<String> countEmail = new ArrayList<String>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
+ columnEmail + "=?;");
pst.setString(1, email); pst.setString(1, email);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -561,8 +491,7 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
for (String name : banned) { for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
+ " WHERE " + columnName + "=?;");
pst.setString(1, name); pst.setString(1, name);
pst.executeUpdate(); pst.executeUpdate();
} }

View File

@ -5,7 +5,7 @@ import org.bukkit.entity.Player;
/** /**
* *
* This event is call when AuthMe try to teleport a player * This event is call when AuthMe try to teleport a player
* *
* @author Xephi59 * @author Xephi59
*/ */

View File

@ -5,44 +5,44 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
/** /**
* *
* This event is called when a player login or register through AuthMe. * This event is called when a player login or register through AuthMe. The
* The boolean 'isLogin' will be false if, and only if, login/register failed. * boolean 'isLogin' will be false if, and only if, login/register failed.
* *
* @author Xephi59 * @author Xephi59
*/ */
public class LoginEvent extends Event { public class LoginEvent extends Event {
private Player player; private Player player;
private boolean isLogin; private boolean isLogin;
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
public LoginEvent(Player player, boolean isLogin) { public LoginEvent(Player player, boolean isLogin) {
this.player = player; this.player = player;
this.isLogin = isLogin; this.isLogin = isLogin;
} }
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
public void setPlayer(Player player) { public void setPlayer(Player player) {
this.player = player; this.player = player;
} }
@Deprecated @Deprecated
public void setLogin(boolean isLogin) { public void setLogin(boolean isLogin) {
this.isLogin = isLogin; this.isLogin = isLogin;
} }
public boolean isLogin() { public boolean isLogin() {
return isLogin; return isLogin;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;

View File

@ -6,8 +6,10 @@ import org.bukkit.event.HandlerList;
import fr.xephi.authme.security.crypts.EncryptionMethod; import fr.xephi.authme.security.crypts.EncryptionMethod;
/** /**
* <p>This event is called when we need to compare or get an hash password, * <p>
* for set a custom EncryptionMethod</p> * This event is called when we need to compare or get an hash password, for set
* a custom EncryptionMethod
* </p>
* *
* @see fr.xephi.authme.security.crypts.EncryptionMethod * @see fr.xephi.authme.security.crypts.EncryptionMethod
* *
@ -15,31 +17,31 @@ import fr.xephi.authme.security.crypts.EncryptionMethod;
*/ */
public class PasswordEncryptionEvent extends Event { public class PasswordEncryptionEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private EncryptionMethod method = null; private EncryptionMethod method = null;
private String playerName = ""; private String playerName = "";
public PasswordEncryptionEvent(EncryptionMethod method, String playerName) { public PasswordEncryptionEvent(EncryptionMethod method, String playerName) {
this.method = method; this.method = method;
this.playerName = playerName; this.playerName = playerName;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public void setMethod(EncryptionMethod method) { public void setMethod(EncryptionMethod method) {
this.method = method; this.method = method;
} }
public EncryptionMethod getMethod() { public EncryptionMethod getMethod() {
return method; return method;
} }
public String getPlayerName() { public String getPlayerName() {
return playerName; return playerName;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;

View File

@ -5,8 +5,8 @@ import org.bukkit.inventory.ItemStack;
/** /**
* *
* This event is call just after store inventory into cache and will * This event is call just after store inventory into cache and will empty the
* empty the player inventory. * player inventory.
* *
* @author Xephi59 * @author Xephi59
*/ */

View File

@ -5,8 +5,8 @@ import org.bukkit.entity.Player;
/** /**
* *
* This event is call if, and only if, a player is teleported * This event is call if, and only if, a player is teleported just after a
* just after a register. * register.
* *
* @author Xephi59 * @author Xephi59
*/ */

View File

@ -25,10 +25,8 @@ public class StoreInventoryEvent extends CustomEvent {
public StoreInventoryEvent(Player player, FileCache fileCache) { public StoreInventoryEvent(Player player, FileCache fileCache) {
this.player = player; this.player = player;
this.inventory = fileCache.readCache(player) this.inventory = fileCache.readCache(player).getInventory();
.getInventory(); this.armor = fileCache.readCache(player).getArmour();
this.armor = fileCache.readCache(player)
.getArmour();
} }
public ItemStack[] getInventory() { public ItemStack[] getInventory() {

View File

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

View File

@ -4,6 +4,7 @@ import org.getspout.spoutapi.event.screen.ButtonClickEvent;
import org.getspout.spoutapi.gui.GenericButton; import org.getspout.spoutapi.gui.GenericButton;
public class CustomButton extends GenericButton { public class CustomButton extends GenericButton {
public Clickable handleRef = null; public Clickable handleRef = null;
public CustomButton(Clickable c) { public CustomButton(Clickable c) {

View File

@ -36,8 +36,7 @@ public class LoginScreen extends GenericPopup implements Clickable {
String exitMsg = spoutCfg.getString("LoginScreen.exit message"); String exitMsg = spoutCfg.getString("LoginScreen.exit message");
String title = spoutCfg.getString("LoginScreen.title"); String title = spoutCfg.getString("LoginScreen.title");
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<String> textlines = (List<String>) spoutCfg List<String> textlines = (List<String>) spoutCfg.getList("LoginScreen.text");
.getList("LoginScreen.text");
public SpoutPlayer splayer; public SpoutPlayer splayer;
public LoginScreen(SpoutPlayer player) { public LoginScreen(SpoutPlayer player) {
@ -50,33 +49,24 @@ public class LoginScreen extends GenericPopup implements Clickable {
int part = !(textlines.size() <= 5) ? 195 / objects : 20; int part = !(textlines.size() <= 5) ? 195 / objects : 20;
int h = 3 * part / 4, w = 8 * part; int h = 3 * part / 4, w = 8 * part;
titleLbl = new GenericLabel(); titleLbl = new GenericLabel();
titleLbl.setText(title).setTextColor(new Color(1.0F, 0, 0, 1.0F)) 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);
.setAlign(WidgetAnchor.TOP_CENTER).setHeight(h).setWidth(w)
.setX(maxWidth / 2).setY(25);
this.attachWidget(plugin, titleLbl); this.attachWidget(plugin, titleLbl);
int ystart = 25 + h + part / 2; int ystart = 25 + h + part / 2;
for (int x = 0; x < textlines.size(); x++) { for (int x = 0; x < textlines.size(); x++) {
textLbl = new GenericLabel(); textLbl = new GenericLabel();
textLbl.setText(textlines.get(x)).setAlign(WidgetAnchor.TOP_CENTER) textLbl.setText(textlines.get(x)).setAlign(WidgetAnchor.TOP_CENTER).setHeight(h).setWidth(w).setX(maxWidth / 2).setY(ystart + x * part);
.setHeight(h).setWidth(w).setX(maxWidth / 2)
.setY(ystart + x * part);
this.attachWidget(plugin, textLbl); this.attachWidget(plugin, textLbl);
} }
passBox = new GenericTextField(); passBox = new GenericTextField();
passBox.setMaximumCharacters(18).setMaximumLines(1).setHeight(h - 2) passBox.setMaximumCharacters(18).setMaximumLines(1).setHeight(h - 2).setWidth(w - 2).setY(220 - h - 2 * part);
.setWidth(w - 2).setY(220 - h - 2 * part);
passBox.setPasswordField(true); passBox.setPasswordField(true);
setXToMid(passBox); setXToMid(passBox);
this.attachWidget(plugin, passBox); this.attachWidget(plugin, passBox);
errorLbl = new GenericLabel(); errorLbl = new GenericLabel();
errorLbl.setText("").setTextColor(new Color(1.0F, 0, 0, 1.0F)) errorLbl.setText("").setTextColor(new Color(1.0F, 0, 0, 1.0F)).setHeight(h).setWidth(w).setX(passBox.getX() + passBox.getWidth() + 2).setY(passBox.getY());
.setHeight(h).setWidth(w)
.setX(passBox.getX() + passBox.getWidth() + 2)
.setY(passBox.getY());
this.attachWidget(plugin, errorLbl); this.attachWidget(plugin, errorLbl);
loginBtn = new CustomButton(this); loginBtn = new CustomButton(this);
loginBtn.setText(loginTxt).setHeight(h).setWidth(w) loginBtn.setText(loginTxt).setHeight(h).setWidth(w).setY(220 - h - part);
.setY(220 - h - part);
setXToMid(loginBtn); setXToMid(loginBtn);
this.attachWidget(plugin, loginBtn); this.attachWidget(plugin, loginBtn);
exitBtn = new CustomButton(this); exitBtn = new CustomButton(this);
@ -90,7 +80,8 @@ public class LoginScreen extends GenericPopup implements Clickable {
public void handleClick(ButtonClickEvent event) { public void handleClick(ButtonClickEvent event) {
Button b = event.getButton(); Button b = event.getButton();
SpoutPlayer player = event.getPlayer(); SpoutPlayer player = event.getPlayer();
if (event.isCancelled() || event == null || event.getPlayer() == null) return; if (event.isCancelled() || event == null || event.getPlayer() == null)
return;
if (b.equals(loginBtn)) { if (b.equals(loginBtn)) {
plugin.management.performLogin(player, passBox.getText(), false); plugin.management.performLogin(player, passBox.getText(), false);
} else if (b.equals(exitBtn)) { } else if (b.equals(exitBtn)) {

View File

@ -60,8 +60,7 @@ public class AuthMeBlockListener implements Listener {
return; return;
} }
if (PlayerCache.getInstance().isAuthenticated( if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
player.getName().toLowerCase())) {
return; return;
} }

View File

@ -43,12 +43,14 @@ public class AuthMeEntityListener implements Listener {
return; return;
} }
if (instance.citizens.isNPC(entity, instance)) return; if (instance.citizens.isNPC(entity, instance))
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (CombatTagComunicator.isNPC(player)) return; if (CombatTagComunicator.isNPC(player))
return;
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
return; return;
@ -68,13 +70,15 @@ public class AuthMeEntityListener implements Listener {
if (event.isCancelled()) { if (event.isCancelled()) {
return; return;
} }
if (event.getTarget() == null) return; if (event.getTarget() == null)
return;
Entity entity = event.getTarget(); Entity entity = event.getTarget();
if (!(entity instanceof Player)) { if (!(entity instanceof Player)) {
return; return;
} }
if (instance.citizens.isNPC(entity, instance)) return; if (instance.citizens.isNPC(entity, instance))
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
@ -103,7 +107,8 @@ public class AuthMeEntityListener implements Listener {
return; return;
} }
if (instance.citizens.isNPC(entity, instance)) return; if (instance.citizens.isNPC(entity, instance))
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
@ -133,7 +138,8 @@ public class AuthMeEntityListener implements Listener {
return; return;
} }
if (instance.citizens.isNPC(entity, instance)) return; if (instance.citizens.isNPC(entity, instance))
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
@ -164,15 +170,14 @@ public class AuthMeEntityListener implements Listener {
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if (instance.citizens.isNPC(player, instance)) return; if (instance.citizens.isNPC(player, instance))
return;
if (PlayerCache.getInstance().isAuthenticated( if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
player.getName().toLowerCase())) {
return; return;
} }
@ -197,15 +202,14 @@ public class AuthMeEntityListener implements Listener {
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if (instance.citizens.isNPC(player, instance)) return; if (instance.citizens.isNPC(player, instance))
return;
if (PlayerCache.getInstance().isAuthenticated( if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
player.getName().toLowerCase())) {
return; return;
} }

View File

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

View File

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

View File

@ -24,8 +24,7 @@ public class BungeeCordMessage implements PluginMessageListener {
return; return;
} }
try { try {
final DataInputStream in = new DataInputStream( final DataInputStream in = new DataInputStream(new ByteArrayInputStream(message));
new ByteArrayInputStream(message));
String subchannel = in.readUTF(); String subchannel = in.readUTF();
if (subchannel.equals("IP")) { // We need only the IP channel if (subchannel.equals("IP")) { // We need only the IP channel
String ip = in.readUTF(); String ip = in.readUTF();

View File

@ -19,8 +19,7 @@ public abstract class CombatTagComunicator {
public static boolean isNPC(Entity player) { public static boolean isNPC(Entity player) {
try { try {
if (Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null) { if (Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null) {
combatApi = new CombatTagApi((CombatTag) Bukkit.getServer() combatApi = new CombatTagApi((CombatTag) Bukkit.getServer().getPluginManager().getPlugin("CombatTag"));
.getPluginManager().getPlugin("CombatTag"));
try { try {
combatApi.getClass().getMethod("isNPC"); combatApi.getClass().getMethod("isNPC");
} catch (Exception e) { } catch (Exception e) {

View File

@ -12,7 +12,7 @@ public class EssSpawn extends CustomConfiguration {
private static EssSpawn spawn; private static EssSpawn spawn;
public EssSpawn() { public EssSpawn() {
super(new File("./plugins/Essentials/spawn.yml")); super(new File("." + File.separator + "plugins" + File.separator + "Essentials" + File.separator + "spawn.yml"));
spawn = this; spawn = this;
load(); load();
} }
@ -26,16 +26,11 @@ public class EssSpawn extends CustomConfiguration {
public Location getLocation() { public Location getLocation() {
try { try {
if (!this.contains("spawns.default.world")) return null; if (!this.contains("spawns.default.world"))
if (this.getString("spawns.default.world").isEmpty() return null;
|| this.getString("spawns.default.world") == "") return null; if (this.getString("spawns.default.world").isEmpty() || this.getString("spawns.default.world") == "")
Location location = new Location(Bukkit.getWorld(this return null;
.getString("spawns.default.world")), 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")));
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; return location;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return null; return null;

View File

@ -17,6 +17,7 @@ import fr.xephi.authme.settings.Settings;
* *
*/ */
public class Management extends Thread { public class Management extends Thread {
public DataSource database; public DataSource database;
public AuthMe plugin; public AuthMe plugin;
public static RandomString rdm = new RandomString(Settings.captchaLength); public static RandomString rdm = new RandomString(Settings.captchaLength);
@ -33,13 +34,11 @@ public class Management extends Thread {
public void performLogin(final Player player, final String password, public void performLogin(final Player player, final String password,
final boolean forceLogin) { final boolean forceLogin) {
new AsyncronousLogin(player, password, forceLogin, plugin, database) new AsyncronousLogin(player, password, forceLogin, plugin, database).process();
.process();
} }
public void performRegister(final Player player, final String password, public void performRegister(final Player player, final String password,
final String email) { final String email) {
new AsyncronousRegister(player, password, email, plugin, database) new AsyncronousRegister(player, password, email, plugin, database).process();
.process();
} }
} }

View File

@ -22,6 +22,7 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
public class AsyncronousLogin { public class AsyncronousLogin {
protected Player player; protected Player player;
protected String name; protected String name;
protected String password; protected String password;
@ -56,17 +57,13 @@ public class AsyncronousLogin {
plugin.captcha.remove(name); plugin.captcha.remove(name);
plugin.captcha.put(name, i); plugin.captcha.put(name, i);
} }
if (plugin.captcha.containsKey(name) if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
&& plugin.captcha.get(name) >= Settings.maxLoginTry) {
plugin.cap.put(name, rdm.nextString()); plugin.cap.put(name, rdm.nextString());
for (String s : m._("usage_captcha")) { for (String s : m._("usage_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)).replace("<theCaptcha>", plugin.cap.get(name)));
plugin.cap.get(name)).replace("<theCaptcha>",
plugin.cap.get(name)));
} }
return true; return true;
} else if (plugin.captcha.containsKey(name) } else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
&& plugin.captcha.get(name) >= Settings.maxLoginTry) {
try { try {
plugin.captcha.remove(name); plugin.captcha.remove(name);
plugin.cap.remove(name); plugin.cap.remove(name);
@ -89,28 +86,19 @@ public class AsyncronousLogin {
if (!database.isAuthAvailable(name)) { if (!database.isAuthAvailable(name)) {
m._(player, "user_unknown"); m._(player, "user_unknown");
if (LimboCache.getInstance().hasLimboPlayer(name)) { if (LimboCache.getInstance().hasLimboPlayer(name)) {
Bukkit.getScheduler().cancelTask( Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId());
LimboCache.getInstance().getLimboPlayer(name)
.getMessageTaskId());
String[] msg; String[] msg;
if (Settings.emailRegistration) { if (Settings.emailRegistration) {
msg = m._("reg_email_msg"); msg = m._("reg_email_msg");
} else { } else {
msg = m._("reg_msg"); msg = m._("reg_msg");
} }
int msgT = Bukkit.getScheduler().scheduleSyncDelayedTask( int msgT = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, msg, Settings.getWarnMessageInterval));
plugin, LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
new MessageTask(plugin, name, msg,
Settings.getWarnMessageInterval));
LimboCache.getInstance().getLimboPlayer(name)
.setMessageTaskId(msgT);
} }
return null; return null;
} }
if (Settings.getMaxLoginPerIp > 0 if (Settings.getMaxLoginPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !getIP().equalsIgnoreCase("127.0.0.1") && !getIP().equalsIgnoreCase("localhost")) {
&& !plugin.authmePermissible(player, "authme.allow2accounts")
&& !getIP().equalsIgnoreCase("127.0.0.1")
&& !getIP().equalsIgnoreCase("localhost")) {
if (plugin.isLoggedIp(realName, getIP())) { if (plugin.isLoggedIp(realName, getIP())) {
m._(player, "logged_in"); m._(player, "logged_in");
return null; return null;
@ -121,8 +109,7 @@ public class AsyncronousLogin {
m._(player, "user_unknown"); m._(player, "user_unknown");
return null; return null;
} }
if (!Settings.getMySQLColumnGroup.isEmpty() if (!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) {
&& pAuth.getGroupId() == Settings.getNonActivatedGroup) {
m._(player, "vb_nonActiv"); m._(player, "vb_nonActiv");
return null; return null;
} }
@ -131,22 +118,22 @@ public class AsyncronousLogin {
public void process() { public void process() {
PlayerAuth pAuth = preAuth(); PlayerAuth pAuth = preAuth();
if (pAuth == null || needsCaptcha()) return; if (pAuth == null || needsCaptcha())
return;
String hash = pAuth.getHash(); String hash = pAuth.getHash();
String email = pAuth.getEmail(); String email = pAuth.getEmail();
boolean passwordVerified = true; boolean passwordVerified = true;
if (!forceLogin) try { if (!forceLogin)
passwordVerified = PasswordSecurity.comparePasswordWithHash( try {
password, hash, realName); passwordVerified = PasswordSecurity.comparePasswordWithHash(password, hash, realName);
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
m._(player, "error"); m._(player, "error");
return; return;
} }
if (passwordVerified && player.isOnline()) { if (passwordVerified && player.isOnline()) {
PlayerAuth auth = new PlayerAuth(name, hash, getIP(), PlayerAuth auth = new PlayerAuth(name, hash, getIP(), new Date().getTime(), email, realName);
new Date().getTime(), email, realName);
database.updateSession(auth); database.updateSession(auth);
if (Settings.useCaptcha) { if (Settings.useCaptcha) {
@ -163,12 +150,11 @@ public class AsyncronousLogin {
displayOtherAccounts(auth, player); displayOtherAccounts(auth, player);
if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName() if (!Settings.noConsoleSpam)
+ " logged in!"); ConsoleLogger.info(player.getName() + " logged in!");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification( plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged in!"));
"[AuthMe] " + player.getName() + " logged in!"));
} }
// makes player isLoggedin via API // makes player isLoggedin via API
@ -180,46 +166,32 @@ public class AsyncronousLogin {
// task, we schedule it in the end // task, we schedule it in the end
// so that we can be sure, and have not to care if it might be // so that we can be sure, and have not to care if it might be
// processed in other order. // processed in other order.
ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin( ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin(player, plugin, database);
player, plugin, database);
if (syncronousPlayerLogin.getLimbo() != null) { if (syncronousPlayerLogin.getLimbo() != null) {
player.getServer() player.getServer().getScheduler().cancelTask(syncronousPlayerLogin.getLimbo().getTimeoutTaskId());
.getScheduler() player.getServer().getScheduler().cancelTask(syncronousPlayerLogin.getLimbo().getMessageTaskId());
.cancelTask(
syncronousPlayerLogin.getLimbo()
.getTimeoutTaskId());
player.getServer()
.getScheduler()
.cancelTask(
syncronousPlayerLogin.getLimbo()
.getMessageTaskId());
} }
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, syncronousPlayerLogin);
syncronousPlayerLogin);
} else if (player.isOnline()) { } else if (player.isOnline()) {
if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName() if (!Settings.noConsoleSpam)
+ " used the wrong password"); ConsoleLogger.info(player.getName() + " used the wrong password");
if (Settings.isKickOnWrongPasswordEnabled) { if (Settings.isKickOnWrongPasswordEnabled) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
new Runnable() {
@Override @Override
public void run() { public void run() {
if (AuthMePlayerListener.gameMode != null if (AuthMePlayerListener.gameMode != null && AuthMePlayerListener.gameMode.containsKey(name)) {
&& AuthMePlayerListener.gameMode player.setGameMode(AuthMePlayerListener.gameMode.get(name));
.containsKey(name)) { }
player.setGameMode(AuthMePlayerListener.gameMode player.kickPlayer(m._("wrong_pwd")[0]);
.get(name)); }
} });
player.kickPlayer(m._("wrong_pwd")[0]);
}
});
} else { } else {
m._(player, "wrong_pwd"); m._(player, "wrong_pwd");
return; return;
} }
} else { } else {
ConsoleLogger.showError("Player " + name ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... ");
+ " wasn't online during login process, aborted... ");
} }
} }
@ -260,8 +232,7 @@ public class AsyncronousLogin {
*/ */
for (Player player : plugin.getServer().getOnlinePlayers()) { for (Player player : plugin.getServer().getOnlinePlayers()) {
if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) { if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) {
player.sendMessage("[AuthMe] The player " + auth.getNickname() player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts");
+ " has " + auths.size() + " accounts");
player.sendMessage(message); player.sendMessage(message);
// player.sendMessage(uuidaccounts.replace("%size%", // player.sendMessage(uuidaccounts.replace("%size%",
// ""+uuidlist.size())); // ""+uuidlist.size()));

View File

@ -24,6 +24,7 @@ import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class ProcessSyncronousPlayerLogin implements Runnable { public class ProcessSyncronousPlayerLogin implements Runnable {
private LimboPlayer limbo; private LimboPlayer limbo;
private Player player; private Player player;
private String name; private String name;
@ -51,21 +52,18 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
protected void restoreOpState() { protected void restoreOpState() {
player.setOp(limbo.getOperator()); player.setOp(limbo.getOperator());
if (player.getGameMode() != GameMode.CREATIVE if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
&& !Settings.isMovementAllowed) {
player.setAllowFlight(limbo.isFlying()); player.setAllowFlight(limbo.isFlying());
player.setFlying(limbo.isFlying()); player.setFlying(limbo.isFlying());
} }
} }
protected void packQuitLocation() { protected void packQuitLocation() {
Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(), Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player);
auth.getQuitLocZ(), auth.getWorld(), player);
} }
protected void teleportBackFromSpawn() { protected void teleportBackFromSpawn() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc());
limbo.getLoc());
pm.callEvent(tpEvent); pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo(); Location fLoc = tpEvent.getTo();
@ -78,8 +76,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
protected void teleportToSpawn() { protected void teleportToSpawn() {
Location spawnL = plugin.getSpawnLocation(player); Location spawnL = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnL, true);
player.getLocation(), spawnL, true);
pm.callEvent(tpEvent); pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo(); Location fLoc = tpEvent.getTo();
@ -91,12 +88,10 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
} }
protected void restoreInventory() { protected void restoreInventory() {
RestoreInventoryEvent event = new RestoreInventoryEvent(player, RestoreInventoryEvent event = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour());
limbo.getInventory(), limbo.getArmour());
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
API.setPlayerInventory(player, event.getInventory(), API.setPlayerInventory(player, event.getInventory(), event.getArmor());
event.getArmor());
} }
} }
@ -108,9 +103,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
} }
} }
for (String command : Settings.forceCommandsAsConsole) { for (String command : Settings.forceCommandsAsConsole) {
Bukkit.getServer().dispatchCommand( Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%p", player.getName()));
Bukkit.getServer().getConsoleSender(),
command.replace("%p", player.getName()));
} }
} }
@ -132,16 +125,14 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
// Inventory - Make it after restore GameMode , cause we need to // Inventory - Make it after restore GameMode , cause we need to
// restore the // restore the
// right inventory in the right gamemode // right inventory in the right gamemode
if (Settings.protectInventoryBeforeLogInEnabled if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
&& player.hasPlayedBefore()) {
restoreInventory(); restoreInventory();
} }
} else { } else {
// Inventory - Make it before force the survival GameMode to // Inventory - Make it before force the survival GameMode to
// cancel all // cancel all
// inventory problem // inventory problem
if (Settings.protectInventoryBeforeLogInEnabled if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
&& player.hasPlayedBefore()) {
restoreInventory(); restoreInventory();
} }
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
@ -149,22 +140,15 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
if (!Settings.noTeleport) { if (!Settings.noTeleport) {
// Teleport // Teleport
if (Settings.isTeleportToSpawnEnabled if (Settings.isTeleportToSpawnEnabled && !Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) {
&& !Settings.isForceSpawnLocOnJoinEnabled if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) {
&& Settings.getForcedWorlds.contains(player.getWorld()
.getName())) {
if (Settings.isSaveQuitLocationEnabled
&& auth.getQuitLocY() != 0) {
packQuitLocation(); packQuitLocation();
} else { } else {
teleportBackFromSpawn(); teleportBackFromSpawn();
} }
} else if (Settings.isForceSpawnLocOnJoinEnabled } else if (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) {
&& Settings.getForcedWorlds.contains(player.getWorld()
.getName())) {
teleportToSpawn(); teleportToSpawn();
} else if (Settings.isSaveQuitLocationEnabled } else if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) {
&& auth.getQuitLocY() != 0) {
packQuitLocation(); packQuitLocation();
} else { } else {
teleportBackFromSpawn(); teleportBackFromSpawn();
@ -173,7 +157,8 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
// Re-Force Survival GameMode if we need due to world change // Re-Force Survival GameMode if we need due to world change
// specification // specification
if (Settings.isForceSurvivalModeEnabled) Utils.forceGM(player); if (Settings.isForceSurvivalModeEnabled)
Utils.forceGM(player);
// Restore Permission Group // Restore Permission Group
Utils.getInstance().setGroup(player, groupType.LOGGEDIN); Utils.getInstance().setGroup(player, groupType.LOGGEDIN);
@ -186,35 +171,32 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
} }
// We can now display the join message // We can now display the join message
if (AuthMePlayerListener.joinMessage.containsKey(name) if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
&& AuthMePlayerListener.joinMessage.get(name) != null
&& !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) { for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (p.isOnline()) p if (p.isOnline())
.sendMessage(AuthMePlayerListener.joinMessage.get(name)); p.sendMessage(AuthMePlayerListener.joinMessage.get(name));
} }
AuthMePlayerListener.joinMessage.remove(name); AuthMePlayerListener.joinMessage.remove(name);
} }
if (Settings.applyBlindEffect) player if (Settings.applyBlindEffect)
.removePotionEffect(PotionEffectType.BLINDNESS); player.removePotionEffect(PotionEffectType.BLINDNESS);
// The Loginevent now fires (as intended) after everything is processed // The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager() Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
.callEvent(new LoginEvent(player, true));
player.saveData(); player.saveData();
// Login is finish, display welcome message // Login is finish, display welcome message
if (Settings.useWelcomeMessage) if (Settings.broadcastWelcomeMessage) { if (Settings.useWelcomeMessage)
for (String s : Settings.welcomeMsg) { if (Settings.broadcastWelcomeMessage) {
Bukkit.getServer().broadcastMessage( for (String s : Settings.welcomeMsg) {
plugin.replaceAllInfos(s, player)); Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
player.sendMessage(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 // Login is now finish , we can force all commands
forceCommands(); forceCommands();

View File

@ -54,29 +54,21 @@ public class AsyncronousRegister {
} }
String lowpass = password.toLowerCase(); String lowpass = password.toLowerCase();
if ((lowpass.contains("delete") || lowpass.contains("where") if ((lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null")) || !lowpass.matches(Settings.getPassRegex)) {
|| 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"); m._(player, "password_error");
allowRegister = false; allowRegister = false;
} }
if (database.isAuthAvailable(player.getName().toLowerCase())) { if (database.isAuthAvailable(player.getName().toLowerCase())) {
m._(player, "user_regged"); m._(player, "user_regged");
if (plugin.pllog.getStringList("players") if (plugin.pllog.getStringList("players").contains(player.getName())) {
.contains(player.getName())) {
plugin.pllog.getStringList("players").remove(player.getName()); plugin.pllog.getStringList("players").remove(player.getName());
} }
allowRegister = false; allowRegister = false;
} }
if (Settings.getmaxRegPerIp > 0) { if (Settings.getmaxRegPerIp > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp && !getIp().equalsIgnoreCase("127.0.0.1") && !getIp().equalsIgnoreCase("localhost")) {
&& database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp
&& !getIp().equalsIgnoreCase("127.0.0.1")
&& !getIp().equalsIgnoreCase("localhost")) {
m._(player, "max_reg"); m._(player, "max_reg");
allowRegister = false; allowRegister = false;
} }
@ -86,11 +78,11 @@ public class AsyncronousRegister {
public void process() { public void process() {
preRegister(); preRegister();
if (!allowRegister) return; if (!allowRegister)
return;
if (!email.isEmpty() && email != "") { if (!email.isEmpty() && email != "") {
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
&& database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return; return;
} }
@ -103,21 +95,15 @@ public class AsyncronousRegister {
protected void emailRegister() { protected void emailRegister() {
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
&& database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return; return;
} }
} }
PlayerAuth auth = null; PlayerAuth auth = null;
try { try {
final String hashnew = PasswordSecurity.getHash( final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
Settings.getPasswordHash, password, name); auth = new PlayerAuth(name, hashnew, getIp(), 0, (int) player.getLocation().getX(), (int) player.getLocation().getY(), (int) player.getLocation().getZ(), player.getLocation().getWorld().getName(), email, realName);
auth = new PlayerAuth(name, hashnew, getIp(), 0,
(int) player.getLocation().getX(), (int) player
.getLocation().getY(), (int) player.getLocation()
.getZ(), player.getLocation().getWorld().getName(),
email, realName);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
m._(player, "error"); m._(player, "error");
@ -130,16 +116,13 @@ public class AsyncronousRegister {
database.updateEmail(auth); database.updateEmail(auth);
database.updateSession(auth); database.updateSession(auth);
plugin.mail.main(auth, password); plugin.mail.main(auth, password);
ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister( ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin);
player, plugin); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, syncronous);
return; return;
} }
protected void passwordRegister() { protected void passwordRegister() {
if (password.length() < Settings.getPasswordMinLen if (password.length() < Settings.getPasswordMinLen || password.length() > Settings.passwordMaxLength) {
|| password.length() > Settings.passwordMaxLength) {
m._(player, "pass_len"); m._(player, "pass_len");
return; return;
} }
@ -152,21 +135,16 @@ public class AsyncronousRegister {
PlayerAuth auth = null; PlayerAuth auth = null;
String hash = ""; String hash = "";
try { try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
name);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
m._(player, "error"); m._(player, "error");
return; return;
} }
if (Settings.getMySQLColumnSalt.isEmpty() if (Settings.getMySQLColumnSalt.isEmpty() && !PasswordSecurity.userSalt.containsKey(name)) {
&& !PasswordSecurity.userSalt.containsKey(name)) { auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(), "your@email.com", player.getName());
auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(),
"your@email.com", player.getName());
} else { } else {
auth = new PlayerAuth(name, hash, auth = new PlayerAuth(name, hash, PasswordSecurity.userSalt.get(name), getIp(), new Date().getTime(), player.getName());
PasswordSecurity.userSalt.get(name), getIp(),
new Date().getTime(), player.getName());
} }
if (!database.saveAuth(auth)) { if (!database.saveAuth(auth)) {
m._(player, "error"); m._(player, "error");
@ -177,10 +155,8 @@ public class AsyncronousRegister {
database.setLogged(name); database.setLogged(name);
} }
plugin.otherAccounts.addPlayer(player.getUniqueId()); plugin.otherAccounts.addPlayer(player.getUniqueId());
ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister( ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin);
player, plugin); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, syncronous);
return; return;
} }
} }

View File

@ -40,48 +40,37 @@ public class ProcessSyncronousEmailRegister implements Runnable {
int time = Settings.getRegistrationTimeout * 20; int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval; int msgInterval = Settings.getWarnMessageInterval;
if (time != 0) { if (time != 0) {
Bukkit.getScheduler().cancelTask( Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getTimeoutTaskId());
LimboCache.getInstance().getLimboPlayer(name) int id = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), time);
.getTimeoutTaskId());
int id = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new TimeoutTask(plugin, name), time);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
} }
Bukkit.getScheduler().cancelTask( Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId());
LimboCache.getInstance().getLimboPlayer(name) int nwMsg = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), msgInterval));
.getMessageTaskId());
int nwMsg = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new MessageTask(plugin, name, m._("login_msg"), msgInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(nwMsg); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(nwMsg);
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location loca = plugin.getSpawnLocation(player); Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, loca);
loca);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()) if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
.isLoaded()) { tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.load();
} }
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
} }
if (player.getGameMode() != GameMode.CREATIVE if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
&& !Settings.isMovementAllowed) {
player.setAllowFlight(false); player.setAllowFlight(false);
player.setFlying(false); player.setFlying(false);
} }
if (Settings.applyBlindEffect) player if (Settings.applyBlindEffect)
.removePotionEffect(PotionEffectType.BLINDNESS); player.removePotionEffect(PotionEffectType.BLINDNESS);
player.saveData(); player.saveData();
if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName() if (!Settings.noConsoleSpam)
+ " registered " + plugin.getIP(player)); ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player));
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " has registered by email!"));
+ player.getName() + " has registered by email!"));
} }
} }

View File

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

View File

@ -29,15 +29,15 @@ public enum HashAlgorithm {
ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class), ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class),
CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class), CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class),
CUSTOM(Null.class); CUSTOM(Null.class);
Class<?> classe; Class<?> classe;
HashAlgorithm(Class<?> classe) { HashAlgorithm(Class<?> classe) {
this.classe = classe; this.classe = classe;
}
public Class<?> getclass() {
return classe;
} }
} public Class<?> getclass() {
return classe;
}
}

View File

@ -26,23 +26,20 @@ public class PasswordSecurity {
MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset(); sha1.reset();
byte[] digest = sha1.digest(msg); byte[] digest = sha1.digest(msg);
return String.format("%0" + (digest.length << 1) + "x", return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)).substring(0, length);
new BigInteger(1, digest)).substring(0, length);
} }
public static String getHash(HashAlgorithm alg, String password, public static String getHash(HashAlgorithm alg, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
EncryptionMethod method; EncryptionMethod method;
try { try {
if (alg != HashAlgorithm.CUSTOM) method = (EncryptionMethod) alg if (alg != HashAlgorithm.CUSTOM)
.getclass().newInstance(); method = (EncryptionMethod) alg.getclass().newInstance();
else method = null; else method = null;
} catch (InstantiationException e) { } catch (InstantiationException e) {
throw new NoSuchAlgorithmException( throw new NoSuchAlgorithmException("Problem with this hash algorithm");
"Problem with this hash algorithm");
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException( throw new NoSuchAlgorithmException("Problem with this hash algorithm");
"Problem with this hash algorithm");
} }
String salt = ""; String salt = "";
switch (alg) { switch (alg) {
@ -112,12 +109,11 @@ public class PasswordSecurity {
default: default:
throw new NoSuchAlgorithmException("Unknown hash algorithm"); throw new NoSuchAlgorithmException("Unknown hash algorithm");
} }
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
playerName);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
method = event.getMethod(); method = event.getMethod();
if (method == null) throw new NoSuchAlgorithmException( if (method == null)
"Unknown hash algorithm"); throw new NoSuchAlgorithmException("Unknown hash algorithm");
return method.getHash(password, salt, playerName); return method.getHash(password, salt, playerName);
} }
@ -126,30 +122,29 @@ public class PasswordSecurity {
HashAlgorithm algo = Settings.getPasswordHash; HashAlgorithm algo = Settings.getPasswordHash;
EncryptionMethod method; EncryptionMethod method;
try { try {
if (algo != HashAlgorithm.CUSTOM) method = (EncryptionMethod) algo if (algo != HashAlgorithm.CUSTOM)
.getclass().newInstance(); method = (EncryptionMethod) algo.getclass().newInstance();
else method = null; else method = null;
} catch (InstantiationException e) { } catch (InstantiationException e) {
throw new NoSuchAlgorithmException( throw new NoSuchAlgorithmException("Problem with this hash algorithm");
"Problem with this hash algorithm");
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException( throw new NoSuchAlgorithmException("Problem with this hash algorithm");
"Problem with this hash algorithm");
} }
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
playerName);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
method = event.getMethod(); method = event.getMethod();
if (method == null) throw new NoSuchAlgorithmException( if (method == null)
"Unknown hash algorithm"); throw new NoSuchAlgorithmException("Unknown hash algorithm");
try { try {
if (method.comparePassword(hash, password, playerName)) return true; if (method.comparePassword(hash, password, playerName))
return true;
} catch (Exception e) { } catch (Exception e) {
} }
if (Settings.supportOldPassword) { if (Settings.supportOldPassword) {
try { try {
if (compareWithAllEncryptionMethod(password, hash, playerName)) return true; if (compareWithAllEncryptionMethod(password, hash, playerName))
return true;
} catch (Exception e) { } catch (Exception e) {
} }
} }
@ -159,23 +154,21 @@ public class PasswordSecurity {
private static boolean compareWithAllEncryptionMethod(String password, private static boolean compareWithAllEncryptionMethod(String password,
String hash, String playerName) throws NoSuchAlgorithmException { String hash, String playerName) throws NoSuchAlgorithmException {
for (HashAlgorithm algo : HashAlgorithm.values()) { for (HashAlgorithm algo : HashAlgorithm.values()) {
if (algo != HashAlgorithm.CUSTOM) try { if (algo != HashAlgorithm.CUSTOM)
EncryptionMethod method = (EncryptionMethod) algo.getclass() try {
.newInstance(); EncryptionMethod method = (EncryptionMethod) algo.getclass().newInstance();
if (method.comparePassword(hash, password, playerName)) { if (method.comparePassword(hash, password, playerName)) {
PlayerAuth nAuth = AuthMe.getInstance().database PlayerAuth nAuth = AuthMe.getInstance().database.getAuth(playerName);
.getAuth(playerName); if (nAuth != null) {
if (nAuth != null) { nAuth.setHash(getHash(Settings.getPasswordHash, password, playerName));
nAuth.setHash(getHash(Settings.getPasswordHash, nAuth.setSalt(userSalt.get(playerName));
password, playerName)); AuthMe.getInstance().database.updatePassword(nAuth);
nAuth.setSalt(userSalt.get(playerName)); AuthMe.getInstance().database.updateSalt(nAuth);
AuthMe.getInstance().database.updatePassword(nAuth); }
AuthMe.getInstance().database.updateSalt(nAuth); return true;
} }
return true; } catch (Exception e) {
} }
} catch (Exception e) {
}
} }
return false; return false;
} }

View File

@ -22,8 +22,8 @@ public class RandomString {
private final char[] buf; private final char[] buf;
public RandomString(int length) { public RandomString(int length) {
if (length < 1) throw new IllegalArgumentException("length < 1: " if (length < 1)
+ length); throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length]; buf = new char[length];
} }

File diff suppressed because one or more lines are too long

View File

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

View File

@ -11,8 +11,7 @@ public class CryptPBKDF2 implements EncryptionMethod {
public String getHash(String password, String salt, String name) public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
String result = "pbkdf2_sha256$10000$" + salt + "$"; String result = "pbkdf2_sha256$10000$" + salt + "$";
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000);
salt.getBytes(), 10000);
PBKDF2Engine engine = new PBKDF2Engine(params); PBKDF2Engine engine = new PBKDF2Engine(params);
return result + engine.deriveKey(password, 64).toString(); return result + engine.deriveKey(password, 64).toString();
@ -24,8 +23,7 @@ public class CryptPBKDF2 implements EncryptionMethod {
String[] line = hash.split("\\$"); String[] line = hash.split("\\$");
String salt = line[2]; String salt = line[2];
String derivedKey = line[3]; String derivedKey = line[3];
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000, derivedKey.getBytes());
salt.getBytes(), 10000, derivedKey.getBytes());
PBKDF2Engine engine = new PBKDF2Engine(params); PBKDF2Engine engine = new PBKDF2Engine(params);
return engine.verifyKey(password); return engine.verifyKey(password);
} }

View File

@ -24,8 +24,7 @@ public class DOUBLEMD5 implements EncryptionMethod {
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -17,8 +17,7 @@ public class IPB3 implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName) String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
.getSalt();
return hash.equals(getHash(password, salt, playerName)); return hash.equals(getHash(password, salt, playerName));
} }
@ -28,7 +27,6 @@ public class IPB3 implements EncryptionMethod {
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -25,7 +25,6 @@ public class JOOMLA implements EncryptionMethod {
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -24,7 +24,6 @@ public class MD5 implements EncryptionMethod {
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -25,8 +25,7 @@ public class MD5VB implements EncryptionMethod {
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -17,8 +17,7 @@ public class MYBB implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName) String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
.getSalt();
return hash.equals(getHash(password, salt, playerName)); return hash.equals(getHash(password, salt, playerName));
} }
@ -28,7 +27,6 @@ public class MYBB implements EncryptionMethod {
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -14,6 +14,7 @@ import java.security.NoSuchAlgorithmException;
* @author stefano * @author stefano
*/ */
public class PHPBB implements EncryptionMethod { public class PHPBB implements EncryptionMethod {
private static final int PHP_VERSION = 4; private static final int PHP_VERSION = 4;
private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
@ -29,9 +30,9 @@ public class PHPBB implements EncryptionMethod {
} }
random = random.substring(0, count); random = random.substring(0, count);
} }
String hash = _hash_crypt_private(password, String hash = _hash_crypt_private(password, _hash_gensalt_private(random, itoa64));
_hash_gensalt_private(random, itoa64)); if (hash.length() == 34)
if (hash.length() == 34) return hash; return hash;
return md5(password); return md5(password);
} }
@ -46,8 +47,7 @@ public class PHPBB implements EncryptionMethod {
iteration_count_log2 = 8; iteration_count_log2 = 8;
} }
String output = "$H$"; String output = "$H$";
output += itoa64.charAt(Math.min(iteration_count_log2 output += itoa64.charAt(Math.min(iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30));
+ ((PHP_VERSION >= 5) ? 5 : 3), 30));
output += _hash_encode64(input, 6); output += _hash_encode64(input, 6);
return output; return output;
} }
@ -61,12 +61,16 @@ public class PHPBB implements EncryptionMethod {
do { do {
int value = input.charAt(i++); int value = input.charAt(i++);
output += itoa64.charAt(value & 0x3f); output += itoa64.charAt(value & 0x3f);
if (i < count) value |= input.charAt(i) << 8; if (i < count)
value |= input.charAt(i) << 8;
output += itoa64.charAt((value >> 6) & 0x3f); output += itoa64.charAt((value >> 6) & 0x3f);
if (i++ >= count) break; if (i++ >= count)
if (i < count) value |= input.charAt(i) << 16; break;
if (i < count)
value |= input.charAt(i) << 16;
output += itoa64.charAt((value >> 12) & 0x3f); output += itoa64.charAt((value >> 12) & 0x3f);
if (i++ >= count) break; if (i++ >= count)
break;
output += itoa64.charAt((value >> 18) & 0x3f); output += itoa64.charAt((value >> 18) & 0x3f);
} while (i < count); } while (i < count);
return output; return output;
@ -74,12 +78,15 @@ public class PHPBB implements EncryptionMethod {
String _hash_crypt_private(String password, String setting) { String _hash_crypt_private(String password, String setting) {
String output = "*"; String output = "*";
if (!setting.substring(0, 3).equals("$H$")) return output; if (!setting.substring(0, 3).equals("$H$"))
return output;
int count_log2 = itoa64.indexOf(setting.charAt(3)); int count_log2 = itoa64.indexOf(setting.charAt(3));
if (count_log2 < 7 || count_log2 > 30) return output; if (count_log2 < 7 || count_log2 > 30)
return output;
int count = 1 << count_log2; int count = 1 << count_log2;
String salt = setting.substring(4, 12); String salt = setting.substring(4, 12);
if (salt.length() != 8) return output; if (salt.length() != 8)
return output;
String m1 = md5(salt + password); String m1 = md5(salt + password);
String hash = pack(m1); String hash = pack(m1);
do { do {
@ -91,8 +98,8 @@ public class PHPBB implements EncryptionMethod {
} }
public boolean phpbb_check_hash(String password, String hash) { public boolean phpbb_check_hash(String password, String hash) {
if (hash.length() == 34) return _hash_crypt_private(password, hash) if (hash.length() == 34)
.equals(hash); return _hash_crypt_private(password, hash).equals(hash);
else return md5(password).equals(hash); else return md5(password).equals(hash);
} }
@ -110,9 +117,11 @@ public class PHPBB implements EncryptionMethod {
} }
static int hexToInt(char ch) { static int hexToInt(char ch) {
if (ch >= '0' && ch <= '9') return ch - '0'; if (ch >= '0' && ch <= '9')
return ch - '0';
ch = Character.toUpperCase(ch); ch = Character.toUpperCase(ch);
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 0xA; if (ch >= 'A' && ch <= 'F')
return ch - 'A' + 0xA;
throw new IllegalArgumentException("Not a hex character: " + ch); throw new IllegalArgumentException("Not a hex character: " + ch);
} }
@ -120,7 +129,8 @@ public class PHPBB implements EncryptionMethod {
StringBuffer r = new StringBuffer(32); StringBuffer r = new StringBuffer(32);
for (int i = 0; i < bytes.length; i++) { for (int i = 0; i < bytes.length; i++) {
String x = Integer.toHexString(bytes[i] & 0xff); String x = Integer.toHexString(bytes[i] & 0xff);
if (x.length() < 2) r.append("0"); if (x.length() < 2)
r.append("0");
r.append(x); r.append(x);
} }
return r.toString(); return r.toString();

View File

@ -20,8 +20,7 @@ public class PHPFUSION implements EncryptionMethod {
String algo = "HmacSHA256"; String algo = "HmacSHA256";
String keyString = getSHA1(salt); String keyString = getSHA1(salt);
try { try {
SecretKeySpec key = new SecretKeySpec( SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);
(keyString).getBytes("UTF-8"), algo);
Mac mac = Mac.getInstance(algo); Mac mac = Mac.getInstance(algo);
mac.init(key); mac.init(key);
byte[] bytes = mac.doFinal(password.getBytes("ASCII")); byte[] bytes = mac.doFinal(password.getBytes("ASCII"));
@ -44,8 +43,7 @@ public class PHPFUSION implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName) String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
.getSalt();
return hash.equals(getHash(password, salt, "")); return hash.equals(getHash(password, salt, ""));
} }
@ -55,8 +53,7 @@ public class PHPFUSION implements EncryptionMethod {
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -20,8 +20,7 @@ public class ROYALAUTH implements EncryptionMethod {
byte byteData[] = md.digest(); byte byteData[] = md.digest();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (byte aByteData : byteData) for (byte aByteData : byteData)
sb.append(Integer.toString((aByteData & 0xff) + 0x100, 16) sb.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1));
.substring(1));
return sb.toString(); return sb.toString();
} }

View File

@ -17,8 +17,7 @@ public class SALTED2MD5 implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName) String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
.getSalt();
return hash.equals(getMD5(getMD5(password) + salt)); return hash.equals(getMD5(getMD5(password) + salt));
} }
@ -28,7 +27,6 @@ public class SALTED2MD5 implements EncryptionMethod {
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -24,8 +24,7 @@ public class SHA1 implements EncryptionMethod {
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -25,8 +25,7 @@ public class SHA256 implements EncryptionMethod {
sha256.reset(); sha256.reset();
sha256.update(message.getBytes()); sha256.update(message.getBytes());
byte[] digest = sha256.digest(); byte[] digest = sha256.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -24,7 +24,6 @@ public class SHA512 implements EncryptionMethod {
sha512.reset(); sha512.reset();
sha512.update(message.getBytes()); sha512.update(message.getBytes());
byte[] digest = sha512.digest(); byte[] digest = sha512.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -24,7 +24,6 @@ public class SMF implements EncryptionMethod {
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -17,8 +17,7 @@ public class WBB3 implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName) String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
.getSalt();
return hash.equals(getHash(password, salt, "")); return hash.equals(getHash(password, salt, ""));
} }
@ -28,7 +27,6 @@ public class WBB3 implements EncryptionMethod {
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger( return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
1, digest));
} }
} }

View File

@ -84,22 +84,7 @@ public class WHIRLPOOL implements EncryptionMethod {
/** /**
* The substitution box. * The substitution box.
*/ */
private static final String sbox = "\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152" 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";
+ "\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[][] C = new long[8][256];
private static long[] rc = new long[R + 1]; private static long[] rc = new long[R + 1];
@ -126,8 +111,7 @@ public class WHIRLPOOL implements EncryptionMethod {
* build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2, * build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2,
* 9]: * 9]:
*/ */
C[0][x] = (v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32) C[0][x] = (v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32) | (v8 << 24) | (v5 << 16) | (v2 << 8) | (v9);
| (v8 << 24) | (v5 << 16) | (v2 << 8) | (v9);
/* /*
* build the remaining circulant tables C[t][x] = C[0][x] rotr t * build the remaining circulant tables C[t][x] = C[0][x] rotr t
*/ */
@ -144,14 +128,7 @@ public class WHIRLPOOL implements EncryptionMethod {
*/ */
for (int r = 1; r <= R; r++) { for (int r = 1; r <= R; r++) {
int i = 8 * (r - 1); int i = 8 * (r - 1);
rc[r] = (C[0][i] & 0xff00000000000000L) 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);
^ (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);
} }
} }
@ -195,14 +172,7 @@ public class WHIRLPOOL implements EncryptionMethod {
* map the buffer to a block: * map the buffer to a block:
*/ */
for (int i = 0, j = 0; i < 8; i++, j += 8) { for (int i = 0, j = 0; i < 8; i++, j += 8) {
block[i] = (((long) buffer[j]) << 56) 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));
^ (((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: * compute and apply K^0 to the cipher state:
@ -294,8 +264,7 @@ public class WHIRLPOOL implements EncryptionMethod {
while (sourceBits > 8) { // at least source[sourcePos] and while (sourceBits > 8) { // at least source[sourcePos] and
// source[sourcePos+1] contain data. // source[sourcePos+1] contain data.
// take a byte from the source: // take a byte from the source:
b = ((source[sourcePos] << sourceGap) & 0xff) b = ((source[sourcePos] << sourceGap) & 0xff) | ((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap));
| ((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap));
if (b < 0 || b >= 256) { if (b < 0 || b >= 256) {
throw new RuntimeException("LOGIC ERROR"); throw new RuntimeException("LOGIC ERROR");
} }

View File

@ -7,6 +7,7 @@ import java.security.SecureRandom;
import java.util.Arrays; import java.util.Arrays;
public class WORDPRESS implements EncryptionMethod { public class WORDPRESS implements EncryptionMethod {
private static String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private int iterationCountLog2 = 8; private int iterationCountLog2 = 8;
private SecureRandom randomGen = new SecureRandom(); private SecureRandom randomGen = new SecureRandom();
@ -47,8 +48,7 @@ public class WORDPRESS implements EncryptionMethod {
private String crypt(String password, String setting) { private String crypt(String password, String setting) {
String output = "*0"; String output = "*0";
if (((setting.length() < 2) ? setting : setting.substring(0, 2)) if (((setting.length() < 2) ? setting : setting.substring(0, 2)).equalsIgnoreCase(output)) {
.equalsIgnoreCase(output)) {
output = "*1"; output = "*1";
} }
String id = (setting.length() < 3) ? setting : setting.substring(0, 3); String id = (setting.length() < 3) ? setting : setting.substring(0, 3);
@ -95,8 +95,7 @@ public class WORDPRESS implements EncryptionMethod {
try { try {
return string.getBytes("UTF-8"); return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException( throw new UnsupportedOperationException("This system doesn't support UTF-8!", e);
"This system doesn't support UTF-8!", e);
} }
} }

View File

@ -8,16 +8,14 @@ public class XAUTH implements EncryptionMethod {
public String getHash(String password, String salt, String name) public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
String hash = getWhirlpool(salt + password).toLowerCase(); String hash = getWhirlpool(salt + password).toLowerCase();
int saltPos = (password.length() >= hash.length() ? hash.length() - 1 int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length());
: password.length());
return hash.substring(0, saltPos) + salt + hash.substring(saltPos); return hash.substring(0, saltPos) + salt + hash.substring(saltPos);
} }
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
int saltPos = (password.length() >= hash.length() ? hash.length() - 1 int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length());
: password.length());
String salt = hash.substring(saltPos, saltPos + 12); String salt = hash.substring(saltPos, saltPos + 12);
return hash.equals(getHash(password, salt, "")); return hash.equals(getHash(password, salt, ""));
} }

View File

@ -14,17 +14,14 @@ public class XF implements EncryptionMethod {
@Override @Override
public String getHash(String password, String salt, String name) public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
return getSHA256(getSHA256(password) return getSHA256(getSHA256(password) + regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", salt));
+ regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", salt));
} }
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName) String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
.getSalt(); return hash.equals(regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", salt));
return hash
.equals(regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", salt));
} }
public String getSHA256(String password) throws NoSuchAlgorithmException { public String getSHA256(String password) throws NoSuchAlgorithmException {
@ -33,8 +30,7 @@ public class XF implements EncryptionMethod {
byte byteData[] = md.digest(); byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (byte element : byteData) { for (byte element : byteData) {
sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring( sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1));
1));
} }
StringBuffer hexString = new StringBuffer(); StringBuffer hexString = new StringBuffer();
for (byte element : byteData) { for (byte element : byteData) {

View File

@ -31,6 +31,7 @@ package fr.xephi.authme.security.pbkdf2;
* @version 1.0 * @version 1.0
*/ */
public class BinTools { public class BinTools {
public static final String hex = "0123456789ABCDEF"; public static final String hex = "0123456789ABCDEF";
/** /**
@ -101,9 +102,7 @@ public class BinTools {
if (c >= 'a' && c <= 'f') { if (c >= 'a' && c <= 'f') {
return (c - 'a' + 10); return (c - 'a' + 10);
} }
throw new IllegalArgumentException( throw new IllegalArgumentException("Input string may only contain hex digits, but found '" + c + "'");
"Input string may only contain hex digits, but found '" + c
+ "'");
} }
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -42,6 +42,7 @@ import javax.crypto.spec.SecretKeySpec;
* @version 1.0 * @version 1.0
*/ */
public class MacBasedPRF implements PRF { public class MacBasedPRF implements PRF {
protected Mac mac; protected Mac mac;
protected int hLen; protected int hLen;

View File

@ -32,6 +32,7 @@ package fr.xephi.authme.security.pbkdf2;
* @version 1.0 * @version 1.0
*/ */
public interface PBKDF2 { public interface PBKDF2 {
/** /**
* Convert String-based input to internal byte array, then invoke PBKDF2. * Convert String-based input to internal byte array, then invoke PBKDF2.
* Desired key length defaults to Pseudo Random Function block size. * Desired key length defaults to Pseudo Random Function block size.

View File

@ -70,6 +70,7 @@ import java.security.SecureRandom;
* @version 1.0 * @version 1.0
*/ */
public class PBKDF2Engine implements PBKDF2 { public class PBKDF2Engine implements PBKDF2 {
protected PBKDF2Parameters parameters; protected PBKDF2Parameters parameters;
protected PRF prf; protected PRF prf;
@ -135,8 +136,7 @@ public class PBKDF2Engine implements PBKDF2 {
if (dkLen == 0) { if (dkLen == 0) {
dkLen = prf.getHLen(); dkLen = prf.getHLen();
} }
r = PBKDF2(prf, parameters.getSalt(), parameters.getIterationCount(), r = PBKDF2(prf, parameters.getSalt(), parameters.getIterationCount(), dkLen);
dkLen);
return r; return r;
} }
@ -337,8 +337,7 @@ public class PBKDF2Engine implements PBKDF2 {
byte[] salt = new byte[8]; byte[] salt = new byte[8];
sr.nextBytes(salt); sr.nextBytes(salt);
int iterations = 1000; int iterations = 1000;
PBKDF2Parameters p = new PBKDF2Parameters("HmacSHA1", "ISO-8859-1", PBKDF2Parameters p = new PBKDF2Parameters("HmacSHA1", "ISO-8859-1", salt, iterations);
salt, iterations);
PBKDF2Engine e = new PBKDF2Engine(p); PBKDF2Engine e = new PBKDF2Engine(p);
p.setDerivedKey(e.deriveKey(password)); p.setDerivedKey(e.deriveKey(password));
candidate = formatter.toString(p); candidate = formatter.toString(p);
@ -349,9 +348,7 @@ public class PBKDF2Engine implements PBKDF2 {
p.setHashAlgorithm("HmacSHA1"); p.setHashAlgorithm("HmacSHA1");
p.setHashCharset("ISO-8859-1"); p.setHashCharset("ISO-8859-1");
if (formatter.fromString(p, candidate)) { if (formatter.fromString(p, candidate)) {
throw new IllegalArgumentException( throw new IllegalArgumentException("Candidate data does not have correct format (\"" + candidate + "\")");
"Candidate data does not have correct format (\""
+ candidate + "\")");
} }
PBKDF2Engine e = new PBKDF2Engine(p); PBKDF2Engine e = new PBKDF2Engine(p);
boolean verifyOK = e.verifyKey(password); boolean verifyOK = e.verifyKey(password);

View File

@ -32,6 +32,7 @@ package fr.xephi.authme.security.pbkdf2;
* @version 1.0 * @version 1.0
*/ */
public interface PBKDF2Formatter { public interface PBKDF2Formatter {
/** /**
* Convert parameters to String. * Convert parameters to String.
* *

View File

@ -32,6 +32,7 @@ package fr.xephi.authme.security.pbkdf2;
* @version 1.0 * @version 1.0
*/ */
public class PBKDF2HexFormatter implements PBKDF2Formatter { public class PBKDF2HexFormatter implements PBKDF2Formatter {
public boolean fromString(PBKDF2Parameters p, String s) { public boolean fromString(PBKDF2Parameters p, String s) {
if (p == null || s == null) { if (p == null || s == null) {
return true; return true;
@ -53,9 +54,7 @@ public class PBKDF2HexFormatter implements PBKDF2Formatter {
} }
public String toString(PBKDF2Parameters p) { public String toString(PBKDF2Parameters p) {
String s = BinTools.bin2hex(p.getSalt()) + ":" String s = BinTools.bin2hex(p.getSalt()) + ":" + String.valueOf(p.getIterationCount()) + ":" + BinTools.bin2hex(p.getDerivedKey());
+ String.valueOf(p.getIterationCount()) + ":"
+ BinTools.bin2hex(p.getDerivedKey());
return s; return s;
} }
} }

View File

@ -37,6 +37,7 @@ package fr.xephi.authme.security.pbkdf2;
* @version 1.0 * @version 1.0
*/ */
public class PBKDF2Parameters { public class PBKDF2Parameters {
protected byte[] salt; protected byte[] salt;
protected int iterationCount; protected int iterationCount;

View File

@ -32,6 +32,7 @@ package fr.xephi.authme.security.pbkdf2;
* @version 1.0 * @version 1.0
*/ */
public interface PRF { public interface PRF {
/** /**
* Initialize this instance with the user-supplied password. * Initialize this instance with the user-supplied password.
* *

View File

@ -32,19 +32,12 @@ public class CustomConfiguration extends YamlConfiguration {
try { try {
super.load(configFile); super.load(configFile);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Logger.getLogger(JavaPlugin.class.getName()).log( Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not find " + configFile.getName() + ", creating new one...");
Level.SEVERE,
"Could not find " + configFile.getName()
+ ", creating new one...");
reLoad(); reLoad();
} catch (IOException e) { } catch (IOException e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not load " + configFile.getName(), e);
"Could not load " + configFile.getName(), e);
} catch (InvalidConfigurationException e) { } catch (InvalidConfigurationException e) {
Logger.getLogger(JavaPlugin.class.getName()) Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, configFile.getName() + " is no valid configuration file", e);
.log(Level.SEVERE,
configFile.getName()
+ " is no valid configuration file", e);
} }
} }
@ -53,7 +46,8 @@ public class CustomConfiguration extends YamlConfiguration {
if (!configFile.exists()) { if (!configFile.exists()) {
out = loadRessource(configFile); out = loadRessource(configFile);
} }
if (out) load(); if (out)
load();
return out; return out;
} }
@ -61,8 +55,7 @@ public class CustomConfiguration extends YamlConfiguration {
try { try {
super.save(configFile); super.save(configFile);
} catch (IOException ex) { } catch (IOException ex) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save config to " + configFile.getName(), ex);
"Could not save config to " + configFile.getName(), ex);
} }
} }
@ -70,15 +63,10 @@ public class CustomConfiguration extends YamlConfiguration {
boolean out = true; boolean out = true;
if (!file.exists()) { if (!file.exists()) {
try { try {
InputStream fis = getClass().getResourceAsStream( InputStream fis = getClass().getResourceAsStream("/" + file.getName());
"/" + file.getName()); BufferedReader reader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8").newDecoder()));
BufferedReader reader = new BufferedReader(
new InputStreamReader(fis, Charset.forName("UTF-8")
.newDecoder()));
String str; String str;
Writer writer = new BufferedWriter(new OutputStreamWriter( Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8").newEncoder()));
new FileOutputStream(file), Charset.forName("UTF-8")
.newEncoder()));
while ((str = reader.readLine()) != null) { while ((str = reader.readLine()) != null) {
writer.append(str).append("\r\n"); writer.append(str).append("\r\n");
} }
@ -87,8 +75,7 @@ public class CustomConfiguration extends YamlConfiguration {
reader.close(); reader.close();
fis.close(); fis.close();
} catch (Exception e) { } catch (Exception e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR");
"Failed to load config from JAR");
out = false; out = false;
} }
/* /*

View File

@ -27,7 +27,8 @@ public class Messages extends CustomConfiguration {
*/ */
public final void loadDefaults(File file) { public final void loadDefaults(File file) {
InputStream stream = AuthMe.getInstance().getResource(file.getName()); InputStream stream = AuthMe.getInstance().getResource(file.getName());
if (stream == null) return; if (stream == null)
return;
setDefaults(YamlConfiguration.loadConfiguration(stream)); setDefaults(YamlConfiguration.loadConfiguration(stream));
} }
@ -71,9 +72,7 @@ public class Messages extends CustomConfiguration {
String loc = (String) this.get(msg); String loc = (String) this.get(msg);
if (loc == null) { if (loc == null) {
loc = "Error with Translation files; Please contact the admin for verify or update translation"; loc = "Error with Translation files; Please contact the admin for verify or update translation";
ConsoleLogger.showError("Error with the " + msg ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !");
+ " translation, verify in your " + Settings.MESSAGE_FILE
+ "_" + Settings.messagesLanguage + ".yml !");
} }
for (String l : loc.split("&n")) { for (String l : loc.split("&n")) {
sender.sendMessage(l.replace("&", "\u00a7")); sender.sendMessage(l.replace("&", "\u00a7"));
@ -85,24 +84,18 @@ public class Messages extends CustomConfiguration {
String[] loc = new String[i]; String[] loc = new String[i];
int a; int a;
for (a = 0; a < i; a++) { for (a = 0; a < i; a++) {
loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&", loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&", "\u00a7");
"\u00a7");
} }
if (loc == null || loc.length == 0) { if (loc == null || loc.length == 0) {
loc[0] = "Error with " loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files";
+ msg ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !");
+ " translation; Please contact the admin for verify or update translation files";
ConsoleLogger.showError("Error with the " + msg
+ " translation, verify in your " + Settings.MESSAGE_FILE
+ "_" + Settings.messagesLanguage + ".yml !");
} }
return loc; return loc;
} }
public static Messages getInstance() { public static Messages getInstance() {
if (singleton == null) { if (singleton == null) {
singleton = new Messages(new File(Settings.MESSAGE_FILE + "_" singleton = new Messages(new File(Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml"));
+ Settings.messagesLanguage + ".yml"));
} }
return singleton; return singleton;
} }

View File

@ -13,10 +13,11 @@ import org.bukkit.entity.Player;
* @author Xephi59 * @author Xephi59
*/ */
public class OtherAccounts extends CustomConfiguration { public class OtherAccounts extends CustomConfiguration {
private static OtherAccounts others = null; private static OtherAccounts others = null;
public OtherAccounts() { public OtherAccounts() {
super(new File("./plugins/AuthMe/otheraccounts.yml")); super(new File("." + File.separator + "plugins" + File.separator + "AuthMe" + File.separator + "otheraccounts.yml"));
others = this; others = this;
load(); load();
save(); save();
@ -37,7 +38,8 @@ public class OtherAccounts extends CustomConfiguration {
public void addPlayer(UUID uuid) { public void addPlayer(UUID uuid) {
try { try {
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player == null) return; if (player == null)
return;
if (!this.getStringList(uuid.toString()).contains(player.getName())) { if (!this.getStringList(uuid.toString()).contains(player.getName())) {
this.getStringList(uuid.toString()).add(player.getName()); this.getStringList(uuid.toString()).add(player.getName());
save(); save();
@ -50,7 +52,8 @@ public class OtherAccounts extends CustomConfiguration {
public void removePlayer(UUID uuid) { public void removePlayer(UUID uuid) {
try { try {
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player == null) return; if (player == null)
return;
if (this.getStringList(uuid.toString()).contains(player.getName())) { if (this.getStringList(uuid.toString()).contains(player.getName())) {
this.getStringList(uuid.toString()).remove(player.getName()); this.getStringList(uuid.toString()).remove(player.getName());
save(); save();

View File

@ -9,11 +9,12 @@ import java.util.List;
* @author Xephi59 * @author Xephi59
*/ */
public class PlayersLogs extends CustomConfiguration { public class PlayersLogs extends CustomConfiguration {
private static PlayersLogs pllog = null; private static PlayersLogs pllog = null;
public List<String> players; public List<String> players;
public PlayersLogs() { public PlayersLogs() {
super(new File("./plugins/AuthMe/players.yml")); super(new File("." + File.separator + "plugins" + File.separator + "AuthMe" + File.separator + "players.yml"));
pllog = this; pllog = this;
load(); load();
save(); save();

View File

@ -23,13 +23,11 @@ import fr.xephi.authme.security.HashAlgorithm;
public final class Settings extends YamlConfiguration { public final class Settings extends YamlConfiguration {
public static final String PLUGIN_FOLDER = "./plugins/AuthMe"; public static final String PLUGIN_FOLDER = "." + File.separator + "plugins" + File.separator + "AuthMe";
public static final String CACHE_FOLDER = Settings.PLUGIN_FOLDER + "/cache"; public static final String CACHE_FOLDER = Settings.PLUGIN_FOLDER + File.separator + "cache";
public static final String AUTH_FILE = Settings.PLUGIN_FOLDER + "/auths.db"; public static final String AUTH_FILE = Settings.PLUGIN_FOLDER + File.separator + "auths.db";
public static final String MESSAGE_FILE = Settings.PLUGIN_FOLDER public static final String MESSAGE_FILE = Settings.PLUGIN_FOLDER + File.separator + "messages";
+ "/messages"; public static final String SETTINGS_FILE = Settings.PLUGIN_FOLDER + File.separator + "config.yml";
public static final String SETTINGS_FILE = Settings.PLUGIN_FOLDER
+ "/config.yml";
public static List<String> allowCommands = null; public static List<String> allowCommands = null;
public static List<String> getJoinPermissions = null; public static List<String> getJoinPermissions = null;
public static List<String> getUnrestrictedName = null; public static List<String> getUnrestrictedName = null;
@ -113,271 +111,158 @@ public final class Settings extends YamlConfiguration {
plugin.getLogger().info("Loading Configuration File..."); plugin.getLogger().info("Loading Configuration File...");
mergeConfig(); mergeConfig();
messagesLanguage = checkLang(configFile.getString( messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en"));
"settings.messagesLanguage", "en")); isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false);
isPermissionCheckEnabled = configFile.getBoolean( isForcedRegistrationEnabled = configFile.getBoolean("settings.registration.force", true);
"permission.EnablePermissionCheck", false); isRegistrationEnabled = configFile.getBoolean("settings.registration.enabled", true);
isForcedRegistrationEnabled = configFile.getBoolean( isTeleportToSpawnEnabled = configFile.getBoolean("settings.restrictions.teleportUnAuthedToSpawn", false);
"settings.registration.force", true); getWarnMessageInterval = configFile.getInt("settings.registration.messageInterval", 5);
isRegistrationEnabled = configFile.getBoolean( isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled", false);
"settings.registration.enabled", true);
isTeleportToSpawnEnabled = configFile.getBoolean(
"settings.restrictions.teleportUnAuthedToSpawn", false);
getWarnMessageInterval = configFile.getInt(
"settings.registration.messageInterval", 5);
isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled",
false);
getSessionTimeout = configFile.getInt("settings.sessions.timeout", 10); getSessionTimeout = configFile.getInt("settings.sessions.timeout", 10);
getRegistrationTimeout = configFile.getInt( getRegistrationTimeout = configFile.getInt("settings.restrictions.timeout", 30);
"settings.restrictions.timeout", 30); isChatAllowed = configFile.getBoolean("settings.restrictions.allowChat", false);
isChatAllowed = configFile.getBoolean( getMaxNickLength = configFile.getInt("settings.restrictions.maxNicknameLength", 20);
"settings.restrictions.allowChat", false); getMinNickLength = configFile.getInt("settings.restrictions.minNicknameLength", 3);
getMaxNickLength = configFile.getInt( getPasswordMinLen = configFile.getInt("settings.security.minPasswordLength", 4);
"settings.restrictions.maxNicknameLength", 20); getNickRegex = configFile.getString("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_?]*");
getMinNickLength = configFile.getInt( isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser", false);
"settings.restrictions.minNicknameLength", 3); getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser");
getPasswordMinLen = configFile.getInt( isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement", false);
"settings.security.minPasswordLength", 4); getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius", 100);
getNickRegex = configFile.getString( getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin");
"settings.restrictions.allowedNicknameCharacters", isKickOnWrongPasswordEnabled = configFile.getBoolean("settings.restrictions.kickOnWrongPassword", false);
"[a-zA-Z0-9_?]*"); isKickNonRegisteredEnabled = configFile.getBoolean("settings.restrictions.kickNonRegistered", false);
isAllowRestrictedIp = configFile.getBoolean( isForceSingleSessionEnabled = configFile.getBoolean("settings.restrictions.ForceSingleSession", true);
"settings.restrictions.AllowRestrictedUser", false); isForceSpawnLocOnJoinEnabled = configFile.getBoolean("settings.restrictions.ForceSpawnLocOnJoinEnabled", false);
getRestrictedIp = configFile isSaveQuitLocationEnabled = configFile.getBoolean("settings.restrictions.SaveQuitLocation", false);
.getStringList("settings.restrictions.AllowedRestrictedUser"); isForceSurvivalModeEnabled = configFile.getBoolean("settings.GameMode.ForceSurvivalMode", false);
isMovementAllowed = configFile.getBoolean( isResetInventoryIfCreative = configFile.getBoolean("settings.GameMode.ResetInventoryIfCreative", false);
"settings.restrictions.allowMovement", false); getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp", 1);
getMovementRadius = configFile.getInt(
"settings.restrictions.allowedMovementRadius", 100);
getJoinPermissions = configFile
.getStringList("GroupOptions.Permissions.PermissionsOnJoin");
isKickOnWrongPasswordEnabled = configFile.getBoolean(
"settings.restrictions.kickOnWrongPassword", false);
isKickNonRegisteredEnabled = configFile.getBoolean(
"settings.restrictions.kickNonRegistered", false);
isForceSingleSessionEnabled = configFile.getBoolean(
"settings.restrictions.ForceSingleSession", true);
isForceSpawnLocOnJoinEnabled = configFile.getBoolean(
"settings.restrictions.ForceSpawnLocOnJoinEnabled", false);
isSaveQuitLocationEnabled = configFile.getBoolean(
"settings.restrictions.SaveQuitLocation", false);
isForceSurvivalModeEnabled = configFile.getBoolean(
"settings.GameMode.ForceSurvivalMode", false);
isResetInventoryIfCreative = configFile.getBoolean(
"settings.GameMode.ResetInventoryIfCreative", false);
getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp",
1);
getPasswordHash = getPasswordHash(); getPasswordHash = getPasswordHash();
getUnloggedinGroup = configFile.getString( getUnloggedinGroup = configFile.getString("settings.security.unLoggedinGroup", "unLoggedInGroup");
"settings.security.unLoggedinGroup", "unLoggedInGroup");
getDataSource = getDataSource(); getDataSource = getDataSource();
isCachingEnabled = configFile.getBoolean("DataSource.caching", true); isCachingEnabled = configFile.getBoolean("DataSource.caching", true);
getMySQLHost = configFile getMySQLHost = configFile.getString("DataSource.mySQLHost", "127.0.0.1");
.getString("DataSource.mySQLHost", "127.0.0.1");
getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306"); getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306");
getMySQLUsername = configFile.getString("DataSource.mySQLUsername", getMySQLUsername = configFile.getString("DataSource.mySQLUsername", "authme");
"authme"); getMySQLPassword = configFile.getString("DataSource.mySQLPassword", "12345");
getMySQLPassword = configFile.getString("DataSource.mySQLPassword", getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", "authme");
"12345"); getMySQLTablename = configFile.getString("DataSource.mySQLTablename", "authme");
getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", getMySQLColumnEmail = configFile.getString("DataSource.mySQLColumnEmail", "email");
"authme"); getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName", "username");
getMySQLTablename = configFile.getString("DataSource.mySQLTablename", getMySQLColumnPassword = configFile.getString("DataSource.mySQLColumnPassword", "password");
"authme"); getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp", "ip");
getMySQLColumnEmail = configFile.getString( getMySQLColumnLastLogin = configFile.getString("DataSource.mySQLColumnLastLogin", "lastlogin");
"DataSource.mySQLColumnEmail", "email"); getMySQLColumnSalt = configFile.getString("ExternalBoardOptions.mySQLColumnSalt");
getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName", getMySQLColumnGroup = configFile.getString("ExternalBoardOptions.mySQLColumnGroup", "");
"username"); getMySQLlastlocX = configFile.getString("DataSource.mySQLlastlocX", "x");
getMySQLColumnPassword = configFile.getString( getMySQLlastlocY = configFile.getString("DataSource.mySQLlastlocY", "y");
"DataSource.mySQLColumnPassword", "password"); getMySQLlastlocZ = configFile.getString("DataSource.mySQLlastlocZ", "z");
getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp", getMySQLlastlocWorld = configFile.getString("DataSource.mySQLlastlocWorld", "world");
"ip"); getNonActivatedGroup = configFile.getInt("ExternalBoardOptions.nonActivedUserGroup", -1);
getMySQLColumnLastLogin = configFile.getString( unRegisteredGroup = configFile.getString("GroupOptions.UnregisteredPlayerGroup", "");
"DataSource.mySQLColumnLastLogin", "lastlogin"); getUnrestrictedName = configFile.getStringList("settings.unrestrictions.UnrestrictedName");
getMySQLColumnSalt = configFile getRegisteredGroup = configFile.getString("GroupOptions.RegisteredPlayerGroup", "");
.getString("ExternalBoardOptions.mySQLColumnSalt"); getEnablePasswordVerifier = configFile.getBoolean("settings.restrictions.enablePasswordVerifier", true);
getMySQLColumnGroup = configFile.getString( protectInventoryBeforeLogInEnabled = configFile.getBoolean("settings.restrictions.ProtectInventoryBeforeLogIn", true);
"ExternalBoardOptions.mySQLColumnGroup", ""); passwordMaxLength = configFile.getInt("settings.security.passwordMaxLength", 20);
getMySQLlastlocX = configFile isBackupActivated = configFile.getBoolean("BackupSystem.ActivateBackup", false);
.getString("DataSource.mySQLlastlocX", "x"); isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart", false);
getMySQLlastlocY = configFile isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop", false);
.getString("DataSource.mySQLlastlocY", "y"); backupWindowsPath = configFile.getString("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\");
getMySQLlastlocZ = configFile enablePasspartu = configFile.getBoolean("Passpartu.enablePasspartu", false);
.getString("DataSource.mySQLlastlocZ", "z"); isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer", true);
getMySQLlastlocWorld = configFile.getString( reloadSupport = configFile.getBoolean("Security.ReloadCommand.useReloadCommandSupport", true);
"DataSource.mySQLlastlocWorld", "world"); allowCommands = (List<String>) configFile.getList("settings.restrictions.allowCommands");
getNonActivatedGroup = configFile.getInt(
"ExternalBoardOptions.nonActivedUserGroup", -1);
unRegisteredGroup = configFile.getString(
"GroupOptions.UnregisteredPlayerGroup", "");
getUnrestrictedName = configFile
.getStringList("settings.unrestrictions.UnrestrictedName");
getRegisteredGroup = configFile.getString(
"GroupOptions.RegisteredPlayerGroup", "");
getEnablePasswordVerifier = configFile.getBoolean(
"settings.restrictions.enablePasswordVerifier", true);
protectInventoryBeforeLogInEnabled = configFile.getBoolean(
"settings.restrictions.ProtectInventoryBeforeLogIn", true);
passwordMaxLength = configFile.getInt(
"settings.security.passwordMaxLength", 20);
isBackupActivated = configFile.getBoolean(
"BackupSystem.ActivateBackup", false);
isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart",
false);
isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop",
false);
backupWindowsPath = configFile.getString(
"BackupSystem.MysqlWindowsPath",
"C:\\Program Files\\MySQL\\MySQL Server 5.1\\");
enablePasspartu = configFile.getBoolean("Passpartu.enablePasspartu",
false);
isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer",
true);
reloadSupport = configFile.getBoolean(
"Security.ReloadCommand.useReloadCommandSupport", true);
allowCommands = (List<String>) configFile
.getList("settings.restrictions.allowCommands");
if (configFile.contains("allowCommands")) { if (configFile.contains("allowCommands")) {
if (!allowCommands.contains("/login")) allowCommands.add("/login"); if (!allowCommands.contains("/login"))
if (!allowCommands.contains("/register")) allowCommands allowCommands.add("/login");
.add("/register"); if (!allowCommands.contains("/register"))
if (!allowCommands.contains("/l")) allowCommands.add("/l"); allowCommands.add("/register");
if (!allowCommands.contains("/reg")) allowCommands.add("/reg"); if (!allowCommands.contains("/l"))
if (!allowCommands.contains("/passpartu")) allowCommands allowCommands.add("/l");
.add("/passpartu"); if (!allowCommands.contains("/reg"))
if (!allowCommands.contains("/email")) allowCommands.add("/email"); allowCommands.add("/reg");
if (!allowCommands.contains("/captcha")) allowCommands if (!allowCommands.contains("/passpartu"))
.add("/captcha"); allowCommands.add("/passpartu");
if (!allowCommands.contains("/email"))
allowCommands.add("/email");
if (!allowCommands.contains("/captcha"))
allowCommands.add("/captcha");
} }
rakamakUsers = configFile.getString("Converter.Rakamak.fileName", rakamakUsers = configFile.getString("Converter.Rakamak.fileName", "users.rak");
"users.rak"); rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName", "UsersIp.rak");
rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName",
"UsersIp.rak");
rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false); rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false);
noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", false);
false); removePassword = configFile.getBoolean("Security.console.removePassword", true);
removePassword = configFile.getBoolean(
"Security.console.removePassword", true);
getmailAccount = configFile.getString("Email.mailAccount", ""); getmailAccount = configFile.getString("Email.mailAccount", "");
getmailPassword = configFile.getString("Email.mailPassword", ""); getmailPassword = configFile.getString("Email.mailPassword", "");
getmailSMTP = configFile.getString("Email.mailSMTP", "smtp.gmail.com"); getmailSMTP = configFile.getString("Email.mailSMTP", "smtp.gmail.com");
getMailPort = configFile.getInt("Email.mailPort", 465); getMailPort = configFile.getInt("Email.mailPort", 465);
getRecoveryPassLength = configFile.getInt( getRecoveryPassLength = configFile.getInt("Email.RecoveryPasswordLength", 8);
"Email.RecoveryPasswordLength", 8); getMySQLOtherUsernameColumn = (List<String>) configFile.getList("ExternalBoardOptions.mySQLOtherUsernameColumns", new ArrayList<String>());
getMySQLOtherUsernameColumn = (List<String>) configFile.getList( displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true);
"ExternalBoardOptions.mySQLOtherUsernameColumns", getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id");
new ArrayList<String>());
displayOtherAccounts = configFile.getBoolean(
"settings.restrictions.displayOtherAccounts", true);
getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId",
"id");
getmailSenderName = configFile.getString("Email.mailSenderName", ""); getmailSenderName = configFile.getString("Email.mailSenderName", "");
useCaptcha = configFile useCaptcha = configFile.getBoolean("Security.captcha.useCaptcha", false);
.getBoolean("Security.captcha.useCaptcha", false);
maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5); maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5);
captchaLength = configFile.getInt("Security.captcha.captchaLength", 5); captchaLength = configFile.getInt("Security.captcha.captchaLength", 5);
getMailSubject = configFile.getString("Email.mailSubject", getMailSubject = configFile.getString("Email.mailSubject", "Your new AuthMe Password");
"Your new AuthMe Password"); getMailText = configFile.getString("Email.mailText", "Dear <playername>, <br /><br /> This is your new AuthMe password for the server <br /><br /> <servername> : <br /><br /> <generatedpass><br /><br />Do not forget to change password after login! <br /> /changepassword <generatedpass> newPassword");
getMailText = configFile emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false);
.getString( saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8);
"Email.mailText",
"Dear <playername>, <br /><br /> This is your new AuthMe password for the server <br /><br /> <servername> : <br /><br /> <generatedpass><br /><br />Do not forget to change password after login! <br /> /changepassword <generatedpass> newPassword");
emailRegistration = configFile.getBoolean(
"settings.registration.enableEmailRegistrationSystem", false);
saltLength = configFile.getInt("settings.security.doubleMD5SaltLength",
8);
getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1);
multiverse = configFile.getBoolean("Hooks.multiverse", true); multiverse = configFile.getBoolean("Hooks.multiverse", true);
chestshop = configFile.getBoolean("Hooks.chestshop", true); chestshop = configFile.getBoolean("Hooks.chestshop", true);
notifications = configFile.getBoolean("Hooks.notifications", true); notifications = configFile.getBoolean("Hooks.notifications", true);
bungee = configFile.getBoolean("Hooks.bungeecord", false); bungee = configFile.getBoolean("Hooks.bungeecord", false);
getForcedWorlds = (List<String>) configFile.getList( getForcedWorlds = (List<String>) configFile.getList("settings.restrictions.ForceSpawnOnTheseWorlds", new ArrayList<String>());
"settings.restrictions.ForceSpawnOnTheseWorlds", banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false);
new ArrayList<String>()); doubleEmailCheck = configFile.getBoolean("settings.registration.doubleEmailCheck", false);
banUnsafeIp = configFile.getBoolean( sessionExpireOnIpChange = configFile.getBoolean("settings.sessions.sessionExpireOnIpChange", false);
"settings.restrictions.banUnsafedIP", false); useLogging = configFile.getBoolean("Security.console.logConsole", false);
doubleEmailCheck = configFile.getBoolean( disableSocialSpy = configFile.getBoolean("Hooks.disableSocialSpy", true);
"settings.registration.doubleEmailCheck", false); bCryptLog2Rounds = configFile.getInt("ExternalBoardOptions.bCryptLog2Round", 10);
sessionExpireOnIpChange = configFile.getBoolean( forceOnlyAfterLogin = configFile.getBoolean("settings.GameMode.ForceOnlyAfterLogin", false);
"settings.sessions.sessionExpireOnIpChange", false); useEssentialsMotd = configFile.getBoolean("Hooks.useEssentialsMotd", false);
useLogging = configFile
.getBoolean("Security.console.logConsole", false);
disableSocialSpy = configFile
.getBoolean("Hooks.disableSocialSpy", true);
bCryptLog2Rounds = configFile.getInt(
"ExternalBoardOptions.bCryptLog2Round", 10);
forceOnlyAfterLogin = configFile.getBoolean(
"settings.GameMode.ForceOnlyAfterLogin", false);
useEssentialsMotd = configFile.getBoolean("Hooks.useEssentialsMotd",
false);
usePurge = configFile.getBoolean("Purge.useAutoPurge", false); usePurge = configFile.getBoolean("Purge.useAutoPurge", false);
purgeDelay = configFile.getInt("Purge.daysBeforeRemovePlayer", 60); purgeDelay = configFile.getInt("Purge.daysBeforeRemovePlayer", 60);
purgePlayerDat = configFile.getBoolean("Purge.removePlayerDat", false); purgePlayerDat = configFile.getBoolean("Purge.removePlayerDat", false);
purgeEssentialsFile = configFile.getBoolean( purgeEssentialsFile = configFile.getBoolean("Purge.removeEssentialsFile", false);
"Purge.removeEssentialsFile", false);
defaultWorld = configFile.getString("Purge.defaultWorld", "world"); defaultWorld = configFile.getString("Purge.defaultWorld", "world");
getPhpbbPrefix = configFile.getString( getPhpbbPrefix = configFile.getString("ExternalBoardOptions.phpbbTablePrefix", "phpbb_");
"ExternalBoardOptions.phpbbTablePrefix", "phpbb_"); getPhpbbGroup = configFile.getInt("ExternalBoardOptions.phpbbActivatedGroupId", 2);
getPhpbbGroup = configFile.getInt( supportOldPassword = configFile.getBoolean("settings.security.supportOldPasswordHash", false);
"ExternalBoardOptions.phpbbActivatedGroupId", 2); getWordPressPrefix = configFile.getString("ExternalBoardOptions.wordpressTablePrefix", "wp_");
supportOldPassword = configFile.getBoolean( purgeLimitedCreative = configFile.getBoolean("Purge.removeLimitedCreativesInventories", false);
"settings.security.supportOldPasswordHash", false); purgeAntiXray = configFile.getBoolean("Purge.removeAntiXRayFile", false);
getWordPressPrefix = configFile.getString(
"ExternalBoardOptions.wordpressTablePrefix", "wp_");
purgeLimitedCreative = configFile.getBoolean(
"Purge.removeLimitedCreativesInventories", false);
purgeAntiXray = configFile
.getBoolean("Purge.removeAntiXRayFile", false);
// purgePermissions = configFile.getBoolean("Purge.removePermissions", // purgePermissions = configFile.getBoolean("Purge.removePermissions",
// false); // false);
enableProtection = configFile.getBoolean("Protection.enableProtection", enableProtection = configFile.getBoolean("Protection.enableProtection", false);
false); countries = (List<String>) configFile.getList("Protection.countries", new ArrayList<String>());
countries = (List<String>) configFile.getList("Protection.countries", enableAntiBot = configFile.getBoolean("Protection.enableAntiBot", false);
new ArrayList<String>()); antiBotSensibility = configFile.getInt("Protection.antiBotSensibility", 5);
enableAntiBot = configFile
.getBoolean("Protection.enableAntiBot", false);
antiBotSensibility = configFile.getInt("Protection.antiBotSensibility",
5);
antiBotDuration = configFile.getInt("Protection.antiBotDuration", 10); antiBotDuration = configFile.getInt("Protection.antiBotDuration", 10);
forceCommands = (List<String>) configFile.getList( forceCommands = (List<String>) configFile.getList("settings.forceCommands", new ArrayList<String>());
"settings.forceCommands", new ArrayList<String>()); forceCommandsAsConsole = (List<String>) configFile.getList("settings.forceCommandsAsConsole", new ArrayList<String>());
forceCommandsAsConsole = (List<String>) configFile.getList(
"settings.forceCommandsAsConsole", new ArrayList<String>());
recallEmail = configFile.getBoolean("Email.recallPlayers", false); recallEmail = configFile.getBoolean("Email.recallPlayers", false);
delayRecall = configFile.getInt("Email.delayRecall", 5); delayRecall = configFile.getInt("Email.delayRecall", 5);
useWelcomeMessage = configFile.getBoolean("settings.useWelcomeMessage", useWelcomeMessage = configFile.getBoolean("settings.useWelcomeMessage", true);
true); unsafePasswords = (List<String>) configFile.getList("settings.security.unsafePasswords", new ArrayList<String>());
unsafePasswords = (List<String>) configFile.getList( countriesBlacklist = (List<String>) configFile.getList("Protection.countriesBlacklist", new ArrayList<String>());
"settings.security.unsafePasswords", new ArrayList<String>()); broadcastWelcomeMessage = configFile.getBoolean("settings.broadcastWelcomeMessage", false);
countriesBlacklist = (List<String>) configFile.getList( forceRegKick = configFile.getBoolean("settings.registration.forceKickAfterRegister", false);
"Protection.countriesBlacklist", new ArrayList<String>()); forceRegLogin = configFile.getBoolean("settings.registration.forceLoginAfterRegister", false);
broadcastWelcomeMessage = configFile.getBoolean( getMySQLColumnLogged = configFile.getString("DataSource.mySQLColumnLogged", "isLogged");
"settings.broadcastWelcomeMessage", false); spawnPriority = configFile.getString("settings.restrictions.spawnPriority", "authme,essentials,multiverse,default");
forceRegKick = configFile.getBoolean( getMaxLoginPerIp = configFile.getInt("settings.restrictions.maxLoginPerIp", 0);
"settings.registration.forceKickAfterRegister", false); getMaxJoinPerIp = configFile.getInt("settings.restrictions.maxJoinPerIp", 0);
forceRegLogin = configFile.getBoolean( checkVeryGames = configFile.getBoolean("VeryGames.enableIpCheck", false);
"settings.registration.forceLoginAfterRegister", false); delayJoinMessage = configFile.getBoolean("settings.delayJoinMessage", false);
getMySQLColumnLogged = configFile.getString( noTeleport = configFile.getBoolean("settings.restrictions.noTeleport", false);
"DataSource.mySQLColumnLogged", "isLogged"); crazyloginFileName = configFile.getString("Converter.CrazyLogin.fileName", "accounts.db");
spawnPriority = configFile.getString( getPassRegex = configFile.getString("settings.restrictions.allowedPasswordCharacters", "[a-zA-Z0-9_?!@+&-]*");
"settings.restrictions.spawnPriority", applyBlindEffect = configFile.getBoolean("settings.applyBlindEffect", false);
"authme,essentials,multiverse,default");
getMaxLoginPerIp = configFile.getInt(
"settings.restrictions.maxLoginPerIp", 0);
getMaxJoinPerIp = configFile.getInt(
"settings.restrictions.maxJoinPerIp", 0);
checkVeryGames = configFile
.getBoolean("VeryGames.enableIpCheck", false);
delayJoinMessage = configFile.getBoolean("settings.delayJoinMessage",
false);
noTeleport = configFile.getBoolean("settings.restrictions.noTeleport",
false);
crazyloginFileName = configFile.getString(
"Converter.CrazyLogin.fileName", "accounts.db");
getPassRegex = configFile.getString(
"settings.restrictions.allowedPasswordCharacters",
"[a-zA-Z0-9_?!@+&-]*");
applyBlindEffect = configFile.getBoolean("settings.applyBlindEffect",
false);
emailBlacklist = configFile.getStringList("Email.emailBlacklisted"); emailBlacklist = configFile.getStringList("Email.emailBlacklisted");
emailWhitelist = configFile.getStringList("Email.emailWhitelisted"); emailWhitelist = configFile.getStringList("Email.emailWhitelisted");
@ -391,269 +276,158 @@ public final class Settings extends YamlConfiguration {
public static void reloadConfigOptions(YamlConfiguration newConfig) { public static void reloadConfigOptions(YamlConfiguration newConfig) {
configFile = newConfig; configFile = newConfig;
messagesLanguage = checkLang(configFile.getString( messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en"));
"settings.messagesLanguage", "en")); isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false);
isPermissionCheckEnabled = configFile.getBoolean( isForcedRegistrationEnabled = configFile.getBoolean("settings.registration.force", true);
"permission.EnablePermissionCheck", false); isRegistrationEnabled = configFile.getBoolean("settings.registration.enabled", true);
isForcedRegistrationEnabled = configFile.getBoolean( isTeleportToSpawnEnabled = configFile.getBoolean("settings.restrictions.teleportUnAuthedToSpawn", false);
"settings.registration.force", true); getWarnMessageInterval = configFile.getInt("settings.registration.messageInterval", 5);
isRegistrationEnabled = configFile.getBoolean( isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled", false);
"settings.registration.enabled", true);
isTeleportToSpawnEnabled = configFile.getBoolean(
"settings.restrictions.teleportUnAuthedToSpawn", false);
getWarnMessageInterval = configFile.getInt(
"settings.registration.messageInterval", 5);
isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled",
false);
getSessionTimeout = configFile.getInt("settings.sessions.timeout", 10); getSessionTimeout = configFile.getInt("settings.sessions.timeout", 10);
getRegistrationTimeout = configFile.getInt( getRegistrationTimeout = configFile.getInt("settings.restrictions.timeout", 30);
"settings.restrictions.timeout", 30); isChatAllowed = configFile.getBoolean("settings.restrictions.allowChat", false);
isChatAllowed = configFile.getBoolean( getMaxNickLength = configFile.getInt("settings.restrictions.maxNicknameLength", 20);
"settings.restrictions.allowChat", false); getMinNickLength = configFile.getInt("settings.restrictions.minNicknameLength", 3);
getMaxNickLength = configFile.getInt( getPasswordMinLen = configFile.getInt("settings.security.minPasswordLength", 4);
"settings.restrictions.maxNicknameLength", 20); getNickRegex = configFile.getString("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_?]*");
getMinNickLength = configFile.getInt( isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser", false);
"settings.restrictions.minNicknameLength", 3); getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser");
getPasswordMinLen = configFile.getInt( isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement", false);
"settings.security.minPasswordLength", 4); getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius", 100);
getNickRegex = configFile.getString( getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin");
"settings.restrictions.allowedNicknameCharacters", isKickOnWrongPasswordEnabled = configFile.getBoolean("settings.restrictions.kickOnWrongPassword", false);
"[a-zA-Z0-9_?]*"); isKickNonRegisteredEnabled = configFile.getBoolean("settings.restrictions.kickNonRegistered", false);
isAllowRestrictedIp = configFile.getBoolean( isForceSingleSessionEnabled = configFile.getBoolean("settings.restrictions.ForceSingleSession", true);
"settings.restrictions.AllowRestrictedUser", false); isForceSpawnLocOnJoinEnabled = configFile.getBoolean("settings.restrictions.ForceSpawnLocOnJoinEnabled", false);
getRestrictedIp = configFile isSaveQuitLocationEnabled = configFile.getBoolean("settings.restrictions.SaveQuitLocation", false);
.getStringList("settings.restrictions.AllowedRestrictedUser"); isForceSurvivalModeEnabled = configFile.getBoolean("settings.GameMode.ForceSurvivalMode", false);
isMovementAllowed = configFile.getBoolean( isResetInventoryIfCreative = configFile.getBoolean("settings.GameMode.ResetInventoryIfCreative", false);
"settings.restrictions.allowMovement", false); getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp", 1);
getMovementRadius = configFile.getInt(
"settings.restrictions.allowedMovementRadius", 100);
getJoinPermissions = configFile
.getStringList("GroupOptions.Permissions.PermissionsOnJoin");
isKickOnWrongPasswordEnabled = configFile.getBoolean(
"settings.restrictions.kickOnWrongPassword", false);
isKickNonRegisteredEnabled = configFile.getBoolean(
"settings.restrictions.kickNonRegistered", false);
isForceSingleSessionEnabled = configFile.getBoolean(
"settings.restrictions.ForceSingleSession", true);
isForceSpawnLocOnJoinEnabled = configFile.getBoolean(
"settings.restrictions.ForceSpawnLocOnJoinEnabled", false);
isSaveQuitLocationEnabled = configFile.getBoolean(
"settings.restrictions.SaveQuitLocation", false);
isForceSurvivalModeEnabled = configFile.getBoolean(
"settings.GameMode.ForceSurvivalMode", false);
isResetInventoryIfCreative = configFile.getBoolean(
"settings.GameMode.ResetInventoryIfCreative", false);
getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp",
1);
getPasswordHash = getPasswordHash(); getPasswordHash = getPasswordHash();
getUnloggedinGroup = configFile.getString( getUnloggedinGroup = configFile.getString("settings.security.unLoggedinGroup", "unLoggedInGroup");
"settings.security.unLoggedinGroup", "unLoggedInGroup");
getDataSource = getDataSource(); getDataSource = getDataSource();
isCachingEnabled = configFile.getBoolean("DataSource.caching", true); isCachingEnabled = configFile.getBoolean("DataSource.caching", true);
getMySQLHost = configFile getMySQLHost = configFile.getString("DataSource.mySQLHost", "127.0.0.1");
.getString("DataSource.mySQLHost", "127.0.0.1");
getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306"); getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306");
getMySQLUsername = configFile.getString("DataSource.mySQLUsername", getMySQLUsername = configFile.getString("DataSource.mySQLUsername", "authme");
"authme"); getMySQLPassword = configFile.getString("DataSource.mySQLPassword", "12345");
getMySQLPassword = configFile.getString("DataSource.mySQLPassword", getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", "authme");
"12345"); getMySQLTablename = configFile.getString("DataSource.mySQLTablename", "authme");
getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", getMySQLColumnEmail = configFile.getString("DataSource.mySQLColumnEmail", "email");
"authme"); getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName", "username");
getMySQLTablename = configFile.getString("DataSource.mySQLTablename", getMySQLColumnPassword = configFile.getString("DataSource.mySQLColumnPassword", "password");
"authme"); getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp", "ip");
getMySQLColumnEmail = configFile.getString( getMySQLColumnLastLogin = configFile.getString("DataSource.mySQLColumnLastLogin", "lastlogin");
"DataSource.mySQLColumnEmail", "email"); getMySQLlastlocX = configFile.getString("DataSource.mySQLlastlocX", "x");
getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName", getMySQLlastlocY = configFile.getString("DataSource.mySQLlastlocY", "y");
"username"); getMySQLlastlocZ = configFile.getString("DataSource.mySQLlastlocZ", "z");
getMySQLColumnPassword = configFile.getString( getMySQLlastlocWorld = configFile.getString("DataSource.mySQLlastlocWorld", "world");
"DataSource.mySQLColumnPassword", "password"); getMySQLColumnSalt = configFile.getString("ExternalBoardOptions.mySQLColumnSalt", "");
getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp", getMySQLColumnGroup = configFile.getString("ExternalBoardOptions.mySQLColumnGroup", "");
"ip"); getNonActivatedGroup = configFile.getInt("ExternalBoardOptions.nonActivedUserGroup", -1);
getMySQLColumnLastLogin = configFile.getString( unRegisteredGroup = configFile.getString("GroupOptions.UnregisteredPlayerGroup", "");
"DataSource.mySQLColumnLastLogin", "lastlogin"); getUnrestrictedName = configFile.getStringList("settings.unrestrictions.UnrestrictedName");
getMySQLlastlocX = configFile getRegisteredGroup = configFile.getString("GroupOptions.RegisteredPlayerGroup", "");
.getString("DataSource.mySQLlastlocX", "x"); getEnablePasswordVerifier = configFile.getBoolean("settings.restrictions.enablePasswordVerifier", true);
getMySQLlastlocY = configFile protectInventoryBeforeLogInEnabled = configFile.getBoolean("settings.restrictions.ProtectInventoryBeforeLogIn", true);
.getString("DataSource.mySQLlastlocY", "y"); passwordMaxLength = configFile.getInt("settings.security.passwordMaxLength", 20);
getMySQLlastlocZ = configFile isBackupActivated = configFile.getBoolean("BackupSystem.ActivateBackup", false);
.getString("DataSource.mySQLlastlocZ", "z"); isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart", false);
getMySQLlastlocWorld = configFile.getString( isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop", false);
"DataSource.mySQLlastlocWorld", "world"); backupWindowsPath = configFile.getString("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\");
getMySQLColumnSalt = configFile.getString( enablePasspartu = configFile.getBoolean("Passpartu.enablePasspartu", false);
"ExternalBoardOptions.mySQLColumnSalt", ""); isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer", true);
getMySQLColumnGroup = configFile.getString( reloadSupport = configFile.getBoolean("Security.ReloadCommand.useReloadCommandSupport", true);
"ExternalBoardOptions.mySQLColumnGroup", ""); allowCommands = (List<String>) configFile.getList("settings.restrictions.allowCommands");
getNonActivatedGroup = configFile.getInt(
"ExternalBoardOptions.nonActivedUserGroup", -1);
unRegisteredGroup = configFile.getString(
"GroupOptions.UnregisteredPlayerGroup", "");
getUnrestrictedName = configFile
.getStringList("settings.unrestrictions.UnrestrictedName");
getRegisteredGroup = configFile.getString(
"GroupOptions.RegisteredPlayerGroup", "");
getEnablePasswordVerifier = configFile.getBoolean(
"settings.restrictions.enablePasswordVerifier", true);
protectInventoryBeforeLogInEnabled = configFile.getBoolean(
"settings.restrictions.ProtectInventoryBeforeLogIn", true);
passwordMaxLength = configFile.getInt(
"settings.security.passwordMaxLength", 20);
isBackupActivated = configFile.getBoolean(
"BackupSystem.ActivateBackup", false);
isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart",
false);
isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop",
false);
backupWindowsPath = configFile.getString(
"BackupSystem.MysqlWindowsPath",
"C:\\Program Files\\MySQL\\MySQL Server 5.1\\");
enablePasspartu = configFile.getBoolean("Passpartu.enablePasspartu",
false);
isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer",
true);
reloadSupport = configFile.getBoolean(
"Security.ReloadCommand.useReloadCommandSupport", true);
allowCommands = (List<String>) configFile
.getList("settings.restrictions.allowCommands");
if (configFile.contains("allowCommands")) { if (configFile.contains("allowCommands")) {
if (!allowCommands.contains("/login")) allowCommands.add("/login"); if (!allowCommands.contains("/login"))
if (!allowCommands.contains("/register")) allowCommands allowCommands.add("/login");
.add("/register"); if (!allowCommands.contains("/register"))
if (!allowCommands.contains("/l")) allowCommands.add("/l"); allowCommands.add("/register");
if (!allowCommands.contains("/reg")) allowCommands.add("/reg"); if (!allowCommands.contains("/l"))
if (!allowCommands.contains("/passpartu")) allowCommands allowCommands.add("/l");
.add("/passpartu"); if (!allowCommands.contains("/reg"))
if (!allowCommands.contains("/email")) allowCommands.add("/email"); allowCommands.add("/reg");
if (!allowCommands.contains("/captcha")) allowCommands if (!allowCommands.contains("/passpartu"))
.add("/captcha"); allowCommands.add("/passpartu");
if (!allowCommands.contains("/email"))
allowCommands.add("/email");
if (!allowCommands.contains("/captcha"))
allowCommands.add("/captcha");
} }
rakamakUsers = configFile.getString("Converter.Rakamak.fileName", rakamakUsers = configFile.getString("Converter.Rakamak.fileName", "users.rak");
"users.rak"); rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName", "UsersIp.rak");
rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName",
"UsersIp.rak");
rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false); rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false);
noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", false);
false); removePassword = configFile.getBoolean("Security.console.removePassword", true);
removePassword = configFile.getBoolean(
"Security.console.removePassword", true);
getmailAccount = configFile.getString("Email.mailAccount", ""); getmailAccount = configFile.getString("Email.mailAccount", "");
getmailPassword = configFile.getString("Email.mailPassword", ""); getmailPassword = configFile.getString("Email.mailPassword", "");
getmailSMTP = configFile.getString("Email.mailSMTP", "smtp.gmail.com"); getmailSMTP = configFile.getString("Email.mailSMTP", "smtp.gmail.com");
getMailPort = configFile.getInt("Email.mailPort", 465); getMailPort = configFile.getInt("Email.mailPort", 465);
getRecoveryPassLength = configFile.getInt( getRecoveryPassLength = configFile.getInt("Email.RecoveryPasswordLength", 8);
"Email.RecoveryPasswordLength", 8); getMySQLOtherUsernameColumn = (List<String>) configFile.getList("ExternalBoardOptions.mySQLOtherUsernameColumns", new ArrayList<String>());
getMySQLOtherUsernameColumn = (List<String>) configFile.getList( displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true);
"ExternalBoardOptions.mySQLOtherUsernameColumns", getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id");
new ArrayList<String>());
displayOtherAccounts = configFile.getBoolean(
"settings.restrictions.displayOtherAccounts", true);
getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId",
"id");
getmailSenderName = configFile.getString("Email.mailSenderName", ""); getmailSenderName = configFile.getString("Email.mailSenderName", "");
useCaptcha = configFile useCaptcha = configFile.getBoolean("Security.captcha.useCaptcha", false);
.getBoolean("Security.captcha.useCaptcha", false);
maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5); maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5);
captchaLength = configFile.getInt("Security.captcha.captchaLength", 5); captchaLength = configFile.getInt("Security.captcha.captchaLength", 5);
getMailSubject = configFile.getString("Email.mailSubject", getMailSubject = configFile.getString("Email.mailSubject", "Your new AuthMe Password");
"Your new AuthMe Password"); getMailText = configFile.getString("Email.mailText", "Dear <playername>, <br /><br /> This is your new AuthMe password for the server <br /><br /> <servername> : <br /><br /> <generatedpass><br /><br />Do not forget to change password after login! <br /> /changepassword <generatedpass> newPassword");
getMailText = configFile emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false);
.getString( saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8);
"Email.mailText",
"Dear <playername>, <br /><br /> This is your new AuthMe password for the server <br /><br /> <servername> : <br /><br /> <generatedpass><br /><br />Do not forget to change password after login! <br /> /changepassword <generatedpass> newPassword");
emailRegistration = configFile.getBoolean(
"settings.registration.enableEmailRegistrationSystem", false);
saltLength = configFile.getInt("settings.security.doubleMD5SaltLength",
8);
getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1);
multiverse = configFile.getBoolean("Hooks.multiverse", true); multiverse = configFile.getBoolean("Hooks.multiverse", true);
chestshop = configFile.getBoolean("Hooks.chestshop", true); chestshop = configFile.getBoolean("Hooks.chestshop", true);
notifications = configFile.getBoolean("Hooks.notifications", true); notifications = configFile.getBoolean("Hooks.notifications", true);
bungee = configFile.getBoolean("Hooks.bungeecord", false); bungee = configFile.getBoolean("Hooks.bungeecord", false);
getForcedWorlds = (List<String>) configFile getForcedWorlds = (List<String>) configFile.getList("settings.restrictions.ForceSpawnOnTheseWorlds");
.getList("settings.restrictions.ForceSpawnOnTheseWorlds"); banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false);
banUnsafeIp = configFile.getBoolean( doubleEmailCheck = configFile.getBoolean("settings.registration.doubleEmailCheck", false);
"settings.restrictions.banUnsafedIP", false); sessionExpireOnIpChange = configFile.getBoolean("settings.sessions.sessionExpireOnIpChange", false);
doubleEmailCheck = configFile.getBoolean( useLogging = configFile.getBoolean("Security.console.logConsole", false);
"settings.registration.doubleEmailCheck", false); disableSocialSpy = configFile.getBoolean("Hooks.disableSocialSpy", true);
sessionExpireOnIpChange = configFile.getBoolean( bCryptLog2Rounds = configFile.getInt("ExternalBoardOptions.bCryptLog2Round", 10);
"settings.sessions.sessionExpireOnIpChange", false); forceOnlyAfterLogin = configFile.getBoolean("settings.GameMode.ForceOnlyAfterLogin", false);
useLogging = configFile useEssentialsMotd = configFile.getBoolean("Hooks.useEssentialsMotd", false);
.getBoolean("Security.console.logConsole", false);
disableSocialSpy = configFile
.getBoolean("Hooks.disableSocialSpy", true);
bCryptLog2Rounds = configFile.getInt(
"ExternalBoardOptions.bCryptLog2Round", 10);
forceOnlyAfterLogin = configFile.getBoolean(
"settings.GameMode.ForceOnlyAfterLogin", false);
useEssentialsMotd = configFile.getBoolean("Hooks.useEssentialsMotd",
false);
usePurge = configFile.getBoolean("Purge.useAutoPurge", false); usePurge = configFile.getBoolean("Purge.useAutoPurge", false);
purgeDelay = configFile.getInt("Purge.daysBeforeRemovePlayer", 60); purgeDelay = configFile.getInt("Purge.daysBeforeRemovePlayer", 60);
purgePlayerDat = configFile.getBoolean("Purge.removePlayerDat", false); purgePlayerDat = configFile.getBoolean("Purge.removePlayerDat", false);
purgeEssentialsFile = configFile.getBoolean( purgeEssentialsFile = configFile.getBoolean("Purge.removeEssentialsFile", false);
"Purge.removeEssentialsFile", false);
defaultWorld = configFile.getString("Purge.defaultWorld", "world"); defaultWorld = configFile.getString("Purge.defaultWorld", "world");
getPhpbbPrefix = configFile.getString( getPhpbbPrefix = configFile.getString("ExternalBoardOptions.phpbbTablePrefix", "phpbb_");
"ExternalBoardOptions.phpbbTablePrefix", "phpbb_"); getPhpbbGroup = configFile.getInt("ExternalBoardOptions.phpbbActivatedGroupId", 2);
getPhpbbGroup = configFile.getInt( supportOldPassword = configFile.getBoolean("settings.security.supportOldPasswordHash", false);
"ExternalBoardOptions.phpbbActivatedGroupId", 2); getWordPressPrefix = configFile.getString("ExternalBoardOptions.wordpressTablePrefix", "wp_");
supportOldPassword = configFile.getBoolean( purgeLimitedCreative = configFile.getBoolean("Purge.removeLimitedCreativesInventories", false);
"settings.security.supportOldPasswordHash", false); purgeAntiXray = configFile.getBoolean("Purge.removeAntiXRayFile", false);
getWordPressPrefix = configFile.getString(
"ExternalBoardOptions.wordpressTablePrefix", "wp_");
purgeLimitedCreative = configFile.getBoolean(
"Purge.removeLimitedCreativesInventories", false);
purgeAntiXray = configFile
.getBoolean("Purge.removeAntiXRayFile", false);
// purgePermissions = configFile.getBoolean("Purge.removePermissions", // purgePermissions = configFile.getBoolean("Purge.removePermissions",
// false); // false);
enableProtection = configFile.getBoolean("Protection.enableProtection", enableProtection = configFile.getBoolean("Protection.enableProtection", false);
false);
countries = (List<String>) configFile.getList("Protection.countries"); countries = (List<String>) configFile.getList("Protection.countries");
enableAntiBot = configFile enableAntiBot = configFile.getBoolean("Protection.enableAntiBot", false);
.getBoolean("Protection.enableAntiBot", false); antiBotSensibility = configFile.getInt("Protection.antiBotSensibility", 5);
antiBotSensibility = configFile.getInt("Protection.antiBotSensibility",
5);
antiBotDuration = configFile.getInt("Protection.antiBotDuration", 10); antiBotDuration = configFile.getInt("Protection.antiBotDuration", 10);
forceCommands = (List<String>) configFile.getList( forceCommands = (List<String>) configFile.getList("settings.forceCommands", new ArrayList<String>());
"settings.forceCommands", new ArrayList<String>()); forceCommandsAsConsole = (List<String>) configFile.getList("settings.forceCommandsAsConsole", new ArrayList<String>());
forceCommandsAsConsole = (List<String>) configFile.getList(
"settings.forceCommandsAsConsole", new ArrayList<String>());
recallEmail = configFile.getBoolean("Email.recallPlayers", false); recallEmail = configFile.getBoolean("Email.recallPlayers", false);
delayRecall = configFile.getInt("Email.delayRecall", 5); delayRecall = configFile.getInt("Email.delayRecall", 5);
useWelcomeMessage = configFile.getBoolean("settings.useWelcomeMessage", useWelcomeMessage = configFile.getBoolean("settings.useWelcomeMessage", true);
true); unsafePasswords = (List<String>) configFile.getList("settings.security.unsafePasswords", new ArrayList<String>());
unsafePasswords = (List<String>) configFile.getList( countriesBlacklist = (List<String>) configFile.getList("Protection.countriesBlacklist", new ArrayList<String>());
"settings.security.unsafePasswords", new ArrayList<String>()); broadcastWelcomeMessage = configFile.getBoolean("settings.broadcastWelcomeMessage", false);
countriesBlacklist = (List<String>) configFile.getList( forceRegKick = configFile.getBoolean("settings.registration.forceKickAfterRegister", false);
"Protection.countriesBlacklist", new ArrayList<String>()); forceRegLogin = configFile.getBoolean("settings.registration.forceLoginAfterRegister", false);
broadcastWelcomeMessage = configFile.getBoolean( getMySQLColumnLogged = configFile.getString("DataSource.mySQLColumnLogged", "isLogged");
"settings.broadcastWelcomeMessage", false); spawnPriority = configFile.getString("settings.restrictions.spawnPriority", "authme,essentials,multiverse,default");
forceRegKick = configFile.getBoolean( getMaxLoginPerIp = configFile.getInt("settings.restrictions.maxLoginPerIp", 0);
"settings.registration.forceKickAfterRegister", false); getMaxJoinPerIp = configFile.getInt("settings.restrictions.maxJoinPerIp", 0);
forceRegLogin = configFile.getBoolean( checkVeryGames = configFile.getBoolean("VeryGames.enableIpCheck", false);
"settings.registration.forceLoginAfterRegister", false); delayJoinMessage = configFile.getBoolean("settings.delayJoinMessage", false);
getMySQLColumnLogged = configFile.getString( noTeleport = configFile.getBoolean("settings.restrictions.noTeleport", false);
"DataSource.mySQLColumnLogged", "isLogged"); crazyloginFileName = configFile.getString("Converter.CrazyLogin.fileName", "accounts.db");
spawnPriority = configFile.getString( getPassRegex = configFile.getString("settings.restrictions.allowedPasswordCharacters", "[a-zA-Z0-9_?!@+&-]*");
"settings.restrictions.spawnPriority", applyBlindEffect = configFile.getBoolean("settings.applyBlindEffect", false);
"authme,essentials,multiverse,default");
getMaxLoginPerIp = configFile.getInt(
"settings.restrictions.maxLoginPerIp", 0);
getMaxJoinPerIp = configFile.getInt(
"settings.restrictions.maxJoinPerIp", 0);
checkVeryGames = configFile
.getBoolean("VeryGames.enableIpCheck", false);
delayJoinMessage = configFile.getBoolean("settings.delayJoinMessage",
false);
noTeleport = configFile.getBoolean("settings.restrictions.noTeleport",
false);
crazyloginFileName = configFile.getString(
"Converter.CrazyLogin.fileName", "accounts.db");
getPassRegex = configFile.getString(
"settings.restrictions.allowedPasswordCharacters",
"[a-zA-Z0-9_?!@+&-]*");
applyBlindEffect = configFile.getBoolean("settings.applyBlindEffect",
false);
emailBlacklist = configFile.getStringList("Email.emailBlacklisted"); emailBlacklist = configFile.getStringList("Email.emailBlacklisted");
emailWhitelist = configFile.getStringList("Email.emailWhitelisted"); emailWhitelist = configFile.getStringList("Email.emailWhitelisted");
@ -664,14 +438,10 @@ public final class Settings extends YamlConfiguration {
public void mergeConfig() { public void mergeConfig() {
boolean changes = false; boolean changes = false;
if (contains("Xenoforo.predefinedSalt")) set("Xenoforo.predefinedSalt", if (contains("Xenoforo.predefinedSalt"))
null); set("Xenoforo.predefinedSalt", null);
if (configFile.getString("settings.security.passwordHash", "SHA256") if (configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA1") || configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA256"))
.toUpperCase().equals("XFSHA1") set("settings.security.passwordHash", "XENFORO");
|| configFile
.getString("settings.security.passwordHash", "SHA256")
.toUpperCase().equals("XFSHA256")) set(
"settings.security.passwordHash", "XENFORO");
if (!contains("Protection.enableProtection")) { if (!contains("Protection.enableProtection")) {
set("Protection.enableProtection", false); set("Protection.enableProtection", false);
changes = true; changes = true;
@ -745,8 +515,7 @@ public final class Settings extends YamlConfiguration {
changes = true; changes = true;
} }
if (!contains("settings.restrictions.spawnPriority")) { if (!contains("settings.restrictions.spawnPriority")) {
set("settings.restrictions.spawnPriority", set("settings.restrictions.spawnPriority", "authme,essentials,multiverse,default");
"authme,essentials,multiverse,default");
changes = true; changes = true;
} }
if (!contains("settings.restrictions.maxLoginPerIp")) { if (!contains("settings.restrictions.maxLoginPerIp")) {
@ -761,10 +530,8 @@ public final class Settings extends YamlConfiguration {
set("VeryGames.enableIpCheck", false); set("VeryGames.enableIpCheck", false);
changes = true; changes = true;
} }
if (getString("settings.restrictions.allowedNicknameCharacters") if (getString("settings.restrictions.allowedNicknameCharacters").equals("[a-zA-Z0-9_?]*"))
.equals("[a-zA-Z0-9_?]*")) set( set("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_]*");
"settings.restrictions.allowedNicknameCharacters",
"[a-zA-Z0-9_]*");
if (!contains("settings.delayJoinMessage")) { if (!contains("settings.delayJoinMessage")) {
set("settings.delayJoinMessage", false); set("settings.delayJoinMessage", false);
changes = true; changes = true;
@ -773,15 +540,14 @@ public final class Settings extends YamlConfiguration {
set("settings.restrictions.noTeleport", false); set("settings.restrictions.noTeleport", false);
changes = true; changes = true;
} }
if (contains("Converter.Rakamak.newPasswordHash")) set( if (contains("Converter.Rakamak.newPasswordHash"))
"Converter.Rakamak.newPasswordHash", null); set("Converter.Rakamak.newPasswordHash", null);
if (!contains("Converter.CrazyLogin.fileName")) { if (!contains("Converter.CrazyLogin.fileName")) {
set("Converter.CrazyLogin.fileName", "accounts.db"); set("Converter.CrazyLogin.fileName", "accounts.db");
changes = true; changes = true;
} }
if (!contains("settings.restrictions.allowedPasswordCharacters")) { if (!contains("settings.restrictions.allowedPasswordCharacters")) {
set("settings.restrictions.allowedPasswordCharacters", set("settings.restrictions.allowedPasswordCharacters", "[a-zA-Z0-9_?!@+&-]*");
"[a-zA-Z0-9_?!@+&-]*");
changes = true; changes = true;
} }
if (!contains("settings.applyBlindEffect")) { if (!contains("settings.applyBlindEffect")) {
@ -800,11 +566,8 @@ public final class Settings extends YamlConfiguration {
} }
if (changes) { if (changes) {
plugin.getLogger() plugin.getLogger().warning("Merge new Config Options - I'm not an error, please don't report me");
.warning( plugin.getLogger().warning("Please check your config.yml file for new configs!");
"Merge new Config Options - I'm not an error, please don't report me");
plugin.getLogger().warning(
"Please check your config.yml file for new configs!");
} }
plugin.saveConfig(); plugin.saveConfig();
@ -814,11 +577,9 @@ public final class Settings extends YamlConfiguration {
private static HashAlgorithm getPasswordHash() { private static HashAlgorithm getPasswordHash() {
String key = "settings.security.passwordHash"; String key = "settings.security.passwordHash";
try { try {
return HashAlgorithm.valueOf(configFile.getString(key, "SHA256") return HashAlgorithm.valueOf(configFile.getString(key, "SHA256").toUpperCase());
.toUpperCase());
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
ConsoleLogger ConsoleLogger.showError("Unknown Hash Algorithm; defaulting to SHA256");
.showError("Unknown Hash Algorithm; defaulting to SHA256");
return HashAlgorithm.SHA256; return HashAlgorithm.SHA256;
} }
} }
@ -826,11 +587,9 @@ public final class Settings extends YamlConfiguration {
private static DataSourceType getDataSource() { private static DataSourceType getDataSource() {
String key = "DataSource.backend"; String key = "DataSource.backend";
try { try {
return DataSource.DataSourceType.valueOf(configFile.getString(key) return DataSource.DataSourceType.valueOf(configFile.getString(key).toUpperCase());
.toUpperCase());
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
ConsoleLogger ConsoleLogger.showError("Unknown database backend; defaulting to file database");
.showError("Unknown database backend; defaulting to file database");
return DataSource.DataSourceType.FILE; return DataSource.DataSourceType.FILE;
} }
} }
@ -918,7 +677,8 @@ public final class Settings extends YamlConfiguration {
*/ */
public final void loadDefaults(String filename) { public final void loadDefaults(String filename) {
InputStream stream = plugin.getResource(filename); InputStream stream = plugin.getResource(filename);
if (stream == null) return; if (stream == null)
return;
setDefaults(YamlConfiguration.loadConfiguration(stream)); setDefaults(YamlConfiguration.loadConfiguration(stream));
} }
@ -970,9 +730,9 @@ public final class Settings extends YamlConfiguration {
} }
public static void switchAntiBotMod(boolean mode) { public static void switchAntiBotMod(boolean mode) {
if (mode) isKickNonRegisteredEnabled = true; if (mode)
else isKickNonRegisteredEnabled = configFile.getBoolean( isKickNonRegisteredEnabled = true;
"settings.restrictions.kickNonRegistered", false); else isKickNonRegisteredEnabled = configFile.getBoolean("settings.restrictions.kickNonRegistered", false);
} }
private static void getWelcomeMessage(AuthMe plugin) { private static void getWelcomeMessage(AuthMe plugin) {
@ -980,11 +740,9 @@ public final class Settings extends YamlConfiguration {
if (!useWelcomeMessage) { if (!useWelcomeMessage) {
return; return;
} }
if (!(new File(plugin.getDataFolder() + File.separator + "welcome.txt") if (!(new File(plugin.getDataFolder() + File.separator + "welcome.txt").exists())) {
.exists())) {
try { try {
FileWriter fw = new FileWriter(plugin.getDataFolder() FileWriter fw = new FileWriter(plugin.getDataFolder() + File.separator + "welcome.txt", true);
+ File.separator + "welcome.txt", true);
BufferedWriter w = new BufferedWriter(fw); BufferedWriter w = new BufferedWriter(fw);
w.write("Welcome {PLAYER} on {SERVER} server"); w.write("Welcome {PLAYER} on {SERVER} server");
w.newLine(); w.newLine();
@ -995,8 +753,7 @@ public final class Settings extends YamlConfiguration {
} }
} }
try { try {
FileReader fr = new FileReader(plugin.getDataFolder() FileReader fr = new FileReader(plugin.getDataFolder() + File.separator + "welcome.txt");
+ File.separator + "welcome.txt");
BufferedReader br = new BufferedReader(fr); BufferedReader br = new BufferedReader(fr);
String line = ""; String line = "";
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
@ -1011,8 +768,10 @@ public final class Settings extends YamlConfiguration {
} }
public static boolean isEmailCorrect(String email) { public static boolean isEmailCorrect(String email) {
if (!email.contains("@")) return false; if (!email.contains("@"))
if (email.equalsIgnoreCase("your@email.com")) return false; return false;
if (email.equalsIgnoreCase("your@email.com"))
return false;
String emailDomain = email.split("@")[1]; String emailDomain = email.split("@")[1];
boolean correct = true; boolean correct = true;
if (emailWhitelist != null && !emailWhitelist.isEmpty()) { if (emailWhitelist != null && !emailWhitelist.isEmpty()) {
@ -1038,6 +797,26 @@ public final class Settings extends YamlConfiguration {
} }
public enum messagesLang { public enum messagesLang {
en, de, br, cz, pl, fr, uk, ru, hu, sk, es, fi, zhtw, zhhk, zhcn, lt, it, ko, pt, nl, gl en,
de,
br,
cz,
pl,
fr,
uk,
ru,
hu,
sk,
es,
fi,
zhtw,
zhhk,
zhcn,
lt,
it,
ko,
pt,
nl,
gl
} }
} }

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