Add initial project setup and core functionality

This commit introduces the WebInterface plugin with core modules, including a login command, reload command, and event listener for player bans. Gradle build files, configuration management, and supporting scripts (gradlew) are also included to enable project setup and build automation.
This commit is contained in:
Teriuihi 2025-05-03 03:20:46 +02:00
commit d928ea4b87
13 changed files with 870 additions and 0 deletions

43
.gitignore vendored Normal file
View File

@ -0,0 +1,43 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
/.idea/

25
build.gradle.kts Normal file
View File

@ -0,0 +1,25 @@
plugins {
id("java")
}
group = "com.alttd.webinterface"
version = "1.0-SNAPSHOT"
description = "WebInterface"
repositories {
mavenCentral()
maven("https://nexus.velocitypowered.com/repository/maven-public/")
maven("https://jitpack.io") //Litebans
}
dependencies {
compileOnly("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT") // Velocity
annotationProcessor("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT")
compileOnly("com.gitlab.ruany:LiteBansAPI:0.6.1")
compileOnly("org.projectlombok:lombok:1.18.30")
annotationProcessor("org.projectlombok:lombok:1.18.30")
}
tasks.test {
useJUnitPlatform()
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Sat May 03 02:13:55 CEST 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
settings.gradle.kts Normal file
View File

@ -0,0 +1,2 @@
rootProject.name = "WebInterface"

View File

@ -0,0 +1,43 @@
package com.alttd.webinterface;
import com.alttd.webinterface.commands.Login;
import com.alttd.webinterface.commands.Reload;
import com.alttd.webinterface.config.Config;
import com.alttd.webinterface.listeners.ProxyPlayerListener;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.proxy.ProxyServer;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Plugin(id = "webinterface", name = "WebInterface", version = "1.0.0",
description = "A plugin to manage web interactions.",
authors = {"akastijn"}
)
public class WebInterface {
private final ProxyServer server;
@Inject
public WebInterface(ProxyServer proxyServer) {
server = proxyServer;
}
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
reloadConfig();
server.getEventManager().register(this, new ProxyPlayerListener());
loadCommands();
}
public void reloadConfig() {
Config.init();
log.info("Reloaded ShutdownInfo config.");
}
public void loadCommands() {// all (proxy)commands go here
new Reload(server, this);
new Login(server);
}
}

View File

@ -0,0 +1,53 @@
package com.alttd.webinterface.commands;
import com.alttd.webinterface.config.Config;
import com.alttd.webinterface.web_interact.AuthService;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.tree.LiteralCommandNode;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.command.CommandMeta;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.jetbrains.annotations.NotNull;
public class Login {
public Login(ProxyServer proxyServer) {
LiteralCommandNode<CommandSource> commandStart = LiteralArgumentBuilder
.<CommandSource>literal("login")
.requires(ctx -> ctx.hasPermission("command.proxy.login"))
.executes(context -> {
if (!(context.getSource() instanceof Player player)) {
context.getSource().sendMessage(MiniMessage.miniMessage().deserialize("<red>You must be a player to use this command.</red>"));
return 0;
}
AuthService.getLoginCodeAsync(player.getUniqueId()).thenAccept(optionalLoginCode -> {
optionalLoginCode.ifPresentOrElse((loginCode) -> {
player.sendMessage(MiniMessage.miniMessage().deserialize(Config.YOUR_LOGIN_CODE, resolveLogin(loginCode)));
}, () -> {
player.sendMessage(MiniMessage.miniMessage().deserialize("<red>Failed to get login code.</red>"));
});
});
return 1;
})
.build();
BrigadierCommand brigadierCommandStart = new BrigadierCommand(commandStart);
CommandMeta.Builder metaBuilderStart = proxyServer.getCommandManager().metaBuilder(brigadierCommandStart);
CommandMeta metaStart = metaBuilderStart.build();
proxyServer.getCommandManager().register(metaStart, brigadierCommandStart);
}
private @NotNull TagResolver resolveLogin(String loginCode) {
return TagResolver.resolver(
Placeholder.unparsed("login_endpoint", Config.LOGIN_ENDPOINT),
Placeholder.unparsed("code", loginCode)
);
}
}

View File

@ -0,0 +1,31 @@
package com.alttd.webinterface.commands;
import com.alttd.webinterface.WebInterface;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.tree.LiteralCommandNode;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.command.CommandMeta;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.ProxyServer;
public class Reload {
public Reload(ProxyServer proxyServer, WebInterface webInterface) {
LiteralCommandNode<CommandSource> command = LiteralArgumentBuilder
.<CommandSource>literal("webreload")
.requires(ctx -> ctx.hasPermission("command.proxy.webreload"))
.executes(context -> {
webInterface.reloadConfig();
return 1;
})
.build();
BrigadierCommand brigadierCommand = new BrigadierCommand(command);
CommandMeta.Builder metaBuilder = proxyServer.getCommandManager().metaBuilder(brigadierCommand);
CommandMeta meta = metaBuilder.build();
proxyServer.getCommandManager().register(meta, brigadierCommand);
}
}

