Is there a way to use jSecurity to specify whether a specific user could edit specific pages? e.g., I want to permit users to edit their own user record but only view other peoples. I've been searching through the docs and forums but can't seem to find anything on this.
Thanks
Re: Permission based on specific principal
Hi ssak,
Yes, you can, by using instance-level permissions, and one alternative.
Here it is using instance-level permissions:
For example:
if ( subject.hasPermission( "user:edit:12345" ) ) {
//edit their own information
}
This would require you to assign the "user:edit:<userId>" permission to the user in your domain model somehow. In my applications, a user always has a private role which they 'own' and no one else uses. I just add that permission to their private role.
However, there is an alternative to the above if statement that is worth investigating:
When you use instance-level permissions, it is usually a good idea to only have a relatively small number of them for things that can be enacted upon by several users - e.g. a forum permission, a printer permission, etc. If you start to have an instance-level permission for _everything_ in the system that is editable by only one or two users, you'll quickly see your 'permissions' database table get huge really fast - not something that is desirable for performance reasons.
The alternative is that you perform an a more general permission check as well as an explicit check for the current user. For example, assuming subject.getPrincipal() returns the current user's ID and 'userIdToEdit' is the id of the user to edit, say, passed in via a form POST:
if ( userIdToEdit.equals( subect.getPrincipal() ) || subject.hasPermission("user:edit") ) {
//allow the current user to edit the account data for user 'userIdToEdit'
}
The "user:edit" permission is the ability to "edit" _any_ "user", using jsecurity's colon delimited syntax. This is a much broader permission than user:edit:12345, which pertains only to a specific user. The more general one (user:edit) would be assigned to say, an administrator role.
This approach ensures that your permission table does not grow to be unmanageably large, but requires you to do a little extra work (just one extra condition of the if statement really - pretty good trade off for performance, I think).
HTH,
Les