Skip to content

Commit

Permalink
More consistent use of IO context
Browse files Browse the repository at this point in the history
  • Loading branch information
blootsvoets committed Oct 25, 2023
1 parent 8931cd0 commit 54d5c90
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ class GarminSourceAuthorizationService(
// request to pull the external id is needed.
val response = request(HttpMethod.Get, GARMIN_USER_ID_ENDPOINT, this@getExternalId, sourceType)
when (response.status) {
HttpStatusCode.OK -> response.body<RestOauth1UserId>().userId
HttpStatusCode.OK -> withContext(Dispatchers.IO) {
response.body<RestOauth1UserId>().userId
}
HttpStatusCode.BadRequest, HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden -> throw HttpBadGatewayException("Service was unable to fetch the external ID")
else -> throw HttpBadGatewayException("Cannot connect to ${response.request.url}: HTTP status ${response.status}")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,9 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.time.Instant
import java.util.concurrent.ThreadLocalRandom
import kotlin.collections.Map
import kotlin.collections.MutableMap
import kotlin.collections.buildMap
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.joinToString
import kotlin.collections.mutableMapOf
import kotlin.collections.set
import kotlin.collections.toSortedMap

abstract class OAuth1RestSourceAuthorizationService(
@Context private val clientService: RestSourceClientService,
Expand Down Expand Up @@ -94,37 +88,34 @@ abstract class OAuth1RestSourceAuthorizationService(
}

val authConfig = clientService.forSourceType(user.sourceType)
return withContext(Dispatchers.IO) {
val response = request(
HttpMethod.Delete,
authConfig.deregistrationEndpoint!!,
RestOauth1AccessToken(accessToken, user.refreshToken),
user.sourceType,
)
when (response.status) {
HttpStatusCode.OK, HttpStatusCode.NoContent -> {
userRepository.updateToken(null, user)
true
}

HttpStatusCode.BadRequest, HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden -> false
else -> throw HttpBadGatewayException("Cannot connect to ${response.request.url}: HTTP status ${response.status}")
val response = request(
HttpMethod.Delete,
authConfig.deregistrationEndpoint!!,
RestOauth1AccessToken(accessToken, user.refreshToken),
user.sourceType,
)
return when (response.status) {
HttpStatusCode.OK, HttpStatusCode.NoContent -> {
userRepository.updateToken(null, user)
true
}

HttpStatusCode.BadRequest, HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden -> false
else -> throw HttpBadGatewayException("Cannot connect to ${response.request.url}: HTTP status ${response.status}")
}
}

override suspend fun revokeToken(externalId: String, sourceType: String, token: String): Boolean {
val authConfig = clientService.forSourceType(sourceType)

if (token.isEmpty()) throw HttpBadRequestException("token-empty", "Token cannot be null or empty")
val response = withContext(Dispatchers.IO) {
request(
HttpMethod.Delete,
authConfig.deregistrationEndpoint!!,
RestOauth1AccessToken(token, ""),
sourceType,
)
}
val response = request(
HttpMethod.Delete,
authConfig.deregistrationEndpoint!!,
RestOauth1AccessToken(token, ""),
sourceType,
)

return when (response.status) {
HttpStatusCode.OK, HttpStatusCode.NoContent -> true
Expand Down Expand Up @@ -185,19 +176,26 @@ abstract class OAuth1RestSourceAuthorizationService(
}
}

suspend fun request(method: HttpMethod, url: String, tokens: RestOauth1AccessToken, sourceType: String): HttpResponse {
suspend fun request(
method: HttpMethod,
url: String,
tokens: RestOauth1AccessToken,
sourceType: String,
): HttpResponse {
val authConfig = clientService.forSourceType(sourceType)
val params = this.getAuthParams(authConfig, tokens.token, tokens.tokenVerifier)
params[OAUTH_SIGNATURE] =
OauthSignature(url, params, method, authConfig.clientSecret, tokens.tokenSecret).getEncodedSignature()

return httpClient.request(url = Url(url)) {
headers {
append("Authorization", "OAuth ${params.toFormattedHeader()}")
}
this.method = method
if (method == HttpMethod.Post) {
setBody("")
return withContext(Dispatchers.IO){
httpClient.request(url = Url(url)) {
headers {
append("Authorization", "OAuth ${params.toFormattedHeader()}")
}
this.method = method
if (method == HttpMethod.Post) {
setBody("")
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ open class OAuth2RestSourceAuthorizationService(
override fun signRequest(user: RestSourceUser, payload: SignRequestParams): SignRequestParams =
throw HttpBadRequestException("", "Not available for auth type")

private suspend fun submitForm(sourceType: String, builder: ParametersBuilder.(RestSourceClient) -> Unit): HttpResponse {
private suspend fun submitForm(
sourceType: String,
builder: ParametersBuilder.(RestSourceClient) -> Unit,
): HttpResponse {
val authorizationConfig = clients.forSourceType(sourceType)

return httpClient.submitForm(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import io.ktor.client.statement.bodyAsText
import io.ktor.http.isSuccess
import io.ktor.http.takeFrom
import jakarta.ws.rs.core.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.radarbase.authorizer.config.AuthorizerConfig
import org.radarbase.authorizer.doa.entity.RestSourceUser

Expand All @@ -24,21 +26,27 @@ class OuraAuthorizationService(
val deregistrationEndpoint = checkNotNull(authConfig.deregistrationEndpoint)

val isSuccess = try {
val response = httpClient.submitForm {
url {
takeFrom(deregistrationEndpoint)
parameters.append("access_token", accessToken)
withContext(Dispatchers.IO) {
val response = httpClient.submitForm {
url {
takeFrom(deregistrationEndpoint)
parameters.append("access_token", accessToken)
}
basicAuth(
username = checkNotNull(authConfig.clientId),
password = checkNotNull(authConfig.clientSecret),
)
}
if (response.status.isSuccess()) {
true
} else {
logger.error(
"Failed to revoke token for user {}: {}",
user.userId,
response.bodyAsText().take(512)
)
false
}
basicAuth(
username = checkNotNull(authConfig.clientId),
password = checkNotNull(authConfig.clientSecret),
)
}
if (response.status.isSuccess()) {
true
} else {
logger.error("Failed to revoke token for user {}: {}", user.userId, response.bodyAsText().take(512))
false
}
} catch (ex: Exception) {
logger.warn("Revoke endpoint error: {}", ex.toString())
Expand Down

0 comments on commit 54d5c90

Please sign in to comment.