Skip to content

Commit

Permalink
Merge pull request #85 from opatry/84-fix-http-auth-redirect
Browse files Browse the repository at this point in the history
Fix Http auth redirect & provide nice looking UI feedback (fixes #84)
  • Loading branch information
opatry authored Oct 29, 2024
2 parents 7a8f55f + a52867a commit 06329b9
Show file tree
Hide file tree
Showing 19 changed files with 367 additions and 14 deletions.
2 changes: 2 additions & 0 deletions google/oauth-http/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ kotlin {

implementation(libs.bundles.ktor.client)
implementation(libs.bundles.ktor.server)
implementation(libs.ktor.server.htmlBuilder)
implementation(libs.ktor.server.statusPages)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,26 @@ import io.ktor.http.fullPath
import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.ApplicationStarted
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.response.respond
import io.ktor.server.html.respondHtml
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.response.respondRedirect
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeout
import kotlinx.html.a
import kotlinx.html.code
import kotlinx.html.details
import kotlinx.html.pre
import kotlinx.html.summary
import net.opatry.google.auth.html.authScaffold
import net.opatry.google.auth.html.internalError
import net.opatry.google.auth.html.notFound
import java.net.URLDecoder
import java.net.URLEncoder
import kotlin.time.Duration.Companion.minutes
import kotlin.uuid.ExperimentalUuidApi
Expand Down Expand Up @@ -110,23 +121,77 @@ class HttpGoogleAuthenticator(private val config: ApplicationConfig) : GoogleAut
"${it.key}=${it.value}"
}

var authCode: String? = null

return withTimeout(5.minutes) {
callbackFlow {
val url = Url(config.redirectUrl)
val server = embeddedServer(ServerEngineCIO, port = url.port, host = url.host) {
install(StatusPages) {
notFound()
internalError()
}

routing {
get("signed-in") {
val status = HttpStatusCode.OK
call.respond(status, "$status: Authorization accepted.")
// FIXME redirect URL coupled to product
val redirectToAppUrl = "taskfolio://signin/success"
call.respondHtml(HttpStatusCode.OK) {
authScaffold(
pageTitle = "Google Authorization",
subTitle = "Google Authorization successful",
illustrationName = "undraw_completing_re_i7ap",
redirectUrl = redirectToAppUrl
) {
+"You can "
a(href = redirectToAppUrl) {
+" go back to the application"
}
+" and close this window."
}
}

authCode?.let {
send(it)
close(null)
} ?: close(IllegalStateException("No auth code"))
}
get("error") {
val errorMessage = call.request.queryParameters["message"] ?: "Unknown error"
val status = HttpStatusCode.BadRequest
call.respond(status, "$status: $errorMessage")
val errorDetails = call.request.queryParameters["details"]
// FIXME redirect URL coupled to product
val redirectToAppUrl = "taskfolio://signin/failure?message=${errorMessage}"
call.respondHtml(HttpStatusCode.BadRequest) {
authScaffold(
pageTitle = "Google Authorization",
subTitle = "Google Authorization failed",
illustrationName = "undraw_warning_re_eoyh",
redirectUrl = redirectToAppUrl
) {
+"An error occurred ("
code {
+URLDecoder.decode(errorMessage, Charsets.UTF_8.name())
}
+") during the Google Authorization process. Please try again."

if (errorDetails != null) {
details {
summary {
+"See details"
}
pre {
+URLDecoder.decode(errorDetails, Charsets.UTF_8.name())
}
}
}
}
}
close(IllegalStateException(errorMessage))
}
get(url.fullPath.takeIf(String::isNotEmpty) ?: "/") {
fun Parameters.require(key: String): String =
requireNotNull(get(key)) { "Expected '$key' query parameter not available." }
fun Parameters.require(key: String): String {
return requireNotNull(get(key)) { "Expected '$key' query parameter not available." }
}

val queryParams = call.request.queryParameters
try {
Expand All @@ -135,14 +200,20 @@ class HttpGoogleAuthenticator(private val config: ApplicationConfig) : GoogleAut

val state = queryParams.require("state")
require(uuid == Uuid.parse(state)) { "Mismatch between expected & provided state ($state)." }
val authCode = queryParams.require("code")
// store the auth code in memory for further reuse in /signed-in route
// redirect immediately minimizes the time the code is visible to the user in the URL
authCode = queryParams.require("code")
// redirect to another endpoint to hide the code from the user as quickly as possible
call.respondRedirect("${url}/signed-in")
send(authCode)
close(null)
} catch (e: Exception) {
call.respondRedirect("${url}/error?message=${e.message}")
close(e)
// FIXME URLEncoder is not KMP-friendly
val errorQueryParams = mapOf(
"message" to e.message,
"details" to e.stackTraceToString(),
).entries.joinToString(prefix = "?", separator = "&") { (key, value) ->
"${URLEncoder.encode(key, Charsets.UTF_8.name())}=${URLEncoder.encode(value, Charsets.UTF_8.name())}"
}
call.respondRedirect("${url}/error$errorQueryParams")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* Copyright (c) 2024 Olivier Patry
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package net.opatry.google.auth.html

import kotlinx.html.HTML
import kotlinx.html.P
import kotlinx.html.body
import kotlinx.html.div
import kotlinx.html.h2
import kotlinx.html.head
import kotlinx.html.id
import kotlinx.html.img
import kotlinx.html.link
import kotlinx.html.meta
import kotlinx.html.noScript
import kotlinx.html.p
import kotlinx.html.style
import kotlinx.html.title
import kotlinx.html.unsafe
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi

private object Resources

// FIXME not KMP-friendly
internal fun inlinedResource(resourcePath: String): String {
return Resources.javaClass.getResource(resourcePath)?.readText() ?: ""
}

// FIXME not KMP-friendly
internal fun inlinedResourceData(resourcePath: String): ByteArray {
return Resources.javaClass.getResource(resourcePath)?.readBytes() ?: ByteArray(0)
}

@OptIn(ExperimentalEncodingApi::class)
internal fun base64Image(resourcePath: String): String {
val data = inlinedResourceData(resourcePath)
return Base64.encode(data)
}

internal fun base64ImageData(resourcePath: String, mimeType: String): String {
return "data:$mimeType;base64,${base64Image(resourcePath)}"
}

// FIXME branding color not customizable (PNG, SVG, CSS)
fun HTML.authScaffold(
pageTitle: String,
subTitle: String = pageTitle,
illustrationName: String? = null,
redirectUrl: String? = null,
message: (P.() -> Unit)? = null
) {
head {
title(pageTitle)
// inline CSS stylesheet instead of using an HTTP served file to let the page be self-contained avoid request on stopped short-lived server
style(type = "text/css") {
unsafe {
// load CSS resource from classpath
+inlinedResource("/static/style.css")
}
}
link(rel="shortcut icon") {
type = "image/x-icon"
href = base64ImageData("/static/favicon.ico", "image/x-icon")
}
if (redirectUrl != null) {
// HTML meta tag to redirect to the app
meta {
httpEquiv = "refresh"
content = "0; url=$redirectUrl"
}
}
}
body {
div {
id = "content"

h2 {
+subTitle
}

if (illustrationName != null) {
div("illustration") {
p {
// base64 SVG image to avoid an HTTP request being made after short-lived server is stopped
img(src = base64ImageData("/static/$illustrationName.svg", "image/svg+xml"), alt = "", classes = "centered-image")
}

noScript {
// base64 PNG image to avoid an HTTP request being made after short-lived server is stopped
img(src = base64ImageData("/static/$illustrationName.png", "image/png"), alt = "", classes = "centered-image")
}
}
}

if (message != null) {
p {
message()
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright (c) 2024 Olivier Patry
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package net.opatry.google.auth.html

import io.ktor.http.HttpStatusCode
import io.ktor.server.html.respondHtml
import io.ktor.server.plugins.statuspages.StatusPagesConfig
import kotlinx.html.code

fun StatusPagesConfig.notFound() {
status(HttpStatusCode.NotFound) { call, code ->
call.respondHtml(code) {
authScaffold(
pageTitle = "Resource not found",
illustrationName = "undraw_page_not_found_re_e9o6"
) {
+"Can't find the requested resource."
}
}
}
}

fun StatusPagesConfig.internalError() {
exception<Throwable> { call, cause ->
call.respondHtml(HttpStatusCode.InternalServerError) {
authScaffold(
pageTitle = "Internal server error",
illustrationName = "undraw_fixing_bugs_w7gi"
) {
+"An unexpected error occurred ("
code {
+(cause.message ?: "unknown error")
}
+")."
}
}
}
}
Binary file not shown.
35 changes: 35 additions & 0 deletions google/oauth-http/src/commonMain/resources/static/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
body {
padding: 0;
margin: 0;
font-family: sans-serif;
font-size: 16px;
}

a {
color: #006b58;
}

#content {
margin: 0 auto;
padding: 0;
width: 100%;
max-width: 800px;
}

.centered-image {
max-width: 200px;
max-height: 200px;
margin: auto;
display: block;
}

.illustration {
margin: 48px;
}

pre {
background-color: #f4f4f4;
padding: 10px;
border-radius: 5px;
overflow-x: auto;
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 06329b9

Please sign in to comment.