Skip to content

Commit

Permalink
Merge pull request #2530 from diesalbla/authentication_simplify
Browse files Browse the repository at this point in the history
Authentication: simplify code.
  • Loading branch information
aeons committed Apr 28, 2019
2 parents cb405f4 + d7550fb commit 672cd14
Showing 1 changed file with 9 additions and 9 deletions.
Expand Up @@ -3,22 +3,22 @@ package server
package middleware

import cats.data.{Kleisli, OptionT}
import cats.effect._
import cats.effect.Sync
import org.http4s.headers._

package object authentication {
def challenged[F[_], A](
challenge: Kleisli[F, Request[F], Either[Challenge, AuthedRequest[F, A]]])(
routes: AuthedService[A, F])(implicit F: Sync[F]): HttpRoutes[F] =
Kleisli { req =>
challenge
.mapF(OptionT.liftF(_))
.run(req)
.flatMap {
case Right(authedRequest) =>
routes(authedRequest)
case Left(challenge) =>
OptionT.some(Response(Status.Unauthorized).putHeaders(`WWW-Authenticate`(challenge)))
OptionT[F, Response[F]] {
F.flatMap(challenge(req)) {
case Left(challenge) => F.pure(Some(unauthorized(challenge)))
case Right(authedRequest) => routes(authedRequest).value
}
}
}

private[this] def unauthorized[F[_]](challenge: Challenge): Response[F] =
Response(Status.Unauthorized).putHeaders(`WWW-Authenticate`(challenge))
}

0 comments on commit 672cd14

Please sign in to comment.