首页 > 解决方案 > Play/Scala:使用 orElse 与 ActionBuilder 组合?

问题描述

我们在 play 应用程序中使用 play-pac4j 进行身份验证。

我们希望拥有相同的路由/控制器端点,但具有取决于用户角色的不同行为。

从概念上讲,这将执行以下操作:

 val ACTION_ONE: ActionBuilder[Request, AnyContent] = Secure(
    JWT_CLIENT,  Authorizers.Role1
 )(anyContentLarge)

 val ACTION_TWO: ActionBuilder[Request, AnyContent] = Secure(
    JWT_CLIENT,  Authorizers.Role2
 )(anyContentLarge)

 def index = ACTION_ONE.async{ req => index1(req) } orElse ACTION_TWO.async{ req => index2(req) }

 def index1(req: Request[AnyContent]) = //... behavior with role1

 def index2(req: Request[AnyContent]) = //... behavior with role2

但是 Play 的组成Actions只提供了andThen,没有orElse。有没有办法做到这一点?

标签: scalaplayframeworkpac4j

解决方案


我不认为你能以 s 的orElse方式作曲Action

但是,您应该能够创建一个ActionBuilder使用您现有的 2 个ActionBuilders 并执行orElse逻辑的“组合”。虽然你只能提供一个身体来运行。而这个机构将不得不依靠类似的东西AuthenticatedRequest#profiles来确定要做什么。

就像是:

def index = ACTION_COMBINED.async{ req: AuthenticatedRequest =>
  // Check something on req.profiles
  if (...) index1(req) else index2(req)
}

更准确地说,我不熟悉 play-pac4j


推荐阅读