重载方法值适用于ActionFunction和Thhen的替代方法

时间:2014-12-27 12:04:52

标签: scala playframework playframework-2.3

我正在关注play框架的动作组合文档,我试图通过动作组合来模仿用户身份验证和权限。当我尝试使用andThen进行管道身份验证和权限检查时,我收到编译错误,如文档中所述。

我的包裹请求:

type UserRequest[A] = AuthenticatedRequest[A,User]

请求UserRequest转换:

  case object AuthAction extends ActionBuilder[UserRequest] with ActionRefiner[Request,UserRequest]{
    override def refine[A](request: Request[A]): Future[Either[Result,UserRequest[A]]] = {
      getUser(request) match {
        case Some(user) => Future.successful(Right(new UserRequest(user,request))) 
        case _ => Future.successful(Left(oauthLogin(request)))
      }
    }
  }

ActionFilter来管理权限:

  object PermissionHandler extends ActionFilter[UserRequest]{
    override def filter[A](req:UserRequest[A]) = Future.successful{
      if (!req.user.hasPermission(Employee)) {
         Some(Unauthorized(views.html.defaultpages.unauthorized()))
      } else None
    }
  }

我的索引页面:

  def index = (AuthAction andThen PermissionHandler) { 
    Future.successful(Redirect(routes.Application.requestLeave))
  }

编译错误:

[error] /home/venki/play/lrs/app/controllers/Application.scala:119: overloaded method value apply with alternatives:
[error]   (block: => play.api.mvc.Result)play.api.mvc.Action[play.api.mvc.AnyContent] <and>
[error]   (block: controllers.Application.UserRequest[play.api.mvc.AnyContent] => play.api.mvc.Result)play.api.mvc.Action[play.api.mvc.AnyContent] <and>
[error]   [A](bodyParser: play.api.mvc.BodyParser[A])(block: controllers.Application.UserRequest[A] => play.api.mvc.Result)play.api.mvc.Action[A]
[error]  cannot be applied to (scala.concurrent.Future[play.api.mvc.Result])
[error]   def index = (AuthAction andThen PermissionHandler) { 
[error]                           ^
[error] one error found
[error] (compile:compile) Compilation failed

使用的文档:https://www.playframework.com/documentation/2.3.x/ScalaActionsComposition

1 个答案:

答案 0 :(得分:1)

刚刚发布到SO帮助我解决了这个问题。如下所示修改我的索引页面修复了问题,我不应该在使用正常版本的操作时用Future.succesful包装结果。

  def index = (AuthAction andThen PermissionHandler) { 
   Redirect(routes.Application.requestLeave)
  }

如果我想使用动作的异步版本,我应该在下面提到它

  def index = (AuthAction andThen PermissionHandler).async { 
   Future.successful(Redirect(routes.Application.requestLeave))
  }