Search code examples
scalajwtakkaakka-httpscala-cats

Akka HTTP Route Handling


I have the following route setup

 val routes = protectedRoute("wallet") { user =>
    concat {
      path("wallet" / "deposit") {
        get {
          completeEitherT(walletService.deposit(user._id, "dollars", 50))
        }
      }
      path("wallet") {
        get {
          completeEitherT(walletService.getForUser(user._id))
        }
      }
    }
  }

The completeEitherT function is as follows

def completeEitherT[T](t: EitherT[Future, DatabaseError, T])(implicit marsh: ToResponseMarshaller[T]): Route = {
    onSuccess(t.value) {
      case Left(x: DatabaseErrors.NotFound) =>
        logger.error(x.toString)
        complete(StatusCodes.NotFound)
      case Left(error) => complete(StatusCodes.InternalServerError)
      case Right(value) => complete(value)
    }
  }

The protectedRoute Directive is:

def protectedRoute(permissions: String*): Directive1[User] = new Directive1[User] {
    override def tapply(f: (Tuple1[User]) => Route): Route = {
      headerValueByName("Authorization") { jwt =>
        Jwt.decode(jwt, jwtSecret, List(algo)) match {
          case Failure(_) =>
            logger.error("Unauthorized access from jwtToken:", jwt)
            complete(StatusCodes.Unauthorized)
          case Success(value) =>
            val user = JsonParser(value.content).convertTo[User]
            if (user.roles.flatMap(_.permissions).exists(permissions.contains)) f(Tuple1(user))
            else complete(StatusCodes.Forbidden)
        }
      }
    }
  }

The issue that I am having is that whichever path is defined first results in a 404 when called via Postman.

The requested resource could not be found.

This is not a response from completeEitherT as it does not log the error

How do I define two or more paths inside the same directive?


Solution

  • Please mark as duplicate, I could not find this on Google Search but SO showed this as related.

    Answer

    Essentially I am missing a ~ between the paths

    val routes = protectedRoute("wallet") { user =>
        concat {
          path("wallet" / "deposit") {
            get {
              completeEitherT(walletService.deposit(user._id, "dollars", 50))
            }
          } ~
          path("wallet") {
            get {
              completeEitherT(walletService.getForUser(user._id))
            }
          }
        }
      }