View File

@ -0,0 +1,216 @@
package com.alttd.webinterface.config;
import com.google.common.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.ConfigurationOptions;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
import org.yaml.snakeyaml.DumperOptions;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@Slf4j
public final class Config {
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
private static final String HEADER = "";
private static final String PLUGIN_NAME = "WebInterface";
private static File CONFIG_FILE;
public static ConfigurationNode config;
public static YAMLConfigurationLoader configLoader;
static int version;
static boolean verbose;
public static File CONFIGPATH;
public static void init() {
CONFIGPATH = new File(File.separator + "mnt" + File.separator + "configs" + File.separator + PLUGIN_NAME);
CONFIG_FILE = new File(CONFIGPATH, "config.yml");
configLoader = YAMLConfigurationLoader.builder()
.setFile(CONFIG_FILE)
.setFlowStyle(DumperOptions.FlowStyle.BLOCK)
.build();
if (!CONFIG_FILE.getParentFile().exists()) {
if (!CONFIG_FILE.getParentFile().mkdirs()) {
return;
}
}
if (!CONFIG_FILE.exists()) {
try {
if (!CONFIG_FILE.createNewFile()) {
return;
}
} catch (IOException error) {
log.error("Failed to create config file", error);
}
}
try {
config = configLoader.load(ConfigurationOptions.defaults().setHeader(HEADER));
} catch (IOException e) {
log.error("Failed to load config file", e);
}
verbose = getBoolean("verbose", true);
version = getInt("config-version", 1);
readConfig(Config.class, null);
try {
configLoader.save(config);
} catch (IOException e) {
log.error("Failed to save config file", e);
}
}
public static void readConfig(Class<?> clazz, Object instance) {
for (Method method : clazz.getDeclaredMethods()) {
if (Modifier.isPrivate(method.getModifiers())) {
if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE) {
try {
method.setAccessible(true);
method.invoke(instance);
} catch (InvocationTargetException | IllegalAccessException ex) {
throw (RuntimeException) ex.getCause();
}
}
}
}
try {
configLoader.save(config);
} catch (IOException ex) {
throw (RuntimeException) ex.getCause();
}
}
public static void saveConfig() {
try {
configLoader.save(config);
} catch (IOException ex) {
throw (RuntimeException) ex.getCause();
}
}
private static Object[] splitPath(String key) {
return PATH_PATTERN.split(key);
}
private static void set(String path, Object def) {
if (config.getNode(splitPath(path)).isVirtual())
config.getNode(splitPath(path)).setValue(def);
}
private static void setString(String path, String def) {
try {
if (config.getNode(splitPath(path)).isVirtual())
config.getNode(splitPath(path)).setValue(TypeToken.of(String.class), def);
} catch (ObjectMappingException ignored) {
}
}
private static boolean getBoolean(String path, boolean def) {
set(path, def);
return config.getNode(splitPath(path)).getBoolean(def);
}
private static double getDouble(String path, double def) {
set(path, def);
return config.getNode(splitPath(path)).getDouble(def);
}
private static int getInt(String path, int def) {
set(path, def);
return config.getNode(splitPath(path)).getInt(def);
}
private static String getString(String path, String def) {
setString(path, def);
return config.getNode(splitPath(path)).getString(def);
}
private static Long getLong(String path, Long def) {
set(path, def);
return config.getNode(splitPath(path)).getLong(def);
}
private static <T> List<String> getList(String path, T def) {
try {
set(path, def);
return config.getNode(splitPath(path)).getList(TypeToken.of(String.class));
} catch (ObjectMappingException ignored) {
}
return new ArrayList<>();
}
private static ConfigurationNode getNode(String path) {
if (config.getNode(splitPath(path)).isVirtual()) {
//new RegexConfig("Dummy");
}
config.getChildrenMap();
return config.getNode(splitPath(path));
}
/** ONLY EDIT ANYTHING BELOW THIS LINE **/
public static String BASE_MESSAGE = """
<gray><st>-----</st><dark_gray><st>[--</st></dark_gray></gray><red> Banned </red><gray><dark_gray><st>--]</st></dark_gray><st>-----</st></gray>
<dark_gray>Banned on<dark_gray><gray>: <date_start></gray>
<dark_gray>Banned by<dark_gray><gray>: <executor></gray>
<dark_gray>Reason<dark_gray><gray>: <reason></gray>
<gray><st>-----</st><dark_gray><st>[--</st></dark_gray></gray> <gray><dark_gray><st>--]</st></dark_gray><st>-----</st></gray>
""";
public static String TEMP_BAN = """
<base>
<red>Expires in <duration>.</red>
<red>You will be given another chance.
<appeal_message>
""";
public static String PERM_BAN = """
<base>
<red>You are permanently banned!</red>
<appeal_message>
""";
public static String APPEAL_MESSAGE = """
<dark_gray>Appeal</dark_gray><gray>: alttd.com/appeal/<code>
""";
private static void banned_messages() {
BASE_MESSAGE = getString("messages.ban-message", BASE_MESSAGE);
TEMP_BAN = getString("messages.temp-ban", TEMP_BAN);
PERM_BAN = getString("messages.perm-ban", PERM_BAN);
APPEAL_MESSAGE = getString("messages.appeal-message", APPEAL_MESSAGE);
}
public static String YOUR_LOGIN_CODE = "<green>Log in on <gold><click:open_url:'<login_endpoint>/<code>'>alttd.com</click>" +
"</gold> with code: <code></green>";
private static void login_messages() {
YOUR_LOGIN_CODE = getString("messages.your-login-code", YOUR_LOGIN_CODE);
}
public static String LOGIN_CODE_ENDPOINT = "https://alttd.com/auth/get_login_code/<uuid>";
public static String LOGIN_ENDPOINT = "https://alttd.com/login";
public static String SECRET = "";
private static void site() {
if (SECRET.isEmpty()) {
byte[] randomBytes = new byte[256];
new java.security.SecureRandom().nextBytes(randomBytes);
SECRET = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(randomBytes);
config.getNode("secret").setValue(SECRET);
}
SECRET = getString("secret", SECRET);
LOGIN_ENDPOINT = getString("login-endpoint", LOGIN_ENDPOINT);
LOGIN_CODE_ENDPOINT = getString("login-code-endpoint", LOGIN_CODE_ENDPOINT);
}
}

