Scala中的Deadbolt 2询问用户是否可以访问路由

时间:2013-05-13 12:55:11

标签: scala playframework-2.0 playframework-2.1 deadbolt

在scala模板中制作菜单,其中包含一些授权链接,如下所示:

<ul>
    <li><a href="@routes.Application.index()">Home</a></li>
    @subjectNotPresent() {
        <li><a href="@routes.Application.login()">Login</a></li>
    }
    @@restrict(handler, List(as("foo"))) {
        <li><a href="@routes.Application.foo()">foo</a></li>
    }
    @subjectPresent() {
        <li><a href="@routes.Application.logout()">Logout</a></li>
    }    
</ul>

我指向Application.foo的链接需要放置角色foo。但是,我想将此语句@@restrict(handler, List(as("foo")))更改为更动态的语句。我想询问用户是否也访问了application.foo ,而不是询问用户是否有角色foo。

这使得菜单不那么复杂。一个重要的好处是只需要在控制器中修改限制,而不是scala模板。

这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用动态标记,它可以完全满足您的需求。你可以在http://deadbolt-2-scala.herokuapp.com/#template-dynamic看到一个例子来说明这一点。要在这里充实,

@dynamic(handler, "foo") {
  This content may be visible, depending on your luck
}

其中foo是您要限制的资源的名称。在DeadboltHandler中,您需要返回一个定义动态控件的DynamicResourceHandler。

class MyDeadboltHandler(dynamicResourceHandler: Option[DynamicResourceHandler] = None) extends DeadboltHandler {

    override def getDynamicResourceHandler[A](request: Request[A]): Option[DynamicResourceHandler] = {
        if (dynamicResourceHandler.isDefined) dynamicResourceHandler
        else Some(new MyDynamicResourceHandler())
    }
}

DynamicResourceHandler可以通过多种方式实现,但外观通常很有效。为了简化示例,我们将在这种情况下对值进行硬编码。

class MyDynamicResourceHandler extends DynamicResourceHandler
{
    def isAllowed[A](name: String, meta: String, handler: DeadboltHandler, request: Request[A]) = {
        MyDynamicResourceHandler.handlers(name).isAllowed(name,
                                                          meta,
                                                          handler,
                                                          request)
    }

    def checkPermission[A](permissionValue: String, deadboltHandler: DeadboltHandler, request: Request[A]) = {
        // todo implement this when demonstrating permissions
        false
    }
}

object MyDynamicResourceHandler {
    val handlers: Map[String, DynamicResourceHandler] = Map(
        "foo" -> new DynamicResourceHandler() {
           def isAllowed[A](name: String, meta: String, deadboltHandler: DeadboltHandler, request: Request[A]) =
         // do something here to determine if the subject has access

           def checkPermission[A](permissionValue: String, deadboltHandler: DeadboltHandler, request: Request[A]) = false
     }
   )
}