Skip to content

Commit

Permalink
Add test that uses authentication with context
Browse files Browse the repository at this point in the history
  • Loading branch information
987Nabil committed Oct 11, 2023
1 parent f20cab3 commit 6ea13b2
Showing 1 changed file with 19 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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") {
Expand All @@ -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") {
Expand Down

0 comments on commit 6ea13b2

Please sign in to comment.