From c85d582a646165e46d7c7c85cf9685fc3951dc4c Mon Sep 17 00:00:00 2001 From: Anton Keks Date: Thu, 14 Mar 2024 16:29:09 +0200 Subject: [PATCH] support for missing locale --- CHANGELOG.md | 2 +- oauth/src/OAuthClient.kt | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a520e5d..f57a73cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ * core: Registry and TypedHttpClient moved from server module, so that JsonHttpClient can be used without the server * server: HttpExchange.path<>() and query<>() now allow for automatic String conversion into value types * jobs: deprecated non-Duration schedule() methods -* oauth: support for missing first or last names +* oauth: support for missing first or last names or locale # 1.6.6 * core: Converter will force initialize companion objects to better support `init { Converter.use {...} }` diff --git a/oauth/src/OAuthClient.kt b/oauth/src/OAuthClient.kt index f8fa6b0c..424a3b9e 100644 --- a/oauth/src/OAuthClient.kt +++ b/oauth/src/OAuthClient.kt @@ -51,6 +51,8 @@ abstract class OAuthClient(scope: String, authUrl: String, tokenUrl: String, pro protected suspend fun fetchProfileResponse(token: OAuthTokenResponse): JsonNode = http.get(profileUrl) { authBearer(token.accessToken) } abstract suspend fun profile(token: OAuthTokenResponse, exchange: HttpExchange): UserProfile + + protected fun JsonNode.getLocale(key: String = "locale") = getOrNull(key)?.let { Locale.forLanguageTag(it) } } /** https://console.cloud.google.com/apis/credentials */ @@ -66,7 +68,7 @@ class GoogleOAuthClient(httpClient: HttpClient): OAuthClient( val email = Email(res.getString("email")) return UserProfile(provider, res.getString("id"), email, res.getOrNull("givenName") ?: email.value.substringBefore("@").capitalize(), res.getOrNull("familyName") ?: "", - res.getOrNull("picture")?.let { URI(it) }, Locale.forLanguageTag(res.getString("locale"))) + res.getOrNull("picture")?.let { URI(it) }, res.getLocale()) } } @@ -82,7 +84,7 @@ class MicrosoftOAuthClient(httpClient: HttpClient): OAuthClient( val res = fetchProfileResponse(token) val email = res.getOrNull("mail") ?: res.getOrNull("userPrincipalName") ?: error("Cannot obtain user's email") return UserProfile(provider, res.getString("id"), Email(email), res.getOrNull("givenName") ?: email.substringBefore("@").capitalize(), res.getOrNull("surname") ?: "", - locale = Locale.forLanguageTag(res.getString("preferredLanguage"))) + locale = res.getLocale("preferredLanguage")) } } @@ -102,7 +104,7 @@ class FacebookOAuthClient(httpClient: HttpClient): OAuthClient( return UserProfile(provider, res.getString("id"), email, res.getOrNull("firstName") ?: email.value.substringBefore("@").capitalize(), res.getOrNull("lastName") ?: "", avatarData?.getOrNull("url")?.takeIf { avatarExists }?.let { URI(it) }, - Locale.forLanguageTag(res.getString("locale"))) + res.getLocale()) } }