View File

@ -0,0 +1,75 @@
package com.alttd.webinterface.listeners;
import com.alttd.webinterface.config.Config;
import com.alttd.webinterface.web_interact.AuthService;
import com.velocitypowered.api.event.ResultedEvent;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.LoginEvent;
import com.velocitypowered.api.proxy.Player;
import litebans.api.Database;
import litebans.api.Entry;
import lombok.extern.slf4j.Slf4j;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
@Slf4j
public class ProxyPlayerListener {
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
public ProxyPlayerListener() {
}
@Subscribe
public void playerLogin(@NotNull LoginEvent event) {
final Player player = event.getPlayer();
final UUID uuid = player.getUniqueId();
boolean playerBanned = Database.get().isPlayerBanned(uuid, null);
if (!playerBanned) {
return;
}
Entry ban = Database.get().getBan(uuid, null, null);
if (ban == null) {
throw new IllegalStateException("Ban is null");
}
String displayMessage = ban.isPermanent() ? Config.PERM_BAN : Config.TEMP_BAN;
try {
miniMessage.deserialize(displayMessage, TagResolver.resolver(
Placeholder.component("base", miniMessage.deserialize(Config.BASE_MESSAGE, resolveBase(ban))),
Placeholder.component("appeal_message", miniMessage.deserialize(Config.APPEAL_MESSAGE,
resolveAppealMessage(uuid))),
Placeholder.unparsed("duration", Instant.ofEpochMilli(ban.getDateEnd()).toString())));
} catch (IllegalStateException e) {
log.error("Failed to deserialize ban message", e);
event.setResult(ResultedEvent.ComponentResult.denied(miniMessage.deserialize(
"<red>Unable to display punishment and appeal code, please contact us via email at appeal@alttd.com</red>")));
return;
}
event.setResult(ResultedEvent.ComponentResult.denied(miniMessage.deserialize(ban.getReason())));
}
private static @NotNull TagResolver resolveAppealMessage(UUID uuid) {
Optional<String> optionalLoginCode = AuthService.getLoginCodeAsync(uuid).join();
if (optionalLoginCode.isEmpty()) {
throw new IllegalStateException("Login code is not present");
}
return TagResolver.resolver(Placeholder.unparsed("code", optionalLoginCode.get()));
}
private static @NotNull TagResolver resolveBase(Entry ban) {
return TagResolver.resolver(
Placeholder.unparsed("date_start", Instant.ofEpochMilli(ban.getDateStart()).toString()),
Placeholder.unparsed("executor", ban.getExecutorName() == null ? "Unknown" : ban.getExecutorName()),
Placeholder.unparsed("reason", ban.getReason())
);
}
}

View File

@ -0,0 +1,53 @@
package com.alttd.webinterface.web_interact;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import com.alttd.webinterface.config.Config;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
@Slf4j
public class AuthService {
/**
* Asynchronously sends a GET request to the login endpoint with the required authorization header.
*
* @param uuid The UUID to insert into the login endpoint URL
* @return A CompletableFuture containing an Optional with the response body if status is 200,
* or an empty Optional otherwise
*/
public static @NotNull CompletableFuture<Optional<String>> getLoginCodeAsync(UUID uuid) {
String loginUrl = Config.LOGIN_CODE_ENDPOINT.replaceAll("<uuid>", uuid.toString());
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(loginUrl))
.header("Authorization", "SECRET " + Config.SECRET)
.GET()
.build();
return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() == 200) {
String body = response.body();
return Optional.ofNullable(body);
} else {
log.error("Failed to get login code. Status code: {}", response.statusCode());
return Optional.<String>empty();
}
})
.exceptionally(e -> {
log.error("Exception occurred while getting login code", e);
return Optional.empty();
});
}
}
}