From b0c613daf3bd32ee966c462a0ed1b9694d9eb955 Mon Sep 17 00:00:00 2001 From: sebivh Date: Tue, 14 Oct 2025 13:24:20 +0200 Subject: [PATCH] init commit --- .gitignore | 5 + build.gradle.kts | 32 +++ gradlew | 234 ++++++++++++++++++ gradlew.bat | 89 +++++++ settings.gradle.kts | 9 + .../de/sebastianvonhelmersen/AuthInfos.java | 32 +++ .../de/sebastianvonhelmersen/AuthState.java | 8 + .../de/sebastianvonhelmersen/Database.java | 64 +++++ .../java/de/sebastianvonhelmersen/Ldap.java | 102 ++++++++ .../de/sebastianvonhelmersen/LdapUser.java | 32 +++ .../de/sebastianvonhelmersen/fetmcplugin.java | 187 ++++++++++++++ src/main/resources/plugin.yml | 11 + 12 files changed, 805 insertions(+) create mode 100644 .gitignore create mode 100644 build.gradle.kts create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle.kts create mode 100644 src/main/java/de/sebastianvonhelmersen/AuthInfos.java create mode 100644 src/main/java/de/sebastianvonhelmersen/AuthState.java create mode 100644 src/main/java/de/sebastianvonhelmersen/Database.java create mode 100644 src/main/java/de/sebastianvonhelmersen/Ldap.java create mode 100644 src/main/java/de/sebastianvonhelmersen/LdapUser.java create mode 100644 src/main/java/de/sebastianvonhelmersen/fetmcplugin.java create mode 100644 src/main/resources/plugin.yml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..75b7c48 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +build +.gradle +.idea +gradle/wrapper +.DS_Store diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..ffbd4c1 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,32 @@ +plugins { + id("java") + kotlin("jvm") +} + +group = "org.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() + maven { + name = "papermc" + url = uri("https://repo.papermc.io/repository/maven-public/") + } +} + +dependencies { + testImplementation(platform("org.junit:junit-bom:5.10.0")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + implementation(kotlin("stdlib-jdk8")) + implementation("org.xerial:sqlite-jdbc:3.50.3.0") +} + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(21)) +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..07dae01 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,9 @@ +pluginManagement { + plugins { + kotlin("jvm") version "2.2.0" + } +} +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} +rootProject.name = "fetmcplugin" \ No newline at end of file diff --git a/src/main/java/de/sebastianvonhelmersen/AuthInfos.java b/src/main/java/de/sebastianvonhelmersen/AuthInfos.java new file mode 100644 index 0000000..5d9a664 --- /dev/null +++ b/src/main/java/de/sebastianvonhelmersen/AuthInfos.java @@ -0,0 +1,32 @@ +package de.sebastianvonhelmersen; + +import java.util.UUID; + +public class AuthInfos { + private UUID uuid; + private AuthState state; + private String username = null; + private Database db; + + public AuthInfos(Database db, UUID uuid) { + this.uuid = uuid; + assert db != null; + this.db = db; + this.state = checkState(); + } + + /** + * Checks the authstate in the Database + * @return The determined AuthState + */ + private AuthState checkState() { + return db.isAuthenticated(this.uuid.toString()) ? AuthState.AUTHENTICATED : AuthState.AUTH_WAITING_USERNAME; + } + public void setUsername(String username) { + this.username = username; + this.state = AuthState.AUTH_WAITING_PASSWORD; + } + public AuthState getState() { return this.state; } + public String getUsername() { return this.username; } + public void reset() { this.state = AuthState.AUTH_WAITING_USERNAME; } +} diff --git a/src/main/java/de/sebastianvonhelmersen/AuthState.java b/src/main/java/de/sebastianvonhelmersen/AuthState.java new file mode 100644 index 0000000..d3dd102 --- /dev/null +++ b/src/main/java/de/sebastianvonhelmersen/AuthState.java @@ -0,0 +1,8 @@ +package de.sebastianvonhelmersen; + +public enum AuthState { + AUTHENTICATED, + AUTH_FAILED, + AUTH_WAITING_USERNAME, + AUTH_WAITING_PASSWORD +} diff --git a/src/main/java/de/sebastianvonhelmersen/Database.java b/src/main/java/de/sebastianvonhelmersen/Database.java new file mode 100644 index 0000000..0414250 --- /dev/null +++ b/src/main/java/de/sebastianvonhelmersen/Database.java @@ -0,0 +1,64 @@ +package de.sebastianvonhelmersen; + +import java.io.File; +import java.sql.*; + +public class Database { + private Statement statement; + public Database(File dbFile) { + try + { + String path = "jdbc:sqlite:" + dbFile.getAbsolutePath(); + // create a database connection + Connection connection = DriverManager.getConnection(path); + Statement statement = connection.createStatement(); + this.statement = statement; + + statement.setQueryTimeout(30); // set timeout to 30 sec. + + statement.executeUpdate( + "CREATE TABLE IF NOT EXISTS players (" + + "uuid VARCHAR(36) PRIMARY KEY, " + + "uid VARCHAR(50), " + + "mcusername VARCHAR(50), " + + "ladp_username VARCHAR(50), " + + "firstName VARCHAR(50), " + + "lastName VARCHAR(50)," + + "mail VARCHAR(320))" + ); + } + catch(SQLException e) + { + // if the error message is "out of memory", + // it probably means no database file is found + e.printStackTrace(System.err); + } + } + + public boolean isAuthenticated(String uuid) { + String query = "select * from players where uuid = ?"; + try(PreparedStatement prep_query = this.statement.getConnection().prepareStatement(query)){ + prep_query.setString(1, uuid); + ResultSet rs = prep_query.executeQuery(); + return rs.next(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public void addPlayer(String uuid, String mcusername, LdapUser user) { + String query = "insert into players values (?, ?, ?, ?, ?, ?, ?)"; + try(PreparedStatement prep_query = this.statement.getConnection().prepareStatement(query)){ + prep_query.setString(1, uuid); + prep_query.setString(2, String.valueOf(user.uid)); + prep_query.setString(3, mcusername); + prep_query.setString(4, user.ldapName); + prep_query.setString(5, user.firstName); + prep_query.setString(6, user.lastName); + prep_query.setString(7, user.email); + prep_query.executeUpdate(); + } catch ( SQLException e ) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/de/sebastianvonhelmersen/Ldap.java b/src/main/java/de/sebastianvonhelmersen/Ldap.java new file mode 100644 index 0000000..96b8e7c --- /dev/null +++ b/src/main/java/de/sebastianvonhelmersen/Ldap.java @@ -0,0 +1,102 @@ +package de.sebastianvonhelmersen; + +import javax.naming.Context; +import javax.naming.NamingEnumeration; +import javax.naming.directory.*; +import java.util.Hashtable; + +public class Ldap { + + /* + private static final String LDAP_URL = "ldap://192.168.1.11:389"; + private static final String BASE_DN = "dc=authentik,dc=vonhelmersen,dc=online"; + private static final String ADMIN_DN = "cn=akadmin,ou=users,dc=authentik,dc=vonhelmersen,dc=online"; // service account + private static final String ADMIN_PASSWORD = "cuwgoH-9biqto-xiddin"; + */ + + private static final String LDAP_URL = "ldap://juri:389"; + private static final String BASE_DN = "dc=fet,dc=htu,dc=tuwien,dc=ac,dc=at"; + private static final String ADMIN_DN = "cn=admin,dc=fet,dc=htu,dc=tuwien,dc=ac,dc=at"; // service account + public static LdapUser authenticate(String username, String password) { + + try { + // 1. Bind as admin/service account + Hashtable env = new Hashtable<>(); + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + env.put(Context.PROVIDER_URL, LDAP_URL); + env.put(Context.SECURITY_AUTHENTICATION, "simple"); + env.put(Context.SECURITY_PRINCIPAL, ADMIN_DN); + env.put(Context.SECURITY_CREDENTIALS, ADMIN_PASSWORD); + + DirContext ctx = new InitialDirContext(env); + + // 2. Search for user DN + String filter = "(uid=" + escapeLDAPSearchFilter(username) + ")"; + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.SUBTREE_SCOPE); + NamingEnumeration results = ctx.search(BASE_DN, filter, controls); + + if (!results.hasMore()) { + ctx.close(); + return null; // user not found + } + + /* + { + givenname=givenName: Sebastian, + sn=sn: Helmersen, + userpassword=userPassword: [B@2b6cb5b5, + loginshell=loginShell: /bin/bash, + gidnumber=gidNumber: 2000, + uidnumber=uidNumber: 1196, + mail=mail: helmi@fet.at, + objectclass=objectClass: posixAccount, + inetOrgPerson, + organizationalPerson, + person, + uid=uid: helmi, + cn=cn: Sebastian Helmersen, + homedirectory=homeDirectory: /home/helmi + } + */ + // System.out.println("Results: " + results.toString()); + + + SearchResult result = results.next(); + String userDN = result.getNameInNamespace(); + ctx.close(); + + // 3. Try binding with userDN + password + Hashtable authEnv = new Hashtable<>(); + authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + authEnv.put(Context.PROVIDER_URL, LDAP_URL); + authEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); + authEnv.put(Context.SECURITY_PRINCIPAL, userDN); + authEnv.put(Context.SECURITY_CREDENTIALS, password); + + new InitialDirContext(authEnv).close(); // bind attempt + + return new LdapUser(result.getAttributes()); // success + + } catch (Exception e) { + e.printStackTrace(); + return null; // failed (invalid credentials or LDAP error) + } + } + + public static String escapeLDAPSearchFilter(String input) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < input.length(); i++) { + char c = input.charAt(i); + switch (c) { + case '\\': sb.append("\\5c"); break; + case '*': sb.append("\\2a"); break; + case '(': sb.append("\\28"); break; + case ')': sb.append("\\29"); break; + case '\u0000': sb.append("\\00"); break; + default: sb.append(c); + } + } + return sb.toString(); + } +} diff --git a/src/main/java/de/sebastianvonhelmersen/LdapUser.java b/src/main/java/de/sebastianvonhelmersen/LdapUser.java new file mode 100644 index 0000000..034e03c --- /dev/null +++ b/src/main/java/de/sebastianvonhelmersen/LdapUser.java @@ -0,0 +1,32 @@ +package de.sebastianvonhelmersen; + +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class LdapUser { + public String firstName; + public String lastName; + public String email; + public int uid; + public int gid; + public String ldapName; + + public LdapUser(Attributes attributes) { + firstName = trimAttribute(attributes.get("givenname")); + lastName = trimAttribute(attributes.get("sn")); + email = trimAttribute(attributes.get("mail")); + uid = Integer.parseInt(trimAttribute(attributes.get("uidnumber"))); + gid = Integer.parseInt(trimAttribute(attributes.get("gidnumber"))); + ldapName = trimAttribute(attributes.get("uid")); + } + + private String trimAttribute(Attribute raw) { + Pattern pattern = Pattern.compile("^[^:]+:\\s*(.+)$"); + Matcher matcher = pattern.matcher(raw.toString()); + if (!matcher.find()) return ""; + + return matcher.group(1).trim(); + } +} diff --git a/src/main/java/de/sebastianvonhelmersen/fetmcplugin.java b/src/main/java/de/sebastianvonhelmersen/fetmcplugin.java new file mode 100644 index 0000000..28c91b1 --- /dev/null +++ b/src/main/java/de/sebastianvonhelmersen/fetmcplugin.java @@ -0,0 +1,187 @@ +package de.sebastianvonhelmersen; + +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.logging.Level; + +public class fetmcplugin extends JavaPlugin implements Listener { + private Database db; + private Map allInfos = HashMap.newHashMap(0); + + @Override + public void onEnable() { + // Make sure the plugin's data folder exists + File dataFolder = this.getDataFolder(); + + if (!dataFolder.exists()) { + dataFolder.mkdirs(); + } + + // Define the actual SQLite database file + File dbFile = new File(dataFolder, "auth.db"); + + Bukkit.getPluginManager().registerEvents(this, this); + this.db = new Database(dbFile); + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + UUID uuid = event.getPlayer().getUniqueId(); + AuthInfos authInfos = new AuthInfos(db, uuid); + getLogger().log(Level.INFO,"Detected new Player with Auth State " + authInfos.getState().toString()); + + if( authInfos.getState() == AuthState.AUTHENTICATED ) { + return; + } + + allInfos.put(uuid, authInfos); + String greeting = "Hallo, " + event.getPlayer().getName() +"! Willkommen auf dem MC Server der FET!\nBitte registriere dich mit deinen Anmeldedaten um zu beginnen!"; + // Set timings: fadeIn = 0, stay = very long, fadeOut = 0 + event.getPlayer().sendTitlePart(net.kyori.adventure.title.TitlePart.TIMES, + net.kyori.adventure.title.Title.Times.times( + java.time.Duration.ZERO, + java.time.Duration.ofSeconds(9999), // basically "forever" + java.time.Duration.ZERO + ) + ); + + // Send the title text + event.getPlayer().sendTitlePart(net.kyori.adventure.title.TitlePart.TITLE, + Component.text("§cBenutzername")); + + // Send the subtitle text + event.getPlayer().sendTitlePart(net.kyori.adventure.title.TitlePart.SUBTITLE, + Component.text("§eBitte gib den Benutzernamen deines FET Accounts ein!")); + + event.getPlayer().sendMessage(greeting); + event.getPlayer().setGameMode(GameMode.ADVENTURE); + + } + + @EventHandler + public void onPlayerMove(PlayerMoveEvent event) { + UUID uuid = event.getPlayer().getUniqueId(); + event.getPlayer().setAllowFlight(true); + + if ( allInfos.containsKey(uuid) ) { + event.setCancelled(true); + return; + } + } + + @EventHandler + public void onPlayerDamage(EntityDamageEvent event) { + if ( event.getEntity() instanceof Player) { + UUID uuid = event.getEntity().getUniqueId(); + if ( allInfos.containsKey(uuid) ) { + event.setCancelled(true); + return; + } + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent event) { + UUID uuid = event.getPlayer().getUniqueId(); + if ( allInfos.containsKey(uuid) ) { + event.setCancelled(true); + return; + } + } + + @EventHandler + public void onEntityTarget(EntityTargetLivingEntityEvent event) { + if (event.getTarget() instanceof Player) { + UUID uuid = event.getTarget().getUniqueId(); + if ( allInfos.containsKey(uuid) ) { + event.setCancelled(true); + return; + } + } + } + + @EventHandler + public void onChat(AsyncPlayerChatEvent event) { + UUID uuid = event.getPlayer().getUniqueId(); + + if (!allInfos.containsKey(uuid)) { + return; + } + + AuthInfos info = allInfos.get(uuid); + String message = event.getMessage(); + + switch ( info.getState() ) { + case AUTHENTICATED, AUTH_FAILED: + break; + case AUTH_WAITING_USERNAME: + getLogger().log(Level.INFO, "Auth Waiting for Player " + event.getPlayer().getName()); + allInfos.get(uuid).setUsername(message.trim()); + getLogger().log(Level.INFO, "Got Username '" + message.trim() + "'"); + event.setCancelled(true); + event.getRecipients().clear(); + // Send the title text + event.getPlayer().sendTitlePart(net.kyori.adventure.title.TitlePart.TITLE, + Component.text("§cPasswort")); + + // Send the subtitle text + event.getPlayer().sendTitlePart(net.kyori.adventure.title.TitlePart.SUBTITLE, + Component.text("§eBitte gib das Password deines FET Accounts ein!")); + break; + case AUTH_WAITING_PASSWORD: + LdapUser user = checkLdap(info.getUsername(), message.trim()); + event.setCancelled(true); + event.getRecipients().clear(); + if(user != null) { + allInfos.remove(uuid); + this.db.addPlayer(uuid.toString(), event.getPlayer().getName(), user); + Bukkit.getScheduler().runTask(this, () -> { + event.getPlayer().sendMessage( + "Der Account " + event.getPlayer().getName() + " wurde erfolgreich mit dem FET Account " + user.ldapName + " verbunden!\r\n" + + "Danke " + user.firstName + " " + user.lastName + " das du dich für den FET Server angemeldet hast! Ab jetzt kannst du so spielen wie du es gewohnt bist!"); + event.getPlayer().setGameMode(GameMode.SURVIVAL); + event.getPlayer().setHealth(20); + event.getPlayer().setFoodLevel(20); + event.getPlayer().setAllowFlight(false); + event.getPlayer().resetTitle(); + }); + } else { + event.getPlayer().sendMessage("That did not work, please try again!\nPlease enter your Username"); + // Send the title text + event.getPlayer().sendTitlePart(net.kyori.adventure.title.TitlePart.TITLE, + Component.text("§cBenutzername")); + + // Send the subtitle text + event.getPlayer().sendTitlePart(net.kyori.adventure.title.TitlePart.SUBTITLE, + Component.text("§eBitte gib den Benutzernamen deines FET Accounts ein!")); + allInfos.get(uuid).reset(); + } + break; + } + return; + + } + + private LdapUser checkLdap(String username, String password) { + getLogger().log(Level.INFO, "Checking LDAP for user " + username); + return Ldap.authenticate(username, password); + //return true; + } + +} \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..2885115 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,11 @@ +name: FetMCPlugin +version: 1.0.0 +main: de.sebastianvonhelmersen.fetmcplugin +description: Plugin handeling logging in and authorization for FET +author: Sebastian von Helmersen +website: https://sebastianvonhelmersen.de +api-version: '1.21.10' +commands: + fetAuthPlayer: + description: Registriert einen Minecraft UUID + usage: /hello \ No newline at end of file