From 82c66d4b3a7c7ca16f677857ec4941110d768d6b Mon Sep 17 00:00:00 2001 From: gowthaman Date: Mon, 29 Apr 2024 18:39:56 +0530 Subject: [PATCH] sync plants --- src/main/kotlin/com/restapi/config/Auth.kt | 75 ++++++++++++++-------- 1 file changed, 47 insertions(+), 28 deletions(-) diff --git a/src/main/kotlin/com/restapi/config/Auth.kt b/src/main/kotlin/com/restapi/config/Auth.kt index 792d279..9b00803 100644 --- a/src/main/kotlin/com/restapi/config/Auth.kt +++ b/src/main/kotlin/com/restapi/config/Auth.kt @@ -59,11 +59,15 @@ object Auth { } - private val jwtConsumer = JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30).setRequireSubject().setExpectedAudience("account") - .setExpectedIssuer(getAuthEndpoint().issuer).setVerificationKeyResolver(HttpsJwksVerificationKeyResolver(HttpsJwks(getAuthEndpoint().jwksUri))).build() + private val jwtConsumer = + JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30).setRequireSubject() + .setExpectedAudience("account") + .setExpectedIssuer(getAuthEndpoint().issuer) + .setVerificationKeyResolver(HttpsJwksVerificationKeyResolver(HttpsJwks(getAuthEndpoint().jwksUri))).build() private val jwtConsumerSkipValidate = - JwtConsumerBuilder().setSkipAllValidators().setVerificationKeyResolver(HttpsJwksVerificationKeyResolver(HttpsJwks(getAuthEndpoint().jwksUri))).build() + JwtConsumerBuilder().setSkipAllValidators() + .setVerificationKeyResolver(HttpsJwksVerificationKeyResolver(HttpsJwks(getAuthEndpoint().jwksUri))).build() fun validateAuthToken(authToken: String, skipValidate: Boolean = false): AuthUser { @@ -75,27 +79,34 @@ object Auth { val roles = ((jwtClaims.jwtClaims.claimsMap["realm_access"] as Map)["roles"]) as List val date = Date(jwtClaims.jwtClaims.expirationTime.valueInMillis) -// try { -// HttpClients.createDefault().use { h -> -// //sync plant's from rmc to here, just name and id -// for (plantId in plantIds) { -// -// val existing = Session.database.find(Plant::class.java).where().eq("plantId", plantId).findOne() -// if (existing == null) { -// h.execute(HttpGet("${appConfig.integrationRmc()}/plant?id=${plantId}")).use { r -> -// if (r.statusLine.statusCode == 200) { -// Session.database.save(Plant().apply { -// this.plantId = plantId -// this.plantName = EntityUtils.toString(r.entity) -// }) -// } -// } -// } -// } -// } -// } catch (e: Exception) { -// logger.warn("Exception in syncing plants", e) -// } + try { + HttpClients.createDefault().use { h -> + //sync plant's from rmc to here, just name and id + for (plantId in plantIds) { + + val existing = Session.database.find(Plant::class.java).where().eq("plantId", plantId).findOne() + + h.execute(HttpGet("${appConfig.integrationRmc()}/plant?id=${plantId}")).use { r -> + if (r.statusLine.statusCode == 200) { + val response = EntityUtils.toString(r.entity) + if (existing == null) { + Session.database.save(Plant().apply { + this.plantId = plantId + this.plantName = response + }) + } else { + existing.apply { + this.plantName = response + this.save() + } + } + } + } + } + } + } catch (e: Exception) { + logger.warn("Exception in syncing plants", e) + } return AuthUser( userName = userId, @@ -140,7 +151,8 @@ object Auth { fun init(ctx: Context) { val endpoint = getAuthEndpoint().authorizationEndpoint - val redirectUrl = "$endpoint?response_type=code&client_id=${appConfig.iamClient()}&redirect_uri=${appConfig.iamClientRedirectUri()}&scope=profile&state=1234zyx" + val redirectUrl = + "$endpoint?response_type=code&client_id=${appConfig.iamClient()}&redirect_uri=${appConfig.iamClientRedirectUri()}&scope=profile&state=1234zyx" ctx.redirect(redirectUrl) } @@ -181,7 +193,8 @@ object Auth { fun refreshToken(ctx: Context) { //refresh authToken - val authToken = ctx.header("Authorization")?.replace("Bearer ", "")?.replace("Bearer: ", "")?.trim() ?: throw UnauthorizedResponse() + val authToken = ctx.header("Authorization")?.replace("Bearer ", "")?.replace("Bearer: ", "")?.trim() + ?: throw UnauthorizedResponse() val authUser = validateAuthToken(authToken, skipValidate = true) val client = ctx.queryParam("client") ?: throw BadRequestResponse("client not sent") @@ -190,7 +203,8 @@ object Auth { val key = "$AUTH_TOKEN${authUser.userName}" val found = Session.redis.llen(key) logger.warn("for user ${authUser.userName}, found from redis, $key => $found entries") - val foundOldAt = (0..found).mapNotNull { Session.redis.lindex(key, it) }.map { objectMapper.readValue(it) }.firstOrNull { it.accessToken == authToken } + val foundOldAt = (0..found).mapNotNull { Session.redis.lindex(key, it) } + .map { objectMapper.readValue(it) }.firstOrNull { it.accessToken == authToken } ?: throw BadRequestResponse("authToken not found in cache") val createdAt = foundOldAt.createdAt ?: throw BadRequestResponse("created at is missing") @@ -244,7 +258,12 @@ object Auth { } data class AuthUser( - val userName: String, val tenant: String, val roles: List, val token: String, val expiry: LocalDateTime, val plantIds: List + val userName: String, + val tenant: String, + val roles: List, + val token: String, + val expiry: LocalDateTime, + val plantIds: List ) enum class Action {