Code cleaning and optimization

This commit is contained in:
Carlos 2020-06-28 20:05:34 +02:00
parent f177d1fe2d
commit fc4235074b
11 changed files with 223 additions and 268 deletions

View File

@ -1,33 +1,34 @@
package es.mesacarlos.webconsole.auth; package es.mesacarlos.webconsole.auth;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import es.mesacarlos.webconsole.util.Internationalization; import es.mesacarlos.webconsole.config.UserType;
import es.mesacarlos.webconsole.util.Internationalization;
public class User {
private String username; public class ConnectedUser {
private InetSocketAddress socketAddress; private String username;
private UserType userType; private InetSocketAddress socketAddress;
private UserType userType;
public User(InetSocketAddress socketAddress, String username, UserType userType) {
this.socketAddress = socketAddress; public ConnectedUser(InetSocketAddress socketAddress, String username, UserType userType) {
this.username = username; this.socketAddress = socketAddress;
this.userType = userType; this.username = username;
} this.userType = userType;
}
public InetSocketAddress getSocketAddress() {
return socketAddress; public InetSocketAddress getSocketAddress() {
} return socketAddress;
}
public String getUsername() {
return username; public String getUsername() {
} return username;
}
public UserType getUserType() {
return userType; public UserType getUserType() {
} return userType;
}
public String toString() {
return Internationalization.getPhrase("user-tostring", username, socketAddress, userType); public String toString() {
} return Internationalization.getPhrase("user-tostring", username, socketAddress, userType);
}
} }

View File

