1+ package com.jackharrhy.whitelist
2+
3+ import io.javalin.Javalin
4+ import io.javalin.http.BadRequestResponse
5+ import io.javalin.http.UnauthorizedResponse
6+ import org.bukkit.Bukkit
7+ import java.util.*
8+ import kotlin.collections.HashSet
9+
10+ class WebServer (plugin : Whitelist , bearerToken : String ) {
11+ private data class User (val uuid : UUID )
12+
13+ init {
14+ val port = 7500
15+
16+ val classLoader = Thread .currentThread().contextClassLoader
17+ Thread .currentThread().contextClassLoader = Whitelist ::class .java.classLoader
18+ val app = Javalin .create().start(port)
19+ Thread .currentThread().contextClassLoader = classLoader
20+
21+ app.before { ctx ->
22+ val auth = ctx.header(" authorization" )
23+
24+ if (auth.isNullOrBlank()) {
25+ throw UnauthorizedResponse ()
26+ } else {
27+ if (! (auth.startsWith(" WHA" ) && auth.endsWith(bearerToken))) {
28+ throw UnauthorizedResponse (" Invalid Token" )
29+ }
30+ }
31+ }
32+
33+ app.get(" /" ) { ctx ->
34+ val players = HashSet <UUID >()
35+ for (player in Bukkit .getWhitelistedPlayers()) {
36+ players.add(player.uniqueId)
37+ }
38+ ctx.json(players)
39+ }
40+
41+ app.post(" /" ) { ctx ->
42+ val uuid = ctx.body<User >().uuid
43+ val player = Bukkit .getOfflinePlayer(uuid)
44+ if (player.isWhitelisted) {
45+ throw BadRequestResponse (" Already whitelisted!" )
46+ } else {
47+ player.isWhitelisted = true
48+ ctx.status(201 ).result(" " )
49+ }
50+ }
51+
52+ app.delete(" /" ) { ctx ->
53+ val uuid = ctx.body<User >().uuid
54+ val player = Bukkit .getOfflinePlayer(uuid)
55+ if (player.isWhitelisted) {
56+ player.isWhitelisted = false
57+ ctx.status(201 ).result(" " )
58+ } else {
59+ throw BadRequestResponse (" Not whitelisted!" )
60+ }
61+ }
62+
63+ plugin.logger.info(" WebServer now running on port $port " )
64+ }
65+ }
0 commit comments