#450 Move Settings#loadEmailText and #getWelcomeMessage

This commit is contained in:
ljacqu 2016-02-03 22:36:01 +01:00
parent 155881ef05
commit 3e30a34714
9 changed files with 183 additions and 181 deletions

View File

@ -86,6 +86,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import static fr.xephi.authme.settings.properties.EmailSettings.MAIL_ACCOUNT;
import static fr.xephi.authme.settings.properties.EmailSettings.MAIL_PASSWORD;
import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER; import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER;
/** /**
@ -328,12 +330,9 @@ public class AuthMe extends JavaPlugin {
*/ */
private void setupMailApi() { private void setupMailApi() {
// Make sure the mail API is enabled // Make sure the mail API is enabled
if (Settings.getmailAccount.isEmpty() || Settings.getmailPassword.isEmpty()) { if (!newSettings.getProperty(MAIL_ACCOUNT).isEmpty() && !newSettings.getProperty(MAIL_PASSWORD).isEmpty()) {
return; this.mail = new SendMailSSL(this, newSettings);
} }
// Set up the mail API
this.mail = new SendMailSSL(this);
} }
/** /**
@ -483,7 +482,7 @@ public class AuthMe extends JavaPlugin {
Graph databaseBackend = metrics.createGraph("Database backend"); Graph databaseBackend = metrics.createGraph("Database backend");
// Custom graphs // Custom graphs
if (Settings.messageFile.exists()) { if (newSettings.getMessagesFile().exists()) {
messagesLanguage.addPlotter(new Metrics.Plotter(Settings.messagesLanguage) { messagesLanguage.addPlotter(new Metrics.Plotter(Settings.messagesLanguage) {
@Override @Override

View File

@ -1,25 +1,26 @@
package fr.xephi.authme.mail; package fr.xephi.authme.mail;
import java.io.File;
import java.io.IOException;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;
import javax.mail.Session;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.bukkit.Bukkit;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.ImageGenerator; import fr.xephi.authme.ImageGenerator;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.util.StringUtils; import fr.xephi.authme.util.StringUtils;
import org.apache.commons.mail.EmailConstants;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.bukkit.Bukkit;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;
import javax.mail.Session;
import java.io.File;
import java.io.IOException;
import java.security.Security;
import java.util.Properties;
/** /**
* @author Xephi59 * @author Xephi59
@ -27,13 +28,15 @@ import fr.xephi.authme.util.StringUtils;
public class SendMailSSL { public class SendMailSSL {
private final AuthMe plugin; private final AuthMe plugin;
private final NewSetting settings;
public SendMailSSL(AuthMe plugin) { public SendMailSSL(AuthMe plugin, NewSetting settings) {
this.plugin = plugin; this.plugin = plugin;
this.settings = settings;
} }
public void main(final PlayerAuth auth, final String newPass) { public void main(final PlayerAuth auth, final String newPass) {
final String mailText = replaceMailTags(Settings.getMailText, plugin, auth, newPass); final String mailText = replaceMailTags(settings.getEmailMessage(), plugin, auth, newPass);
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override @Override
@ -41,21 +44,23 @@ public class SendMailSSL {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
HtmlEmail email; HtmlEmail email;
try { try {
email = initializeMail(auth); email = initializeMail(auth, settings);
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.showError("Failed to create email with the given settings: " + StringUtils.formatException(e)); ConsoleLogger.showError("Failed to create email with the given settings: "
+ StringUtils.formatException(e));
return; return;
} }
String content = mailText; String content = mailText;
// Generate an image? // Generate an image?
File file = null; File file = null;
if (Settings.generateImage) { if (settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)) {
try { try {
file = generateImage(auth, plugin, newPass); file = generateImage(auth, plugin, newPass);
content = embedImageIntoEmailContent(file, email, content); content = embedImageIntoEmailContent(file, email, content);
} catch (IOException | EmailException e) { } catch (IOException | EmailException e) {
ConsoleLogger.showError("Unable to send new password as image for email " + auth.getEmail() + ": " + StringUtils.formatException(e)); ConsoleLogger.showError("Unable to send new password as image for email " + auth.getEmail()
+ ": " + StringUtils.formatException(e));
} }
} }
@ -68,43 +73,39 @@ public class SendMailSSL {
}); });
} }
private static File generateImage(PlayerAuth auth, AuthMe plugin, private static File generateImage(PlayerAuth auth, AuthMe plugin, String newPass) throws IOException {
String newPass) throws IOException {
ImageGenerator gen = new ImageGenerator(newPass); ImageGenerator gen = new ImageGenerator(newPass);
File file = new File(plugin.getDataFolder() + File.separator + auth.getNickname() + "_new_pass.jpg"); File file = new File(plugin.getDataFolder(), auth.getNickname() + "_new_pass.jpg");
ImageIO.write(gen.generateImage(), "jpg", file); ImageIO.write(gen.generateImage(), "jpg", file);
return file; return file;
} }
private static String embedImageIntoEmailContent(File image, private static String embedImageIntoEmailContent(File image, HtmlEmail email, String content)
HtmlEmail email, String content) throws EmailException { throws EmailException {
DataSource source = new FileDataSource(image); DataSource source = new FileDataSource(image);
String tag = email.embed(source, image.getName()); String tag = email.embed(source, image.getName());
return content.replace("<image />", "<img src=\"cid:" + tag + "\">"); return content.replace("<image />", "<img src=\"cid:" + tag + "\">");
} }
private static HtmlEmail initializeMail(PlayerAuth auth) private static HtmlEmail initializeMail(PlayerAuth auth, NewSetting settings)
throws EmailException { throws EmailException {
String senderName; String senderMail = settings.getProperty(EmailSettings.MAIL_ACCOUNT);
if (StringUtils.isEmpty(Settings.getmailSenderName)) { String senderName = StringUtils.isEmpty(settings.getProperty(EmailSettings.MAIL_SENDER_NAME))
senderName = Settings.getmailAccount; ? senderMail
} else { : settings.getProperty(EmailSettings.MAIL_SENDER_NAME);
senderName = Settings.getmailSenderName; String mailPassword = settings.getProperty(EmailSettings.MAIL_PASSWORD);
} int port = settings.getProperty(EmailSettings.SMTP_PORT);
String senderMail = Settings.getmailAccount;
String mailPassword = Settings.getmailPassword;
int port = Settings.getMailPort;
HtmlEmail email = new HtmlEmail(); HtmlEmail email = new HtmlEmail();
email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8); email.setCharset(EmailConstants.UTF_8);
email.setSmtpPort(port); email.setSmtpPort(port);
email.setHostName(Settings.getmailSMTP); email.setHostName(settings.getProperty(EmailSettings.SMTP_HOST));
email.addTo(auth.getEmail()); email.addTo(auth.getEmail());
email.setFrom(senderMail, senderName); email.setFrom(senderMail, senderName);
email.setSubject(Settings.getMailSubject); email.setSubject(settings.getProperty(EmailSettings.RECOVERY_MAIL_SUBJECT));
email.setAuthentication(senderMail, mailPassword); email.setAuthentication(senderMail, mailPassword);
setPropertiesForPort(email, port); setPropertiesForPort(email, port, settings);
return email; return email;
} }
@ -113,7 +114,8 @@ public class SendMailSSL {
email.setHtmlMsg(content); email.setHtmlMsg(content);
email.setTextMsg(content); email.setTextMsg(content);
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.showError("Your email.html config contains an error and cannot be sent: " + StringUtils.formatException(e)); ConsoleLogger.showError("Your email.html config contains an error and cannot be sent: "
+ StringUtils.formatException(e));
return false; return false;
} }
try { try {
@ -125,17 +127,19 @@ public class SendMailSSL {
} }
} }
private static String replaceMailTags(String mailText, AuthMe plugin, private static String replaceMailTags(String mailText, AuthMe plugin, PlayerAuth auth, String newPass) {
PlayerAuth auth, String newPass) { return mailText
return mailText.replace("<playername />", auth.getNickname()).replace("<servername />", plugin.getServer().getServerName()).replace("<generatedpass />", newPass); .replace("<playername />", auth.getNickname())
.replace("<servername />", plugin.getServer().getServerName())
.replace("<generatedpass />", newPass);
} }
@SuppressWarnings("deprecation") private static void setPropertiesForPort(HtmlEmail email, int port, NewSetting settings)
private static void setPropertiesForPort(HtmlEmail email, int port)
throws EmailException { throws EmailException {
switch (port) { switch (port) {
case 587: case 587:
if (!Settings.emailOauth2Token.isEmpty()) { String oAuth2Token = settings.getProperty(EmailSettings.OAUTH2_TOKEN);
if (!oAuth2Token.isEmpty()) {
if (Security.getProvider("Google OAuth2 Provider") == null) { if (Security.getProvider("Google OAuth2 Provider") == null) {
Security.addProvider(new OAuth2Provider()); Security.addProvider(new OAuth2Provider());
} }
@ -146,7 +150,7 @@ public class SendMailSSL {
mailProperties.setProperty("mail.smtp.sasl.mechanisms", "XOAUTH2"); mailProperties.setProperty("mail.smtp.sasl.mechanisms", "XOAUTH2");
mailProperties.setProperty("mail.smtp.auth.login.disable", "true"); mailProperties.setProperty("mail.smtp.auth.login.disable", "true");
mailProperties.setProperty("mail.smtp.auth.plain.disable", "true"); mailProperties.setProperty("mail.smtp.auth.plain.disable", "true");
mailProperties.setProperty(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, Settings.emailOauth2Token); mailProperties.setProperty(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oAuth2Token);
email.setMailSession(Session.getInstance(mailProperties)); email.setMailSession(Session.getInstance(mailProperties));
} else { } else {
email.setStartTLSEnabled(true); email.setStartTLSEnabled(true);
@ -159,7 +163,7 @@ public class SendMailSSL {
email.setSSLCheckServerIdentity(true); email.setSSLCheckServerIdentity(true);
break; break;
case 465: case 465:
email.setSslSmtpPort("" + port); email.setSslSmtpPort(Integer.toString(port));
email.setSSL(true); email.setSSL(true);
break; break;
default: default:

View File

@ -36,7 +36,8 @@ public class Management {
@Override @Override
public void run() { public void run() {
new AsynchronousLogin(player, password, forceLogin, plugin, plugin.getDataSource()).process(); new AsynchronousLogin(player, password, forceLogin, plugin, plugin.getDataSource(), settings)
.process();
} }
}); });
} }
@ -56,7 +57,7 @@ public class Management {
@Override @Override
public void run() { public void run() {
new AsyncRegister(player, password, email, plugin, plugin.getDataSource()).process(); new AsyncRegister(player, password, email, plugin, plugin.getDataSource(), settings).process();
} }
}); });
} }

View File

@ -11,8 +11,11 @@ import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.security.RandomString; import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages; import fr.xephi.authme.output.Messages;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.util.StringUtils;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -34,6 +37,7 @@ public class AsynchronousLogin {
private final DataSource database; private final DataSource database;
private final Messages m; private final Messages m;
private final String ip; private final String ip;
private final NewSetting settings;
/** /**
* Constructor for AsynchronousLogin. * Constructor for AsynchronousLogin.
@ -43,8 +47,10 @@ public class AsynchronousLogin {
* @param forceLogin boolean * @param forceLogin boolean
* @param plugin AuthMe * @param plugin AuthMe
* @param data DataSource * @param data DataSource
* @param settings The settings
*/ */
public AsynchronousLogin(Player player, String password, boolean forceLogin, AuthMe plugin, DataSource data) { public AsynchronousLogin(Player player, String password, boolean forceLogin, AuthMe plugin, DataSource data,
NewSetting settings) {
this.m = plugin.getMessages(); this.m = plugin.getMessages();
this.player = player; this.player = player;
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
@ -54,6 +60,7 @@ public class AsynchronousLogin {
this.plugin = plugin; this.plugin = plugin;
this.database = data; this.database = data;
this.ip = plugin.getIP(player); this.ip = plugin.getIP(player);
this.settings = settings;
} }
protected boolean needsCaptcha() { protected boolean needsCaptcha() {
@ -98,7 +105,7 @@ public class AsynchronousLogin {
msg = m.retrieve(MessageKey.REGISTER_MESSAGE); msg = m.retrieve(MessageKey.REGISTER_MESSAGE);
} }
BukkitTask msgT = Bukkit.getScheduler().runTaskAsynchronously(plugin, BukkitTask msgT = Bukkit.getScheduler().runTaskAsynchronously(plugin,
new MessageTask(plugin, name, msg, Settings.getWarnMessageInterval)); new MessageTask(plugin, name, msg, settings.getProperty(RegistrationSettings.MESSAGE_INTERVAL)));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
} }
return null; return null;
@ -165,12 +172,10 @@ public class AsynchronousLogin {
if (!forceLogin) if (!forceLogin)
m.send(player, MessageKey.LOGIN_SUCCESS); m.send(player, MessageKey.LOGIN_SUCCESS);
displayOtherAccounts(auth, player); displayOtherAccounts(auth);
if (Settings.recallEmail) { if (Settings.recallEmail && (StringUtils.isEmpty(email) || "your@email.com".equalsIgnoreCase(email))) {
if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) { m.send(player, MessageKey.EMAIL_ADDED_SUCCESS);
m.send(player, MessageKey.EMAIL_ADDED_SUCCESS);
}
} }
if (!Settings.noConsoleSpam) { if (!Settings.noConsoleSpam) {
@ -186,7 +191,7 @@ public class AsynchronousLogin {
// 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.
ProcessSyncPlayerLogin syncPlayerLogin = new ProcessSyncPlayerLogin(player, plugin, database); ProcessSyncPlayerLogin syncPlayerLogin = new ProcessSyncPlayerLogin(player, plugin, database, settings);
if (syncPlayerLogin.getLimbo() != null) { if (syncPlayerLogin.getLimbo() != null) {
if (syncPlayerLogin.getLimbo().getTimeoutTaskId() != null) { if (syncPlayerLogin.getLimbo().getTimeoutTaskId() != null) {
syncPlayerLogin.getLimbo().getTimeoutTaskId().cancel(); syncPlayerLogin.getLimbo().getTimeoutTaskId().cancel();
@ -215,7 +220,7 @@ public class AsynchronousLogin {
} }
} }
public void displayOtherAccounts(PlayerAuth auth, Player p) { public void displayOtherAccounts(PlayerAuth auth) {
if (!Settings.displayOtherAccounts) { if (!Settings.displayOtherAccounts) {
return; return;
} }
@ -223,30 +228,16 @@ public class AsynchronousLogin {
return; return;
} }
List<String> auths = this.database.getAllAuthsByName(auth); List<String> auths = this.database.getAllAuthsByName(auth);
if (auths.isEmpty()) { if (auths.isEmpty() || auths.size() == 1) {
return; return;
} }
if (auths.size() == 1) { String message = "[AuthMe] " + StringUtils.join(", ", auths) + ".";
return;
}
StringBuilder message = new StringBuilder("[AuthMe] ");
int i = 0;
for (String account : auths) {
i++;
message.append(account);
if (i != auths.size()) {
message.append(", ");
} else {
message.append('.');
}
}
for (Player player : Utils.getOnlinePlayers()) { for (Player player : Utils.getOnlinePlayers()) {
if (plugin.getPermissionsManager().hasPermission(player, PlayerPermission.SEE_OTHER_ACCOUNTS) if (plugin.getPermissionsManager().hasPermission(player, PlayerPermission.SEE_OTHER_ACCOUNTS)
|| (player.getName().equals(this.player.getName()) || (player.getName().equals(this.player.getName())
&& plugin.getPermissionsManager().hasPermission(player, PlayerPermission.SEE_OWN_ACCOUNTS))) { && plugin.getPermissionsManager().hasPermission(player, PlayerPermission.SEE_OWN_ACCOUNTS))) {
player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts"); player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts");
player.sendMessage(message.toString()); player.sendMessage(message);
} }
} }
} }

View File

@ -1,5 +1,7 @@
package fr.xephi.authme.process.login; package fr.xephi.authme.process.login;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.properties.HooksSettings;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -24,6 +26,8 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils;
import fr.xephi.authme.util.Utils.GroupType; import fr.xephi.authme.util.Utils.GroupType;
import static fr.xephi.authme.settings.properties.RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN;
/** /**
*/ */
public class ProcessSyncPlayerLogin implements Runnable { public class ProcessSyncPlayerLogin implements Runnable {
@ -36,24 +40,26 @@ public class ProcessSyncPlayerLogin implements Runnable {
private final DataSource database; private final DataSource database;
private final PluginManager pm; private final PluginManager pm;
private final JsonCache playerCache; private final JsonCache playerCache;
private final NewSetting settings;
/** /**
* Constructor for ProcessSyncPlayerLogin. * Constructor for ProcessSyncPlayerLogin.
* *
* @param player Player * @param player Player
* @param plugin AuthMe * @param plugin AuthMe
* @param data DataSource * @param database DataSource
*/ */
public ProcessSyncPlayerLogin(Player player, AuthMe plugin, public ProcessSyncPlayerLogin(Player player, AuthMe plugin,
DataSource data) { DataSource database, NewSetting settings) {
this.plugin = plugin; this.plugin = plugin;
this.database = data; this.database = database;
this.pm = plugin.getServer().getPluginManager(); this.pm = plugin.getServer().getPluginManager();
this.player = player; this.player = player;
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
this.limbo = LimboCache.getInstance().getLimboPlayer(name); this.limbo = LimboCache.getInstance().getLimboPlayer(name);
this.auth = database.getAuth(name); this.auth = database.getAuth(name);
this.playerCache = new JsonCache(); this.playerCache = new JsonCache();
this.settings = settings;
} }
/** /**
@ -152,7 +158,7 @@ public class ProcessSyncPlayerLogin implements Runnable {
} }
} }
if (Settings.protectInventoryBeforeLogInEnabled) { if (settings.getProperty(PROTECT_INVENTORY_BEFORE_LOGIN)) {
restoreInventory(); restoreInventory();
} }
@ -188,27 +194,27 @@ public class ProcessSyncPlayerLogin implements Runnable {
// Login is finish, display welcome message if we use email registration // Login is finish, display welcome message if we use email registration
if (Settings.useWelcomeMessage && Settings.emailRegistration) if (Settings.useWelcomeMessage && Settings.emailRegistration)
if (Settings.broadcastWelcomeMessage) { if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) { for (String s : settings.getWelcomeMessage()) {
Bukkit.getServer().broadcastMessage(plugin.replaceAllInfo(s, player)); Bukkit.getServer().broadcastMessage(plugin.replaceAllInfo(s, player));
} }
} else { } else {
for (String s : Settings.welcomeMsg) { for (String s : settings.getWelcomeMessage()) {
player.sendMessage(plugin.replaceAllInfo(s, player)); player.sendMessage(plugin.replaceAllInfo(s, player));
} }
} }
// Login is now finish , we can force all commands // Login is now finished; we can force all commands
forceCommands(); forceCommands();
sendTo(); sendTo();
} }
private void sendTo() { private void sendTo() {
if (Settings.sendPlayerTo.isEmpty()) if (!settings.getProperty(HooksSettings.BUNGEECORD_SERVER).isEmpty()) {
return; ByteArrayDataOutput out = ByteStreams.newDataOutput();
ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect");
out.writeUTF("Connect"); out.writeUTF(settings.getProperty(HooksSettings.BUNGEECORD_SERVER));
out.writeUTF(Settings.sendPlayerTo); player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); }
} }
} }

View File

@ -9,6 +9,7 @@ import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages; import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -24,8 +25,10 @@ public class AsyncRegister {
private final AuthMe plugin; private final AuthMe plugin;
private final DataSource database; private final DataSource database;
private final Messages m; private final Messages m;
private final NewSetting settings;
public AsyncRegister(Player player, String password, String email, AuthMe plugin, DataSource data) { public AsyncRegister(Player player, String password, String email, AuthMe plugin, DataSource data,
NewSetting settings) {
this.m = plugin.getMessages(); this.m = plugin.getMessages();
this.player = player; this.player = player;
this.password = password; this.password = password;
@ -34,6 +37,7 @@ public class AsyncRegister {
this.plugin = plugin; this.plugin = plugin;
this.database = data; this.database = data;
this.ip = plugin.getIP(player); this.ip = plugin.getIP(player);
this.settings = settings;
} }
private boolean preRegisterCheck() throws Exception { private boolean preRegisterCheck() throws Exception {
@ -137,7 +141,7 @@ public class AsyncRegister {
plugin.getManagement().performLogin(player, "dontneed", true); plugin.getManagement().performLogin(player, "dontneed", true);
} }
plugin.otherAccounts.addPlayer(player.getUniqueId()); plugin.otherAccounts.addPlayer(player.getUniqueId());
ProcessSyncPasswordRegister sync = new ProcessSyncPasswordRegister(player, plugin); ProcessSyncPasswordRegister sync = new ProcessSyncPasswordRegister(player, plugin, settings);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, sync); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, sync);
} }
} }

View File

@ -1,5 +1,7 @@
package fr.xephi.authme.process.register; package fr.xephi.authme.process.register;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.properties.HooksSettings;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
@ -30,6 +32,7 @@ public class ProcessSyncPasswordRegister implements Runnable {
protected final String name; protected final String name;
private final AuthMe plugin; private final AuthMe plugin;
private final Messages m; private final Messages m;
private final NewSetting settings;
/** /**
* Constructor for ProcessSyncPasswordRegister. * Constructor for ProcessSyncPasswordRegister.
@ -37,11 +40,12 @@ public class ProcessSyncPasswordRegister implements Runnable {
* @param player Player * @param player Player
* @param plugin AuthMe * @param plugin AuthMe
*/ */
public ProcessSyncPasswordRegister(Player player, AuthMe plugin) { public ProcessSyncPasswordRegister(Player player, AuthMe plugin, NewSetting settings) {
this.m = plugin.getMessages(); this.m = plugin.getMessages();
this.player = player; this.player = player;
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
this.plugin = plugin; this.plugin = plugin;
this.settings = settings;
} }
private void sendBungeeMessage() { private void sendBungeeMessage() {
@ -63,11 +67,6 @@ public class ProcessSyncPasswordRegister implements Runnable {
} }
} }
/**
* Method forceLogin.
*
* @param player Player
*/
private void forceLogin(Player player) { private void forceLogin(Player player) {
Utils.teleportToSpawn(player); Utils.teleportToSpawn(player);
LimboCache cache = LimboCache.getInstance(); LimboCache cache = LimboCache.getInstance();
@ -88,11 +87,6 @@ public class ProcessSyncPasswordRegister implements Runnable {
} }
} }
/**
* Method run.
*
* @see java.lang.Runnable#run()
*/
@Override @Override
public void run() { public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
@ -141,11 +135,11 @@ public class ProcessSyncPasswordRegister 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.useWelcomeMessage) {
if (Settings.broadcastWelcomeMessage) { if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) { for (String s : settings.getWelcomeMessage()) {
plugin.getServer().broadcastMessage(plugin.replaceAllInfo(s, player)); plugin.getServer().broadcastMessage(plugin.replaceAllInfo(s, player));
} }
} else { } else {
for (String s : Settings.welcomeMsg) { for (String s : settings.getWelcomeMessage()) {
player.sendMessage(plugin.replaceAllInfo(s, player)); player.sendMessage(plugin.replaceAllInfo(s, player));
} }
} }
@ -161,18 +155,18 @@ public class ProcessSyncPasswordRegister implements Runnable {
sendBungeeMessage(); sendBungeeMessage();
} }
// Register is now finish , we can force all commands // Register is now finished; we can force all commands
forceCommands(); forceCommands();
sendTo(); sendTo();
} }
private void sendTo() { private void sendTo() {
if (Settings.sendPlayerTo.isEmpty()) if (!settings.getProperty(HooksSettings.BUNGEECORD_SERVER).isEmpty()) {
return; ByteArrayDataOutput out = ByteStreams.newDataOutput();
ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect");
out.writeUTF("Connect"); out.writeUTF(settings.getProperty(HooksSettings.BUNGEECORD_SERVER));
out.writeUTF(Settings.sendPlayerTo); player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); }
} }
} }