@ -4,7 +4,7 @@ import java.net.InetSocketAddress;
import java.util.ArrayList; import java.util.ArrayList;
public class LoginManager { public class LoginManager {
private ArrayList<User> loggedInUsers = new ArrayList<User>(); private ArrayList<ConnectedUser> loggedInUsers = new ArrayList<ConnectedUser>();
private static LoginManager instance; private static LoginManager instance;
private LoginManager() {} private LoginManager() {}
@ -19,7 +19,7 @@ public class LoginManager {
* Logs user in * Logs user in
* @param user User to login * @param user User to login
*/ */
public void logIn(User user) { public void logIn(ConnectedUser user) {
loggedInUsers.add(user); loggedInUsers.add(user);
} }
@ -28,7 +28,7 @@ public class LoginManager {
* @param address User to logout * @param address User to logout
*/ */
public void logOut(InetSocketAddress address) { public void logOut(InetSocketAddress address) {
for(User user : loggedInUsers) for(ConnectedUser user : loggedInUsers)
if(user.getSocketAddress().equals(address)) if(user.getSocketAddress().equals(address))
loggedInUsers.remove(user); loggedInUsers.remove(user);
} }
@ -38,8 +38,8 @@ public class LoginManager {
* @param address socket of the user * @param address socket of the user
* @return User object, null if no user logged in from that address * @return User object, null if no user logged in from that address
*/ */
public User getUser(InetSocketAddress address) { public ConnectedUser getUser(InetSocketAddress address) {
for(User user : loggedInUsers) for(ConnectedUser user : loggedInUsers)
if(user.getSocketAddress().equals(address)) if(user.getSocketAddress().equals(address))
return user; return user;
return null; return null;
@ -51,7 +51,7 @@ public class LoginManager {
* @return true if user is logged in, false otherwise * @return true if user is logged in, false otherwise
*/ */
public boolean isLoggedIn(InetSocketAddress address) { public boolean isLoggedIn(InetSocketAddress address) {
for(User user : loggedInUsers) for(ConnectedUser user : loggedInUsers)
if(user.getSocketAddress().equals(address)) if(user.getSocketAddress().equals(address))
return true; return true;
return false; return false;
@ -61,7 +61,7 @@ public class LoginManager {
* Retrieve the full logged-in user list * Retrieve the full logged-in user list
* @return list of logged in users * @return list of logged in users
*/ */
public ArrayList<User> getLoggedInUsers() { public ArrayList<ConnectedUser> getLoggedInUsers() {
return loggedInUsers; return loggedInUsers;
} }

View File

@ -1,52 +0,0 @@
package es.mesacarlos.webconsole.auth;
import es.mesacarlos.webconsole.config.ConfigManager;
import es.mesacarlos.webconsole.config.UserData;
public class PasswordManager {
/**
* Get the user type of a given password
* @param password Password to check
* @return ADMIN if password correspond to a admin user, VIEWER if viewer or UNKNOWN if invalid password
*/
public static UserType isValidUser(String password) {
//Check if is an admin
String username = getAdminUsernameFromPassword(password);
if(username != null)
return UserType.ADMIN;
//Check if is a viewer
username = getViewerUsernameFromPassword(password);
if(username != null)
return UserType.VIEWER;
//He is nothing
return UserType.UNKNOWN;
}
/**
* Check if the provided password corresponds to any admin
* @param password Provided password
* @return Name of the user if password corresponds to a valid admin, null if is a viewer or an invalid password
*/
public static String getAdminUsernameFromPassword(String password) {
for(UserData ud : ConfigManager.getInstance().getAdmins())
if(ud.getPassword().equals(password))
return ud.getUsername();
return null;
}
/**
* Check if the provided password corresponds to any viewer
* @param password Provided password
* @return Name of the user if password corresponds to a valid viewer, null if is a admin or invalid password
*/
public static String getViewerUsernameFromPassword(String password) {
for(UserData ud : ConfigManager.getInstance().getViewers())
if(ud.getPassword().equals(password))
return ud.getUsername();
return null;
}
}

View File

@ -1,7 +0,0 @@
package es.mesacarlos.webconsole.auth;
public enum UserType {
ADMIN,
VIEWER,
UNKNOWN
}

View File

@ -1,122 +1,132 @@
package es.mesacarlos.webconsole.config; package es.mesacarlos.webconsole.config;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import es.mesacarlos.webconsole.WebConsole; import es.mesacarlos.webconsole.WebConsole;
public class ConfigManager { public class ConfigManager {
private static ConfigManager instance; private static ConfigManager instance;
private WebConsole plugin = (WebConsole) Bukkit.getPluginManager().getPlugin("WebConsole"); private WebConsole plugin = (WebConsole) Bukkit.getPluginManager().getPlugin("WebConsole");
private FileConfiguration config = plugin.getConfig(); private FileConfiguration config = plugin.getConfig();
private ConfigManager() { private ConfigManager() {
loadConfig(); loadConfig();
} }
public static ConfigManager getInstance() { public static ConfigManager getInstance() {
if(instance == null) if(instance == null)
instance = new ConfigManager(); instance = new ConfigManager();
return instance; return instance;
} }
/** /**
* Create configuration file or load it if already exist * Create configuration file or load it if already exist
*/ */
private void loadConfig() { private void loadConfig() {
// SSL variables // SSL variables
config.addDefault("useSSL", false); config.addDefault("useSSL", false);
config.addDefault("StoreType", "JKS"); config.addDefault("StoreType", "JKS");
config.addDefault("KeyStore", "plugins/WebConsole/keystore.jks"); config.addDefault("KeyStore", "plugins/WebConsole/keystore.jks");
config.addDefault("StorePassword", "storepassword"); config.addDefault("StorePassword", "storepassword");
config.addDefault("KeyPassword", "keypassword"); config.addDefault("KeyPassword", "keypassword");
// Connection config variables // Connection config variables
config.addDefault("host", "0.0.0.0"); config.addDefault("host", "0.0.0.0");
config.addDefault("port", 8080); config.addDefault("port", 8080);
// Language config // Language config
config.addDefault("language", "en"); config.addDefault("language", "en");
if(config.getConfigurationSection("passwords") == null) { if(config.getConfigurationSection("passwords") == null) {
ConfigurationSection passwordsSection = config.createSection("passwords"); ConfigurationSection passwordsSection = config.createSection("passwords");
ConfigurationSection adminPasswordSection = passwordsSection.createSection("admin"); ConfigurationSection adminPasswordSection = passwordsSection.createSection("admin");
adminPasswordSection.addDefault("user1", "mySecurePassword"); adminPasswordSection.addDefault("user1", "mySecurePassword");
passwordsSection.createSection("viewer"); passwordsSection.createSection("viewer");
} }
config.options().copyDefaults(true); config.options().copyDefaults(true);
plugin.saveConfig(); plugin.saveConfig();
} }
public boolean isSslEnabled() { public boolean isSslEnabled() {
return config.getBoolean("useSSL"); return config.getBoolean("useSSL");
} }
public String getStoreType() { public String getStoreType() {
return config.getString("StoreType"); return config.getString("StoreType");
} }
public String getKeyStore() { public String getKeyStore() {
return config.getString("KeyStore"); return config.getString("KeyStore");
} }
public String getStorePassword() { public String getStorePassword() {
return config.getString("StorePassword"); return config.getString("StorePassword");
} }
public String getKeyPassword() { public String getKeyPassword() {
return config.getString("KeyPassword"); return config.getString("KeyPassword");
} }
/** /**
* Get host and port fields already as InetSocketAddress * Get host and port fields already as InetSocketAddress
* @return InetSocketAddress created from the fields host and port of config.yml * @return InetSocketAddress created from the fields host and port of config.yml
*/ */
public InetSocketAddress getSocketAdress() { public InetSocketAddress getSocketAdress() {
return new InetSocketAddress(config.getString("host"), config.getInt("port")); return new InetSocketAddress(config.getString("host"), config.getInt("port"));
} }
/** /**
* Language code from config.yml * Language code from config.yml
* @return language code * @return language code
*/ */
public String getLanguage() { public String getLanguage() {
return config.getString("language"); return config.getString("language");
} }
/** /**
* Get all admins as a UserData list * Get all admins as a UserData list
* @return list of admin users * @return list of admin users
*/ */
public List<UserData> getAdmins() { private List<UserData> getAdmins() {
Map<String, Object> passwords = plugin.getConfig().getConfigurationSection("passwords").getConfigurationSection("admin").getValues(false); Map<String, Object> passwords = plugin.getConfig().getConfigurationSection("passwords").getConfigurationSection("admin").getValues(false);
List<UserData> adminUsers = new ArrayList<UserData>(); List<UserData> adminUsers = new ArrayList<UserData>();
for(Map.Entry<String, Object> entry : passwords.entrySet()) for(Map.Entry<String, Object> entry : passwords.entrySet())
adminUsers.add(new UserData(entry.getKey(), entry.getValue().toString())); adminUsers.add(new UserData(entry.getKey(), entry.getValue().toString(), UserType.ADMIN));
return adminUsers; return adminUsers;
} }
/** /**
* Get all viewers as a UserData list * Get all viewers as a UserData list
* @return list of viewer users * @return list of viewer users
*/ */
public List<UserData> getViewers() { private List<UserData> getViewers() {
Map<String, Object> passwords = plugin.getConfig().getConfigurationSection("passwords").getConfigurationSection("viewer").getValues(false); Map<String, Object> passwords = plugin.getConfig().getConfigurationSection("passwords").getConfigurationSection("viewer").getValues(false);
List<UserData> viewerUsers = new ArrayList<UserData>(); List<UserData> viewerUsers = new ArrayList<UserData>();
for(Map.Entry<String, Object> entry : passwords.entrySet()) for(Map.Entry<String, Object> entry : passwords.entrySet())
viewerUsers.add(new UserData(entry.getKey(), entry.getValue().toString())); viewerUsers.add(new UserData(entry.getKey(), entry.getValue().toString(), UserType.VIEWER));
return viewerUsers; return viewerUsers;
} }
/**
* Get all registered users
* @return All Admin and Viewer users inside config.yml
*/
public List<UserData> getAllUsers(){
List<UserData> users = getAdmins();
users.addAll(getViewers());
return users;
}
} }

View File

@ -1,19 +1,25 @@
package es.mesacarlos.webconsole.config; package es.mesacarlos.webconsole.config;
public class UserData { public class UserData {
private String username; private String username;
private String password; private String password;
private UserType userType;
public UserData(String username, String password) {
this.username = username; public UserData(String username, String password, UserType userType) {
this.password = password; this.username = username;
} this.password = password;
this.userType = userType;
public String getUsername() { }
return username;
} public String getUsername() {
return username;
public String getPassword() { }
return password;
} public String getPassword() {
return password;
}
public UserType getUserType() {
return userType;
}
} }

View File

@ -0,0 +1,6 @@
package es.mesacarlos.webconsole.config;
public enum UserType {
ADMIN,
VIEWER
}

View File

@ -7,7 +7,7 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import es.mesacarlos.webconsole.auth.LoginManager; import es.mesacarlos.webconsole.auth.LoginManager;
import es.mesacarlos.webconsole.auth.User; import es.mesacarlos.webconsole.auth.ConnectedUser;
import es.mesacarlos.webconsole.util.Internationalization; import es.mesacarlos.webconsole.util.Internationalization;
public class WebConsoleCommand implements CommandExecutor { public class WebConsoleCommand implements CommandExecutor {
@ -22,14 +22,14 @@ public class WebConsoleCommand implements CommandExecutor {
StringBuilder msg = new StringBuilder(); StringBuilder msg = new StringBuilder();
msg.append(Internationalization.getPhrase("webconsole-version", version) + "\n"); msg.append(Internationalization.getPhrase("webconsole-version", version) + "\n");
ArrayList<User> users = LoginManager.getInstance().getLoggedInUsers(); ArrayList<ConnectedUser> users = LoginManager.getInstance().getLoggedInUsers();
if (users.isEmpty()) { if (users.isEmpty()) {
msg.append(Internationalization.getPhrase("webconsole-no-connections")); msg.append(Internationalization.getPhrase("webconsole-no-connections"));
} else { } else {
msg.append(Internationalization.getPhrase("webconsole-active-connections") + "\n"); msg.append(Internationalization.getPhrase("webconsole-active-connections") + "\n");
for (int i = 0; i < users.size(); i++) { for (int i = 0; i < users.size(); i++) {
User user = users.get(i); ConnectedUser user = users.get(i);
msg.append(user.toString()); msg.append(user.toString());
if(i+1 < users.size()) if(i+1 < users.size())
msg.append("\n"); msg.append("\n");

View File

@ -8,8 +8,8 @@ import org.java_websocket.WebSocket;
import es.mesacarlos.webconsole.WebConsole; import es.mesacarlos.webconsole.WebConsole;
import es.mesacarlos.webconsole.auth.LoginManager; import es.mesacarlos.webconsole.auth.LoginManager;
import es.mesacarlos.webconsole.auth.User; import es.mesacarlos.webconsole.auth.ConnectedUser;
import es.mesacarlos.webconsole.auth.UserType; import es.mesacarlos.webconsole.config.UserType;
import es.mesacarlos.webconsole.util.Internationalization; import es.mesacarlos.webconsole.util.Internationalization;
import es.mesacarlos.webconsole.websocket.WSServer; import es.mesacarlos.webconsole.websocket.WSServer;
@ -17,7 +17,7 @@ public class ExecCommand implements WSCommand {
@Override @Override
public void execute(WSServer wsServer, WebSocket conn, String command) { public void execute(WSServer wsServer, WebSocket conn, String command) {
User u = LoginManager.getInstance().getUser(conn.getRemoteSocketAddress()); ConnectedUser u = LoginManager.getInstance().getUser(conn.getRemoteSocketAddress());
if(u == null || u.getUserType() != UserType.ADMIN) { if(u == null || u.getUserType() != UserType.ADMIN) {
if(u != null) if(u != null)
Bukkit.getLogger().warning(Internationalization.getPhrase("viewer-error-console", u, command)); Bukkit.getLogger().warning(Internationalization.getPhrase("viewer-error-console", u, command));

View File

@ -4,9 +4,9 @@ import org.bukkit.Bukkit;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
import es.mesacarlos.webconsole.auth.LoginManager; import es.mesacarlos.webconsole.auth.LoginManager;
import es.mesacarlos.webconsole.auth.PasswordManager; import es.mesacarlos.webconsole.auth.ConnectedUser;
import es.mesacarlos.webconsole.auth.User; import es.mesacarlos.webconsole.config.ConfigManager;
import es.mesacarlos.webconsole.auth.UserType; import es.mesacarlos.webconsole.config.UserData;
import es.mesacarlos.webconsole.util.Internationalization; import es.mesacarlos.webconsole.util.Internationalization;
import es.mesacarlos.webconsole.websocket.WSServer; import es.mesacarlos.webconsole.websocket.WSServer;
import es.mesacarlos.webconsole.websocket.response.LoginRequired; import es.mesacarlos.webconsole.websocket.response.LoginRequired;
@ -20,28 +20,19 @@ public class LogInCommand implements WSCommand {
if (LoginManager.getInstance().isLoggedIn(conn.getRemoteSocketAddress())) if (LoginManager.getInstance().isLoggedIn(conn.getRemoteSocketAddress()))
return; return;
//Check user type and login is password is valid //Check if user exists
switch(PasswordManager.isValidUser(password)) { for(UserData ud : ConfigManager.getInstance().getAllUsers()) {
case ADMIN: if(ud.getPassword().equals(password)) {
login(wsServer, conn, PasswordManager.getAdminUsernameFromPassword(password), UserType.ADMIN); ConnectedUser user = new ConnectedUser(conn.getRemoteSocketAddress(), ud.getUsername(), ud.getUserType());
break; LoginManager.getInstance().logIn(user);
case VIEWER:
login(wsServer, conn, PasswordManager.getViewerUsernameFromPassword(password), UserType.VIEWER); wsServer.sendToClient(conn, new LoggedIn(Internationalization.getPhrase("login-sucessful-message"), "LOGIN ********", user.getUsername(), user.getUserType()));
break; Bukkit.getLogger().info(Internationalization.getPhrase("login-sucessful-console", user.toString()));
default: return;
wsServer.sendToClient(conn, new LoginRequired(Internationalization.getPhrase("login-failed-message"))); }
Bukkit.getLogger().info(Internationalization.getPhrase("login-failed-console", conn.getRemoteSocketAddress()));
break;
} }
wsServer.sendToClient(conn, new LoginRequired(Internationalization.getPhrase("login-failed-message")));
} Bukkit.getLogger().info(Internationalization.getPhrase("login-failed-console", conn.getRemoteSocketAddress()));
private void login(WSServer wsServer, WebSocket conn, String username, UserType as) {
User user = new User(conn.getRemoteSocketAddress(), username, as);
LoginManager.getInstance().logIn(user);
wsServer.sendToClient(conn, new LoggedIn(Internationalization.getPhrase("login-sucessful-message"), "LOGIN ********", user.getUsername(), user.getUserType()));
Bukkit.getLogger().info(Internationalization.getPhrase("login-sucessful-console", user.toString()));
} }
} }

View File

@ -2,7 +2,7 @@ package es.mesacarlos.webconsole.websocket.response;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import es.mesacarlos.webconsole.auth.UserType; import es.mesacarlos.webconsole.config.UserType;
public class LoggedIn implements JSONOutput{ public class LoggedIn implements JSONOutput{
private String message; private String message;