diff options
Diffstat (limited to 'src/main/java')
15 files changed, 2315 insertions, 0 deletions
diff --git a/src/main/java/net/elytrium/limboauth/LimboAuth.java b/src/main/java/net/elytrium/limboauth/LimboAuth.java new file mode 100644 index 0000000..a901bc2 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/LimboAuth.java @@ -0,0 +1,371 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth; + +import com.google.inject.Inject; +import com.google.inject.name.Named; +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.field.FieldType; +import com.j256.ormlite.jdbc.JdbcPooledConnectionSource; +import com.j256.ormlite.table.TableUtils; +import com.velocitypowered.api.command.CommandManager; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.plugin.Dependency; +import com.velocitypowered.api.plugin.Plugin; +import com.velocitypowered.api.plugin.PluginContainer; +import com.velocitypowered.api.plugin.annotation.DataDirectory; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Path; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import net.elytrium.limboapi.api.Limbo; +import net.elytrium.limboapi.api.LimboFactory; +import net.elytrium.limboapi.api.chunk.Dimension; +import net.elytrium.limboapi.api.chunk.VirtualWorld; +import net.elytrium.limboapi.api.file.SchematicFile; +import net.elytrium.limboapi.api.file.WorldFile; +import net.elytrium.limboauth.command.ChangePasswordCommand; +import net.elytrium.limboauth.command.DestroySessionCommand; +import net.elytrium.limboauth.command.ForceUnregisterCommand; +import net.elytrium.limboauth.command.LimboAuthCommand; +import net.elytrium.limboauth.command.TotpCommand; +import net.elytrium.limboauth.command.UnregisterCommand; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.listener.AuthListener; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.elytrium.limboauth.utils.UpdatesChecker; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.slf4j.Logger; + +@Plugin( + id = "limboauth", + name = "LimboAuth", + version = BuildConstants.AUTH_VERSION, + url = "https://elytrium.net/", + authors = {"hevav", "mdxd44"}, + dependencies = {@Dependency(id = "limboapi")} +) +public class LimboAuth { + + private static LimboAuth instance; + + private final HttpClient client = HttpClient.newHttpClient(); + private final Path dataDirectory; + private final Logger logger; + private final ProxyServer server; + private final LimboFactory factory; + + private Dao<RegisteredPlayer, String> playerDao; + private Limbo authServer; + private Map<String, CachedUser> cachedAuthChecks; + private Component nicknameInvalid; + private Pattern nicknameValidationPattern; + + @Inject + @SuppressWarnings("OptionalGetWithoutIsPresent") + public LimboAuth(ProxyServer server, Logger logger, @Named("limboapi") PluginContainer factory, @DataDirectory Path dataDirectory) { + setInstance(this); + + this.server = server; + this.logger = logger; + this.dataDirectory = dataDirectory; + this.factory = (LimboFactory) factory.getInstance().get(); + } + + @Subscribe + public void onProxyInitialization(ProxyInitializeEvent event) throws SQLException { + System.setProperty("com.j256.simplelogging.level", "ERROR"); + + this.reload(); + + UpdatesChecker.checkForUpdates(this.getLogger()); + } + + @SuppressWarnings("SwitchStatementWithTooFewBranches") + public void reload() throws SQLException { + Settings.IMP.reload(new File(this.dataDirectory.toFile().getAbsoluteFile(), "config.yml")); + + this.cachedAuthChecks = new ConcurrentHashMap<>(); + + Settings.DATABASE dbConfig = Settings.IMP.DATABASE; + + JdbcPooledConnectionSource connectionSource; + // requireNonNull prevents the shade plugin from excluding the drivers in minimized jar. + switch (dbConfig.STORAGE_TYPE.toLowerCase(Locale.ROOT)) { + case "h2": { + Objects.requireNonNull(org.h2.Driver.class); + Objects.requireNonNull(org.h2.engine.Engine.class); + connectionSource = new JdbcPooledConnectionSource("jdbc:h2:" + this.dataDirectory.toFile().getAbsoluteFile() + "/" + "limboauth"); + break; + } + case "mysql": { + Objects.requireNonNull(com.mysql.cj.jdbc.Driver.class); + Objects.requireNonNull(com.mysql.cj.conf.url.SingleConnectionUrl.class); + connectionSource = new JdbcPooledConnectionSource( + "jdbc:mysql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD + ); + break; + } + case "postgresql": { + Objects.requireNonNull(org.postgresql.Driver.class); + connectionSource = new JdbcPooledConnectionSource( + "jdbc:postgresql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD + ); + break; + } + default: { + this.getLogger().error("WRONG DATABASE TYPE."); + this.server.shutdown(); + return; + } + } + + TableUtils.createTableIfNotExists(connectionSource, RegisteredPlayer.class); + this.playerDao = DaoManager.createDao(connectionSource, RegisteredPlayer.class); + this.nicknameValidationPattern = Pattern.compile(Settings.IMP.MAIN.ALLOWED_NICKNAME_REGEX); + + this.migrateDb(this.playerDao); + + CommandManager manager = this.server.getCommandManager(); + manager.unregister("unregister"); + manager.unregister("forceunregister"); + manager.unregister("changepassword"); + manager.unregister("destroysession"); + manager.unregister("2fa"); + manager.unregister("limboauth"); + + manager.register("unregister", new UnregisterCommand(this, this.playerDao), "unreg"); + manager.register("forceunregister", new ForceUnregisterCommand(this, this.server, this.playerDao), "forceunreg"); + manager.register("changepassword", new ChangePasswordCommand(this.playerDao), "changepass"); + manager.register("destroysession", new DestroySessionCommand(this)); + if (Settings.IMP.MAIN.ENABLE_TOTP) { + manager.register("2fa", new TotpCommand(this.playerDao), "totp"); + } + manager.register("limboauth", new LimboAuthCommand(), "la", "auth", "lauth"); + + Settings.MAIN.AUTH_COORDS authCoords = Settings.IMP.MAIN.AUTH_COORDS; + VirtualWorld authWorld = this.factory.createVirtualWorld( + Dimension.valueOf(Settings.IMP.MAIN.DIMENSION), + authCoords.X, authCoords.Y, authCoords.Z, + (float) authCoords.YAW, (float) authCoords.PITCH + ); + + if (Settings.IMP.MAIN.LOAD_WORLD) { + try { + Path path = this.dataDirectory.resolve(Settings.IMP.MAIN.WORLD_FILE_PATH); + WorldFile file; + switch (Settings.IMP.MAIN.WORLD_FILE_TYPE) { + case "schematic": { + file = new SchematicFile(path); + break; + } + default: { + this.getLogger().error("Incorrect world file type."); + this.server.shutdown(); + return; + } + } + + Settings.MAIN.WORLD_COORDS coords = Settings.IMP.MAIN.WORLD_COORDS; + file.toWorld(this.factory, authWorld, coords.X, coords.Y, coords.Z); + } catch (IOException e) { + e.printStackTrace(); + } + } + + this.authServer = this.factory.createLimbo(authWorld); + + this.nicknameInvalid = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NICKNAME_INVALID); + + this.server.getEventManager().unregisterListeners(this); + this.server.getEventManager().register(this, new AuthListener(this.playerDao)); + + Executors.newScheduledThreadPool(1, task -> new Thread(task, "purge-cache")).scheduleAtFixedRate(() -> + this.checkCache(this.cachedAuthChecks, Settings.IMP.MAIN.PURGE_CACHE_MILLIS), + Settings.IMP.MAIN.PURGE_CACHE_MILLIS, + Settings.IMP.MAIN.PURGE_CACHE_MILLIS, + TimeUnit.MILLISECONDS + ); + } + + public void migrateDb(Dao<RegisteredPlayer, String> playerDao) { + Set<FieldType> tables = new HashSet<>(); + Collections.addAll(tables, playerDao.getTableInfo().getFieldTypes()); + + String findSql; + switch (Settings.IMP.DATABASE.STORAGE_TYPE) { + case "h2": { + findSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + + playerDao.getTableInfo().getTableName() + "';"; + break; + } + case "postgresql": + case "mysql": { + findSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" + Settings.IMP.DATABASE.DATABASE + + "' AND TABLE_NAME = '" + playerDao.getTableInfo().getTableName() + "';"; + break; + } + default: { + this.getLogger().error("WRONG DATABASE TYPE."); + this.server.shutdown(); + return; + } + } + + try { + playerDao.queryRaw(findSql).forEach(e -> tables.removeIf(q -> q.getColumnName().equalsIgnoreCase(e[0]))); + + tables.forEach(t -> { + try { + String columnDefinition = t.getColumnDefinition(); + StringBuilder builder = new StringBuilder("ALTER TABLE `auth` ADD "); + List<String> dummy = new ArrayList<>(); + if (columnDefinition == null) { + playerDao.getConnectionSource().getDatabaseType().appendColumnArg(t.getTableName(), builder, t, dummy, dummy, dummy, dummy); + } else { + playerDao.getConnectionSource().getDatabaseType().appendEscapedEntityName(builder, t.getColumnName()); + builder.append(" ").append(columnDefinition).append(" "); + } + + playerDao.executeRawNoArgs(builder.toString()); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void cacheAuthUser(Player player) { + String username = player.getUsername(); + this.cachedAuthChecks.remove(username); + this.cachedAuthChecks.put(username, new CachedUser(player.getRemoteAddress().getAddress(), System.currentTimeMillis())); + } + + public void removePlayerFromCache(Player player) { + this.cachedAuthChecks.remove(player.getUsername()); + } + + public boolean needAuth(Player player) { + String username = player.getUsername(); + + if (!this.cachedAuthChecks.containsKey(username)) { + return true; + } + + return !this.cachedAuthChecks.get(username).getInetAddress().equals(player.getRemoteAddress().getAddress()); + } + + public void authPlayer(Player player) { + String nickname = player.getUsername(); + if (!this.nicknameValidationPattern.matcher(nickname).matches()) { + player.disconnect(this.nicknameInvalid); + return; + } + + if (!Settings.IMP.MAIN.ONLINE_MODE_NEED_AUTH && player.isOnlineMode()) { + RegisteredPlayer registeredPlayer = AuthSessionHandler.fetchInfo(this.playerDao, player.getUsername()); + + if (registeredPlayer == null || registeredPlayer.getHash().isEmpty()) { + this.factory.passLoginLimbo(player); + return; + } + } + + // Send player to auth virtual server. + try { + this.authServer.spawnPlayer(player, new AuthSessionHandler(this.playerDao, player, nickname)); + } catch (Throwable t) { + this.getLogger().error("Error", t); + } + } + + public boolean isPremium(String nickname) { + try { + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(String.format(Settings.IMP.MAIN.ISPREMIUM_AUTH_URL, nickname))) + .build(); + HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString()); + return response.statusCode() == 200; + } catch (IOException | InterruptedException e) { + this.getLogger().error("Unable to authenticate with Mojang", e); + return true; + } + } + + public Logger getLogger() { + return this.logger; + } + + private void checkCache(Map<String, CachedUser> userMap, long time) { + userMap.entrySet().stream() + .filter(u -> u.getValue().getCheckTime() + time <= System.currentTimeMillis()) + .map(Map.Entry::getKey) + .forEach(userMap::remove); + } + + private static void setInstance(LimboAuth instance) { + LimboAuth.instance = instance; + } + + public static LimboAuth getInstance() { + return instance; + } + + private static class CachedUser { + + private final InetAddress inetAddress; + private final long checkTime; + + public CachedUser(InetAddress inetAddress, long checkTime) { + this.inetAddress = inetAddress; + this.checkTime = checkTime; + } + + public InetAddress getInetAddress() { + return this.inetAddress; + } + + public long getCheckTime() { + return this.checkTime; + } + } +} diff --git a/src/main/java/net/elytrium/limboauth/Settings.java b/src/main/java/net/elytrium/limboauth/Settings.java new file mode 100644 index 0000000..9e59830 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/Settings.java @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth; + +import java.io.File; +import net.elytrium.limboauth.config.Config; + +public class Settings extends Config { + + @Ignore + public static final Settings IMP = new Settings(); + + @Final + public String VERSION = BuildConstants.AUTH_VERSION; + + public String PREFIX = "LimboAuth &6>>&f"; + + @Create + public MAIN MAIN; + + public static class MAIN { + + public boolean ENABLE_BOSSBAR = true; + public boolean ONLINE_MODE_NEED_AUTH = true; + public boolean FORCE_OFFLINE_UUID = false; + @Comment({ + "Forcibly set player's UUID to the value from the database", + "If the player had the cracked account, and switched to the premium account, the cracked UUID will be used." + }) + public boolean SAVE_UUID = true; + public boolean ENABLE_TOTP = true; + public boolean TOTP_NEED_PASSWORD = true; + public boolean REGISTER_NEED_REPEAT_PASSWORD = true; + public boolean CHANGE_PASSWORD_NEED_OLD_PASSWORD = true; + @Comment({ + "If you want to migrate your database from another plugin, which is not using BCrypt", + "You can set an old hash algorithm to migrate from. Currently, only AUTHME is supported yet" + }) + public String MIGRATION_HASH = ""; + @Comment("Available dimensions: OVERWORLD, NETHER, THE_END") + public String DIMENSION = "THE_END"; + public long PURGE_CACHE_MILLIS = 3600000; + @Comment("QR Generator URL, set {data} placeholder") + public String QR_GENERATOR_URL = "https://api.qrserver.com/v1/create-qr-code/?data={data}&size=200x200&ecc=M&margin=30"; + public String TOTP_ISSUER = "LimboAuth by Elytrium"; + public int BCRYPT_COST = 10; + public int LOGIN_ATTEMPTS = 3; + public int IP_LIMIT_REGISTRATIONS = 3; + public int TOTP_RECOVERY_CODES_AMOUNT = 16; + @Comment("Time in milliseconds, when ip limit works, set to 0 for disable") + public long IP_LIMIT_VALID_TIME = 21600000; + @Comment({ + "Regex of allowed nicknames", + "^ means the start of the line, $ means the end of the line", + "[A-Za-z0-9_] is a character set of A-Z, a-z, 0-9 and _", + "{3,16} means that allowed length is from 3 to 16 chars" + }) + public String ALLOWED_NICKNAME_REGEX = "^[A-Za-z0-9_]{3,16}$"; + + public boolean LOAD_WORLD = false; + @Comment("World file type: schematic") + public String WORLD_FILE_TYPE = "schematic"; + public String WORLD_FILE_PATH = "world.schematic"; + @Comment({ + "Custom isPremium URL", + "You can use Mojang one's API (set by default)", + "Or CloudFlare one's: https://api.ashcon.app/mojang/v1/user/%s", + "Or use this code to make your own API: https://blog.cloudflare.com/minecraft-api-with-workers-coffeescript/", + "Or implement your own API, it should just respond with HTTP code 200 only if the player is premium" + }) + public String ISPREMIUM_AUTH_URL = "https://api.mojang.com/users/profiles/minecraft/%s"; + + @Create + public Settings.MAIN.WORLD_COORDS WORLD_COORDS; + + public static class WORLD_COORDS { + + public int X = 0; + public int Y = 0; + public int Z = 0; + } + + @Create + public MAIN.STRINGS STRINGS; + + //@Comment("Leave empty to disable.") + public static class STRINGS { + + public String RELOAD = "{PRFX} &aReloaded successfully!"; + public String RELOAD_FAILED = "{PRFX} &cReload failed, check console for details."; + public String ERROR_OCCURRED = "{PRFX} &cAn internal error has occurred!"; + + public String NOT_PLAYER = "{PRFX} &cСonsole is not allowed to execute this command!"; + public String NOT_REGISTERED = "{PRFX} &cYou are not registered!"; + public String WRONG_PASSWORD = "{PRFX} &cPassword is wrong!"; + + public String NICKNAME_INVALID = "{NL}{NL}&cYour nickname contains forbidden characters. Please, change your nickname!"; + @Comment("6 hours by default in ip-limit-valid-time") + public String IP_LIMIT = "{PRFX} &cYour IP has reached max registered accounts. If this is an error, restart your router, or wait about 6 hours."; + public String WRONG_NICKNAME_CASE = "{NL}{NL}&cThe case of your nickname is wrong. Nickname is CaSe SeNsItIvE."; + + public String LOGIN = "{PRFX} Please, login using &6/login &6<password>. You have &6{0} &cattempts."; + public String LOGIN_SUCCESS = "{PRFX} &aSuccessfully logged in!"; + public String LOGIN_WRONG_PASSWORD = "{PRFX} &cYou've entered the wrong password. You have &6{0} &cattempts left."; + public String LOGIN_TITLE = ""; + public String LOGIN_SUBTITLE = ""; + public String LOGIN_SUCCESS_TITLE = ""; + public String LOGIN_SUCCESS_SUBTITLE = ""; + + @Comment("Or if register-need-repeat-password set to false remove the \"<repeat password>\" part.") + public String REGISTER = "{PRFX} Please, register using &6/register <password> <repeat password>"; + public String REGISTER_TITLE = ""; + public String REGISTER_SUBTITLE = ""; + public String DIFFERENT_PASSWORDS = "{PRFX} The entered passwords differ from each other."; + public String KICK_PASSWORD_WRONG = "{NL}{NL}&cYou've entered the wrong password numerous times!"; + + public String UNREGISTER_SUCCESSFUL = "{PRFX}{NL}{NL}&aSuccessfully unregistered!"; + public String UNREGISTER_USAGE = "{PRFX} Usage: &6/unregister <current password> confirm"; + + public String FORCE_UNREGISTER_SUCCESSFUL = "{PRFX} &a{0} successfully unregistered!"; + public String FORCE_UNREGISTER_SUCCESSFUL_PLAYER = "{PRFX}{NL}{NL}&aYou have been unregistered by administrator!"; + public String FORCE_UNREGISTER_NOT_SUCCESSFUL = "{PRFX} &cUnable to unregister {0}. Most likely this player has never been on this server."; + public String FORCE_UNREGISTER_USAGE = "{PRFX} Usage: &6/forceunregister <nickname>"; + + public String CHANGE_PASSWORD_SUCCESSFUL = "{PRFX} &aSuccessfully changed password!"; + @Comment("Or if change-password-need-old-pass set to false remove the \"<old password>\" part.") + public String CHANGE_PASSWORD_USAGE = "{PRFX} Usage: &6/changepassword <old password> <new password>"; + + public String TOTP = "{PRFX} Please, enter your 2FA key using &6/2fa <key>"; + public String TOTP_SUCCESSFUL = "{PRFX} &aSuccessfully enabled 2FA!"; + public String TOTP_DISABLED = "{PRFX} &aSuccessfully disabled 2FA!"; + @Comment("Or if totp-need-pass set to false remove the \"<current password>\" part.") + public String TOTP_USAGE = "{PRFX} Usage: &6/2fa enable <current password>&f or &6/2fa disable <totp key>&f."; + public String TOTP_WRONG = "{PRFX} &cWrong 2FA key!"; + public String TOTP_ALREADY_ENABLED = "{PRFX} &c2FA is already enabled. Disable it using &6/2fa disable <key>&c."; + public String TOTP_QR = "{PRFX} Click here to open 2FA QR code in browser."; + public String TOTP_TOKEN = "{PRFX} &aYour 2FA token &7(Click to copy)&a: &6{0}"; + public String TOTP_RECOVERY = "{PRFX} &aYour recovery codes &7(Click to copy)&a: &6{0}"; + + public String DESTROY_SESSION_SUCCESSFUL = "{PRFX} &eYour session is now destroyed, you'll need to log in again after reconnecting."; + } + + @Create + public MAIN.AUTH_COORDS AUTH_COORDS; + + public static class AUTH_COORDS { + + public double X = 0; + public double Y = 0; + public double Z = 0; + public double YAW = 0; + public double PITCH = 0; + } + } + + @Create + public DATABASE DATABASE; + + @Comment("Database settings") + public static class DATABASE { + + @Comment("Database type: mysql, postgresql or h2.") + public String STORAGE_TYPE = "h2"; + + @Comment("Settings for Network-based database (like MySQL, PostgreSQL): ") + public String HOSTNAME = "127.0.0.1:3306"; + public String USER = "user"; + public String PASSWORD = "password"; + public String DATABASE = "limboauth"; + public String CONNECTION_PARAMETERS = "?autoReconnect=true&initialTimeout=1&useSSL=false"; + } + + public void reload(File file) { + if (this.load(file, this.PREFIX)) { + this.save(file); + } else { + this.save(file); + this.load(file, this.PREFIX); + } + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java b/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java new file mode 100644 index 0000000..2373938 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/ChangePasswordCommand.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.UpdateBuilder; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import java.sql.SQLException; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.handler.AuthSessionHandler; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class ChangePasswordCommand implements SimpleCommand { + + private final Dao<RegisteredPlayer, String> playerDao; + + private final Component notPlayer; + private final boolean needOldPass; + private final Component notRegistered; + private final Component wrongPassword; + private final Component successful; + private final Component errorOccurred; + private final Component usage; + + public ChangePasswordCommand(Dao<RegisteredPlayer, String> playerDao) { + this.playerDao = playerDao; + + this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); + this.needOldPass = Settings.IMP.MAIN.CHANGE_PASSWORD_NEED_OLD_PASSWORD; + this.notRegistered = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_REGISTERED); + this.wrongPassword = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.WRONG_PASSWORD); + this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.CHANGE_PASSWORD_SUCCESSFUL); + this.errorOccurred = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.ERROR_OCCURRED); + this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.CHANGE_PASSWORD_USAGE); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + + if (!(source instanceof Player)) { + source.sendMessage(this.notPlayer); + return; + } + + if (this.needOldPass ? args.length == 2 : args.length == 1) { + if (this.needOldPass) { + RegisteredPlayer player = AuthSessionHandler.fetchInfo(this.playerDao, ((Player) source).getUsername()); + if (player == null) { + source.sendMessage(this.notRegistered); + return; + } else if (!AuthSessionHandler.checkPassword(args[0], player, this.playerDao)) { + source.sendMessage(this.wrongPassword); + return; + } + } + + try { + UpdateBuilder<RegisteredPlayer, String> updateBuilder = this.playerDao.updateBuilder(); + updateBuilder.where().eq("nickname", ((Player) source).getUsername()); + updateBuilder.updateColumnValue("hash", AuthSessionHandler.genHash(this.needOldPass ? args[1] : args[0])); + updateBuilder.update(); + + source.sendMessage(this.successful); + } catch (SQLException e) { + source.sendMessage(this.errorOccurred); + e.printStackTrace(); + } + + return; + } + + source.sendMessage(this.usage); + } + + @Override + public boolean hasPermission(SimpleCommand.Invocation invocation) { + return invocation.source().getPermissionValue("limboauth.commands.changepassword") != Tristate.FALSE; + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java b/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java new file mode 100644 index 0000000..27dff72 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/DestroySessionCommand.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.permission.Tristate; +import com.velocitypowered.api.proxy.Player; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class DestroySessionCommand implements SimpleCommand { + + private final LimboAuth plugin; + + private final Component notPlayer; + private final Component successful; + + public DestroySessionCommand(LimboAuth plugin) { + this.plugin = plugin; + + this.notPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.NOT_PLAYER); + this.successful = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.DESTROY_SESSION_SUCCESSFUL); + } + + @Override + public void execute(SimpleCommand.Invocation invocation) { + CommandSource source = invocation.source(); + + if (!(source instanceof Player)) { + source.sendMessage(this.notPlayer); + return; + } + + this.plugin.removePlayerFromCache((Player) source); + source.sendMessage(this.successful); + } + + @Override + public boolean hasPermission(SimpleCommand.Invocation invocation) { + return invocation.source().getPermissionValue("limboauth.commands.destroysession") != Tristate.FALSE; + } +} diff --git a/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java b/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java new file mode 100644 index 0000000..d45eae9 --- /dev/null +++ b/src/main/java/net/elytrium/limboauth/command/ForceUnregisterCommand.java @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2021 Elytrium + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package net.elytrium.limboauth.command; + +import com.google.common.collect.ImmutableList; +import com.j256.ormlite.dao.Dao; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import net.elytrium.limboauth.LimboAuth; +import net.elytrium.limboauth.Settings; +import net.elytrium.limboauth.model.RegisteredPlayer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; + +public class ForceUnregisterCommand implements SimpleCommand { + + private final LimboAuth plugin; + private final ProxyServer server; + private final Dao<RegisteredPlayer, String> playerDao; + + private final Component successfulPlayer; + private final String successful; + private final String notSuccessful; + private final Component usage; + + public ForceUnregisterCommand(LimboAuth plugin, ProxyServer server, Dao<RegisteredPlayer, String> playerDao) { + this.plugin = plugin; + this.server = server; + this.playerDao = playerDao; + + this.successfulPlayer = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_SUCCESSFUL_PLAYER); + this.successful = Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_SUCCESSFUL; + this.notSuccessful = Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_NOT_SUCCESSFUL; + this.usage = LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.FORCE_UNREGISTER_USAGE); + } + + @Override + public List<String> suggest(SimpleCommand.Invocation invocation) { + String[] args = invocation.arguments(); + + if (args.length == 0) { + return this.server.getAllPlayers().stream() + .map(Player::getUsername) + .collect(Collectors.toList()); + } else if (args.length == 1) { + return this.server.getAllPlayers().stream() + .map(Player::getUsername) + .filter(str -> str.regionMatches(true, 0, args[0], 0, args[0].length())) + .collect(Collectors.toList()); + } + + return ImmutableList.of(); + } |
