您可以使用動態標籤,它完全符合您的需求。你可以在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
}
)
}