Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example of Auth Middleware with Http4s.
- // See https://pastebin.com/zUjAgTdw for more details.
- import cats.data.{Kleisli, OptionT}
- import cats.effect.Sync
- import org.http4s.dsl.Http4sDsl
- import org.http4s.headers.Authorization
- import org.http4s.server.AuthMiddleware
- import org.http4s.{AuthedRoutes, HttpRoutes, Request}
- object SettingSecuredRoutes {
- def routes[F[_]: Sync](authService: AuthService[F], service: SomeService[F]): HttpRoutes[F] = {
- val dsl = new Http4sDsl[F] {}
- import dsl._
- import cats.implicits._
- import io.circe.syntax._
- import org.http4s.circe.CirceEntityDecoder._
- import org.http4s.circe.CirceEntityEncoder._
- val onFailure: AuthedRoutes[String, F] = Kleisli(req => OptionT.liftF(Forbidden(req.authInfo)))
- val authUser: Kleisli[F, Request[F], Either[String, Long]] = Kleisli { request =>
- val either = for {
- token <- request.headers.get(Authorization).map(_.value.toLowerCase.replace("bearer ", "")).toRight(s"Authorization header not found")
- result <- authService.isTokenValid(token).leftMap(_.toString)
- } yield result
- implicitly[Sync[F]].pure(either) // we must wrap it into effect F for possible changes that might require IO operations
- }
- AuthMiddleware(authUser, onFailure).apply(AuthedRoutes.of {
- case GET -> Root / "settings" as userId => {
- for {
- result <- service.getByUserId(userId)
- ok <- Ok(result)
- } yield ok
- }
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement