Skip to content

Commit

Permalink
Added DBManager, commands, translations and first step to auth
Browse files Browse the repository at this point in the history
  • Loading branch information
TheCGuyGitHub committed Jul 3, 2024
1 parent 9081059 commit 0bdfd60
Show file tree
Hide file tree
Showing 5 changed files with 228 additions and 124 deletions.
5 changes: 4 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,16 @@ dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version")
implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.ktor:ktor-server-swagger:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")
implementation("io.ktor:ktor-server-auth:$ktor_version")

implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
implementation("com.google.code.gson:gson:2.8.9")

implementation("com.zaxxer:HikariCP:5.1.0")
implementation("org.slf4j:slf4j-api:1.7.25")
implementation("ch.qos.logback:logback-classic:1.5.6")

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package io.github.thecguy.cloudnet_rest_module



import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import eu.cloudnetservice.common.log.LogManager
import eu.cloudnetservice.common.log.Logger

import eu.cloudnetservice.common.language.I18n
import eu.cloudnetservice.driver.document.Document
import eu.cloudnetservice.driver.document.DocumentFactory
import eu.cloudnetservice.driver.inject.InjectionLayer
Expand All @@ -17,7 +15,9 @@ import eu.cloudnetservice.node.command.CommandProvider
import eu.cloudnetservice.node.service.CloudServiceManager
import io.github.thecguy.cloudnet_rest_module.commands.rest
import io.github.thecguy.cloudnet_rest_module.config.Configuration
import io.github.thecguy.cloudnet_rest_module.utli.DBManager
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
Expand All @@ -29,24 +29,19 @@ import kong.unirest.core.json.JSONObject
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.annotations.NotNull
import kotlin.concurrent.Volatile
import kotlin.properties.Delegates
import java.util.Base64


@Singleton
class CloudNet_Rest_Module : DriverModule() {


var configuration: Configuration? = null
private val logger: Logger = LogManager.logger(CloudNet_Rest_Module::class.java)
var host: String? = null
var port: Int? = null
var port: Int? = null
var database: String? = null
var username: String? = null
var password: String? = null



@ModuleTask(order = 127, lifecycle = ModuleLifeCycle.LOADED)
fun convertConfig() {
val config = this.readConfig(DocumentFactory.json())
Expand Down Expand Up @@ -80,86 +75,37 @@ class CloudNet_Rest_Module : DriverModule() {
},
DocumentFactory.json()
)

host = configuration?.host
port = configuration?.port
database = configuration?.database
username = configuration?.username
password = configuration?.password

val config = HikariConfig()

config.jdbcUrl = "jdbc:mysql://${configuration?.host}:${configuration?.port}/${configuration?.database}"
config.username = configuration?.username
config.password = configuration?.password
config.driverClassName = "com.mysql.cj.jdbc.Driver"
config.addDataSourceProperty("cachePrepStmts", "true")
config.addDataSourceProperty("prepStmtCacheSize", "250")
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")

val ds = HikariDataSource(config)
ds.connection.use { connection ->
connection.prepareStatement("CREATE TABLE IF NOT EXISTS cloudnet_rest_users (id SERIAL PRIMARY KEY, user TEXT, password TEXT)").use { statement ->
statement.executeUpdate()
}
connection.prepareStatement("CREATE TABLE IF NOT EXISTS cloudnet_rest_permission (id SERIAL PRIMARY KEY, user TEXT, permission TEXT)").use { statement ->
statement.executeUpdate()
}
connection.prepareStatement("CREATE TABLE IF NOT EXISTS cloudnet_rest_auths (id SERIAL PRIMARY KEY, type TEXT, value TEXT, timestamp TEXT)").use { statement ->
statement.executeUpdate()
}
}
ds.close()
val dbm = DBManager()
dbm.dbexecute("CREATE TABLE IF NOT EXISTS cloudnet_rest_users (id SERIAL PRIMARY KEY, user TEXT, password TEXT)")
dbm.dbexecute("CREATE TABLE IF NOT EXISTS cloudnet_rest_permission (id SERIAL PRIMARY KEY, user TEXT, permission TEXT)")
dbm.dbexecute("CREATE TABLE IF NOT EXISTS cloudnet_rest_auths (id SERIAL PRIMARY KEY, type TEXT, value TEXT, timestamp TEXT)")
}