View File

@ -1,9 +1,11 @@
package fr.xephi.authme.settings; package fr.xephi.authme.settings;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.Files;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.settings.properties.SettingsFieldRetriever; import fr.xephi.authme.settings.properties.SettingsFieldRetriever;
import fr.xephi.authme.settings.propertymap.PropertyMap; import fr.xephi.authme.settings.propertymap.PropertyMap;
import fr.xephi.authme.util.CollectionUtils; import fr.xephi.authme.util.CollectionUtils;
@ -16,6 +18,7 @@ import org.yaml.snakeyaml.Yaml;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -31,7 +34,10 @@ public class NewSetting {
private final File pluginFolder; private final File pluginFolder;
private final File configFile; private final File configFile;
private FileConfiguration configuration; private FileConfiguration configuration;
/** The file with the localized messages based on {@link PluginSettings#MESSAGES_LANGUAGE}. */
private File messagesFile; private File messagesFile;
private List<String> welcomeMessage;
private String emailMessage;
/** /**
* Constructor. Checks the given {@link FileConfiguration} object for completeness. * Constructor. Checks the given {@link FileConfiguration} object for completeness.
@ -45,6 +51,8 @@ public class NewSetting {
this.configFile = configFile; this.configFile = configFile;
this.pluginFolder = pluginFolder; this.pluginFolder = pluginFolder;
messagesFile = buildMessagesFile(); messagesFile = buildMessagesFile();
welcomeMessage = readWelcomeMessage();
emailMessage = readEmailMessage();
PropertyMap propertyMap = SettingsFieldRetriever.getAllPropertyFields(); PropertyMap propertyMap = SettingsFieldRetriever.getAllPropertyFields();
if (SettingsMigrationService.checkAndMigrate(configuration, propertyMap, pluginFolder)) { if (SettingsMigrationService.checkAndMigrate(configuration, propertyMap, pluginFolder)) {
@ -110,6 +118,14 @@ public class NewSetting {
return messagesFile; return messagesFile;
} }
public String getEmailMessage() {
return emailMessage;
}
public List<String> getWelcomeMessage() {
return welcomeMessage;
}
/** /**
* Reload the configuration. * Reload the configuration.
*/ */
@ -189,6 +205,54 @@ public class NewSetting {
makePath("messages", "messages_" + language + ".yml")); makePath("messages", "messages_" + language + ".yml"));
} }
private List<String> readWelcomeMessage() {
if (getProperty(RegistrationSettings.USE_WELCOME_MESSAGE)) {
final File welcomeFile = new File(pluginFolder, "welcome.txt");
final Charset charset = Charset.forName("UTF-8");
if (!welcomeFile.exists()) {
try {
Files.write(
"Welcome {PLAYER} to {SERVER} server\n\nThis server uses AuthMe protection!",
welcomeFile, charset);
} catch (IOException e) {
ConsoleLogger.showError("Failed to create file '" + welcomeFile.getPath() + "': "
+ StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
}
}
try {
return Files.readLines(welcomeFile, charset);
} catch (IOException e) {
ConsoleLogger.showError("Failed to read file '" + welcomeFile.getPath() + "': " +
StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
}
}
return new ArrayList<>(0);
}
private String readEmailMessage() {
final File emailFile = new File(pluginFolder, "email.txt");
final Charset charset = Charset.forName("UTF-8");
if (!emailFile.exists()) {
try {
Files.write("", emailFile, charset);
} catch (IOException e) {
ConsoleLogger.showError("Failed to create file '" + emailFile.getPath() + "': "
+ StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
}
}
try {
return StringUtils.join("", Files.readLines(emailFile, charset));
} catch (IOException e) {
ConsoleLogger.showError("Failed to read file '" + emailFile.getPath() + "': " +
StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
}
return "";
}
private static Yaml newYaml(boolean useSingleQuotes) { private static Yaml newYaml(boolean useSingleQuotes) {
DumperOptions options = new DumperOptions(); DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

View File

@ -1,13 +1,10 @@
package fr.xephi.authme.settings; package fr.xephi.authme.settings;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DataSource.DataSourceType; import fr.xephi.authme.datasource.DataSource.DataSourceType;
import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.util.StringUtils;
import fr.xephi.authme.util.Wrapper; import fr.xephi.authme.util.Wrapper;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -30,12 +27,10 @@ public final class Settings {
public static final File PLUGIN_FOLDER = Wrapper.getInstance().getDataFolder(); public static final File PLUGIN_FOLDER = Wrapper.getInstance().getDataFolder();
public static final File MODULE_FOLDER = new File(PLUGIN_FOLDER, "modules"); public static final File MODULE_FOLDER = new File(PLUGIN_FOLDER, "modules");
public static final File CACHE_FOLDER = new File(PLUGIN_FOLDER, "cache"); public static final File CACHE_FOLDER = new File(PLUGIN_FOLDER, "cache");
private static final File EMAIL_FILE = new File(PLUGIN_FOLDER, "email.html");
private static final File SETTINGS_FILE = new File(PLUGIN_FOLDER, "config.yml"); private static final File SETTINGS_FILE = new File(PLUGIN_FOLDER, "config.yml");
public static final File LOG_FILE = new File(PLUGIN_FOLDER, "authme.log"); public static final File LOG_FILE = new File(PLUGIN_FOLDER, "authme.log");
// This is not an option! // This is not an option!
public static boolean antiBotInAction = false; public static boolean antiBotInAction = false;
public static File messageFile;
public static List<String> allowCommands; public static List<String> allowCommands;
public static List<String> getJoinPermissions; public static List<String> getJoinPermissions;
public static List<String> getUnrestrictedName; public static List<String> getUnrestrictedName;
@ -48,7 +43,6 @@ public final class Settings {
public static List<String> forceCommandsAsConsole; public static List<String> forceCommandsAsConsole;
public static List<String> forceRegisterCommands; public static List<String> forceRegisterCommands;
public static List<String> forceRegisterCommandsAsConsole; public static List<String> forceRegisterCommandsAsConsole;
public static List<String> welcomeMsg;
public static List<String> unsafePasswords; public static List<String> unsafePasswords;
public static List<String> emailBlacklist; public static List<String> emailBlacklist;
public static List<String> emailWhitelist; public static List<String> emailWhitelist;
@ -85,11 +79,10 @@ public final class Settings {
backupWindowsPath, getRegisteredGroup, backupWindowsPath, getRegisteredGroup,
messagesLanguage, getMySQLlastlocX, getMySQLlastlocY, messagesLanguage, getMySQLlastlocX, getMySQLlastlocY,
getMySQLlastlocZ, rakamakUsers, rakamakUsersIp, getmailAccount, getMySQLlastlocZ, rakamakUsers, rakamakUsersIp, getmailAccount,
getmailPassword, getmailSMTP, getMySQLColumnId, getmailSenderName, getMySQLColumnId, getMySQLlastlocWorld, defaultWorld,
getMailSubject, getMailText, getMySQLlastlocWorld, defaultWorld,
getPhpbbPrefix, getWordPressPrefix, getMySQLColumnLogged, getPhpbbPrefix, getWordPressPrefix, getMySQLColumnLogged,
spawnPriority, crazyloginFileName, getPassRegex, spawnPriority, crazyloginFileName, getPassRegex,
getMySQLColumnRealName, emailOauth2Token, sendPlayerTo; getMySQLColumnRealName, sendPlayerTo;
public static int getWarnMessageInterval, getSessionTimeout, public static int getWarnMessageInterval, getSessionTimeout,
getRegistrationTimeout, getMaxNickLength, getMinNickLength, getRegistrationTimeout, getMaxNickLength, getMinNickLength,
getPasswordMinLen, getMovementRadius, getmaxRegPerIp, getPasswordMinLen, getMovementRadius, getmaxRegPerIp,
@ -129,7 +122,6 @@ public final class Settings {
if (exist) { if (exist) {
instance.saveDefaults(); instance.saveDefaults();
} }
messageFile = new File(PLUGIN_FOLDER, "messages" + File.separator + "messages_" + messagesLanguage + ".yml");
} }
public static void loadVariables() { public static void loadVariables() {
@ -217,19 +209,14 @@ public final class Settings {
noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", false); noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", 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", "");
getmailSMTP = configFile.getString("Email.mailSMTP", "smtp.gmail.com");
getMailPort = configFile.getInt("Email.mailPort", 465); getMailPort = configFile.getInt("Email.mailPort", 465);
getRecoveryPassLength = configFile.getInt("Email.RecoveryPasswordLength", 8); getRecoveryPassLength = configFile.getInt("Email.RecoveryPasswordLength", 8);
getMySQLOtherUsernameColumn = configFile.getStringList("ExternalBoardOptions.mySQLOtherUsernameColumns"); getMySQLOtherUsernameColumn = configFile.getStringList("ExternalBoardOptions.mySQLOtherUsernameColumns");
displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true); displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true);
getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id"); getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id");
getmailSenderName = configFile.getString("Email.mailSenderName", "");
useCaptcha = configFile.getBoolean("Security.captcha.useCaptcha", false); useCaptcha = configFile.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", "Your new AuthMe Password");
getMailText = loadEmailText();
emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false); emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false);
saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8); saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8);
getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1);
@ -288,25 +275,8 @@ public final class Settings {
generateImage = configFile.getBoolean("Email.generateImage", false); generateImage = configFile.getBoolean("Email.generateImage", false);
preventOtherCase = configFile.getBoolean("settings.preventOtherCase", false); preventOtherCase = configFile.getBoolean("settings.preventOtherCase", false);
kickPlayersBeforeStopping = configFile.getBoolean("Security.stop.kickPlayersBeforeStopping", true); kickPlayersBeforeStopping = configFile.getBoolean("Security.stop.kickPlayersBeforeStopping", true);
emailOauth2Token = configFile.getString("Email.emailOauth2Token", "");
sendPlayerTo = configFile.getString("Hooks.sendPlayerTo", ""); sendPlayerTo = configFile.getString("Hooks.sendPlayerTo", "");
// Load the welcome message
getWelcomeMessage();
}
private static String loadEmailText() {
if (!EMAIL_FILE.exists()) {
plugin.saveResource("email.html", false);
}
try {
return Files.toString(EMAIL_FILE, Charsets.UTF_8);
} catch (IOException e) {
ConsoleLogger.showError("Error loading email text: " + StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
return "";
}
} }
/** /**
@ -388,37 +358,6 @@ public final class Settings {
} }
} }
private static void getWelcomeMessage() {
AuthMe plugin = AuthMe.getInstance();
welcomeMsg = new ArrayList<>();
if (!useWelcomeMessage) {
return;
}
if (!(new File(plugin.getDataFolder() + File.separator + "welcome.txt").exists())) {
try {
FileWriter fw = new FileWriter(plugin.getDataFolder() + File.separator + "welcome.txt", true);
BufferedWriter w = new BufferedWriter(fw);
w.write("Welcome {PLAYER} on {SERVER} server");
w.newLine();
w.write("This server uses " + AuthMe.getPluginName() + " protection!");
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileReader fr = new FileReader(plugin.getDataFolder() + File.separator + "welcome.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
welcomeMsg.add(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/** /**
* Saves current configuration (plus defaults) to disk. * Saves current configuration (plus defaults) to disk.
* <p> * <p>