From 6ea13b21f8f84c25cb86d592c31457056624bfdc Mon Sep 17 00:00:00 2001 From: Nabil Abdel-Hafeez <7283535+987Nabil@users.noreply.github.com> Date: Tue, 10 Oct 2023 19:32:07 +0200 Subject: [PATCH] Add test that uses authentication with context --- .../http/internal/middlewares/AuthSpec.scala | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/zio-http/src/test/scala/zio/http/internal/middlewares/AuthSpec.scala b/zio-http/src/test/scala/zio/http/internal/middlewares/AuthSpec.scala index d2694803d5..a59f875e47 100644 --- a/zio-http/src/test/scala/zio/http/internal/middlewares/AuthSpec.scala +++ b/zio-http/src/test/scala/zio/http/internal/middlewares/AuthSpec.scala @@ -18,7 +18,7 @@ package zio.http.internal.middlewares import zio.test.Assertion._ import zio.test._ -import zio.{Ref, ZIO, ZLayer} +import zio.{Ref, ZIO} import zio.http._ import zio.http.internal.HttpAppTestExtensions @@ -45,6 +45,18 @@ object AuthSpec extends ZIOHttpSpec with HttpAppTestExtensions { ZIO.succeed(c == bearerToken) } + private val basicAuthContextM = HandlerAspect.customAuthProviding[AuthContext] { r => + { + r.headers.get(Header.Authorization).flatMap { + case Header.Authorization.Basic(uname, password) if uname.reverse == password => + Some(AuthContext(uname)) + case _ => + None + } + + } + } + def spec = suite("AuthSpec")( suite("basicAuth")( test("HttpApp is accepted if the basic authentication succeeds") { @@ -59,6 +71,12 @@ object AuthSpec extends ZIOHttpSpec with HttpAppTestExtensions { val app = (Handler.ok @@ basicAuthM).merge.header(Header.WWWAuthenticate) assertZIO(app.runZIO(Request.get(URL.empty).copy(headers = failureBasicHeader)))(isSome) }, + test("Extract username via context") { + val app = (Handler.fromFunction[(AuthContext, Request)] { case (c, _) => + Response.text(c.value) + } @@ basicAuthContextM).merge.mapZIO(_.body.asString) + assertZIO(app.runZIO(Request.get(URL.empty).copy(headers = successBasicHeader)))(equalTo("user")) + }, ), suite("basicAuthZIO")( test("HttpApp is accepted if the basic authentication succeeds") {