Skip to content

Commit

Permalink
check shortened url to be valid
Browse files Browse the repository at this point in the history
  • Loading branch information
avan1235 committed Feb 9, 2024
1 parent c03556c commit a53b00b
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions server/src/main/kotlin/in/procyk/shin/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -77,7 +81,7 @@ private fun Application.routes(): Routing = routing {
post<Shorten> {
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<Decode> {
val shortenedId = it.shortenedId
Expand All @@ -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) {
Expand Down Expand Up @@ -130,4 +136,16 @@ private inline fun <reified T : Any> 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}")
}
}
}

private inline val String.isValidURL: Boolean
get() {
try {
URL(this).toURI()
return true
} catch (e: MalformedURLException) {
return false
} catch (e: URISyntaxException) {
return false
}
}

0 comments on commit a53b00b

Please sign in to comment.