score:2
trouble here that action(request)
is returning future[result]
not just result
. so type of whole expression before getorelse
is option[future[result]]
and it awaits future[result]
as parameter to getorelse
.
so at first you can wrap your unauthorized.withheaders
thing into future.successfull( ... )
next thing is that result of whole expression then is future[result]
and it's not correct argument type for the action.apply(bodyparser)( ... )
, but there is action.async
method that could handle it.
so whole corrected block with minimum type corrections \ refactoring is
import org.apache.commons.codec.binary.base64
def secured[a](username: string, password: string)(action: action[a]) =
action.async(action.parser) {
request => request.headers.get("authorization").flatmap { authorization =>
authorization.split(" ").drop(1).headoption.filter { encoded =>
val bytes = base64.decodebase64(encoded.getbytes)
new string(bytes).split(":").tolist match {
case u :: p :: nil if u == username && password == p => true
case _ => false
}
}.map(_ => action(request))
}.getorelse {
future.successful(
unauthorized.withheaders(
"www-authenticate" -> """basic realm="secured""""))
}
}
further sugar injections could lead to even more readable version:
import org.apache.commons.codec.binary.base64
def secured[a](username: string, password: string)(action: action[a]) =
action.async(action.parser) { request =>
val result = for {
authorization <- request.headers.get("authorization")
array(_, encoded, _*) <- some(authorization.split(" "))
bytes = base64.decodebase64(encoded.getbytes)
credentials = new string(bytes).split(":").tolist
list(`username`, `password`) <- some(credentials)
} yield action(request)
result.getorelse {
future.successful(
unauthorized.withheaders(
"www-authenticate" -> """basic realm="secured""""))
}
}
note that unpacking in the left hand side of <-
is transformed to filter
with match
Source: stackoverflow.com
Related Query
- Getting better error messages from Play JSON API
- Error "scala.reflect.internal.MissingRequirementError: object scala.runtime in compiler mirror not found" when compiling Play framework tests
- How to read and write Anorm object with the new JSON API in Play Framework 2.1-RC2?
- Request is missing required `Host` header error in Scala Play 2.6.7 Akka
- Play Framework compilation error when passing List object from controller to view
- Scala Play Json JSResultException Error API
- Play 2.4 migration:JavascriptReverseRoute is not a member of object play.core.Router error
- Scala object to Json with Play API
- Play Framework - add a field to JSON object
- Securing REST API on Play framework and OAuth2
- found Unit: required Int. Why is the error not obvious?
- Why use @Singleton over Scala's object in Play Framework?
- Get companion object instance with new Scala reflection API
- How to implement implicit Json Writes of embedded object in Play Framework 2.x
- Caching an action in a multi-language website using Play Framework's Cached API
- "host not allowed" error when deploying a play framework application to Amazon AWS with Boxfuse
- Play 2.5.3: Cryptic error message: Exception caught in Netty java.lang.NoClassDefFoundError
- Dependency injection with abstract class and object in Play Framework 2.5
- Object is not a value error in scala
- How to respond with a pretty-printed JSON object using play framework?
- Are there any plugins for generating API documentation for Play 2.x?
- How to improve the error message readability returned from JsError.toFlatJson or JsError.toJson in Play framework 2.x?
- play 2: "reference to form is ambiguous" error message in template
- Play 2 - Can't return Json object in Response
- Scala Play 2.0. Compilation error: IO error while decoding
- Case class companion object generation error for compound type
- Why do I get a “Hive support is required to CREATE Hive TABLE (AS SELECT)” error when creating a table?
- play framework - error parsing expression in build.sbt
- Error on scala class : recursive method printExpr needs result type
- How to print validation error outside of field constructor in Play framework 2
More Query from same tag
- Scala RDD String manipulation
- Using Scala 2.10 `to` to convert a List to a SortedMap
- What class/object to invoke in order to run Scala Spark job built from source?
- Play! 2.5: deactivate slick logs
- geting value by comparing a date with a range of date scala spark
- Using Guavas Range in Scala
- specifying trait constraint in scala
- Spark unable to Explode column
- Pipeline failed if scanning scala files
- scala: value not a member of a DataFrame
- How to reduce Dataset of tuple
- non-alphanumeric operator name leads to compile errors
- How to test type equality at type-level in scala?
- for-comprehension vs Future.sequence
- When to use Akka Microkernel?
- How do I integrate ScalaTest with Spring
- Testing Right[Seq[MyClass]] and properties
- Variable substitution in scala
- How to use @unchecked for an Option in a higher order function
- Anorm query, flatten not found
- Scala conditional sum of elements in a filtered tuples list
- How do I insert JSON into a postgres table using Anorm?
- Unable to load hive table from spark dataframe with more than 25 columns in hdp 3
- Line wrapping Scala XML literal
- publish to kafka topic within a map method
- Perfomance using orientdb graph api vs sql query
- Using attachments with macros in Scala 2.10
- Build Jar with dependencies including multiple main classes using Gradle in IntelliJ
- Finatra - reading a request in chunks
- Task not serializable about aggegateByKey