Skip to content

Commit

Permalink
Add /admin/server/shutdown. Not Implemented yet
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewcell committed Aug 14, 2023
1 parent 95cd7e1 commit 63621ea
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main/kotlin/webapi/WebApiApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import mu.KLoggable
import org.slf4j.event.Level
import tools.ServerJSON
import webapi.controller.account
import webapi.controller.adminServer
import webapi.controller.index
import webapi.tools.ApiResponse
import webapi.tools.JWTVariables
Expand Down Expand Up @@ -69,6 +70,7 @@ object WebApiApplication : KLoggable {
install(Routing) {
index()
account()
adminServer()
}
}.start(wait = false)
}
Expand Down
47 changes: 47 additions & 0 deletions src/main/kotlin/webapi/controller/AdminServer.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package webapi.controller

import database.Accounts
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.logging.*
import mu.KotlinLogging
import net.server.Server
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.transaction
import webapi.tools.ApiResponse
import webapi.tools.ResponseMessage

private val logger = KotlinLogging.logger { }
fun Route.adminServer() {
authenticate("auth") {
route("/admin/server") {
post("/shutdown") {
val principal = call.principal<JWTPrincipal>() ?: return@post
val gm = (principal.payload.getClaim("gm").asInt() ?: -1)
val isAdmin = gm > 1
val name = principal.payload.getClaim("name").asString()
val id = principal.payload.getClaim("id").asInt()
if (!isAdmin || name == null || id == null) return@post
var validated = false
transaction { // Validate username and id is not malformed
val account = Accounts.slice(Accounts.id, Accounts.name, Accounts.gm).select { Accounts.name eq name }
if (account.empty()) return@transaction
val accountEntry = account.first()
val dbName = accountEntry[Accounts.name]
val dbId = accountEntry[Accounts.id]
val dbGm = accountEntry[Accounts.gm]
if (dbName != name || dbId != id || dbGm != gm) return@transaction
validated = true
}
if (validated) {
logger.error { "Warning. Server is going to be shut down. triggered by Admin $name, Id: $id, GM Level: $gm" }
Runtime.getRuntime().addShutdownHook(Thread(Server.shutdown(false)))
}
}
}
}
}

0 comments on commit 63621ea

Please sign in to comment.