简体   繁体   中英

How to limit properties bound when using domain model as a command object

This really powerful feature of grails

def save(MyDomain model) {
  model.save()
  render ''
}

will parse the request body or params, run MyDomain.get(id) , fill in the properties from the request body or params and save. That's a lot for this little bit of code.

How do I limit the properties to bind to model ? Say I have an accountBalance property that is read only and I don't want a malicious user to be able to change their account balance.

Also, I want to have multiple actions that save a different subset of properties of MyDomain ... say one action could be for a bank teller user that is making a deposit for the account holder. In this case the teller should be able to set accountBalance but not password .

I realize that an actual banking app wouldn't work like this, it's just an example.

I had other problems that led me to use command objects to bind data (see Grails fails to parse request when content type is specified during post ). Any solution would also have to address that post. I imagine if the solution uses command objects then it will work, but if command objects aren't in the solution, then the request body problem has to be addressed.

Have not tried on an actual domain class but can you try using bindData instead of implicitly binding where you can particularly specify which property to exclude?

def save() {
  //params - A Map of source parameters
  //It can be params or any other representation of request body
  //request.JSON, request.XML

  MyDomain model = MyDomain.get(params.id?.toLong())

  bindData(model, params, [exclude: ['accountBalance']])

  model.save()
  render ''
}    

I suggest you take a look at the documentation about binding. There is a lot of information, in particular the section about security which is similar to your concerns. Looking at the fact bindData() allows you include/exclude properties you should be able to write any variation of your binding you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM