This commit is contained in:
Xeovalyte 2023-05-03 11:36:20 +02:00
parent 12320b6a09
commit 5aa8dce299
7 changed files with 247 additions and 138 deletions

View File

@ -2,23 +2,33 @@ package com.xeovalyte.polarcraft;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.network.message.SignedMessage;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text; import net.minecraft.text.Text;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.io.File;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.UUID; import java.util.UUID;
import com.google.gson.stream.JsonReader;
import java.io.StringReader;
import net.fabricmc.fabric.api.message.v1.ServerMessageEvents;
public class PolarcraftMod implements ModInitializer { public class PolarcraftMod implements ModInitializer {
// This logger is used to write text to the console and the log file. // This logger is used to write text to the console and the log file.
@ -26,63 +36,159 @@ public class PolarcraftMod implements ModInitializer {
// That way, it's clear which mod wrote info, warnings, and errors. // That way, it's clear which mod wrote info, warnings, and errors.
public static final Logger LOGGER = LoggerFactory.getLogger("polarcraft-mod"); public static final Logger LOGGER = LoggerFactory.getLogger("polarcraft-mod");
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final File CONFIG_FILE = new File(FabricLoader.getInstance().getConfigDir().toFile(), "polarcraft.json");
private String configWebhookUrl = "https://discordapp.com/api/webhooks/webhookid/webhooktoken";
private String configVerifyUrl = "https://example.com/api/minecraft/verifyuuid";
@Override @Override
public void onInitialize() { public void onInitialize() {
// This code runs as soon as Minecraft is in a mod-load-ready state. // This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized. // However, some things (like resources) may still be uninitialized.
// Proceed with mild caution. // Proceed with mild caution.
loadConfig();
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> { ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
ServerPlayerEntity player = (ServerPlayerEntity) handler.player; ServerPlayerEntity player = (ServerPlayerEntity) handler.player;
LOGGER.info("Player {} joined the game.", player.getUuidAsString());
onPlayerJoin(player); onPlayerJoin(player);
}); });
LOGGER.info("Hello Fabric world!"); ServerMessageEvents.CHAT_MESSAGE.register((message, sender, params) -> {
onChatMessage(message, sender);
});
ServerMessageEvents.GAME_MESSAGE.register((server, message, overlay) -> {
onGameMessage(server, message);
});
}
private void loadConfig() {
if (!CONFIG_FILE.exists()) {
saveConfig();
return;
}
try {
MyModConfig config = GSON.fromJson(FileUtils.readFileToString(CONFIG_FILE, StandardCharsets.UTF_8), MyModConfig.class);
configWebhookUrl = config.webhookUrl;
configVerifyUrl = config.verifyUrl;
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveConfig() {
try {
FileUtils.writeStringToFile(CONFIG_FILE, GSON.toJson(new MyModConfig(configWebhookUrl, configVerifyUrl)), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public static class MyModConfig {
public String webhookUrl;
public String verifyUrl;
public MyModConfig(String webhookUrl, String verifyUrl) {
this.webhookUrl = webhookUrl;
this.verifyUrl = verifyUrl;
}
}
private void onChatMessage( SignedMessage message, ServerPlayerEntity sender) {
try {
// Create a URL object for the server endpoint
URL url = new URL(configWebhookUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String requestBody = "{\"content\":\"" + sender.getName().getString() + " > "+ message.getSignedContent() + "\"}";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void onGameMessage( MinecraftServer server, Text message) {
try {
// Create a URL object for the server endpoint
URL url = new URL(configWebhookUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String requestBody = "{\"content\":\"" + "**" + message.getString() + "**" + "\"}";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
private void onPlayerJoin(ServerPlayerEntity player) { private void onPlayerJoin(ServerPlayerEntity player) {
UUID uuid = player.getUuid(); UUID uuid = player.getUuid();
try { try {
// Create the POST request URL url = new URL(configVerifyUrl);
URL url = new URL("http://localhost:3000/api/minecraft/verifyuuid"); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST"); connection.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true); connection.setDoOutput(true);
// Write the request body String requestBody = "{\"uuid\":\"" + uuid + "\"}";
String jsonInputString = "{\"uuid\":\"" + uuid + "\"}";
con.getOutputStream().write(jsonInputString.getBytes()); OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
// Read the response outputStream.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); outputStream.close();
StringBuilder responseBuilder = new StringBuilder();
String responseLine; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((responseLine = in.readLine()) != null) { String line;
responseBuilder.append(responseLine); StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
} }
String responseBody = responseBuilder.toString(); reader.close();
// Parse the response as a JSON object Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(responseBody)); JsonElement element = gson.fromJson(response.toString(), JsonElement.class);
jsonReader.beginObject(); JsonObject jsonResponse = element.getAsJsonObject();
boolean verified = false;
int code = -1; boolean verified = jsonResponse.get("verified").getAsBoolean();
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("verified")) {
verified = jsonReader.nextBoolean();
} else if (key.equals("code")) {
code = jsonReader.nextInt();
} else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
// Kick the player if verified is true
if (!verified) { if (!verified) {
int code = jsonResponse.get("code").getAsInt();
player.networkHandler.disconnect(Text.literal("Whitelist yourself by using this code: " + code)); player.networkHandler.disconnect(Text.literal("Whitelist yourself by using this code: " + code));
} }
} catch (IOException e) { } catch (IOException e) {

View File

@ -0,0 +1,43 @@
<template>
<div class="w-full text-primary flex items-center flex-col">
<div v-if="!user.minecraft.uuid" class="flex flex-col items-center">
<p class="max-w-xl mb-10 sm:text-base text-sm">
Je bent momenteel niet gewhitelist. Om toegang te krijgen tot de Minecraft server moet je in Minecraft naar de
server met het ip <span class="highlight">play.polarcraft.xeovalyte.com</span> gaan. Vervolgens krijg je een code
te zien, vul deze code hieronder in.
</p>
<div class="flex gap-2">
<Input v-model:value="code">Code</Input>
<Button @click="submitCode">Submit</Button>
</div>
</div>
</div>
</template>
<script setup>
definePageMeta({
middleware: ["auth"]
})
const user = useState('user')
const code = ref('')
const submitCode = async () => {
try {
const response = await $fetch('/api/minecraft/whitelist', {
method: 'POST',
body: {
code: code.value
}
})
user.value.minecraft.uuid = response.uuid
user.value.minecraft.username = response.username
useToast().success('Successfully whitelisted')
} catch (e) {
console.log(e);
useToast().error(e.statusMessage)
}
}
</script>

View File

@ -4,10 +4,6 @@
<Icon size="1.5em" name="ph:house" class="mr-3" /> <Icon size="1.5em" name="ph:house" class="mr-3" />
Home Home
</NuxtLink> </NuxtLink>
<NuxtLink to="/whitelist" class="sidebar-item">
<Icon size="1.5em" name="ph:shield-check" class="mr-3" />
Whitelist
</NuxtLink>
<NuxtLink to="/team" class="sidebar-item"> <NuxtLink to="/team" class="sidebar-item">
<Icon size="1.5em" name="ph:users-three" class="mr-3" /> <Icon size="1.5em" name="ph:users-three" class="mr-3" />
Team Team

View File

@ -2,8 +2,8 @@
<div class="h-full bg-neutral-900"> <div class="h-full bg-neutral-900">
<div class="hidden sm:grid grid-cols-desktoplayout grid-rows-desktoplayout h-full"> <div class="hidden sm:grid grid-cols-desktoplayout grid-rows-desktoplayout h-full">
<LayoutNavbar class="col-span-2" /> <LayoutNavbar class="col-span-2" />
<LayoutSidebar class="" /> <LayoutSidebar v-if="user.minecraft.uuid" class="" />
<div class="overflow-y-auto px-10 pt-5"> <div class="overflow-y-auto px-10 pt-5" :class="{ 'col-span-2': !user.minecraft.uuid }">
<NuxtPage /> <NuxtPage />
</div> </div>
</div> </div>
@ -14,3 +14,7 @@
</div> </div>
</div> </div>
</template> </template>
<script setup>
const user = useState('user')
</script>

View File

@ -1,6 +1,24 @@
<template> <template>
<div class="w-full h-full text-primary flex justify-center items-center flex-col"> <div class="w-full h-full text-primary flex flex-col">
<h1 class="text-5xl font-bold text-center mb-10">Welkom, {{ user.discord.username }}</h1> <h1 class="text-5xl font-bold text-center mt-20 mb-10">Welkom, {{ user.discord.username }}</h1>
<Whitelist v-if="!user.minecraft.uuid" />
<div v-else class="flex justify-center gap-4 flex-wrap max-w-3xl w-full">
<img :src="'https://api.mineatar.io/face/' + user.minecraft.uuid + '?scale=16'" class="w-24 rounded shadow">
<div class="rounded flex border-2 border-primary p-4 w-full max-w-md">
<ul class="my-auto">
<li>Username: <b>{{ user.minecraft.username }}</b></li>
<li>UUID: <b>{{ user.minecraft.uuid }}</b></li>
</ul>
</div>
<div class="w-full flex justify-center gap-4 mt-2">
<Button type="danger" @click="removeWhitelist">
Remove from whitelist
</Button>
<Button @click="refreshUsername">
Refresh Username
</Button>
</div>
</div>
</div> </div>
</template> </template>
@ -10,4 +28,32 @@ definePageMeta({
}) })
const user = useState('user') const user = useState('user')
const refreshUsername = async () => {
try {
const response = await $fetch('/api/minecraft/refreshusername')
user.value.minecraft.username = response.username
useToast().success('Username is ververst')
} catch (e) {
console.log(e)
useToast().error(e.statusMessage)
}
}
const removeWhitelist = async () => {
try {
await $fetch('/api/minecraft/removewhitelist')
user.value.minecraft.uuid = null
user.value.minecraft.username = null
useToast().success('Minecraft is niet meer gekoppeld')
} catch (e) {
console.log(e)
useToast().error(e.statusMessage)
}
}
</script> </script>

View File

@ -1,87 +0,0 @@
<template>
<div class="w-full h-full text-primary flex pt-20 items-center flex-col">
<h1 class="sm:text-4xl text-2xl font-bold text-center mb-10">Whitelist</h1>
<div v-if="!user.minecraft.uuid" class="flex flex-col items-center">
<p class="max-w-xl mb-10 sm:text-base text-sm">
Je bent momenteel niet gewhitelist. Om toegang te krijgen tot de Minecraft server moet je in Minecraft naar de server met het ip <span class="highlight">play.polarcraft.xeovalyte.com</span> gaan. Vervolgens krijg je een code te zien, vul deze code hieronder in.
</p>
<div class="flex gap-2">
<Input v-model:value="code">Code</Input>
<Button @click="submitCode">Submit</Button>
</div>
</div>
<div v-else class="flex justify-center gap-4 flex-wrap max-w-3xl w-full">
<img :src="'https://api.mineatar.io/face/' + user.minecraft.uuid + '?scale=16'" class="w-24 rounded shadow">
<div class="rounded flex border-2 border-primary p-4 w-full max-w-md">
<ul class="my-auto">
<li>Username: <b>{{ user.minecraft.username }}</b></li>
<li>UUID: <b>{{ user.minecraft.uuid }}</b></li>
</ul>
</div>
<div class="w-full flex justify-center gap-4 mt-2">
<Button type="danger" @click="removeWhitelist">
Remove from whitelist
</Button>
<Button @click="refreshUsername">
Refresh Username
</Button>
</div>
</div>
</div>
</template>
<script setup>
definePageMeta({
middleware: ["auth"]
})
const user = useState('user')
const code = ref('')
const refreshUsername = async () => {
try {
const response = await $fetch('/api/minecraft/refreshusername')
user.value.minecraft.username = response.username
useToast().success('Username is ververst')
} catch (e) {
console.log(e)
useToast().error(e.statusMessage)
}
}
const removeWhitelist = async () => {
try {
await $fetch('/api/minecraft/removewhitelist')
user.value.minecraft.uuid = null
user.value.minecraft.username = null
useToast().success('Minecraft is niet meer gekoppeld')
} catch (e) {
console.log(e)
useToast().error(e.statusMessage)
}
}
const submitCode = async () => {
try {
const response = await $fetch('/api/minecraft/whitelist', {
method: 'POST',
body: {
code: code.value
}
})
user.value.minecraft.uuid = response.uuid
user.value.minecraft.username = response.username
useToast().success('Successfully whitelisted')
} catch (e) {
console.log(e);
useToast().error(e.statusMessage)
}
}
</script>

View File

@ -1,4 +1,5 @@
{ {
// https://nuxt.com/docs/guide/concepts/typescript // https://nuxt.com/docs/guide/concepts/typescript
"extends": "./.nuxt/tsconfig.json" "extends": "./.nuxt/tsconfig.json",
"allowJS": true
} }