fun sqlwr(sql: String) {
val host = "192.168.0.226"
val port = 3306
val database = "cloudnet_rest"
val username = "cloudnet"
val password = "cloudnet"
val CONNECT_URL_FORMAT: String = "jdbc:mysql://%s:%d/%s?serverTimezone=UTC"
val config = HikariConfig()
config.jdbcUrl = String.format(
CONNECT_URL_FORMAT,
host, port, database
)
config.username = username
config.password = password
config.driverClassName = "com.mysql.cj.jdbc.Driver"
config.addDataSourceProperty("cachePrepStmts", "true")
config.addDataSourceProperty("prepStmtCacheSize", "250")
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
val ds = HikariDataSource(config)
ds.connection.use { connection ->
connection.prepareStatement("SELECT user FROM cloudnet_rest_users").use { statement ->
statement.executeQuery().use { resultSet ->
while (resultSet.next()) {
val user = resultSet.getString("user")
}
}
}
}
ds.close()
}

@ModuleTask(order = 127, lifecycle = ModuleLifeCycle.STARTED)
fun started(
@NotNull cloudServiceManager: CloudServiceManager,
@NotNull shutdownHandler: ShutdownHandler,
@NotNull @Named("module") injectionLayer: InjectionLayer<*>
) {
println("Decoded: ${Base64.getDecoder().decode("amV0YnJhaW5zOmZvb2Jhcg")}")


I18n.loadFromLangPath(CloudNet_Rest_Module::class.java)
GlobalScope.launch {
main(cloudServiceManager, shutdownHandler)
}
logger.info("Rest API listening on port ${configuration!!.restapi_port.toString()}!")
println("Rest API listening on port ${configuration!!.restapi_port.toString()}!")
}

@ModuleTask(lifecycle = ModuleLifeCycle.STARTED)
fun start(commandProvider: CommandProvider) {
commandProvider.register(rest::class.java)
}
@ModuleTask(lifecycle = ModuleLifeCycle.STOPPED)
fun stop() {
val dbm = DBManager()
println("Closing DB connection!")
dbm.closedb()
println("Closed DB connection!")
}


