Property interception of Grails domain classes
I would like to intercept calls to properties of domain classes to implement access control.
My first try was to override setProperty and getProperty. By doing this, I disabled all nice functionality of Grails domain classes, such as
domainClass.properties = params
and the automatic conv开发者_如何学Pythonersion of data types.
The next try was to use the DelegatingMetaClass, which enabled me at least to print out some nice log messages around the actual call. But I could not figure out how to access the actual object to evaluate the permissions.
Last, groovy.lang.Interceptor seems to be a good choice, as I can access the actual object. But is this the right way? How am I able to force all domain classes to be intercepted?
Thanks a lot in advance.
Regards, Daniel
You can override getProperty and setProperty as long as you reference the real versions. Add code like this to BootStrap for add interceptors for all domain classes:
class BootStrap {
def grailsApplication
def init = { servletContext ->
for (dc in grailsApplication.domainClasses) {
dc.class.metaClass.getProperty = { String name ->
// do stuff before access
def result
def metaProperty = delegate.class.metaClass.getMetaProperty(name)
if (metaProperty) {
result = metaProperty.getProperty(delegate)
}
else {
throw new MissingPropertyException(name, delegate.class)
}
// do stuff after access
result
}
dc.class.metaClass.setProperty = { String name, value ->
// do stuff before update
def metaProperty = delegate.class.metaClass.getMetaProperty(name)
if (metaProperty) {
metaProperty.setProperty(delegate, value)
}
else {
throw new MissingPropertyException(name, delegate.class)
}
// do stuff after update
}
}
}
def destroy = {}
}
精彩评论