If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

Sometimes we would connect our Web2Py application with an Active Directory and we would use those users for accessing our content. We need to put some code in two different places :

db.py - here we need to setup the connection to the server. Obviously you have to check before if is ping-able and its LDAP tree is accessible.

 

from gluon.tools import Auth, Crud, Service, PluginManager, prettydate
auth = Auth(db, hmac_key = Auth.get_or_create_key())
 
then
 
auth.define_tables(username=True)
#auth.settings.create_user_groups=False
 
after
 
# all we need is login
auth.settings.actions_disabled=['register','change_password','request_reset_password','retrieve_username','profile']
 
# you don't have to remember me
auth.settings.remember_me_form = False
 
and
 
from gluon.contrib.login_methods.ldap_auth import ldap_auth
auth.settings.login_methods = [ldap_auth(mode='ad',
    manage_groups= True, 
    db = db,
    group_name_attrib = 'cn',
    group_member_attrib = 'member',
    group_filterstr = 'objectClass=Group',
    server='<server>',
    base_dn='OU=<my org unit>,DC=<domain>,DC=<domain>')]

 

default.py - here we can put our decorator to restrict the access to the a Group.

@auth.requires_membership('<group name in AD>')
def function_restrictedgroup():
    return 'you are member of a group!' 
 
menu.py - just an example we can connect a link on the menubar for testing the restriction
 
(T('My Login 2'), False, URL('default', 'function_restrictedgroup'))
 
Now if we log in with credentials that we already have and are present into the AD we'll be able to see the 
private area, but if we are not member of the defined group in the decorator we won't be able to see anything other (the message).
 
When a user log in for the first time its username - group and membership will be inserted into the tables : db.auth_user, db.auth_group and db.auth_membership.
 
Good luck 
Luca
 
 

Related slices

Comments (0)


Hosting graciously provided by:
Python Anywhere