diff --git a/server/src/main/kotlin/in/procyk/shin/Application.kt b/server/src/main/kotlin/in/procyk/shin/Application.kt index ed61f6f..195f916 100644 --- a/server/src/main/kotlin/in/procyk/shin/Application.kt +++ b/server/src/main/kotlin/in/procyk/shin/Application.kt @@ -24,9 +24,13 @@ import org.jetbrains.exposed.sql.transactions.transaction import org.koin.dsl.module import org.koin.ktor.ext.inject import org.koin.ktor.plugin.Koin +import java.net.MalformedURLException +import java.net.URISyntaxException +import java.net.URL import java.security.MessageDigest import java.util.* + fun main() { val dotenv = dotenv { ignoreIfMissing = true @@ -77,7 +81,7 @@ private fun Application.routes(): Routing = routing { post { val shortId = findShortenedId(it.url) if (shortId != null) call.respond(HttpStatusCode.OK, "$redirectBaseUrl$shortId") - else call.respond(HttpStatusCode.InternalServerError) + else call.respond(HttpStatusCode.BadRequest) } get { val shortenedId = it.shortenedId @@ -90,6 +94,8 @@ private fun Application.routes(): Routing = routing { } private suspend fun findShortenedId(url: String): String? { + if (!url.isValidURL) return null + val id = url.sha256() return newSuspendedTransaction txn@{ for (n in 1..id.length) { @@ -130,4 +136,16 @@ private inline fun Dotenv.env(name: String): T { Int::class -> value.toIntOrNull() as? T ?: error("$value cannot be converted to ${T::class.simpleName}") else -> throw IllegalArgumentException("Unsupported type ${T::class.simpleName}") } -} \ No newline at end of file +} + +private inline val String.isValidURL: Boolean + get() { + try { + URL(this).toURI() + return true + } catch (e: MalformedURLException) { + return false + } catch (e: URISyntaxException) { + return false + } + } \ No newline at end of file