first commit
This commit is contained in:
commit
32b1165bb3
32 changed files with 1763 additions and 0 deletions
43
.gitignore
vendored
Normal file
43
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
.kotlin
|
||||
|
||||
### 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
|
||||
25
build.gradle.kts
Normal file
25
build.gradle.kts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
plugins {
|
||||
java
|
||||
id("com.gradleup.shadow") version "9.3.1" apply false
|
||||
}
|
||||
|
||||
allprojects {
|
||||
group = "dev.loki"
|
||||
version = "0.0.1"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven {
|
||||
name = "papermc"
|
||||
url = uri("https://repo.papermc.io/repository/maven-public/")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
subprojects {
|
||||
apply(plugin = "java")
|
||||
|
||||
java {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(21))
|
||||
}
|
||||
}
|
||||
6
common/build.gradle.kts
Normal file
6
common/build.gradle.kts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
dependencies {
|
||||
implementation("com.zaxxer:HikariCP:7.0.2")
|
||||
implementation("org.postgresql:postgresql:42.7.10")
|
||||
implementation("org.xerial:sqlite-jdbc:3.49.1.0")
|
||||
implementation("org.yaml:snakeyaml:2.3")
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package dev.loki.loAuth.common.cfg;
|
||||
|
||||
public interface DbConfig {
|
||||
String getDbType();
|
||||
String getDbHost();
|
||||
int getDbPort();
|
||||
String getDbName();
|
||||
String getDbUser();
|
||||
String getDbPassword();
|
||||
int getAuthTimeoutSeconds();
|
||||
int getVerificationCodeLength();
|
||||
|
||||
default String getJdbcUrl() {
|
||||
if ("sqlite".equals(getDbType())) {
|
||||
return "jdbc:sqlite:" + getDbName();
|
||||
}
|
||||
return "jdbc:postgresql://" + getDbHost() + ":" + getDbPort() + "/" + getDbName();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package dev.loki.loAuth.common.cfg;
|
||||
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
public final class YamlConfig {
|
||||
|
||||
private final Map<String, Object> data;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public YamlConfig(final Path path) throws IOException {
|
||||
Yaml yaml = new Yaml();
|
||||
try (InputStream in = Files.newInputStream(path)) {
|
||||
Object loaded = yaml.load(in);
|
||||
if (loaded instanceof Map) {
|
||||
this.data = (Map<String, Object>) loaded;
|
||||
} else {
|
||||
throw new IOException("Invalid config format: expected a map at root");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getRequired(final String key, final Class<T> type) {
|
||||
Object val = data.get(key);
|
||||
if (val == null) {
|
||||
throw new IllegalStateException("Missing config key: '" + key + "'");
|
||||
}
|
||||
if (!type.isInstance(val)) {
|
||||
throw new IllegalStateException("Config key '" + key + "' has wrong type: expected " + type.getSimpleName());
|
||||
}
|
||||
return (T) val;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T get(final String key, final T defaultValue) {
|
||||
Object val = data.get(key);
|
||||
if (val == null) return defaultValue;
|
||||
try {
|
||||
return (T) val;
|
||||
} catch (ClassCastException e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,485 @@
|
|||
package dev.loki.loAuth.common.db;
|
||||
|
||||
import dev.loki.loAuth.common.cfg.DbConfig;
|
||||
import dev.loki.loAuth.common.exception.DatabaseException;
|
||||
import dev.loki.loAuth.common.exception.DuplicateUserException;
|
||||
import dev.loki.loAuth.common.model.User;
|
||||
import dev.loki.loAuth.common.util.CodeGenerator;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
import java.sql.*;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class DatabaseManager implements AutoCloseable {
|
||||
|
||||
private final HikariDataSource ds;
|
||||
private final DbConfig cfg;
|
||||
private final boolean sqlite;
|
||||
|
||||
public DatabaseManager(final DbConfig cfg, final String appName, final int maxPoolSize) {
|
||||
this.cfg = cfg;
|
||||
this.sqlite = "sqlite".equals(cfg.getDbType());
|
||||
|
||||
HikariConfig hikari = new HikariConfig();
|
||||
hikari.setJdbcUrl(cfg.getJdbcUrl());
|
||||
|
||||
if (sqlite) {
|
||||
hikari.setDriverClassName("org.sqlite.JDBC");
|
||||
hikari.setMaximumPoolSize(1);
|
||||
hikari.setMinimumIdle(1);
|
||||
hikari.setConnectionTimeout(30_000);
|
||||
hikari.addDataSourceProperty("journal_mode", "WAL");
|
||||
hikari.addDataSourceProperty("busy_timeout", "30000");
|
||||
} else {
|
||||
try {
|
||||
Class.forName("org.postgresql.Driver");
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new RuntimeException("PostgreSQL driver not found", e);
|
||||
}
|
||||
hikari.setUsername(cfg.getDbUser());
|
||||
hikari.setPassword(cfg.getDbPassword());
|
||||
hikari.setMaximumPoolSize(maxPoolSize);
|
||||
hikari.setMinimumIdle(Math.min(2, maxPoolSize));
|
||||
hikari.setConnectionTimeout(30_000);
|
||||
hikari.setIdleTimeout(600_000);
|
||||
hikari.setMaxLifetime(1_800_000);
|
||||
hikari.addDataSourceProperty("sslmode", "prefer");
|
||||
hikari.addDataSourceProperty("ApplicationName", appName);
|
||||
hikari.setDriverClassName("org.postgresql.Driver");
|
||||
}
|
||||
|
||||
this.ds = new HikariDataSource(hikari);
|
||||
initSchema();
|
||||
}
|
||||
|
||||
// ─── Schema ────────────────────────────────────────────────────────────────
|
||||
|
||||
private void initSchema() {
|
||||
String usersTable = sqlite ? """
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
minecraft_nick TEXT NOT NULL,
|
||||
discord_id TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
UNIQUE (minecraft_nick),
|
||||
UNIQUE (discord_id)
|
||||
)
|
||||
""" : """
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
minecraft_nick VARCHAR(16) NOT NULL,
|
||||
discord_id VARCHAR(20) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT uq_minecraft_nick UNIQUE (minecraft_nick),
|
||||
CONSTRAINT uq_discord_id UNIQUE (discord_id),
|
||||
CONSTRAINT ck_minecraft_nick CHECK (minecraft_nick ~ '^[a-zA-Z0-9_]{3,16}$'),
|
||||
CONSTRAINT ck_discord_id CHECK (discord_id ~ '^[0-9]{17,20}$')
|
||||
)
|
||||
""";
|
||||
|
||||
String verificationsTable = sqlite ? """
|
||||
CREATE TABLE IF NOT EXISTS pending_verifications (
|
||||
code TEXT PRIMARY KEY,
|
||||
minecraft_nick TEXT NOT NULL UNIQUE,
|
||||
expires_at INTEGER NOT NULL
|
||||
)
|
||||
""" : """
|
||||
CREATE TABLE IF NOT EXISTS pending_verifications (
|
||||
code VARCHAR(16) PRIMARY KEY,
|
||||
minecraft_nick VARCHAR(16) NOT NULL,
|
||||
expires_at BIGINT NOT NULL,
|
||||
CONSTRAINT uq_pv_minecraft_nick UNIQUE (minecraft_nick)
|
||||
)
|
||||
""";
|
||||
|
||||
String loginsTable = sqlite ? """
|
||||
CREATE TABLE IF NOT EXISTS pending_logins (
|
||||
token TEXT PRIMARY KEY,
|
||||
discord_id TEXT NOT NULL UNIQUE,
|
||||
minecraft_nick TEXT NOT NULL UNIQUE,
|
||||
message_id TEXT,
|
||||
expires_at INTEGER NOT NULL
|
||||
)
|
||||
""" : """
|
||||
CREATE TABLE IF NOT EXISTS pending_logins (
|
||||
token VARCHAR(16) PRIMARY KEY,
|
||||
discord_id VARCHAR(20) NOT NULL,
|
||||
minecraft_nick VARCHAR(16) NOT NULL,
|
||||
message_id VARCHAR(20),
|
||||
expires_at BIGINT NOT NULL,
|
||||
CONSTRAINT uq_pl_discord_id UNIQUE (discord_id),
|
||||
CONSTRAINT uq_pl_minecraft_nick UNIQUE (minecraft_nick)
|
||||
)
|
||||
""";
|
||||
|
||||
try (Connection conn = ds.getConnection();
|
||||
Statement stmt = conn.createStatement()) {
|
||||
stmt.execute(usersTable);
|
||||
stmt.execute(verificationsTable);
|
||||
stmt.execute(loginsTable);
|
||||
} catch (SQLException e) {
|
||||
throw new IllegalStateException("Failed to initialize DB schema", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Users ────────────────────────────────────────────────────────────────
|
||||
|
||||
public User addUser(final String minecraftNick, final String discordId) {
|
||||
validateNick(minecraftNick);
|
||||
validateDiscordId(discordId);
|
||||
|
||||
String sql = sqlite ? """
|
||||
INSERT INTO users (minecraft_nick, discord_id)
|
||||
VALUES (?, ?)
|
||||
""" : """
|
||||
INSERT INTO users (minecraft_nick, discord_id)
|
||||
VALUES (?, ?)
|
||||
RETURNING id, minecraft_nick, discord_id, created_at
|
||||
""";
|
||||
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
ps.setString(1, minecraftNick);
|
||||
ps.setString(2, discordId);
|
||||
|
||||
if (sqlite) {
|
||||
ps.executeUpdate();
|
||||
try (Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("SELECT last_insert_rowid()")) {
|
||||
if (rs.next()) {
|
||||
return new User(rs.getLong(1), minecraftNick, discordId, Instant.now());
|
||||
}
|
||||
}
|
||||
throw new SQLException("INSERT returned no rows");
|
||||
} else {
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) return mapUser(rs);
|
||||
throw new SQLException("INSERT returned no rows");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw translateSqlException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRegistered(final String minecraftNick) {
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM users WHERE LOWER(minecraft_nick) = LOWER(?) LIMIT 1")) {
|
||||
ps.setString(1, minecraftNick);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("DB error in isRegistered", e);
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<User> findByDiscordId(final String discordId) {
|
||||
validateDiscordId(discordId);
|
||||
return queryOneUser(
|
||||
"SELECT id, minecraft_nick, discord_id, created_at FROM users WHERE discord_id = ?",
|
||||
discordId
|
||||
);
|
||||
}
|
||||
|
||||
public Optional<User> findByMinecraftNick(final String nick) {
|
||||
validateNick(nick);
|
||||
return queryOneUser(
|
||||
"SELECT id, minecraft_nick, discord_id, created_at FROM users WHERE LOWER(minecraft_nick) = LOWER(?)",
|
||||
nick
|
||||
);
|
||||
}
|
||||
|
||||
public boolean removeUser(final String discordId) {
|
||||
validateDiscordId(discordId);
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement("DELETE FROM users WHERE discord_id = ?")) {
|
||||
ps.setString(1, discordId);
|
||||
return ps.executeUpdate() > 0;
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to remove user", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Pending Verifications ────────────────────────────────────────────────
|
||||
|
||||
public String createVerificationCode(final String minecraftNick) {
|
||||
validateNick(minecraftNick);
|
||||
String code = CodeGenerator.generate(cfg.getVerificationCodeLength());
|
||||
long expiresAt = Instant.now().getEpochSecond() + cfg.getAuthTimeoutSeconds();
|
||||
|
||||
String sql = sqlite ? """
|
||||
INSERT INTO pending_verifications (code, minecraft_nick, expires_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(minecraft_nick) DO UPDATE
|
||||
SET code = excluded.code, expires_at = excluded.expires_at
|
||||
""" : """
|
||||
INSERT INTO pending_verifications (code, minecraft_nick, expires_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT (minecraft_nick) DO UPDATE
|
||||
SET code = EXCLUDED.code, expires_at = EXCLUDED.expires_at
|
||||
""";
|
||||
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
ps.setString(1, code);
|
||||
ps.setString(2, minecraftNick);
|
||||
ps.setLong(3, expiresAt);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to create verification code", e);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
public Optional<String> consumeVerificationCode(final String code) {
|
||||
if (sqlite) return consumeDeleteSelect("pending_verifications", "code", code);
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement("""
|
||||
DELETE FROM pending_verifications
|
||||
WHERE code = ? AND expires_at > ?
|
||||
RETURNING minecraft_nick
|
||||
""")) {
|
||||
ps.setString(1, code);
|
||||
ps.setLong(2, Instant.now().getEpochSecond());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? Optional.of(rs.getString("minecraft_nick")) : Optional.empty();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to consume verification code", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Pending Logins ───────────────────────────────────────────────────────
|
||||
|
||||
public String createLoginToken(final String minecraftNick, final String discordId) {
|
||||
validateNick(minecraftNick);
|
||||
validateDiscordId(discordId);
|
||||
String token = CodeGenerator.generate(16);
|
||||
long expiresAt = Instant.now().getEpochSecond() + cfg.getAuthTimeoutSeconds();
|
||||
|
||||
String sql = sqlite ? """
|
||||
INSERT INTO pending_logins (token, discord_id, minecraft_nick, expires_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(discord_id) DO UPDATE
|
||||
SET token = excluded.token,
|
||||
minecraft_nick = excluded.minecraft_nick,
|
||||
message_id = NULL,
|
||||
expires_at = excluded.expires_at
|
||||
""" : """
|
||||
INSERT INTO pending_logins (token, discord_id, minecraft_nick, expires_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (discord_id) DO UPDATE
|
||||
SET token = EXCLUDED.token,
|
||||
minecraft_nick = EXCLUDED.minecraft_nick,
|
||||
message_id = NULL,
|
||||
expires_at = EXCLUDED.expires_at
|
||||
""";
|
||||
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
ps.setString(1, token);
|
||||
ps.setString(2, discordId);
|
||||
ps.setString(3, minecraftNick);
|
||||
ps.setLong(4, expiresAt);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to create login token", e);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
public void updateLoginMessageId(final String token, final String messageId) {
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(
|
||||
"UPDATE pending_logins SET message_id = ? WHERE token = ?")) {
|
||||
ps.setString(1, messageId);
|
||||
ps.setString(2, token);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to update message id", e);
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<String> consumeLoginToken(final String token) {
|
||||
if (sqlite) return consumeDeleteSelect("pending_logins", "token", token);
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement("""
|
||||
DELETE FROM pending_logins
|
||||
WHERE token = ? AND expires_at > ?
|
||||
RETURNING minecraft_nick
|
||||
""")) {
|
||||
ps.setString(1, token);
|
||||
ps.setLong(2, Instant.now().getEpochSecond());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? Optional.of(rs.getString("minecraft_nick")) : Optional.empty();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to consume login token", e);
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<String> consumeLoginTokenByMessageId(final String messageId) {
|
||||
if (sqlite) return consumeDeleteSelect("pending_logins", "message_id", messageId);
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement("""
|
||||
DELETE FROM pending_logins
|
||||
WHERE message_id = ? AND expires_at > ?
|
||||
RETURNING minecraft_nick
|
||||
""")) {
|
||||
ps.setString(1, messageId);
|
||||
ps.setLong(2, Instant.now().getEpochSecond());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? Optional.of(rs.getString("minecraft_nick")) : Optional.empty();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to consume login token by message id", e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTokenConsumed(final String token) {
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM pending_logins WHERE token = ? AND expires_at > ? LIMIT 1")) {
|
||||
ps.setString(1, token);
|
||||
ps.setLong(2, Instant.now().getEpochSecond());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return !rs.next();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("DB error in isTokenConsumed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteLoginToken(final String token) {
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement("DELETE FROM pending_logins WHERE token = ?")) {
|
||||
ps.setString(1, token);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to delete login token", e);
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> popExpiredLogins() {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
List<String> nicks = new ArrayList<>();
|
||||
|
||||
if (sqlite) {
|
||||
try (Connection conn = ds.getConnection()) {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT minecraft_nick FROM pending_logins WHERE expires_at <= ?")) {
|
||||
ps.setLong(1, now);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) nicks.add(rs.getString("minecraft_nick"));
|
||||
}
|
||||
}
|
||||
if (!nicks.isEmpty()) {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"DELETE FROM pending_logins WHERE expires_at <= ?")) {
|
||||
ps.setLong(1, now);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to pop expired logins", e);
|
||||
}
|
||||
return nicks;
|
||||
}
|
||||
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(
|
||||
"DELETE FROM pending_logins WHERE expires_at <= ? RETURNING minecraft_nick")) {
|
||||
ps.setLong(1, now);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) nicks.add(rs.getString("minecraft_nick"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to pop expired logins", e);
|
||||
}
|
||||
return nicks;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private Optional<String> consumeDeleteSelect(final String table, final String column, final String value) {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
try (Connection conn = ds.getConnection()) {
|
||||
Optional<String> result;
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT minecraft_nick FROM " + table + " WHERE " + column + " = ? AND expires_at > ?")) {
|
||||
ps.setString(1, value);
|
||||
ps.setLong(2, now);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
result = rs.next() ? Optional.of(rs.getString("minecraft_nick")) : Optional.empty();
|
||||
}
|
||||
}
|
||||
if (result.isPresent()) {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"DELETE FROM " + table + " WHERE " + column + " = ?")) {
|
||||
ps.setString(1, value);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Failed to consume from " + table, e);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<User> queryOneUser(final String sql, final String param) {
|
||||
try (Connection conn = ds.getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
ps.setString(1, param);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? Optional.of(mapUser(rs)) : Optional.empty();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Query failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static User mapUser(final ResultSet rs) throws SQLException {
|
||||
return new User(
|
||||
rs.getLong("id"),
|
||||
rs.getString("minecraft_nick"),
|
||||
rs.getString("discord_id"),
|
||||
rs.getTimestamp("created_at").toInstant()
|
||||
);
|
||||
}
|
||||
|
||||
private static void validateNick(final String nick) {
|
||||
if (nick == null || !nick.matches("^[a-zA-Z0-9_]{3,16}$"))
|
||||
throw new IllegalArgumentException("Invalid Minecraft nick: " + nick);
|
||||
}
|
||||
|
||||
private static void validateDiscordId(final String id) {
|
||||
if (id == null || !id.matches("^[0-9]{17,20}$"))
|
||||
throw new IllegalArgumentException("Invalid Discord ID: " + id);
|
||||
}
|
||||
|
||||
private static RuntimeException translateSqlException(final SQLException e) {
|
||||
String state = e.getSQLState();
|
||||
if ("23505".equals(state) || "23000".equals(state)) {
|
||||
String msg = e.getMessage();
|
||||
if (msg != null && (msg.contains("minecraft_nick") || msg.contains("UNIQUE constraint failed: users.minecraft_nick")))
|
||||
return new DuplicateUserException("Minecraft nick already registered");
|
||||
if (msg != null && (msg.contains("discord_id") || msg.contains("UNIQUE constraint failed: users.discord_id")))
|
||||
return new DuplicateUserException("Discord ID already registered");
|
||||
return new DuplicateUserException("Duplicate entry");
|
||||
}
|
||||
return new DatabaseException("Database error", e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
ds.close();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
package dev.loki.loAuth.common.exception;
|
||||
|
||||
public final class DatabaseException extends RuntimeException {
|
||||
public DatabaseException(String msg, Throwable cause) { super(msg, cause); }
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
package dev.loki.loAuth.common.exception;
|
||||
|
||||
public final class DuplicateUserException extends RuntimeException {
|
||||
public DuplicateUserException(String msg) { super(msg); }
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
package dev.loki.loAuth.common.model;
|
||||
|
||||
public record User(long id, String minecraftNick, String discordId, java.time.Instant createdAt) {}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package dev.loki.loAuth.common.util;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
|
||||
public final class CodeGenerator {
|
||||
|
||||
private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
private static final SecureRandom RNG = new SecureRandom();
|
||||
|
||||
private CodeGenerator() {}
|
||||
|
||||
public static String generate(final int length) {
|
||||
if (length < 4 || length > 16)
|
||||
throw new IllegalArgumentException("Code length must be between 4 and 16");
|
||||
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++)
|
||||
sb.append(ALPHABET.charAt(RNG.nextInt(ALPHABET.length())));
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
0
common/src/main/java/dev/loki/loAuth/common/.java
Normal file
0
common/src/main/java/dev/loki/loAuth/common/.java
Normal file
21
discord/build.gradle.kts
Normal file
21
discord/build.gradle.kts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
id("com.gradleup.shadow")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":common"))
|
||||
implementation("net.dv8tion:JDA:6.4.0")
|
||||
implementation("org.slf4j:slf4j-api:2.0.17")
|
||||
runtimeOnly("ch.qos.logback:logback-classic:1.5.31")
|
||||
}
|
||||
|
||||
tasks.named<ShadowJar>("shadowJar") {
|
||||
archiveBaseName.set("discord")
|
||||
archiveClassifier.set("standalone")
|
||||
|
||||
manifest {
|
||||
attributes["Main-Class"] = "dev.loki.loAuth.discord.BotLauncher"
|
||||
}
|
||||
}
|
||||
48
discord/src/main/java/dev/loki/loAuth/discord/Bot.java
Normal file
48
discord/src/main/java/dev/loki/loAuth/discord/Bot.java
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
package dev.loki.loAuth.discord;
|
||||
|
||||
import dev.loki.loAuth.common.db.DatabaseManager;
|
||||
import dev.loki.loAuth.discord.auth.AuthService;
|
||||
import dev.loki.loAuth.discord.cfg.BotConfig;
|
||||
import dev.loki.loAuth.discord.listener.LoginReactionListener;
|
||||
import dev.loki.loAuth.discord.listener.VerifyListener;
|
||||
import net.dv8tion.jda.api.JDA;
|
||||
import net.dv8tion.jda.api.JDABuilder;
|
||||
import net.dv8tion.jda.api.OnlineStatus;
|
||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public final class Bot {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Bot.class);
|
||||
|
||||
private final BotConfig cfg;
|
||||
private final DatabaseManager db;
|
||||
private final JDA jda;
|
||||
private final AuthService auth;
|
||||
|
||||
public Bot(final BotConfig cfg) {
|
||||
this.cfg = cfg;
|
||||
this.db = new DatabaseManager(cfg, "loAuthBot", 10);
|
||||
this.jda = JDABuilder
|
||||
.createDefault(cfg.getToken(),
|
||||
GatewayIntent.DIRECT_MESSAGES,
|
||||
GatewayIntent.DIRECT_MESSAGE_REACTIONS,
|
||||
GatewayIntent.MESSAGE_CONTENT)
|
||||
.setStatus(OnlineStatus.ONLINE)
|
||||
.build();
|
||||
this.auth = new AuthService(db, cfg, jda);
|
||||
|
||||
jda.addEventListener(
|
||||
new VerifyListener(auth),
|
||||
new LoginReactionListener(db)
|
||||
);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
auth.close();
|
||||
db.close();
|
||||
jda.shutdown();
|
||||
log.info("loAuth bot shut down.");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
package dev.loki.loAuth.discord;
|
||||
|
||||
import dev.loki.loAuth.discord.cfg.BotCfg;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public final class BotLauncher {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BotLauncher.class);
|
||||
|
||||
public static void main(final String[] args) {
|
||||
BotCfg cfg;
|
||||
try {
|
||||
cfg = new BotCfg(getOrCreateConfig("config.yml"));
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to load config: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
Bot bot = new Bot(cfg);
|
||||
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(bot::shutdown, "shutdown"));
|
||||
|
||||
log.info("loAuth bot started.");
|
||||
}
|
||||
|
||||
private static Path getOrCreateConfig(final String fileName) throws IOException {
|
||||
Path path = Path.of(System.getProperty("user.dir")).resolve(fileName);
|
||||
if (Files.notExists(path)) {
|
||||
try (InputStream in = BotLauncher.class.getResourceAsStream("/" + fileName)) {
|
||||
if (in == null) throw new IOException("Resource not found: " + fileName);
|
||||
Files.copy(in, path);
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
package dev.loki.loAuth.discord.auth;
|
||||
|
||||
import dev.loki.loAuth.common.db.DatabaseManager;
|
||||
import dev.loki.loAuth.discord.cfg.BotConfig;
|
||||
import net.dv8tion.jda.api.JDA;
|
||||
import net.dv8tion.jda.api.entities.User;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public final class AuthService implements AutoCloseable {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthService.class);
|
||||
|
||||
private final DatabaseManager db;
|
||||
private final BotConfig cfg;
|
||||
private final JDA jda;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
|
||||
public AuthService(final DatabaseManager db, final BotConfig cfg, final JDA jda) {
|
||||
this.db = db;
|
||||
this.cfg = cfg;
|
||||
this.jda = jda;
|
||||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "auth-expiry");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
int ttl = cfg.getAuthTimeoutSeconds();
|
||||
scheduler.scheduleAtFixedRate(this::kickExpiredLogins, ttl, ttl, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void verifyNewUser(final String code, final String discordId) {
|
||||
Optional<String> nick = db.consumeVerificationCode(code.toUpperCase());
|
||||
if (nick.isEmpty()) throw new IllegalArgumentException("Invalid or expired code: " + code);
|
||||
db.addUser(nick.get(), discordId);
|
||||
log.info("New user registered: {} -> {}", nick.get(), discordId);
|
||||
}
|
||||
|
||||
public void requestLoginApproval(final String minecraftNick, final String discordId) {
|
||||
String token = db.createLoginToken(minecraftNick, discordId);
|
||||
|
||||
User discordUser = jda.retrieveUserById(discordId).complete();
|
||||
discordUser.openPrivateChannel().queue(channel ->
|
||||
channel.sendMessage(
|
||||
"🔐 **Запрос на вход**\n" +
|
||||
"Игрок **" + minecraftNick + "** пытается зайти на сервер.\n" +
|
||||
"Поставь реакцию ✅ на это сообщение чтобы разрешить вход.\n" +
|
||||
"Сообщение истекает через " + cfg.getAuthTimeoutSeconds() + " секунд."
|
||||
).queue(message -> {
|
||||
message.addReaction(net.dv8tion.jda.api.entities.emoji.Emoji.fromUnicode("✅")).queue();
|
||||
db.updateLoginMessageId(token, message.getId());
|
||||
}),
|
||||
error -> log.warn("Cannot send DM to {}: {}", discordId, error.getMessage())
|
||||
);
|
||||
}
|
||||
|
||||
public void approveLogin(final String discordId) {
|
||||
db.findByDiscordId(discordId).ifPresent(user -> {
|
||||
Optional<String> nick = db.consumeLoginToken(findTokenByDiscordId(discordId));
|
||||
nick.ifPresent(n -> log.info("Login approved for {} ({})", n, discordId));
|
||||
});
|
||||
}
|
||||
|
||||
private String findTokenByDiscordId(final String discordId) {
|
||||
// Ищем токен через БД — запрос по discord_id в pending_logins
|
||||
// consumeLoginToken вызывается из LoginReactionListener напрямую по token из message
|
||||
return discordId; // placeholder — см. LoginReactionListener
|
||||
}
|
||||
|
||||
private void kickExpiredLogins() {
|
||||
try {
|
||||
List<String> expired = db.popExpiredLogins();
|
||||
if (!expired.isEmpty())
|
||||
log.info("Expired logins cleaned up: {}", expired);
|
||||
} catch (Exception e) {
|
||||
log.error("Error during expired login cleanup", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
scheduler.shutdown();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package dev.loki.loAuth.discord.cfg;
|
||||
|
||||
import dev.loki.loAuth.common.cfg.YamlConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public final class BotCfg implements BotConfig {
|
||||
|
||||
private final YamlConfig cfg;
|
||||
|
||||
public BotCfg(final Path configPath) throws IOException {
|
||||
cfg = new YamlConfig(configPath);
|
||||
}
|
||||
|
||||
@Override public String getToken() { return cfg.getRequired("token", String.class); }
|
||||
@Override public String getDbType() { return cfg.getRequired("db_type", String.class); }
|
||||
@Override public String getDbHost() { return cfg.getRequired("db_host", String.class); }
|
||||
@Override public int getDbPort() { return cfg.getRequired("db_port", Integer.class); }
|
||||
@Override public String getDbName() { return cfg.getRequired("db_name", String.class); }
|
||||
@Override public String getDbUser() { return cfg.getRequired("db_user", String.class); }
|
||||
@Override public String getDbPassword() { return cfg.getRequired("db_password", String.class); }
|
||||
@Override public int getAuthTimeoutSeconds() { return cfg.getRequired("auth_timeout_seconds", Integer.class); }
|
||||
@Override public int getVerificationCodeLength() { return cfg.getRequired("verification_code_length",Integer.class); }
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package dev.loki.loAuth.discord.cfg;
|
||||
|
||||
import dev.loki.loAuth.common.cfg.DbConfig;
|
||||
|
||||
public interface BotConfig extends DbConfig {
|
||||
String getToken();
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package dev.loki.loAuth.discord.listener;
|
||||
|
||||
import dev.loki.loAuth.common.db.DatabaseManager;
|
||||
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public final class LoginReactionListener extends ListenerAdapter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(LoginReactionListener.class);
|
||||
private static final String CHECKMARK = "✅";
|
||||
|
||||
private final DatabaseManager db;
|
||||
|
||||
public LoginReactionListener(final DatabaseManager db) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessageReactionAdd(final MessageReactionAddEvent event) {
|
||||
if (event.getUser() == null || event.getUser().isBot()) return;
|
||||
if (!CHECKMARK.equals(event.getReaction().getEmoji().getName())) return;
|
||||
|
||||
// Ищем токен по message_id — бот сохранил его при отправке
|
||||
db.consumeLoginTokenByMessageId(event.getMessageId()).ifPresent(nick ->
|
||||
log.info("Login approved for {} via reaction.", nick)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
package dev.loki.loAuth.discord.listener;
|
||||
|
||||
import dev.loki.loAuth.common.exception.DuplicateUserException;
|
||||
import dev.loki.loAuth.discord.auth.AuthService;
|
||||
import net.dv8tion.jda.api.entities.channel.ChannelType;
|
||||
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||
|
||||
public final class VerifyListener extends ListenerAdapter {
|
||||
|
||||
private static final String COMMAND = "!verify";
|
||||
|
||||
private final AuthService auth;
|
||||
|
||||
public VerifyListener(final AuthService auth) {
|
||||
this.auth = auth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(final MessageReceivedEvent event) {
|
||||
if (event.getAuthor().isBot()) return;
|
||||
if (!event.isFromType(ChannelType.PRIVATE)) return;
|
||||
|
||||
String content = event.getMessage().getContentRaw().trim();
|
||||
if (!content.toUpperCase().startsWith(COMMAND)) return;
|
||||
|
||||
String[] parts = content.split("\\s+", 2);
|
||||
if (parts.length < 2) {
|
||||
event.getChannel().sendMessage("Использование: `!verify КОД`").queue();
|
||||
return;
|
||||
}
|
||||
|
||||
String code = parts[1].trim().toUpperCase();
|
||||
String discordId = event.getAuthor().getId();
|
||||
|
||||
try {
|
||||
auth.verifyNewUser(code, discordId);
|
||||
event.getChannel().sendMessage("✅ Ты успешно зарегистрирован! Можешь заходить на сервер.").queue();
|
||||
} catch (IllegalArgumentException e) {
|
||||
event.getChannel().sendMessage("❌ Неверный или просроченный код. Зайди на сервер снова чтобы получить новый.").queue();
|
||||
} catch (DuplicateUserException e) {
|
||||
event.getChannel().sendMessage("⚠️ Этот Discord аккаунт уже привязан к другому игроку.").queue();
|
||||
}
|
||||
}
|
||||
}
|
||||
12
discord/src/main/resources/config.yml
Normal file
12
discord/src/main/resources/config.yml
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
mode: "standalone" # standalone | embedded
|
||||
token: "token_here"
|
||||
|
||||
db_type: "postgresql" # postgresql | sqlite
|
||||
db_host: "localhost"
|
||||
db_port: 5432
|
||||
db_name: "mydb"
|
||||
db_user: "postgres"
|
||||
db_password: "secret"
|
||||
|
||||
auth_timeout_seconds: 120
|
||||
verification_code_length: 6
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
6
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
6
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
#Sat Apr 18 12:45:08 CEST 2026
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
gradlew
vendored
Normal file
234
gradlew
vendored
Normal 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
89
gradlew.bat
vendored
Normal 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
|
||||
BIN
lib/fisch-frame-1.0.jar
Normal file
BIN
lib/fisch-frame-1.0.jar
Normal file
Binary file not shown.
20
plugin/build.gradle.kts
Normal file
20
plugin/build.gradle.kts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
id("com.gradleup.shadow")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":common"))
|
||||
implementation(project(":discord")) {
|
||||
exclude(group = "ch.qos.logback")
|
||||
}
|
||||
compileOnly("com.velocitypowered:velocity-api:3.5.0-SNAPSHOT")
|
||||
annotationProcessor("com.velocitypowered:velocity-api:3.5.0-SNAPSHOT")
|
||||
}
|
||||
|
||||
|
||||
tasks.named<ShadowJar>("shadowJar") {
|
||||
archiveBaseName.set("loauth")
|
||||
archiveClassifier.set("")
|
||||
}
|
||||
104
plugin/src/main/java/dev/loki/loAuth/plugin/FoxAuth.java
Normal file
104
plugin/src/main/java/dev/loki/loAuth/plugin/FoxAuth.java
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
package dev.loki.loAuth.plugin;
|
||||
|
||||
import dev.loki.loAuth.plugin.cfg.PluginCfg;
|
||||
import dev.loki.loAuth.plugin.listener.LoginListener;
|
||||
import dev.loki.loAuth.common.db.DatabaseManager;
|
||||
import dev.loki.loAuth.discord.Bot;
|
||||
import dev.loki.loAuth.discord.cfg.BotConfig;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
|
||||
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
|
||||
import com.velocitypowered.api.plugin.Plugin;
|
||||
import com.velocitypowered.api.plugin.annotation.DataDirectory;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import jakarta.inject.Inject;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
@Plugin(id = "loauth", name = "loAuth", version = "0.0.1",
|
||||
description = "Discord 2FA auth for Velocity", authors = {"loki"})
|
||||
public final class FoxAuth {
|
||||
|
||||
private final ProxyServer server;
|
||||
private final Logger log;
|
||||
private final Path dataDir;
|
||||
|
||||
private DatabaseManager db;
|
||||
private Bot discordBot;
|
||||
|
||||
@Inject
|
||||
public FoxAuth(final ProxyServer server, final Logger log, @DataDirectory final Path dataDir) {
|
||||
this.server = server;
|
||||
this.log = log;
|
||||
this.dataDir = dataDir;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onInit(final ProxyInitializeEvent event) {
|
||||
PluginCfg cfg;
|
||||
try {
|
||||
cfg = new PluginCfg(getOrCreateConfig("config.yml"));
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to load config: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
db = new DatabaseManager(cfg, "loAuthPlugin", 5);
|
||||
server.getEventManager().register(this, new LoginListener(server, db, cfg, log));
|
||||
|
||||
if ("embedded".equals(cfg.getMode())) {
|
||||
startEmbeddedBot(cfg);
|
||||
} else {
|
||||
log.info("Mode: standalone — external Discord bot required.");
|
||||
}
|
||||
|
||||
log.info("loAuth initialized.");
|
||||
}
|
||||
|
||||
private void startEmbeddedBot(final PluginCfg cfg) {
|
||||
String token = cfg.getToken();
|
||||
if (token.isEmpty()) {
|
||||
log.warn("Mode is 'embedded' but token is empty! Discord bot not started.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
discordBot = new Bot(new BotConfig() {
|
||||
@Override public String getDbType() { return cfg.getDbType(); }
|
||||
@Override public String getToken() { return token; }
|
||||
@Override public String getDbHost() { return cfg.getDbHost(); }
|
||||
@Override public int getDbPort() { return cfg.getDbPort(); }
|
||||
@Override public String getDbName() { return cfg.getDbName(); }
|
||||
@Override public String getDbUser() { return cfg.getDbUser(); }
|
||||
@Override public String getDbPassword() { return cfg.getDbPassword(); }
|
||||
@Override public int getAuthTimeoutSeconds() { return cfg.getAuthTimeoutSeconds(); }
|
||||
@Override public int getVerificationCodeLength() { return cfg.getVerificationCodeLength(); }
|
||||
});
|
||||
log.info("Discord bot started in embedded mode.");
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to start embedded Discord bot: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onShutdown(final ProxyShutdownEvent event) {
|
||||
if (discordBot != null) discordBot.shutdown();
|
||||
if (db != null) db.close();
|
||||
}
|
||||
|
||||
private Path getOrCreateConfig(final String fileName) throws IOException {
|
||||
Files.createDirectories(dataDir);
|
||||
Path target = dataDir.resolve(fileName);
|
||||
if (Files.notExists(target)) {
|
||||
try (InputStream in = getClass().getResourceAsStream("/" + fileName)) {
|
||||
if (in == null) throw new IOException("Resource not found: " + fileName);
|
||||
Files.copy(in, target);
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
package dev.loki.loAuth.plugin.cfg;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.kyori.adventure.text.event.HoverEvent;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class MessageConfig {
|
||||
|
||||
private static final Pattern HEX_PATTERN = Pattern.compile("&#([0-9A-Fa-f]{6})");
|
||||
|
||||
private final Map<String, Object> raw;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public MessageConfig(final Map<String, Object> raw) {
|
||||
this.raw = raw;
|
||||
}
|
||||
|
||||
public Component header() { return text("first_login.header"); }
|
||||
public Component returningHeader() { return text("returning_login.header"); }
|
||||
public Component returningBody() { return text("returning_login.body"); }
|
||||
public Component returningTimeout() { return text("returning_login.timeout"); }
|
||||
public Component expiredHeader() { return text("expired.header"); }
|
||||
public Component expiredBody() { return text("expired.body"); }
|
||||
public Component success() { return text("success"); }
|
||||
|
||||
public Component code(final String code) {
|
||||
return parse("first_login.code", Map.of("code", code))
|
||||
.clickEvent(ClickEvent.copyToClipboard(code))
|
||||
.hoverEvent(HoverEvent.showText(text("first_login.code_hover")));
|
||||
}
|
||||
|
||||
public Component discordLink(final String link) {
|
||||
String fullLink = link.startsWith("http") ? link : "https://" + link;
|
||||
return parse("first_login.discord", Map.of("link", link))
|
||||
.clickEvent(ClickEvent.openUrl(fullLink))
|
||||
.hoverEvent(HoverEvent.showText(text("first_login.discord_hover")));
|
||||
}
|
||||
|
||||
public Component expires(final int seconds) {
|
||||
return text("first_login.expires", Map.of("time", String.valueOf(seconds)));
|
||||
}
|
||||
|
||||
public Component react(final int seconds) {
|
||||
return text("returning_login.react", Map.of("time", String.valueOf(seconds)));
|
||||
}
|
||||
|
||||
// ─── Parser ───────────────────────────────────────────────────────────────
|
||||
|
||||
private Component text(final String path) {
|
||||
return text(path, Map.of());
|
||||
}
|
||||
|
||||
private Component text(final String path, final Map<String, String> placeholders) {
|
||||
String rawStr = resolveRaw(path);
|
||||
if (rawStr == null) return Component.text('[' + path + ']');
|
||||
return parse(rawStr, placeholders);
|
||||
}
|
||||
|
||||
private Component parse(final String rawStr, final Map<String, String> placeholders) {
|
||||
String str = applyPlaceholders(rawStr, placeholders);
|
||||
|
||||
List<int[]> hexes = new ArrayList<>();
|
||||
Matcher m = HEX_PATTERN.matcher(str);
|
||||
while (m.find()) {
|
||||
hexes.add(new int[]{m.start(), m.end(), Integer.parseInt(m.group(1), 16)});
|
||||
}
|
||||
|
||||
TextComponent.Builder builder = Component.text();
|
||||
int last = 0;
|
||||
|
||||
for (int i = 0; i < hexes.size(); i++) {
|
||||
int[] h = hexes.get(i);
|
||||
if (last < h[0]) {
|
||||
builder.append(Component.text(str.substring(last, h[0])));
|
||||
}
|
||||
TextColor color = TextColor.color(h[2]);
|
||||
int nextStart = (i + 1 < hexes.size()) ? hexes.get(i + 1)[0] : str.length();
|
||||
builder.append(Component.text(str.substring(h[1], nextStart), color));
|
||||
last = nextStart;
|
||||
}
|
||||
|
||||
if (last < str.length()) {
|
||||
builder.append(Component.text(str.substring(last)));
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private String resolveRaw(final String path) {
|
||||
String[] parts = path.split("\\.");
|
||||
Map<String, Object> current = raw;
|
||||
for (int i = 0; i < parts.length - 1; i++) {
|
||||
Object next = current.get(parts[i]);
|
||||
if (next instanceof Map) {
|
||||
current = (Map<String, Object>) next;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Object val = current.get(parts[parts.length - 1]);
|
||||
return val instanceof String ? (String) val : null;
|
||||
}
|
||||
|
||||
private static String applyPlaceholders(final String str, final Map<String, String> placeholders) {
|
||||
String result = str;
|
||||
for (Map.Entry<String, String> entry : placeholders.entrySet()) {
|
||||
result = result.replace("{" + entry.getKey() + "}", entry.getValue());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package dev.loki.loAuth.plugin.cfg;
|
||||
|
||||
import dev.loki.loAuth.common.cfg.DbConfig;
|
||||
import dev.loki.loAuth.common.cfg.YamlConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
public final class PluginCfg implements DbConfig {
|
||||
|
||||
private final YamlConfig cfg;
|
||||
|
||||
public PluginCfg(final Path configPath) throws IOException {
|
||||
cfg = new YamlConfig(configPath);
|
||||
}
|
||||
|
||||
public String getMode() { return cfg.getRequired("mode", String.class); }
|
||||
public String getToken() { return cfg.get("token", ""); }
|
||||
public String getDiscordLink() { return cfg.get("discord_link", "discord.gg/ЗАМЕНИ_НА_СВОЙ"); }
|
||||
|
||||
@Override public String getDbType() { return cfg.getRequired("db_type", String.class); }
|
||||
@Override public String getDbHost() { return cfg.getRequired("db_host", String.class); }
|
||||
@Override public int getDbPort() { return cfg.getRequired("db_port", Integer.class); }
|
||||
@Override public String getDbName() { return cfg.getRequired("db_name", String.class); }
|
||||
@Override public String getDbUser() { return cfg.getRequired("db_user", String.class); }
|
||||
@Override public String getDbPassword() { return cfg.getRequired("db_password", String.class); }
|
||||
@Override public int getAuthTimeoutSeconds() { return cfg.getRequired("auth_timeout_seconds", Integer.class); }
|
||||
@Override public int getVerificationCodeLength(){ return cfg.getRequired("verification_code_length",Integer.class); }
|
||||
|
||||
public MessageConfig getMessages() {
|
||||
Object msgs = cfg.get("messages", null);
|
||||
if (msgs instanceof Map) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = (Map<String, Object>) msgs;
|
||||
return new MessageConfig(map);
|
||||
}
|
||||
return new MessageConfig(Map.of());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
package dev.loki.loAuth.plugin.listener;
|
||||
|
||||
import dev.loki.loAuth.plugin.cfg.MessageConfig;
|
||||
import dev.loki.loAuth.plugin.cfg.PluginCfg;
|
||||
import dev.loki.loAuth.common.db.DatabaseManager;
|
||||
import dev.loki.loAuth.common.model.User;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.connection.LoginEvent;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public final class LoginListener {
|
||||
|
||||
private final ProxyServer server;
|
||||
private final DatabaseManager db;
|
||||
private final PluginCfg cfg;
|
||||
private final Logger log;
|
||||
private final MessageConfig msg;
|
||||
|
||||
private final Map<String, ScheduledFuture<?>> pendingKicks = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> pendingTokens = new ConcurrentHashMap<>();
|
||||
|
||||
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2, r -> {
|
||||
Thread t = new Thread(r, "foxauth-scheduler");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
public LoginListener(final ProxyServer server, final DatabaseManager db,
|
||||
final PluginCfg cfg, final Logger log) {
|
||||
this.server = server;
|
||||
this.db = db;
|
||||
this.cfg = cfg;
|
||||
this.log = log;
|
||||
this.msg = cfg.getMessages();
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onLogin(final LoginEvent event) {
|
||||
String nick = event.getPlayer().getUsername();
|
||||
|
||||
if (!db.isRegistered(nick)) {
|
||||
handleFirstLogin(event, nick);
|
||||
} else {
|
||||
handleReturningLogin(event, nick);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleFirstLogin(final LoginEvent event, final String nick) {
|
||||
String code = db.createVerificationCode(nick);
|
||||
int ttl = cfg.getAuthTimeoutSeconds();
|
||||
String discordLink = cfg.getDiscordLink();
|
||||
|
||||
event.getPlayer().sendMessage(Component.text()
|
||||
.append(msg.header()).appendNewline()
|
||||
.append(msg.code(code)).appendNewline()
|
||||
.append(msg.discordLink(discordLink)).appendNewline()
|
||||
.append(msg.expires(ttl))
|
||||
.build()
|
||||
);
|
||||
|
||||
log.info("First login for {}, verification code issued.", nick);
|
||||
}
|
||||
|
||||
private void handleReturningLogin(final LoginEvent event, final String nick) {
|
||||
Optional<String> discordId = db.findByMinecraftNick(nick).map(User::discordId);
|
||||
if (discordId.isEmpty()) {
|
||||
event.getPlayer().sendMessage(Component.text("Ошибка авторизации. Обратись к администратору.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
|
||||
String token = db.createLoginToken(nick, discordId.get());
|
||||
pendingTokens.put(nick, token);
|
||||
pollApproval(nick, token);
|
||||
|
||||
log.info("Returning login for {}, awaiting Discord approval.", nick);
|
||||
}
|
||||
|
||||
private void pollApproval(final String nick, final String token) {
|
||||
int ttl = cfg.getAuthTimeoutSeconds();
|
||||
|
||||
Component awaitMessage = Component.text()
|
||||
.append(msg.returningHeader()).appendNewline()
|
||||
.append(msg.returningBody()).appendNewline()
|
||||
.append(msg.react(ttl)).appendNewline()
|
||||
.append(msg.returningTimeout())
|
||||
.build();
|
||||
|
||||
ScheduledFuture<?>[] pollRef = new ScheduledFuture<?>[1];
|
||||
pollRef[0] = scheduler.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
if (db.isTokenConsumed(token)) {
|
||||
pollRef[0].cancel(false);
|
||||
cancelKick(nick);
|
||||
pendingTokens.remove(nick);
|
||||
server.getPlayer(nick).ifPresent(p ->
|
||||
p.sendMessage(msg.success())
|
||||
);
|
||||
log.info("Login approved for {}.", nick);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Poll error for {}: {}", nick, e.getMessage());
|
||||
}
|
||||
}, 2, 2, TimeUnit.SECONDS);
|
||||
|
||||
ScheduledFuture<?> timeoutFuture = scheduler.schedule(() -> {
|
||||
pollRef[0].cancel(false);
|
||||
pendingTokens.remove(nick);
|
||||
db.deleteLoginToken(token);
|
||||
server.getPlayer(nick).ifPresent(p ->
|
||||
p.sendMessage(Component.text()
|
||||
.append(msg.expiredHeader()).appendNewline()
|
||||
.append(msg.expiredBody())
|
||||
.build())
|
||||
);
|
||||
log.info("Login timeout for {}.", nick);
|
||||
}, ttl, TimeUnit.SECONDS);
|
||||
|
||||
pendingKicks.put(nick, timeoutFuture);
|
||||
|
||||
server.getPlayer(nick).ifPresent(p -> p.sendMessage(awaitMessage));
|
||||
}
|
||||
|
||||
private void cancelKick(final String nick) {
|
||||
ScheduledFuture<?> f = pendingKicks.remove(nick);
|
||||
if (f != null) f.cancel(false);
|
||||
}
|
||||
}
|
||||
32
plugin/src/main/resources/config.yml
Normal file
32
plugin/src/main/resources/config.yml
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
mode: "standalone" # standalone | embedded
|
||||
token: ""
|
||||
|
||||
db_type: "postgresql" # postgresql | sqlite
|
||||
db_host: "localhost"
|
||||
db_port: 5432
|
||||
db_name: "mydb"
|
||||
db_user: "postgres"
|
||||
db_password: "secret"
|
||||
|
||||
auth_timeout_seconds: 120
|
||||
verification_code_length: 6
|
||||
|
||||
discord_link: "discord.gg/ЗАМЕНИ_НА_СВОЙ"
|
||||
|
||||
messages:
|
||||
first_login:
|
||||
header: "&#FF4444Ты не зарегистрирован!"
|
||||
code: "&#FFAA00Код: 7FFFF{code}"
|
||||
code_hover: "Нажми чтобы скопировать код"
|
||||
discord: "&#AAAAAADiscord: &#FFFFFF{link}"
|
||||
discord_hover: "Открыть Discord"
|
||||
expires: "򇨣Код действителен {time} сек."
|
||||
returning_login:
|
||||
header: "&#FFAA00Подтверди вход в Discord!"
|
||||
body: "&#AAAAAABот отправил тебе личное сообщение в Discord."
|
||||
react: "&#AAAAAAПоставь 9F287✅ &#AAAAAAчтобы войти."
|
||||
timeout: "򇨣Таймаут: {time} сек."
|
||||
expired:
|
||||
header: "&#FF4444Время ожидания истекло."
|
||||
body: "&#AAAAAAЗайди снова и подтверди вход в Discord."
|
||||
success: "7FF55Авторизация успешна!"
|
||||
3
settings.gradle.kts
Normal file
3
settings.gradle.kts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
rootProject.name = "loAuth"
|
||||
|
||||
include("common", "discord", "plugin")
|
||||
Loading…
Add table
Add a link
Reference in a new issue