22.2. Validating User Access with Identity
The Identity package includes several features that you can use to create more complex validation logic. The validation method names are self-explanatory; however, you should remember that the values you are checking against are strings from the database. If you wanted to verify that a user was in the admin group you'd write:
Here's a list of the methods you can use to validate that a user has permission to access a resource.
There are also two special methods, Any and All, which allow you to combine any number of the above checks into more complex logical groupings:
@require(identity.All(identity.in_group("superhero"), identity.has_permission("access_hall_of_justice")) as
You can use this validation logic in the @require decorator before any controller method to block access to the whole method. Or, as we saw in Chapter 7, you can subclass SecureResource in one of your controllers and run permission checks using any of the above functions by overriding the require attribute of the SecureResource class.
You can also use identity checks within your controller method. This, too, requires that your controller subclass SecureResource, so that the Identity exceptions you throw will be caught and handled appropriately.
class MyController(controllers.Controller, identity.SecureResource): @turbogears.expose(html="mytemplate") def myFunction(self): if not ("admin" in identity.current.groups or "super" in identity.current.groups): raise identity.GroupMembershipRequiredException(("admin", "super"))
You can also use tg.identity as an automatically-imported alias for turbogears.identity.current. That will allow you to use standard py:if statements to display or hide various page elements based on user permissions:
<a py:if="'superhero' in tg.identity.groups" href="/display_powers> List possible superpowers </a>