Section 22.2. Validating User Access with Identity


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:

@require(identity.in_group("admin")


Here's a list of the methods you can use to validate that a user has permission to access a resource.

  • not_anonymous

  • in_group

  • in_all_groups

  • in_any_group

  • has_permission

  • has_all_permissions

  • has_any_permission

  • from_host

  • from_any_host

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>





Rapid Web Applications with TurboGears(c) Using Python to Create Ajax-Powered Sites
Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites
ISBN: 0132433885
EAN: 2147483647
Year: 2006
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net