/
PluggableAuthService.py
1423 lines (1139 loc) · 49 KB
/
PluggableAuthService.py
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this
# distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Classes: PluggableAuthService
"""
import logging
import six
from AccessControl import ClassSecurityInfo
from AccessControl import ModuleSecurityInfo
from AccessControl.class_init import InitializeClass
from AccessControl.Permissions import manage_users as ManageUsers
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.users import emergency_user
from AccessControl.users import nobody
from Acquisition import Implicit
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from OFS.Cache import Cacheable
from OFS.Folder import Folder
from OFS.interfaces import IObjectManager
from OFS.interfaces import IPropertyManager
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from zExceptions import Unauthorized
from zope.event import notify
from ZPublisher import BeforeTraverse
from ZTUtils import Batch
from Products.PluginRegistry.PluginRegistry import PluginRegistry
from Products.StandardCacheManagers.RAMCacheManager import RAMCacheManager
from .events import PrincipalCreated
from .interfaces.authservice import IPluggableAuthService
from .interfaces.authservice import _noroles
from .interfaces.plugins import IAnonymousUserFactoryPlugin
from .interfaces.plugins import IAuthenticationPlugin
from .interfaces.plugins import IChallengePlugin
from .interfaces.plugins import IChallengeProtocolChooser
from .interfaces.plugins import ICredentialsResetPlugin
from .interfaces.plugins import ICredentialsUpdatePlugin
from .interfaces.plugins import IExtractionPlugin
from .interfaces.plugins import IGroupEnumerationPlugin
from .interfaces.plugins import IGroupsPlugin
from .interfaces.plugins import ILoginPasswordHostExtractionPlugin
from .interfaces.plugins import INotCompetentPlugin
from .interfaces.plugins import IPropertiesPlugin
from .interfaces.plugins import IRequestTypeSniffer
from .interfaces.plugins import IRoleAssignerPlugin
from .interfaces.plugins import IRoleEnumerationPlugin
from .interfaces.plugins import IRolesPlugin
from .interfaces.plugins import IUpdatePlugin
from .interfaces.plugins import IUserAdderPlugin
from .interfaces.plugins import IUserEnumerationPlugin
from .interfaces.plugins import IUserFactoryPlugin
from .interfaces.plugins import IValidationPlugin
from .permissions import SearchPrincipals
from .PropertiedUser import PropertiedUser
from .utils import _wwwdir
from .utils import classImplements
from .utils import createKeywords
from .utils import createViewName
from .utils import url_local
security = ModuleSecurityInfo(
'Products.PluggableAuthService.PluggableAuthService')
logger = logging.getLogger('PluggableAuthService')
# Errors which plugins may raise, and which we suppress:
_SWALLOWABLE_PLUGIN_EXCEPTIONS = (NameError, AttributeError, KeyError,
TypeError, ValueError)
# except if they tell us not to do so
def reraise(plugin):
try:
doreraise = plugin._dont_swallow_my_exceptions
except AttributeError:
return
if doreraise:
raise
MultiPlugins = []
def registerMultiPlugin(meta_type):
""" Register a 'multi-plugin' in order to expose it to the Add List
"""
if meta_type in MultiPlugins:
raise RuntimeError('Meta-type (%s) already available to Add List'
% meta_type)
MultiPlugins.append(meta_type)
class DumbHTTPExtractor(Implicit):
security = ClassSecurityInfo()
@security.private
def extractCredentials(self, request):
""" Pull HTTP credentials out of the request.
"""
creds = {}
login_pw = request._authUserPW()
if login_pw is not None:
name, password = login_pw
creds['login'] = name
creds['password'] = password
creds['remote_host'] = request.get('REMOTE_HOST', '')
try:
creds['remote_address'] = request.getClientAddr()
except AttributeError:
creds['remote_address'] = request.get('REMOTE_ADDR', '')
return creds
classImplements(DumbHTTPExtractor, ILoginPasswordHostExtractionPlugin)
InitializeClass(DumbHTTPExtractor)
class EmergencyUserAuthenticator(Implicit):
security = ClassSecurityInfo()
@security.private
def authenticateCredentials(self, credentials):
""" Check credentials against the emergency user.
"""
if isinstance(credentials, dict):
eu = emergency_user
eu_name = eu.getUserName()
login = credentials.get('login')
if login == eu_name:
password = credentials.get('password')
if eu.authenticate(password, {}):
return (eu_name, None)
return (None, None)
classImplements(EmergencyUserAuthenticator, IAuthenticationPlugin)
InitializeClass(EmergencyUserAuthenticator)
class PluggableAuthService(Folder, Cacheable):
""" All-singing, all-dancing user folder.
"""
security = ClassSecurityInfo()
meta_type = 'Pluggable Auth Service'
zmi_icon = 'fa fa-users-cog'
zmi_show_add_dialog = False
_id = id = 'acl_users'
_emergency_user = emergency_user
_nobody = nobody
maxlistusers = -1 # Don't allow local role form to try to list us!
# Method for transforming a login name. This needs to be the name
# of a method on this plugin. See the applyTransform method.
login_transform = ''
_properties = (
dict(id='title', type='string', mode='w', label='Title'),
dict(id='login_transform', type='string', mode='w',
label='Transform to apply to login name'),
)
def getId(self):
return self._id
#
# IUserFolder implementation
#
@security.protected(ManageUsers)
def getUser(self, name):
""" See IUserFolder.
"""
plugins = self._getOb('plugins')
name = self.applyTransform(name)
user_info = self._verifyUser(plugins, login=name)
if not user_info:
return None
return self._findUser(plugins, user_info['id'], user_info['login'])
@security.protected(ManageUsers)
def getUserById(self, id, default=None):
""" See IUserFolder.
"""
plugins = self._getOb('plugins')
user_info = self._verifyUser(plugins, user_id=id)
if not user_info:
return default
return self._findUser(plugins, user_info['id'], user_info['login'])
@security.public
def validate(self, request, auth='', roles=_noroles):
""" See IUserFolder.
"""
plugins = self._getOb('plugins')
is_top = self._isTop()
if not is_top and self._isNotCompetent(request, plugins):
# this user folder should not try to authenticate this request
return None
user_ids = self._extractUserIds(request, plugins)
(accessed, container, name, value) = \
self._getObjectContext(request['PUBLISHED'], request)
for user_id, login in user_ids:
user = self._findUser(plugins, user_id, login, request=request)
if aq_base(user) is emergency_user:
if is_top:
return user
else:
return None
if self._authorizeUser(user, accessed, container, name, value,
roles):
return user
if not is_top:
return None
#
# No other user folder above us can satisfy, and we have no user;
# return a constructed anonymous only if anonymous is authorized.
#
anonymous = self._createAnonymousUser(plugins)
if self._authorizeUser(anonymous, accessed, container, name,
value, roles):
return anonymous
return None
@security.protected(SearchPrincipals)
def searchUsers(self, **kw):
""" Search for users
"""
search_name = kw.get('name', None)
result = []
max_results = kw.get('max_results', '')
sort_by = kw.get('sort_by', '')
# We apply sorting and slicing here across all sets, so don't
# make the plugin do it
if sort_by:
del kw['sort_by']
if max_results:
del kw['max_results']
if search_name:
if kw.get('id') is not None:
del kw['id'] # don't even bother searching by id
# Note: name can be a sequence.
kw['login'] = self.applyTransform(kw['name'])
if kw.get('login', None):
kw['login'] = self.applyTransform(kw['login'])
plugins = self._getOb('plugins')
enumerators = plugins.listPlugins(IUserEnumerationPlugin)
for enumerator_id, enum in enumerators:
try:
user_list = enum.enumerateUsers(**kw)
for user_info in user_list:
info = {}
info.update(user_info)
info['userid'] = info['id']
info['principal_type'] = 'user'
if 'title' not in info:
info['title'] = info['login']
result.append(info)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
reraise(enum)
logger.debug('UserEnumerationPlugin %s error' % enumerator_id,
exc_info=True)
if sort_by:
result = sorted(result, key=lambda x: x.get(sort_by, '').lower())
if max_results:
try:
max_results = int(max_results)
result = result[:max_results]
except ValueError:
pass
return tuple(result)
@security.protected(SearchPrincipals)
def searchGroups(self, **kw):
""" Search for groups
"""
search_name = kw.get('name', None)
result = []
max_results = kw.get('max_results', '')
sort_by = kw.get('sort_by', '')
# We apply sorting and slicing here across all sets, so don't
# make the plugin do it
if sort_by:
del kw['sort_by']
if max_results:
del kw['max_results']
if search_name:
if kw.get('id') is not None:
del kw['id']
if 'title' not in kw:
kw['title'] = kw['name']
plugins = self._getOb('plugins')
enumerators = plugins.listPlugins(IGroupEnumerationPlugin)
for enumerator_id, enum in enumerators:
try:
group_list = enum.enumerateGroups(**kw)
for group_info in group_list:
info = {}
info.update(group_info)
info['groupid'] = info['id']
info['principal_type'] = 'group'
if 'title' not in info:
info['title'] = '(Group) %s' % info['groupid']
result.append(info)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
reraise(enum)
logger.debug('GroupEnumerationPlugin %s error' % enumerator_id,
exc_info=True)
if sort_by:
result = sorted(result, key=lambda x: x.get(sort_by, '').lower())
if max_results:
try:
max_results = int(max_results)
result = result[:max_results + 1]
except ValueError:
pass
return tuple(result)
@security.protected(SearchPrincipals)
def searchPrincipals(self, groups_first=False, **kw):
""" Search for principals (users, groups, or both)
"""
max_results = kw.get('max_results', '')
search_name = kw.get('name', None)
if search_name:
if 'title' not in kw:
kw['title'] = search_name
kw['login'] = search_name
# For groups we search the original name
# (e.g. Administrators), for users we apply the transform,
# which could lowercase the name.
groups = [d.copy() for d in self.searchGroups(**kw)]
if kw.get('login', None):
kw['login'] = self.applyTransform(kw['login'])
users = [d.copy() for d in self.searchUsers(**kw)]
if groups_first:
result = groups + users
else:
result = users + groups
if max_results:
try:
max_results = int(max_results)
result = result[:max_results + 1]
except ValueError:
pass
return tuple(result)
@security.private
def __creatable_by_emergency_user__(self):
return 1
@security.private
def _setObject(self, id, object, roles=None, user=None, set_owner=0):
#
# Override ObjectManager's version to change the default for
# 'set_owner' (we don't want to enforce ownership on contained
# objects).
Folder._setObject(self, id, object, roles, user, set_owner)
@security.private
def _delOb(self, id):
#
# Override ObjectManager's version to clean up any plugin
# registrations for the deleted object
#
plugins = self._getOb('plugins', None)
if plugins is not None:
plugins.removePluginById(id)
Folder._delOb(self, id)
#
# ZMI stuff
#
security.declareProtected(ManageUsers, 'manage_search') # NOQA: D001
manage_search = PageTemplateFile('www/pasSearch', globals())
manage_options = (Folder.manage_options[:1]
+ ({'label': 'Search', 'action': 'manage_search'},)
+ Folder.manage_options[2:]
+ Cacheable.manage_options)
@security.protected(ManageUsers)
def resultsBatch(self, results, REQUEST, size=20, orphan=2, overlap=0):
""" ZMI helper for getting batching for displaying search results
"""
try:
start_val = REQUEST.get('batch_start', '0')
start = int(start_val)
size = int(REQUEST.get('batch_size', size))
except ValueError:
start = 0
batch = Batch(results, size, start, 0, orphan, overlap)
if batch.end < len(results):
qs = self._getBatchLink(REQUEST.get('QUERY_STRING', ''),
start, batch.end)
REQUEST.set('next_batch_url', '%s?%s' % (REQUEST.get('URL'), qs))
if start > 0:
new_start = start - size - 1
if new_start < 0:
new_start = 0
qs = self._getBatchLink(REQUEST.get('QUERY_STRING', ''),
start, new_start)
REQUEST.set('previous_batch_url',
'%s?%s' % (REQUEST.get('URL'), qs))
return batch
@security.private
def _getBatchLink(self, qs, old_start, new_start):
""" Internal helper to generate correct query strings
"""
if new_start is not None:
if not qs:
qs = 'batch_start=%d' % new_start
elif qs.startswith('batch_start='):
qs = qs.replace('batch_start=%d' % old_start,
'batch_start=%d' % new_start)
elif qs.find('&batch_start=') != -1:
qs = qs.replace('&batch_start=%d' % old_start,
'&batch_start=%d' % new_start)
else:
qs = '%s&batch_start=%d' % (qs, new_start)
return qs
#
# Helper methods
#
@security.private
def _isNotCompetent(self, request, plugins):
""" return true when this user folder should not try authentication.
Never called for top level user folder.
"""
try:
not_competents = plugins.listPlugins(INotCompetentPlugin)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
logger.debug('NotCompetent plugin listing error', exc_info=True)
not_competents = ()
for not_competent_id, not_competent in not_competents:
try:
if not_competent.isNotCompetentToAuthenticate(request):
return True
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
reraise(not_competent)
logger.debug('NotCompetentPlugin %s error' % not_competent_id,
exc_info=True)
continue
return False
@security.private
def _extractUserIds(self, request, plugins):
""" request -> [validated_user_id]
o For each set of extracted credentials, try to authenticate
a user; accumulate a list of the IDs of such users over all
our authentication and extraction plugins.
"""
try:
extractors = plugins.listPlugins(IExtractionPlugin)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
logger.debug('Extractor plugin listing error', exc_info=True)
extractors = ()
if not extractors:
extractors = (('default', DumbHTTPExtractor()),)
try:
authenticators = plugins.listPlugins(IAuthenticationPlugin)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
logger.debug('Authenticator plugin listing error', exc_info=True)
authenticators = ()
result = []
for extractor_id, extractor in extractors:
try:
credentials = extractor.extractCredentials(request)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
reraise(extractor)
logger.debug('ExtractionPlugin %s error' % extractor_id,
exc_info=True)
continue
if credentials:
try:
credentials['extractor'] = extractor_id # ??? in key?
# Test if ObjectCacheEntries.aggregateIndex would work
items = sorted(credentials.items()) # noqa
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
# ???: would reraise be good here, and which plugin to ask
# whether not to swallow the exception - the extractor?
logger.debug('Credentials error: %s' % credentials,
exc_info=True)
continue
# First try to authenticate against the emergency
# user and return immediately if authenticated
user_id, name = self._tryEmergencyUserAuthentication(
credentials)
if user_id is not None:
return [(user_id, name)]
# Now see if the user ids can be retrieved from the cache
credentials['login'] = self.applyTransform(
credentials.get('login'))
view_name = createViewName('_extractUserIds',
credentials.get('login'))
keywords = createKeywords(**credentials)
user_ids = self.ZCacheable_get(view_name=view_name,
keywords=keywords,
default=None)
if user_ids is None:
user_ids = []
for authenticator_id, auth in authenticators:
try:
uid_and_info = auth.authenticateCredentials(
credentials)
if uid_and_info is None:
continue
user_id, info = uid_and_info
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
reraise(auth)
msg = 'AuthenticationPlugin %s error' % (
authenticator_id,)
logger.debug(msg, exc_info=True)
continue
if user_id is not None:
user_ids.append((user_id, info))
if user_ids:
self.ZCacheable_set(user_ids, view_name=view_name,
keywords=keywords)
result.extend(user_ids)
# Emergency user via HTTP basic auth always wins
user_id, name = self._tryEmergencyUserAuthentication(
DumbHTTPExtractor().extractCredentials(request))
if user_id is not None:
return [(user_id, name)]
return result
@security.private
def _tryEmergencyUserAuthentication(self, credentials):
""" credentials -> emergency_user or None
"""
try:
eua = EmergencyUserAuthenticator()
user_id, name = eua.authenticateCredentials(credentials)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
logger.debug('Credentials error: %s' % credentials, exc_info=True)
user_id, name = (None, None)
return (user_id, name)
@security.private
def _getGroupsForPrincipal(self, principal, request=None, plugins=None,
ignore_plugins=None):
all_groups = {}
if ignore_plugins is None:
ignore_plugins = ()
if plugins is None:
plugins = self._getOb('plugins')
groupmakers = plugins.listPlugins(IGroupsPlugin)
for groupmaker_id, groupmaker in groupmakers:
if groupmaker_id in ignore_plugins:
continue
groups = groupmaker.getGroupsForPrincipal(principal, request)
for group in groups:
principal._addGroups([group])
all_groups[group] = 1
return all_groups.keys()
@security.private
def _createAnonymousUser(self, plugins):
""" Allow IAnonymousUserFactoryPlugins to create or fall back.
"""
factories = plugins.listPlugins(IAnonymousUserFactoryPlugin)
for factory_id, factory in factories:
anon = factory.createAnonymousUser()
if anon is not None:
return anon.__of__(self)
return nobody.__of__(self)
@security.private
def _createUser(self, plugins, user_id, name):
""" Allow IUserFactoryPlugins to create, or fall back to default.
"""
name = self.applyTransform(name)
factories = plugins.listPlugins(IUserFactoryPlugin)
for factory_id, factory in factories:
user = factory.createUser(user_id, name)
if user is not None:
return user.__of__(self)
return PropertiedUser(user_id, name).__of__(self)
@security.private
def _findUser(self, plugins, user_id, name=None, request=None):
""" user_id -> decorated_user
"""
if user_id == self._emergency_user.getUserName():
return self._emergency_user
# See if the user can be retrieved from the cache
view_name = createViewName('_findUser', user_id)
name = self.applyTransform(name)
keywords = createKeywords(user_id=user_id, name=name)
user = self.ZCacheable_get(view_name=view_name, keywords=keywords,
default=None)
if user is None:
user = self._createUser(plugins, user_id, name)
propfinders = plugins.listPlugins(IPropertiesPlugin)
for propfinder_id, propfinder in propfinders:
data = propfinder.getPropertiesForUser(user, request)
if data:
user.addPropertysheet(propfinder_id, data)
groups = self._getGroupsForPrincipal(user, request,
plugins=plugins)
user._addGroups(groups)
rolemakers = plugins.listPlugins(IRolesPlugin)
for rolemaker_id, rolemaker in rolemakers:
try:
roles = rolemaker.getRolesForPrincipal(user, request)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
logger.debug('IRolesPlugin %s error' % rolemaker_id,
exc_info=True)
else:
if roles:
user._addRoles(roles)
user._addRoles(['Authenticated'])
# Cache the user if caching is enabled
base_user = aq_base(user)
if getattr(base_user, '_p_jar', None) is None:
self.ZCacheable_set(base_user, view_name=view_name,
keywords=keywords)
return user.__of__(self)
@security.private
def _verifyUser(self, plugins, user_id=None, login=None):
""" user_id -> info_dict or None
"""
if user_id is None and login is None:
# Avoid possible hugely expensive and/or wrong behavior of
# plugin enumerators.
return None
criteria = {'exact_match': True}
if user_id is not None:
criteria['id'] = user_id
if login is not None:
criteria['login'] = self.applyTransform(login)
view_name = createViewName('_verifyUser', user_id or login)
keywords = createKeywords(**criteria)
cached_info = self.ZCacheable_get(view_name=view_name,
keywords=keywords, default=None)
if cached_info is not None:
return cached_info
enumerators = plugins.listPlugins(IUserEnumerationPlugin)
for enumerator_id, enumerator in enumerators:
try:
info = enumerator.enumerateUsers(**criteria)
if info:
# Put the computed value into the cache
self.ZCacheable_set(info[0], view_name=view_name,
keywords=keywords)
return info[0]
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
reraise(enumerator)
msg = 'UserEnumerationPlugin %s error' % enumerator_id
logger.debug(msg, exc_info=True)
return None
@security.private
def _authorizeUser(self, user, accessed, container, name, value,
roles=_noroles):
""" -> boolean (whether user has roles).
o Add the user to the SM's stack, if successful.
o Return
"""
user = aq_base(user).__of__(self)
newSecurityManager(None, user)
security = getSecurityManager()
try:
try:
if roles is _noroles:
if security.validate(accessed, container, name, value):
return 1
else:
if security.validate(accessed, container, name, value,
roles):
return 1
except: # noqa
noSecurityManager()
raise
except Unauthorized:
pass
return 0
@security.private
def _isTop(self):
""" Are we the user folder in the root object?
"""
try:
parent = aq_base(aq_parent(self))
if parent is None:
return 0
return parent.isTopLevelPrincipiaApplicationObject
except AttributeError:
return 0
@security.private
def _getObjectContext(self, v, request):
""" request -> (a, c, n, v)
o 'a 'is the object the object was accessed through
o 'c 'is the physical container of the object
o 'n 'is the name used to access the object
o 'v' is the object (value) we're validating access to
o ???: Lifted from AccessControl.User.BasicUserFolder._getobcontext
"""
if len(request.steps) == 0: # someone deleted root index_html
request['RESPONSE'].notFoundError(
'no default view (root default view was probably deleted)')
root = request['PARENTS'][-1]
request_container = aq_parent(root)
n = request.steps[-1]
# default to accessed and container as v.aq_parent
a = c = request['PARENTS'][0]
# try to find actual container
inner = aq_inner(v)
innerparent = aq_parent(inner)
if innerparent is not None:
# this is not a method, we needn't treat it specially
c = innerparent
elif hasattr(v, '__self__'):
# this is a method, we need to treat it specially
c = v.__self__
c = aq_inner(v)
# if pub's aq_parent or container is the request container, it
# means pub was accessed from the root
if a is request_container:
a = root
if c is request_container:
c = root
return a, c, n, v
@security.private
def _getEmergencyUser(self):
return emergency_user.__of__(self)
@security.private
def _doAddUser(self, login, password, roles, domains, **kw):
""" Create a user with login, password and roles if, and only if,
we have a registered user manager and role manager that will
accept specific plugin interfaces.
"""
plugins = self._getOb('plugins')
useradders = plugins.listPlugins(IUserAdderPlugin)
roleassigners = plugins.listPlugins(IRoleAssignerPlugin)
user = None
login = self.applyTransform(login)
if not (useradders and roleassigners):
raise NotImplementedError('There are no plugins'
' that can create'
' users and assign roles to them.')
for useradder_id, useradder in useradders:
if useradder.doAddUser(login, password):
# ???: Adds user to cache, but without roles...
user = self.getUser(login)
break
# No useradder was successful.
if user is None:
return
for roleassigner_id, roleassigner in roleassigners:
for role in roles:
try:
roleassigner.doAssignRoleToPrincipal(user.getId(), role)
except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
reraise(roleassigner)
logger.debug('RoleAssigner %s error' % roleassigner_id,
exc_info=True)
pass
if user is not None:
notify(PrincipalCreated(user))
return user
@security.public
def all_meta_types(self):
""" What objects can be put in here?
"""
import Products
allowed_types = tuple(MultiPlugins) + (RAMCacheManager.meta_type,)
return [x for x in Products.meta_types if x['name'] in allowed_types]
@security.private
def manage_beforeDelete(self, item, container):
if item is self:
try:
del container.__allow_groups__
except: # noqa
pass
handle = self.meta_type + '/' + self.getId()
BeforeTraverse.unregisterBeforeTraverse(container, handle)
@security.private
def manage_afterAdd(self, item, container):
if item is self:
container.__allow_groups__ = aq_base(self)
handle = self.meta_type + '/' + self.getId()
container = container.this()
nc = BeforeTraverse.NameCaller(self.getId())
BeforeTraverse.registerBeforeTraverse(container, nc, handle)
def __call__(self, container, req):
""" The __before_publishing_traverse__ hook.
"""
resp = req['RESPONSE']
req._hold(ResponseCleanup(resp))
stack = getattr(resp, '_unauthorized_stack', [])
stack.append(resp._unauthorized)
resp._unauthorized_stack = stack
resp._unauthorized = self._unauthorized
resp._has_challenged = False
@security.private
def applyTransform(self, value):
""" Transform for login name.
Possibly transform the login, for example by making it lower
case.
value must be a string (or unicode) or it may be a sequence
(list, tuple), in which case we need to iterate over it.
"""
if not value:
return value
transform = self._get_login_transform_method()
if not transform:
return value
if isinstance(value, six.string_types):
return transform(value)
result = []
for v in value:
result.append(transform(v))
if isinstance(value, tuple):
return tuple(result)