sync plants

This commit is contained in:
gowthaman 2024-04-29 18:39:56 +05:30
parent c96656086e
commit 82c66d4b3a

View File

@ -59,11 +59,15 @@ object Auth {
} }
private val jwtConsumer = JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30).setRequireSubject().setExpectedAudience("account") private val jwtConsumer =
.setExpectedIssuer(getAuthEndpoint().issuer).setVerificationKeyResolver(HttpsJwksVerificationKeyResolver(HttpsJwks(getAuthEndpoint().jwksUri))).build() JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30).setRequireSubject()
.setExpectedAudience("account")
.setExpectedIssuer(getAuthEndpoint().issuer)
.setVerificationKeyResolver(HttpsJwksVerificationKeyResolver(HttpsJwks(getAuthEndpoint().jwksUri))).build()
private val jwtConsumerSkipValidate = 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 { fun validateAuthToken(authToken: String, skipValidate: Boolean = false): AuthUser {
@ -75,27 +79,34 @@ object Auth {
val roles = ((jwtClaims.jwtClaims.claimsMap["realm_access"] as Map<String, Any>)["roles"]) as List<String> val roles = ((jwtClaims.jwtClaims.claimsMap["realm_access"] as Map<String, Any>)["roles"]) as List<String>
val date = Date(jwtClaims.jwtClaims.expirationTime.valueInMillis) val date = Date(jwtClaims.jwtClaims.expirationTime.valueInMillis)
// try { try {
// HttpClients.createDefault().use { h -> HttpClients.createDefault().use { h ->
// //sync plant's from rmc to here, just name and id //sync plant's from rmc to here, just name and id
// for (plantId in plantIds) { for (plantId in plantIds) {
//
// val existing = Session.database.find(Plant::class.java).where().eq("plantId", plantId).findOne() 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 -> h.execute(HttpGet("${appConfig.integrationRmc()}/plant?id=${plantId}")).use { r ->
// if (r.statusLine.statusCode == 200) { if (r.statusLine.statusCode == 200) {
// Session.database.save(Plant().apply { val response = EntityUtils.toString(r.entity)
// this.plantId = plantId if (existing == null) {
// this.plantName = EntityUtils.toString(r.entity) Session.database.save(Plant().apply {
// }) this.plantId = plantId
// } this.plantName = response
// } })
// } } else {
// } existing.apply {
// } this.plantName = response
// } catch (e: Exception) { this.save()
// logger.warn("Exception in syncing plants", e) }
// } }
}
}
}
}
} catch (e: Exception) {
logger.warn("Exception in syncing plants", e)
}
return AuthUser( return AuthUser(
userName = userId, userName = userId,
@ -140,7 +151,8 @@ object Auth {
fun init(ctx: Context) { fun init(ctx: Context) {
val endpoint = getAuthEndpoint().authorizationEndpoint 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) ctx.redirect(redirectUrl)
} }
@ -181,7 +193,8 @@ object Auth {
fun refreshToken(ctx: Context) { fun refreshToken(ctx: Context) {
//refresh authToken //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 authUser = validateAuthToken(authToken, skipValidate = true)
val client = ctx.queryParam("client") ?: throw BadRequestResponse("client not sent") val client = ctx.queryParam("client") ?: throw BadRequestResponse("client not sent")
@ -190,7 +203,8 @@ object Auth {
val key = "$AUTH_TOKEN${authUser.userName}" val key = "$AUTH_TOKEN${authUser.userName}"
val found = Session.redis.llen(key) val found = Session.redis.llen(key)
logger.warn("for user ${authUser.userName}, found from redis, $key => $found entries") 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<AuthTokenResponse>(it) }.firstOrNull { it.accessToken == authToken } val foundOldAt = (0..found).mapNotNull { Session.redis.lindex(key, it) }
.map { objectMapper.readValue<AuthTokenResponse>(it) }.firstOrNull { it.accessToken == authToken }
?: throw BadRequestResponse("authToken not found in cache") ?: throw BadRequestResponse("authToken not found in cache")
val createdAt = foundOldAt.createdAt ?: throw BadRequestResponse("created at is missing") val createdAt = foundOldAt.createdAt ?: throw BadRequestResponse("created at is missing")
@ -244,7 +258,12 @@ object Auth {
} }
data class AuthUser( data class AuthUser(
val userName: String, val tenant: String, val roles: List<String>, val token: String, val expiry: LocalDateTime, val plantIds: List<String> val userName: String,
val tenant: String,
val roles: List<String>,
val token: String,
val expiry: LocalDateTime,
val plantIds: List<String>
) )
enum class Action { enum class Action {