Skip to content

Commit

Permalink
ugfix: refresh before token expires, not after
Browse files Browse the repository at this point in the history
  • Loading branch information
timbertson committed Nov 15, 2023
1 parent 7a5f2a6 commit 75771a9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ object AuthorizationCache {
case Some(cached) =>
F.realTimeInstant
.flatMap { now =>
val shouldRenew =
cached.expirationTimestamp.exists(_.isBefore(now.minusSeconds(refreshBeforeExpiration.toSeconds)))
val minExpiry = now.plusSeconds(refreshBeforeExpiration.toSeconds)
val shouldRenew = cached.expirationTimestamp.exists(_.isBefore(minExpiry))
if (shouldRenew)
getAndCacheToken.flatMap {
case Some(token) => token.pure[F]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import org.http4s.{AuthScheme, Credentials}
import org.http4s.headers.Authorization
import cats.effect.unsafe.implicits.global
import java.time.Instant
import scala.concurrent.duration.*

class AuthorizationCacheTest extends FunSuite {

Expand Down Expand Up @@ -73,6 +74,21 @@ class AuthorizationCacheTest extends FunSuite {
io.unsafeRunSync()
}

test(s"retrieve the token when it's going to expire within refreshBeforeExpiration") {
val io = for {
counter <- IO.ref(1)
auth = mkAuthorization(
expirationTimestamp = IO.realTimeInstant.map(_.plusSeconds(8).some),
token = counter.getAndUpdate(_ + 1).map(i => s"test-token-$i")
)
cache <- AuthorizationCache[IO](retrieve = auth, refreshBeforeExpiration = 10.seconds)
obtained <- (1 to 5).toList.traverse(i => cache.get.product(i.pure))
} yield obtained.foreach { case (obtained, i) =>
assertEquals(obtained, Authorization(Credentials.Token(AuthScheme.Bearer, s"test-token-$i")))
}
io.unsafeRunSync()
}

test(s"fail if cannot retrieve the token when it's expired") {
val io = for {
counter <- IO.ref(1)
Expand Down

0 comments on commit 75771a9

Please sign in to comment.