我正在使用动作组合进行身份验证,并避免在每个动作中传递通用参数。我的问题是如何将它与 BodyParser parse.json 结合起来,就像下面的方法一样?
def setUser() = Action(parse.json) {
implicit request =>
val id = (request.body \ "id").as[String]
val username = (request.body \ "username").as[String]
val previousURI = request.session.get("previousURI") match {
case Some(x) => x
case None => "/"
}
Ok(previousURI).withSession(
"id" -> id,
"username" -> username
)
}
使用上述方法的控制器使用 'Auth' 特征:
case class User(id: Option[String], username: Option[String])
case class Context(user: User, request: Request[AnyContent])
extends WrappedRequest(request)
trait Auth {
def CheckLogin(f: Context => Result) = {
Action { request =>
request.session.get("username").map { token =>
// username? yes continue...
val id = request.session.get("id")
val username = request.session.get("username")
f(Context(new User(id, username), request))
}.getOrElse {
// no redirect to login
Results.Redirect(routes.Application.login).withSession(
"previousURI" -> request.uri
)
}
}
}
}
如果我尝试:
def myMethod() = CheckLogin(parse.json) { ...
我得到:
type mismatch; found : play.api.mvc.BodyParser[play.api.libs.json.JsValue] required: controllers.Context => play.api.mvc.Result
谢谢!