private fun services(cloudServiceManager: CloudServiceManager): JSONObject {
Expand Down Expand Up @@ -194,13 +140,35 @@ class CloudNet_Rest_Module : DriverModule() {
shutDownUrl = "/debug/shutdown"
exitCodeSupplier = { 0 }
}
install(Authentication) {
basic("auth-basic") {
realm = "Access to the '/' path"
validate { credentials ->
if (credentials.name == "jetbrains" && credentials.password == "foobar") {
UserIdPrincipal(credentials.name)
} else {
null
}
}


}
}


routing {

//swaggerUI(path = "swagger", swaggerFile = "openapi/swagger.yaml")


authenticate("auth-basic") {
get("/auth") {
call.respondText("You have reached the auth site!")
}
}



get("/") {

call.respondText("Welcome to my Rest API!")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,43 +1,34 @@
package io.github.thecguy.cloudnet_rest_module.commands

import cloud.commandframework.annotations.Argument
import cloud.commandframework.annotations.CommandMethod
import cloud.commandframework.annotations.CommandPermission
import cloud.commandframework.annotations.parsers.Parser
import cloud.commandframework.annotations.suggestions.Suggestions
import cloud.commandframework.context.CommandContext
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource

import eu.cloudnetservice.common.language.I18n
import eu.cloudnetservice.driver.inject.InjectionLayer
import eu.cloudnetservice.driver.provider.ServiceTaskProvider
import eu.cloudnetservice.driver.service.ServiceTask
import eu.cloudnetservice.driver.database.DatabaseProvider
import eu.cloudnetservice.driver.document.Document
import eu.cloudnetservice.node.command.annotation.Description
import eu.cloudnetservice.node.command.source.CommandSource

import io.github.thecguy.cloudnet_rest_module.CloudNet_Rest_Module
import io.github.thecguy.cloudnet_rest_module.config.Configuration
import io.github.thecguy.cloudnet_rest_module.utli.DBManager

import jakarta.inject.Singleton
import org.checkerframework.checker.nullness.qual.NonNull

import org.jetbrains.annotations.NotNull

import java.util.*


@Singleton
@CommandPermission("thecguy.test")
@Description("test")
class rest {


public class test(
@NotNull config: Configuration
) {
public val config = config
}

private val dbManager = DBManager()
private val taskProvider: ServiceTaskProvider = InjectionLayer.ext().instance(ServiceTaskProvider::class.java)
private val databaseProvider: DatabaseProvider = InjectionLayer.ext().instance(DatabaseProvider::class.java)


@Suggestions("rest")
Expand All @@ -54,38 +45,73 @@ class rest {
fun users(
source: CommandSource,
) {
val host = "127.0.0.1"
val port = 3306
val database = "cloudnet_rest"
val username = "cloudnet"
val password = "cloudnet"
val CONNECT_URL_FORMAT: String = "jdbc:mysql://%s:%d/%s?serverTimezone=UTC"
val config = HikariConfig()
config.jdbcUrl = String.format(
CONNECT_URL_FORMAT,
host, port, database
)
config.username = username
config.password = password
config.driverClassName = "com.mysql.cj.jdbc.Driver"
config.addDataSourceProperty("cachePrepStmts", "true")
config.addDataSourceProperty("prepStmtCacheSize", "250")
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
val ds = HikariDataSource(config)
ds.connection.use { connection ->
connection.prepareStatement("SELECT user FROM cloudnet_rest_users").use { statement ->
statement.executeQuery().use { resultSet ->
source.sendMessage("Current registered RestAPI users:")
while (resultSet.next()) {
val user = resultSet.getString("user")
source.sendMessage(user)
}
}
source.sendMessage(I18n.trans("module-rest-command-users"))
source.sendMessage(dbManager.cmd_rest_users())
}
@CommandMethod("rest user create <username> <password>")
fun createUser(
source: CommandSource,
@NotNull @Argument("username") username: String,
@NotNull @Argument("password") password: String
) {
val users = dbManager.cmd_rest_users()
if (users.contains(username)) {
source.sendMessage(I18n.trans("module-rest-command-usersexist"))
} else {
val encodedpw: String = Base64.getEncoder().encodeToString(password.toByteArray())
dbManager.dbexecute("INSERT INTO cloudnet_rest_users (user, password) VALUES ('$username', '$encodedpw')")
source.sendMessage(I18n.trans("module-rest-command-createduser"))
}
}
@CommandMethod("rest user delete <username>")
fun deleteUser(
source: CommandSource,
@NotNull @Argument("username") username: String
) {
val users = dbManager.cmd_rest_users()
if (users.contains(username)) {
dbManager.dbexecute("DELETE FROM cloudnet_rest_users WHERE user = '$username'")
source.sendMessage(I18n.trans("module-rest-command-deluser"))
} else {
source.sendMessage(I18n.trans("module-rest-command-usernotexist"))
}
}
@CommandMethod("rest user user <username> add permission <permission>")
fun addPermsToUser(
source: CommandSource,
@NotNull @Argument("username") username: String,
@NotNull @Argument("permission") permissison: String
) {
val users = dbManager.cmd_rest_users()
if (users.contains(username)) {
val perms = dbManager.cmd_rest_perms(username)
if (perms.contains(permissison)) {
source.sendMessage(I18n.trans("module-rest-command-permsalredy"))
} else {
dbManager.dbexecute("INSERT INTO cloudnet_rest_permission (user, permission) VALUE ('$username', '$permissison')")
source.sendMessage(I18n.trans("module-rest-command-permsadded"))
}
} else {
source.sendMessage(I18n.trans("module-rest-command-usernotexist"))
}
}
@CommandMethod("rest user user <username> remove permission <permission>")
fun remPerms(
source: CommandSource,
@NotNull @Argument("username") username: String,
@NotNull @Argument("permission") permisison: String
) {
val users = dbManager.cmd_rest_users()
if (users.contains(username)) {
val perms = dbManager.cmd_rest_perms(username)
if (perms.contains(permisison)) {
dbManager.dbexecute("DELETE FROM cloudnet_rest_permission WHERE permission = '$permisison'")
source.sendMessage(I18n.trans("module-rest-command-permsrem"))
} else {
source.sendMessage(I18n.trans("module-rest-command-notperms"))
}
} else {
source.sendMessage(I18n.trans("module-rest-command-usernotexist"))
}
ds.close()
}



}
Loading

0 comments on commit 0bdfd60

Please sign in to comment.