summaryrefslogtreecommitdiffstats
path: root/LDAPLoginAdapter.py
blob: 18c477e3d0cbf4cfca0f9fbebc7e494bc880e0cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
#####################################################################
#
# LDAPLoginAdapter	An LDAP-based user source for Zope
#
# This software is governed by a license. See
# LICENSE.txt for the terms of this license.
#
#####################################################################
__version__='$Revision$'[11:-2]

from LDAPUser import LDAPUser
import string, time, sys, os, urllib, ldap
from base64 import encodestring, decodestring
from Globals import HTMLFile, MessageDialog, package_home
from AccessControl.User import BasicUserFolder
from AccessControl.ZopeSecurityPolicy import _noroles
from Acquisition import Implicit
from ExtensionClass import Base
from OFS.ObjectManager import ObjectManager
from OFS.SimpleItem import SimpleItem
import Products

_marker = []
_dtmldir = os.path.join(package_home(globals()), 'dtml')
addLDAPLoginAdapterForm = HTMLFile('addLDAPLoginAdapter', _dtmldir)
ldap_scopes = (ldap.SCOPE_BASE, ldap.SCOPE_ONELEVEL, ldap.SCOPE_SUBTREE)


class LDAPLoginAdapter(BasicUserFolder, ObjectManager, Implicit, Base):
    """ LDAPLoginAdapter

    The LDAPLoginAdapter is a user database.  It contains management hooks
    so that it can be added to a Zope folder as an 'acl_users'
    database.  Its important public method is validate() which
    returns a Zope user object of type LDAPUser

    """

    meta_type = 'LDAPLoginAdapter'
    id        = 'acl_users'
    title     = 'LDAPLoginAdapter'

    isAUserFolder = 1


    manage_options=(
        (
        {'label' : 'Configure', 		'action' : 'manage_main', 
         'help'  : ('LDAPLoginAdapter','LDAPLoginAdapter_Configure.stx')},
        {'label' : 'Advanced',			'action' : 'manage_advanced',
         'help'  : ('LDAPLoginAdapter','LDAPLoginAdapter_Advanced.stx')	},
        {'label' : 'LDAP Schema',       'action' : 'manage_ldapschema',
         'help'  : ('LDAPLoginAdapter', 'LDAPLoginAdapter_Schema.stx')  },
        {'label' : 'Caches',                    'action' : 'manage_showcache',
         'help'  : ('LDAPLoginAdapter', 'LDAPLoginAdapter_Caches.stx')	},
        {'label' : 'Search',			'action' : 'manage_finduser',
         'help'  : ('LDAPLoginAdapter', 'LDAPLoginAdapter_Search.stx')	},
        {'label' : 'Custom Forms',                  'action' : 'manage_contents',
         'help'  : ('LDAPLoginAdapter', 'LDAPLoginAdapter_Contents.stx')},
        {'label' : 'Log', 			'action' : 'manage_showlog',
         'help'  : ('LDAPLoginAdapter', 'LDAPLoginAdapter_Log.stx')	},
        )
        + SimpleItem.manage_options
        ) 


    __ac_permissions__=(
        ('View management screens',('manage', 'manage_main', 'manage_contents',
                                    'manage_showlog', 'manage_advanced',
                                    'manage_showcache', 'manage_finduser',
                                    'manage_ldapschema')),
        ('Manage users', ('getUserNames','getUser','getUsers', 
                          'getUserById', 'findUser', 'getUserDetails',
                          'getLDAPSchema', 'getLog',
                          'getPublicUserAttrs', 'getProperty')),
        ('Change LDAPLoginAdapter', ('manage_edit', 'manage_editLogVerbosity',
                                     'manage_addPublicUserAttrs',
                                     'manage_deletePublicUserAttrs'
                                     'manage_addLDAPSchemaItem',
                                     'manage_deleteLDAPSchemaItems'))
        )


    manage=manage_main = HTMLFile('dtml/properties',	globals())
    manage_advanced    = HTMLFile('dtml/advancedProps', globals())
    manage_ldapschema  = HTMLFile('dtml/ldapschema',    globals())
    manage_showlog     = HTMLFile('dtml/showlog',	globals())
    manage_showcache   = HTMLFile('dtml/showcache',	globals())
    manage_finduser    = HTMLFile('dtml/finduser',	globals())
    manage_contents    = HTMLFile('dtml/contents',      globals())

    default_loginpage  = HTMLFile('dtml/login',  globals())
    default_logoutpage = HTMLFile('dtml/logout', globals())


    def __setstate__(self, v):
        LDAPLoginAdapter.inheritedAttribute('__setstate__')(self, v)

        self._clearCaches()
        if not hasattr(self, 'verbose'): self.verbose = 1
        self.verbose > 2 and self._logit(3,'Initialized through __setstate__')


    def __init__(self, title, LDAP_server, login_attr, 
                 users_base, users_scope,
                 roles, groups_base, groups_scope,
                 binduid, bindpwd, use_cookies, REQUEST):
        self.verbose              = 2	# _logit needs it
        self._public_userattrs    = []  # safe default
        self._ldapschema          = [('dn', 'Distinguished Name'), 
                                     ('cn', 'Canonical Name'),
                                     ('sn', 'Surname')]

        self.manage_edit(title, LDAP_server, login_attr,
                         users_base, users_scope,
                         roles, groups_base, groups_scope,
                         binduid, bindpwd, use_cookies, REQUEST)


    def all_meta_types(self):
        """ What can you put inside me? """
        f = lambda x: x['name'] in ('DTML Method', 'DTML Document', 'Script (Python)')
        return filter(f, Products.meta_types)


    def objectItems(self, spec=None):
        return ObjectManager.objectItems(self, spec)


    def objectIds(self, spec=None):
        return ObjectManager.objectIds(self, spec)


    def _clearCaches(self):
        """ Clear all logs and caches for user-related information """
        self._v_cache           = {}  # Secondary cache for non-logged in users
        self._v_users           = {}  # this is the cache of logged-in users
        self._v_log             = []
        self._v_userlist        = []
        self._v_userlistexpire  = 0


    def _connect(self):
        """ initialize an ldap server connection """
        try:
            connection = ldap.open(self.LDAP_server,self.LDAP_port)
            connection.simple_bind_s(self._binduid,self._bindpwd)
            self.verbose > 8 and self._logit(9,
                           'Opened connection to ldap server %s' %
                           str(self.LDAP_server) + ':' + str(self.LDAP_port))
            return connection

        except:
            self.verbose > 0 and self._logit(1,
                           'Unable to open connection to ldap server %s' %
                           str(self.LDAP_server) + ':' + str(self.LDAP_port))

        return None


    def _disconnect(self, connection):
        """ close the ldap connection """
        try:
            connection.unbind_s()
            self.verbose > 8 and self._logit(9, 
                                   'Closed connection to ldap server')
        except:
            self.verbose > 0 and self._logit(1, 
                                   'Failed to disconnect from LDAP server')


    def _formatException(self, e):
        """ Format exception output for use in a MessageDialog """
        infotuple = getattr(e, 'args', ())
        if infotuple:
            errordict = infotuple[0]
            msg = '<b>An Error occurred:<br>'
            msg = msg + 'Error Type: %s<br>Server Message: %s</b>' % (
                    errordict.get('desc', 'Not Available'),
                    errordict.get('info', 'Not Available'))       


    def _searchResults(self, search_base, search_scope, search_string, 
                       attr=None, user=None, password=None):
        """ The main search engine """

        connection = self._connect()
        if connection is None:
            return '###Error###: Cannot connect to LDAP server!'

        if user is not None:
            try:
                connection.bind_s(user, password, ldap.AUTH_SIMPLE)
            except ldap.INVALID_CREDENTIALS:
                self.verbose > 3 and self._logit(4, 
                                     'Invalid credentials for user %s' % user)
                self._disconnect(connection)
                raise

        try:
            res = connection.search_s(search_base, search_scope, 
                                      search_string, attr)
        except ldap.NO_SUCH_OBJECT:
            res = '###ERROR###: Cannot find %s under %s!' % (
                         search_string, search_base)
        except ldap.SIZELIMIT_EXCEEDED:
            res = '###Error###: Too many records returned for query \
                     %s under %s!' % (search_string, search_base)
            self.verbose > 1 and self._logit(2, '_searchResults: too many \
                      records for %s under %s' % (search_string, search_base))
        except:
            res = '###Error###: %s, %s' % sys.exc_info()[:2]
            self.verbose > 1 and self._logit(2, 
                                'Call to _searchResults returned ' + str(res))

        self._disconnect(connection)
        return res


    def encodeString(self, string):
        """ 
        A helper to encrypt a string so that it can be used as query 
        string piece
        """
        return urllib.quote(string)


    def getUserDetails(self, dn):
        """
        Return all attributes for a given DN
        """
        lscope = ldap_scopes[self.users_scope]

        res = self._searchResults(dn, lscope, 'objectClass=*')

        if type(res) == type (''):
            result = (('Exception', res),)
        elif len(res) > 0:
            result = res[0][1].items()
            result.sort()
        else:
            result = ()

        return result


    def findUser(self, search_param, search_term):
        """ Look up matching user records based on attributes """
        lscope = ldap_scopes[self.users_scope]
        gscope = ldap_scopes[self.groups_scope]
        users  = []
        groupusers = {}

        res = self._searchResults(self.groups_base,gscope,
             "(uniquemember=*)",['uniquemember'])

        if type(res) == type(''):
            return [{'dn': res }]
        elif len(res) > 0:
            for i in range(len(res)):
                for member in res[i][1]['uniqueMember']:
                    groupusers[string.lower(member)] = None

        groupuser_list = groupusers.keys()

        if search_param == 'dn':
            users_base = search_term
            search_str = 'objectClass=*'
        else:
            users_base = self.users_base
            search_str = '(%s=*%s*)' % (search_param, search_term)

        res = self._searchResults(users_base, lscope, search_str)

        if type(res) == type(''):
            users = [{ 'dn' : res }]
        elif len(res) > 0:
            for i in range(len(res)):
                dn = res[i][0]
                if string.lower(dn) in groupuser_list:
                    rec_dict = {}
                    rec_dict['dn'] = dn
                    rec_dict['sn'] = ''

                    for key in res[i][1].keys():
                        rec_dict[key] = res[i][1][key][0]

                    users.append(rec_dict)

        return users


    def _lookupuser(self, uid, pwd=None):
        """
        returns a unique RID and the groups a uid belongs to 
        as well as a dictionary containing user attributes
        """
        s          = []
        unique     = ''
        user_attrs = {}

        # make sure we translate 0/1/2 into the right codes..
        lscope = ldap_scopes[self.users_scope]
        gscope = ldap_scopes[self.groups_scope]

        if pwd is not None and string.strip(pwd) == '':
            pwd = '~'

        if self.login_attr == 'dn':
            users_base = uid
            search_str = 'objectClass=*'
        else:
            users_base = self.users_base
            search_str = '%s=%s' % (self.login_attr, uid)

        res = self._searchResults(users_base, lscope, search_str)
        if (type(res) == type('') or len(res) < 1):
            return None, None, None
        elif len(res) > 0:
             # gets a dn suitable for the next call for uid=userid  
             unique     = res[0][0]
             user_attrs = res[0][1]

             if pwd is not None:
                 res = self._searchResults(self.groups_base,gscope, 
                   "(uniquemember=%s)" % (unique), attr = ['cn'], 
                   user=unique, password=pwd)
             else:
                 res = self._searchResults(self.groups_base,gscope,
                   "(uniquemember=%s)" % (unique), attr=['cn'])

             if type(res) == type(''):
                 return None, res, {}
             elif len(res) > 0: 
                for i in range(len(res)):
                    for eachcn in range(len(res[i][1]['cn'])):
                        c = res[i][1]['cn'][eachcn]
                        s.append(c)

        return s, unique, user_attrs


    def getGroups(self, dn='*', attr=None):
        """
        returns a list of possible groups from the ldap tree.
        Used e.g. in showgroups.dtml
        """
        group_list = []
        gscope = ldap_scopes[self.groups_scope]

        res = self._searchResults(self.groups_base,gscope,
             "(uniquemember=%s)" % (dn), attr=['dn','cn'])

        if type(res) == type(''):
            group_list = (('', res),)
        elif len(res) > 0:
            for i in range(len(res)):
                if attr is None:
                    group_list.append((res[i][1]['cn'][0], res[i][0]))
                elif attr == 'cn':
                    group_list.append(res[i][1]['cn'][0])
                elif attr == 'dn':
                    group_list.append(res[i][0])

        return group_list


    def getLog(self):
        """ Used by showlog.dtml: returns a list of log entries """
        return self._v_log


    def _logit(self, level, logline):
        """ Logs a single line and keeps log length at max. 500 lines.

        Level: 1 - Catastrophes   
               2 - Major Events   
               3 - Minor events
               4 - Login failures 
               5 - Login Successes
               7 - Login success from cache
               9 - Debugging
        """
        self._v_log.append('(%d)  %s:  %s' % (level,
            time.strftime('%b %d  %H:%M:%S',
                               time.localtime(time.time())),logline))

        if len(self._v_log) > 500:
             self._v_log.pop(0)
        

    def manage_reinit(self, REQUEST=None):
        """ re-initialize and clear out users and log """
        self._clearCaches()
        self.verbose > 1 and self._logit(2,"Reinitialized")

        if REQUEST is not None:
            return MessageDialog(
                    title  ='Reinitialized',
                    message='The LDAPLoginAdapter caches have been cleared',
                    action ='manage_advanced')


    def manage_edit(self, title, LDAP_server, login_attr,
                    users_base, users_scope, roles,  groups_base, 
                    groups_scope, binduid, bindpwd, use_cookies, REQUEST=None):
        """ Edit the LDAPLoginAdapter Object """
        self.title        = title
        self.login_attr   = login_attr
        self.users_base   = users_base
        self.users_scope  = users_scope

        if groups_base == '':
            groups_base = users_base

        self.groups_base  = groups_base
        self.groups_scope = groups_scope

        if string.find(LDAP_server, ':') != -1:
            self.LDAP_server = string.split(LDAP_server, ':')[0]
            self.LDAP_port   = int(string.split(LDAP_server, ':')[1])
        else:
            self.LDAP_server = LDAP_server
            self.LDAP_port   = 389

        self.roles       = roles
        self._binduid     = binduid
        self._bindpwd     = bindpwd
        self.use_cookies = int(use_cookies)

        self._clearCaches()
        self.verbose > 1 and self._logit(2,'Properties changed')
        self.__roles__ = filter(None, map(string.strip,
                                          string.split(roles, ',')))

        connection = self._connect()
        if connection is None and REQUEST is not None:
            return MessageDialog(
                   title = 'Cannot connect to LDAP!',
                   message = '<b>Cannot connect to LDAP server %s port %s!<br>\
                               Please check your connection settings! \
                               </b>' % (self.LDAP_server, str(self.LDAP_port)),
                   action = 'manage_main')

        self._disconnect(connection)

        if REQUEST is not None:
            return MessageDialog(
                     title  ='Properties Changed',
                     message='The LDAPLoginAdapter has been edited',
                     action ='manage_main')


    def manage_editLogVerbosity(self, verbose, REQUEST=None):
        """ Edit LDAPLoginAdapter advanced properties """
        self.verbose              = verbose

        self.verbose > 1 and self._logit(2,'Log Verbosity changed')

        if REQUEST is not None:
            return MessageDialog(
                   title  ='Log Verbosity Changed',
                   message='LDAPLoginAdapter Log Verbosity set to %d' % verbose,
                   action ='manage_advanced')


    def getLDAPSchema(self):
        """ Retrieve the LDAP schema this product knows about """
        return self._ldapschema


    def manage_addLDAPSchemaItem(self, ldap_name, friendly_name='', 
                                    REQUEST=None):
        """ Add a schema item to my list of known schema items """
        schema = self._ldapschema
        schema.append((ldap_name, friendly_name))
        self._ldapschema = schema

        if REQUEST is not None:
            return MessageDialog(
                        title   = 'Added schema item %s' % ldap_name,
                        message = 'Schema item %s added!' % ldap_name,
                        action  = 'manage_ldapschema')

    def manage_deleteLDAPSchemaItems(self, ldap_names=[], REQUEST=None):
        """ Delete schema items from my list of known schema items """
        if len(ldap_names) < 1:
            if REQUEST is not None:
                return MessageDialog(
                            title   = 'No items selected',
                            message = 'You did not select any items to delete',
                            action  = 'manage_ldapschema')
            else:
                return None

        schema = self._ldapschema

        for ldap_name in ldap_names:
            for schema_tuple in schema:
                if schema_tuple[0] == ldap_name:
                    del schema[schema.index(schema_tuple)]

        self._ldapschema = schema

        if REQUEST is not None:
            return MessageDialog(
                        title   = 'Removed schema items',
                        message = 'Schema items removed',
                        action  = 'manage_ldapschema')

    def getPublicUserAttrs(self):
        """ Return the public user attributes """
        return tuple(self._public_userattrs)

    def manage_deletePublicUserAttrs(self, public_attrs=[], REQUEST=None):
        """ Delete a public attribute for user objects """
        if len(public_attrs) < 1:
            if REQUEST is not None:
                return MessageDialog(
                           title   = 'Error deleting user attribute',
                           message = 'You did not specify user attributes to delete!',
                           action  = 'manage_advanced')
            else:
                return None
 
        pubs = self._public_userattrs

        for public_attr in public_attrs:
            for pub in pubs:
                if pub[0] == public_attr:
                    del pubs[pubs.index(pub)]
        
        self._public_userattrs = pubs

        # Need to clear caches so all user records get recreated
        self._clearCaches()

        if REQUEST is not None:
            return MessageDialog(
                   title   = 'Deleted user attributes',
                   message = 'Public user attributes deleted', 
                   action  = 'manage_advanced')

    def manage_addPublicUserAttrs(self, ldap_attribute,
                                   public_attribute='', REQUEST=None):
        """ Delete a public attribute for user objects """
        if len(public_attribute) < 1:
            if REQUEST is not None:
                return MessageDialog(
                           title   = 'Error adding user attribute',
                           message = 'You did not specify a user attribute to add!',
                           action  = 'manage_advanced')
            else:
                return None

        pubs = self._public_userattrs
        pubs.append((public_attribute, ldap_attribute))
        self._public_userattrs = pubs

        # Need to clear caches so all user records get recreated
        self._clearCaches()

        if REQUEST is not None:
            return MessageDialog(
                   title   = 'Added user attribute',
                   message = 'Public user attribute added', 
                   action  = 'manage_advanced')     

    def getUsers(self):
        """Return a list of *cached* user objects"""
        names = self._v_users.keys()
        names.sort()
        users = []

        for n in names:
            if self._v_users[n].notexpired():   # Show only the unexpired
                users.append(self._v_users[n])

        return users                                                      


    def getUserNames(self):
        """ Return a list of usernames """
        if not hasattr(self,'_v_userlistexpire'):
            self._v_userlistexpire = 0

        if self._v_userlistexpire > time.time():
            return self._v_userlist

        s = {}
        lscope = ldap_scopes[self.users_scope]
        login_attr = self.login_attr

        if login_attr == 'dn':
            res = self._searchResults(self.users_base,lscope,
                         "(objectClass=*)")
        else:
            res = self._searchResults(self.users_base,lscope,
                         "(objectClass=*)", attr=[login_attr])

        if type(res) == type(''):
            s[res] = None
        elif len(res) > 0:
            for i in range(len(res)):
                if login_attr != 'dn':
                    name_list = res[i][1].get(login_attr, [])
                else:
                    name_list = [res[i][0]] 

                for name in name_list:
                    s[name] = None

        self._v_userlist = s.keys()
        self._v_userlist.sort()
        self._v_userlistexpire = time.time() + 600 # Expire after 600 seconds

        return self._v_userlist


    def getUser(self, name):
        """Return the named user object or None"""
        if (self._v_cache.has_key(name) and 
            self._v_cache[name].notexpired()):
                return self._v_cache.get(name)

        user_roles, user_dn, user_attrs = self._lookupuser(uid=name)
        if user_roles is not None:
            self.verbose > 8 and self._logit(9,
                                 '%s connect returned %s' % (name, user_dn))
            roles = string.join(user_roles, ',')
            user_obj = LDAPUser(name, 'undef', roles, [], 
                                user_attrs, self._public_userattrs)
            self._v_cache[name] = user_obj
            wrapped_user = user_obj.__of__(self)
            return wrapped_user
        else:
            self.verbose > 8 and self._logit(9,
                                   '%s not found in getUser' % name)

        return None


    def getUserById(self, id, default = _marker):
        """ Return a user object by ID (in this case by username) """
        try:
            if (self._v_cache.has_key(id) and 
                self._v_cache.get(id).notexpired()):
                return self._v_cache.get(id, None) 

            return self.getUser(id)

        except:
            if default is _marker: raise
            return default


    def _validate_from_cache(self,name,password):
        """ Check if the user is in cache, not expired and password matches. """
        tpass='undef'

        if self._v_users.has_key(name) and self._v_users[name].notexpired():
            newuser = self._v_users[name]
            self.verbose > 8 and self._logit(9,'%s found in user cache' % name)

            tpass = newuser._getPassword()
            if tpass == password:
                self.verbose > 6 and self._logit(7,
                                     '%s authenticated from cache' % name)
                newuser._updateActiveTime()
                return newuser
            else:
                self.verbose > 3 and self._logit(4,
                                  '%s password not matched in cache ' % name)
                del self._v_users[name]
                newuser = self.getUser(name)

                if newuser is not None:
                    tpass = newuser._getPassword()
                    if tpass == password:
                        self.verbose > 6 and self._logit(7,
                                '%s auth from cache AFTER LDAP lookup' % name)
                        newuser._updateActiveTime()
                        return newuser
                    else:
                        self.verbose > 3 and self._logit(4, 
                         '%s password not matched in cache and in LDAP' % name)
                        return None

        self.verbose > 8 and self._logit(9,'%s not found in user cache' % name)
        return None


    def authenticate(self, name, password, request):
        super = self._emergency_user

        if name is None:
            return None

        if super and name == super.getUserName():
            user = super
            if self.use_cookies:
                token = '%s:%s' % (name, password)
                token = encodestring(token)
                token = urllib.quote(token)

                request['RESPONSE'].setCookie('__ac', token, path='/')

        else:
            # Check cached password
            self.verbose > 8 and self._logit(9,
                                   'Checking cache for user %s' % (name))
            user = self._validate_from_cache(name, password)
            
            if user is None:
                try:
                    uroles, uid, user_attrs = self._lookupuser(name, password)
                    if uid > '':
                        self.verbose > 8 and self._logit(9,
                                        '%s connect returned %s' % (name,uid))
                    elif (uroles, uid, user_attrs) == (None, None, None):
                        self.verbose > 8 and self._logit(9,
                                      'Unknown user %s not validated' % name)
                        return None
                except ldap.LDAPError, e:
                    infotuple = getattr(e, 'args', ())
                    if infotuple:
                        errordict = infotuple[0]
                        msg = 'Error Type: %s, Server Message: %s' % (
                                 errordict.get('desc', 'Not Available'),
                                 errordict.get('info', 'Not Available'))
                    else:
                        msg = 'Unknown LDAP Error'

                    self.verbose > 0 and self._logit(1,
                    'Exception in _lookupuser looking up %s: %s' % (name, msg))

                    return None

                except Exception, e:
                    msg = getattr(e, 'args', ('Unknown Error',))[0]
                    
                    self.verbose > 0 and self._logit(1,
                    'Exception in _lookupuser looking up  %s: %s' % (name, msg))

                    return None
            
                if uroles is None:
                    self.verbose > 8 and self._logit(9,
                                     '%s returned no roles' % name)
                    return None

                r = string.split(self.roles,',')
                r = r + uroles
                newroles = string.join(r,',')
                user = LDAPUser(name, password, newroles, [], 
                                   user_attrs, self._public_userattrs)
                self._v_users[name] = user
                self._v_cache[name] = user

                if self.use_cookies:
                    token = '%s:%s' % (name, password)
                    token = encodestring(token)
                    token = urllib.quote(token)

                    request['RESPONSE'].setCookie('__ac', token, path='/')

            
        if user is not None and user.authenticate(password, request):
            return user
        else:
            return None



    def validate(self, request, auth='', roles=_noroles):
        """
            The main engine
        """
        if getattr(self, 'use_cookies', 0):
            return self.cookie_validate(request, auth, roles)
        else:
            return self.basic_validate(request, auth, roles)


    def basic_validate(self, request, auth, roles):
        """
        this method performs identification, authentication, and
        authorization
        v is the object (value) we're validating access to
        n is the name used to access the object
        a is the object the object was accessed through
        c is the physical container of the object

        We allow the publishing machinery to defer to higher-level user
        folders or to raise an unauthorized by returning None from this
        method.
        """
        v = request['PUBLISHED'] # the published object
        a, c, n, v = self._getobcontext(v, request)
        name, password = self.identify(auth)

        user = self.authenticate(name, password, request)

        # user will be None if we can't authenticate him or if we can't find
        # his username in this user database.
        emergency = self._emergency_user
        if emergency and user is emergency:
            if self._isTop():
                # we do not need to authorize the emergency user against the
                # published object.
                return emergency.__of__(self)
            else:
                # we're not the top-level user folder
                return None

        elif user is None:
            # either we didn't find the username, or the user's password
            # was incorrect.  try to authorize and return the anonymous user.
            if self._isTop() and self.authorize(self._nobody.__of__(self),a,
                                                c,n,v,roles):
                return self._nobody.__of__(self)
            else:
                # anonymous can't authorize or we're not top-level user folder
                return None
                
        else:
            # We found a user, his password was correct, and the user
            # wasn't the emergency user.  We need to authorize the user
            # against the published object.
            if self.authorize(user.__of__(self), a, c, n, v, roles):
                return user.__of__(self)
            # That didn't work.  Try to authorize the anonymous user.
            elif self._isTop() and self.authorize(self._nobody.__of__(self),
                                                  a,c,n,v,roles):
                return self._nobody.__of__(self)
            else:
                # we can't authorize the user, and we either can't authorize
                # nobody against the published object or we're not top-level
                return None


    def cookie_validate(self, request, auth, roles):
        """
            Validation using Cookies
        """
        req_has   = request.has_key
        resp      = request['RESPONSE']
        login_doc = getattr(self, 'login', self.default_loginpage)
        v = request['PUBLISHED'] # the published object
        a, c, n, v = self._getobcontext(v, request)
        
        if req_has('__ac'):    # Do we have the cookie?
            cookie = request['__ac']
            cookie = urllib.unquote(cookie)

            try:
                cookie = decodestring(cookie)
                name, password = tuple(string.split(cookie, ':'))
            except:
                resp.expireCookie('__ac', path='/')
                raise 'LoginRequired', login_doc(self, request)

        elif req_has('__ac_name') and req_has('__ac_password'):
            name = request['__ac_name']
            password = request['__ac_password']

            try:
                del request['__ac_name']
                del request['__ac_password']
            except:
                pass

        else:
            name, password = None, None

        user = self.authenticate(name, password, request)

        # user will be None if we can't authenticate him or if we can't find
        # his username in this user database.
        if user is not None:
            emergency = self._emergency_user
            if emergency and user is emergency:
                if self._isTop():
                    # we do not need to authorize the emergency user against the
                    # published object.
                    return emergency.__of__(self)
                else:
                    # we're not the top-level user folder
                    return None

            else:
                # We found a user, his password was correct, and the user
                # wasn't the emergency user.  We need to authorize the user
                # against the published object.
                if self.authorize(user.__of__(self), a, c, n, v, roles):
                    return user.__of__(self)
                # That didn't work.  Try to authorize the anonymous user.
                elif self._isTop() and self.authorize(self._nobody.__of__(self),
                                                  a,c,n,v,roles):
                    return self._nobody.__of__(self)
                elif not self._isTop():
                    # we can't authorize the user, and we're not top-level
                    return None
                else:
                    # We cannot authorize the user and we are toplevel
                    raise 'LoginRequired', login_doc(self, request)

        else:
            # either we didn't find the username, or the user's password
            # was incorrect.  try to authorize and return the anonymous user.
            if self._isTop() and self.authorize(self._nobody.__of__(self),a,
                                                c,n,v,roles):
                return self._nobody.__of__(self)
            else:
                # anonymous can't authorize or we're not top-level user folder
                raise 'LoginRequired', login_doc(self, request)
                

    def getProperty(self, prop_name):
        """ Get at LDAPLoginAdapter properties """
        return getattr(self, prop_name, '')


def manage_addLDAPLoginAdapter(self, title, LDAP_server, login_attr,
                               users_base, users_scope, roles,
                               groups_base, groups_scope,
                               binduid, bindpwd, use_cookies, REQUEST=None):
    """ Called by Zope to create and install an LDAPLoginAdapter """
 
    n = LDAPLoginAdapter(title, LDAP_server, login_attr, 
                         users_base, users_scope,
                         roles, groups_base, groups_scope,
                         binduid, bindpwd, use_cookies, REQUEST)
 
    if hasattr(self.aq_base, 'acl_users') and REQUEST is not None:
        return MessageDialog(
               title  ='Item Exists',
               message='This object already contains a User Folder',
               action ='%s/manage_main' % REQUEST['URL1'])
 
    self._setObject('acl_users', n)
    self.__allow_groups__=self.acl_users
 
    # return to the parent object's manage_main
    if REQUEST is not None:
        return self.manage_main(self,REQUEST)