I am trying to validate a devKey using a RawDecorator in Cask HTTP framework, but I am not sure I understand how to return an error response when the devKey is invalid. Here is what I am trying:
class AuthenticatedDevKey extends RawDecorator
{
override def wrapFunction(ctx: Request, delegate: Delegate) =
{
// Get the devKey from header
val devKey = ctx.headers.getOrElse("devKey", "").toString
// Check if this is a valid devKey
if(devKey != "" && MicroServiceManager.isExistingDevKey(devKey))
delegate(Map("devKey" -> devKey))
else
cask.Response("Invalid DevKey", statusCode = StatusCodes.UNAUTHORIZED)
}
}
This gives me a type mismatch error. The documentation (https://com-lihaoyi.github.io/cask/index.html#extending-endpoints-with-decorators) says that I can return a response, but I have not seen any such example. How do I return a Response with error statuscode?
Ran into this myself just recently, as someone new to both Cask and Scala.
In an Endpoint
you can directly return a Response
, but in a Decorator
you need to wrap the Response
in a Result
, because a Decorator
must return a Result
.
In your case, this should do the trick:
cask.router.Result.Success(cask.Response("Invalid DevKey", statusCode = StatusCodes.UNAUTHORIZED))
Note that Result.Success
means that your code executed successfully, not that the request was successful. Here it means that you've "successfully" determined that the request is unauthorized.
It's possible there's a better answer, but this is working for me. I also opened a PR to update the Cask docs with an example, so if there is a better way to do it then hopefully the maintainer will correct me there.