简体   繁体   中英

Grails - access only for object's owner

I'm still working on my first Grails application. This time, my problem is to limit access to some actions for particular users.

Assume users add some object, eg books. I would like to give access to edit a book only to admin and the user that added the book. I'm currently using Acegi plugin. I know there is newer version of that plugin, but I'm not sure if it changes anything in my problem.

The second thing is some kind similar. I have a sidebar and there is "Hello ${currentUser.username}. currentUser is a method that returns an instance of currently logged user. But the problem is that I don't have any idea where can I put this message to be able to use it everywhere. Should I put it in some service and include it everywhere? I tried to create an ApplicationController that is extended by all other controllers, but that doesn't seem to work. Have you got any ideas?

Thanks! Grzegorz

You should use the newer Spring Security Core plugin since it has an ACL add-on plugin that does exactly what you're looking for. See http://grails.org/plugin/spring-security-acl for details.

For the second question, there's a taglib for that. In the Acegi plugin use this:

Hello <g:loggedInUserInfo field="username"/>

(see http://www.grails.org/AcegiSecurity+Plugin+-+Artifacts ) and in the Spring Security Core plugin use this:

Hello <sec:username/>

(see the "Security Tags" section of http://burtbeckwith.github.com/grails-spring-security-core/docs/manual/ )

For ROLE access you'll just need to specify that a particular ROLE for a particular URL has access to that action. That is if you are using the plugin's RequestMap approach. If you're using the annotation approach, just annotate the action in the controller with:

@Secured(['WHATEVER_ROLE'])

As far as only allowing the user who created the book to edit it, you can pull the user domain out of the authentication with authenticateService.userDomain(), then you can compare that user with the user who created the book (assuming you have some sort of createdBy property on your Book domain.

def loggedInUser = authenticateService.userDomain()
if (book.createdBy.equals(loggedInUser)) {
   // allow editing
}

Something like that, anyway.

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