1
2
3
4
5
6
7
8
9
10
11
12
13
14 import types
15
16 from random import choice
17 from copy import copy
18
19 from Globals import DTMLFile
20 from Globals import InitializeClass
21 from AccessControl import ClassSecurityInfo
22 from AccessControl import Permissions
23 from AccessControl import getSecurityManager
24 from Acquisition import aq_base
25 from Products.PluggableAuthService import interfaces
26 from zExceptions import Unauthorized
27 from DateTime import DateTime
28
29 from Products.ZenEvents.ActionRule import ActionRule
30 from Products.ZenEvents.CustomEventView import CustomEventView
31 from Products.ZenRelations.RelSchema import *
32 from Products.ZenModel.AdministrativeRole import AdministrativeRole
33 from Products.ZenUtils import Time
34
35 from ZenossSecurity import *
36 from ZenModelRM import ZenModelRM
37 import Products.ZenUtils.Utils as Utils
38
39 import smtplib
40 from email.MIMEText import MIMEText
41 import socket
42 import sys
43
44 UserSettingsId = "ZenUsers"
45
46
53
54
55 -def rolefilter(r): return r not in ("Anonymous", "Authenticated", "Owner")
56
58 """Manage zenoss user folders.
59 """
60
61 meta_type = "UserSettingsManager"
62
63
64
65 sub_meta_types = ("UserSettings",)
66
67 factory_type_information = (
68 {
69 'id' : 'UserSettingsManager',
70 'meta_type' : 'UserSettingsManager',
71 'description' : """Base class for all devices""",
72 'icon' : 'UserSettingsManager.gif',
73 'product' : 'ZenModel',
74 'factory' : 'manage_addUserSettingsManager',
75 'immediate_view' : 'manageUserFolder',
76 'actions' :
77 (
78 { 'id' : 'settings'
79 , 'name' : 'Settings'
80 , 'action' : '../editSettings'
81 , 'permissions' : ( ZEN_MANAGE_DMD, )
82 },
83 { 'id' : 'manage'
84 , 'name' : 'Commands'
85 , 'action' : '../dataRootManage'
86 , 'permissions' : (ZEN_MANAGE_DMD,)
87 },
88 { 'id' : 'users'
89 , 'name' : 'Users'
90 , 'action' : 'manageUserFolder'
91 , 'permissions' : ( ZEN_MANAGE_DMD, )
92 },
93 { 'id' : 'packs'
94 , 'name' : 'ZenPacks'
95 , 'action' : '../viewZenPacks'
96 , 'permissions' : ( ZEN_MANAGE_DMD, )
97 },
98 { 'id' : 'menus'
99 , 'name' : 'Menus'
100 , 'action' : '../editMenus'
101 , 'permissions' : ( ZEN_MANAGE_DMD, )
102 },
103 { 'id' : 'portlets'
104 , 'name' : 'Portlets'
105 , 'action' : '../editPortletPerms'
106 , 'permissions' : ( ZEN_MANAGE_DMD, )
107 },
108 { 'id' : 'daemons'
109 , 'name' : 'Daemons'
110 , 'action' : '../../About/zenossInfo'
111 , 'permissions' : ( ZEN_MANAGE_DMD, )
112 },
113 { 'id' : 'versions'
114 , 'name' : 'Versions'
115 , 'action' : '../../About/zenossVersions'
116 , 'permissions' : ( ZEN_MANAGE_DMD, )
117 },
118 )
119 },
120 )
121
122
124 """Return list user settings objects.
125 """
126
127
128 return self.objectValues(spec="UserSettings")
129
131 """Return list user settings objects.
132 """
133 return self.objectValues(spec="GroupSettings")
134
135
137 """Return list of all zenoss usernames.
138 """
139 filt = lambda x: x not in filtNames
140 return [ u.id for u in self.getAllUserSettings() if filt(u.id) ]
141
143 """Return list of all zenoss usernames.
144 """
145 filt = lambda x: x not in filtNames
146 return [ g.id for g in self.getAllGroupSettings() if filt(g.id) ]
147
149 """Return list of Users wrapped in their settings folder.
150 """
151 users = []
152 for uset in self.objectValues(spec="UserSettings"):
153 user = self.acl_users.getUser(uset.id)
154 if user: users.append(user.__of__(uset))
155 return users
156
157
159 """Return a user object. If userid is not passed return current user.
160 """
161 if userid is None:
162 user = getSecurityManager().getUser()
163 else:
164 user = self.acl_users.getUser(userid)
165 if user: return user.__of__(self.acl_users)
166
167
172
174 """Return a user folder. If userid is not passed return current user.
175 """
176 user=None
177 if userid is None:
178 user = getSecurityManager().getUser()
179 userid = user.getId()
180 if not userid: raise Unauthorized
181 folder = self._getOb(userid,None)
182 if not folder and userid:
183 ufolder = UserSettings(userid)
184 self._setObject(ufolder.getId(), ufolder)
185 folder = self._getOb(userid)
186 if not user:
187 user = self.getUser(userid)
188 if user:
189 folder.changeOwnership(user)
190 folder.manage_setLocalRoles(userid, ("Owner",))
191 return folder
192
193
199
200
209
216
217
235
236
238 """ Generate a valid password.
239 """
240
241 chars = 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'
242 return ''.join( [ choice(chars) for i in range(6) ] )
243
244
273
274
276 """Delete a list of zenoss users from the system.
277 """
278
279
280
281
282
283 if 'admin' in userids:
284 REQUEST['message'] = "Cannot delete admin user. No users were deleted."
285 return self.callZenScreen(REQUEST)
286
287 ifaces = [interfaces.plugins.IUserAdderPlugin]
288 getPlugins = self.acl_users.plugins.listPlugins
289 plugins = [ getPlugins(x)[0][1] for x in ifaces ]
290 for userid in userids:
291 try:
292 for plugin in plugins:
293 plugin.removeUser(userid)
294 except KeyError:
295
296
297
298 pass
299 if getattr(aq_base(self), userid, False):
300 us = self._getOb(userid)
301 for ar in us.adminRoles():
302 ar.userSetting.removeRelation()
303 mobj = ar.managedObject().primaryAq()
304 mobj.adminRoles._delObject(ar.id)
305 self._delObject(userid)
306 if REQUEST:
307 REQUEST['message'] = "Users deleted"
308 return self.callZenScreen(REQUEST)
309
310
312 """Add a zenoss group to the system and set its default properties.
313 """
314 if not groupid: return
315 try:
316 self.acl_users.groupManager.addGroup(groupid)
317 except KeyError: pass
318 gfolder = self.getGroupSettings(groupid)
319 if REQUEST:
320 REQUEST['message'] = "Group %s added" % groupid
321 return self.callZenScreen(REQUEST)
322
323
325 """ Delete a zenoss group from the system
326 """
327 gm = self.acl_users.groupManager
328 if type(groupids) in types.StringTypes:
329 groupids = [groupids]
330 for groupid in groupids:
331 if self._getOb(groupid): self._delObject(groupid)
332 try:
333 gm.removeGroup(groupid)
334 except KeyError: pass
335 if REQUEST:
336 REQUEST['message'] = "Groups deleted"
337 return self.callZenScreen(REQUEST)
338
339
350
351
361
362
364 ''' Do pager test for given user
365 '''
366 userSettings = self.getUserSettings(userid)
367 msg = userSettings.manage_pagerTest()
368 if msg:
369 REQUEST['message'] = msg
370 if REQUEST:
371 return self.callZenScreen(REQUEST)
372
373
375 """Delete orphaned user folders.
376 """
377 userfolders = self._getOb(UserSettingsId)
378 userids = self.acl_users.getUserNames()
379 for fid in userfolders.objectIds():
380 if fid not in userids:
381 userfolders._delObject(fid)
382
383
385 """Get list of all roles without Anonymous and Authenticated.
386 """
387 return filter(rolefilter, self.valid_roles())
388
389
392
393
394
401
402
403 addUserSettings = DTMLFile('dtml/addUserSettings',globals())
404
405
407 """zenoss user folder has users preferences.
408 """
409
410 meta_type = "UserSettings"
411
412 sub_meta_types = ("ActionRule",)
413
414 email = ""
415 pager = ""
416 defaultPageSize = 40
417 defaultEventPageSize = 30
418 defaultAdminRole = "ZenUser"
419 defaultAdminLevel = 1
420 oncallStart = 0
421 oncallEnd = 0
422 escalationMinutes = 0
423 dashboardState = ''
424 dashboardRefresh = 30
425 dashboardTimeout = 25
426 dashboardOrganizer = 'Devices'
427 netMapStartObject = ''
428
429 _properties = ZenModelRM._properties + (
430 {'id':'email', 'type':'string', 'mode':'w'},
431 {'id':'pager', 'type':'string', 'mode':'w'},
432 {'id':'defaultPageSize', 'type':'int', 'mode':'w'},
433 {'id':'defaultEventPageSize', 'type':'int', 'mode':'w'},
434 {'id':'defaultAdminRole', 'type':'string', 'mode':'w'},
435 {'id':'defaultAdminLevel', 'type':'int', 'mode':'w'},
436 {'id':'oncallStart', 'type':'int', 'mode':'w'},
437 {'id':'oncallEnd', 'type':'int', 'mode':'w'},
438 {'id':'escalationMinutes', 'type':'int', 'mode':'w'},
439 {'id':'dashboardState', 'type':'string', 'mode':'w'},
440 {'id':'dashboardRefresh', 'type':'int', 'mode':'w'},
441 {'id':'dashboardTimeout', 'type':'int', 'mode':'w'},
442 {'id':'dashboardOrganizer', 'type':'string', 'mode':'w'},
443 {'id':'netMapStartObject', 'type':'string', 'mode':'w'},
444 )
445
446
447 _relations = (
448 ("adminRoles", ToMany(ToOne, "Products.ZenModel.AdministrativeRole", "userSetting")),
449 )
450
451
452 factory_type_information = (
453 {
454 'immediate_view' : 'editUserSettings',
455 'actions' :
456 (
457 {'name' : 'Edit',
458 'action' : 'editUserSettings',
459 'permissions' : (ZEN_CHANGE_SETTINGS,),
460 },
461 {'name' : 'Administered Objects',
462 'action' : 'administeredDevices',
463 'permissions' : (ZEN_VIEW,)
464 },
465 {'name' : 'Event Views',
466 'action' : 'editEventViews',
467 'permissions' : (ZEN_VIEW,),
468 },
469 {'name' : 'Alerting Rules',
470 'action' : 'editActionRules',
471 'permissions' : (ZEN_VIEW,),
472 },
473 )
474 },
475 )
476
477 security = ClassSecurityInfo()
478
480 """Get current roles for this user.
481 """
482 user = self.getUser(self.id)
483 if user: return filter(rolefilter, user.getRoles())
484 return ()
485
486
488 """Return group settings objects for user
489 """
490 user = self.getUser(self.id)
491 gm = self.zport.acl_users.groupManager
492 if user:
493 return gm.getGroupsForPrincipal(user)
494 return ()
495
496
497 security.declareProtected(ZEN_CHANGE_SETTINGS, 'updatePropsFromDict')
499 props = self.propertyIds()
500 for k, v in propdict.items():
501 if k in props: setattr(self,k,v)
502
503
505 """Can the current user edit this settings object.
506 """
507 owner = self.getOwner()
508 user = getSecurityManager().getUser()
509 return user.has_role("Manager") or \
510 owner.getUserName() == user.getUserName()
511
512
513 security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_editUserSettings')
517 """Update user settings.
518 """
519
520 user = self.acl_users.getUser(self.id)
521 if not user:
522 user = self.getPhysicalRoot().acl_users.getUser(self.id)
523 if not user:
524 if REQUEST:
525 REQUEST['message'] = "user %s not found" % self.id
526 return self.callZenScreen(REQUEST)
527 else:
528 return
529
530
531 roleManager = self.acl_users.roleManager
532 origRoles = filter(rolefilter, user.getRoles())
533
534 if roles != origRoles:
535
536 try:
537 set()
538 except NameError:
539 from sets import Set as set
540
541 removeRoles = list(set(origRoles).difference(set(roles)))
542 for role in removeRoles:
543 roleManager.removeRoleFromPrincipal(role, self.id)
544
545 addRoles = list(set(roles).difference(set(origRoles)))
546 for role in addRoles:
547 roleManager.assignRoleToPrincipal(role, self.id)
548
549
550 groupManager = self.acl_users.groupManager
551 origGroups = groupManager.getGroupsForPrincipal(user)
552
553 if groups != origGroups:
554
555 try:
556 set()
557 except NameError:
558 from sets import Set as set
559
560 removeGroups = set(origGroups).difference(set(groups))
561 for groupid in removeGroups:
562 groupManager.removePrincipalFromGroup(user.getId(), groupid)
563
564 addGroups = set(groups).difference(set(origGroups))
565 for groupid in addGroups:
566 groupManager.addPrincipalToGroup(user.getId(), groupid)
567
568
569 if domains:
570 msg = 'Zenoss does not currently manage domains for users.'
571 raise NotImplementedError(msg)
572
573
574 if REQUEST:
575 kw = REQUEST.form
576 self.updatePropsFromDict(kw)
577
578
579 userManager = self.acl_users.userManager
580 if password:
581 if password.find(':') >= 0:
582 if REQUEST:
583 REQUEST['message'] = \
584 "Passwords cannot contain a ':'. Password not updated."
585 return self.callZenScreen(REQUEST)
586 else:
587 raise ValueError("Passwords cannot contain a ':' ")
588 elif password != sndpassword:
589 if REQUEST:
590 REQUEST['message'] = \
591 "Passwords didn't match! Password not updated. "
592 return self.callZenScreen(REQUEST)
593 else:
594 raise ValueError("Passwords don't match")
595 else:
596 try: userManager.updateUserPassword(self.id, password)
597 except KeyError:
598 self.getPhysicalRoot().acl_users.userManager.updateUserPassword(
599 self.id, password)
600 loggedInUser = REQUEST['AUTHENTICATED_USER']
601
602
603
604 if loggedInUser.getUserName() == self.id:
605 self.acl_users.logout(REQUEST)
606
607
608 if REQUEST:
609 REQUEST['message'] = Time.SaveMessage()
610 return self.callZenScreen(REQUEST)
611 else:
612 return user
613
614 security.declareProtected(ZEN_CHANGE_ALERTING_RULES, 'manage_addActionRule')
631
634
635 security.declareProtected(ZEN_CHANGE_EVENT_VIEWS,
636 'manage_addCustomEventView')
653
654
655 security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
656 'manage_addAdministrativeRole')
689
690
691 security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
692 'manage_editAdministrativeRoles')
713
714
715 security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
716 'manage_deleteAdministrativeRole')
731
732
733 security.declareProtected(ZEN_CHANGE_SETTINGS, 'getAllAdminRoles')
735 """Return all admin roles for this user and its groups
736 """
737 ars = self.adminRoles()
738 for group in self.getUser().getGroups():
739 gs = self.getGroupSettings(group)
740 ars.extend(gs.adminRoles())
741 return ars
742
743
744 security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_emailTest')
746 ''' Send a test email to the given userid.
747 '''
748 destSettings = self.getUserSettings(self.getId())
749 destAddresses = destSettings.getEmailAddresses()
750 msg = None
751 if destAddresses:
752 fqdn = socket.getfqdn()
753 thisUser = self.getUser()
754 srcId = thisUser.getId()
755 srcSettings = self.getUserSettings(srcId)
756 srcAddress = self.dmd.getEmailFrom()
757
758 body = ('This is a test message sent by %s' % srcId +
759 ' from the Zenoss installation on %s.' % fqdn)
760 emsg = MIMEText(body)
761 emsg['Subject'] = 'Zenoss Email Test'
762 emsg['From'] = srcAddress
763 emsg['To'] = ', '.join(destAddresses)
764 emsg['Date'] = DateTime().rfc822()
765 result, errorMsg = Utils.sendEmail(emsg, self.dmd.smtpHost,
766 self.dmd.smtpPort,
767 self.dmd.smtpUseTLS, self.dmd.smtpUser,
768 self.dmd.smtpPass)
769 if result:
770 msg = 'Test email sent to %s' % destAddresses
771 else:
772 msg = 'Test failed: %s' % errorMsg
773 else:
774 msg = 'Test email not sent, user has no email address.'
775 if REQUEST:
776 REQUEST['message'] = msg
777 return self.callZenScreen(REQUEST)
778 else:
779 return msg
780
781
782 security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_pagerTest')
784 ''' Send a test page
785 '''
786 destSettings = self.getUserSettings(self.getId())
787 destPagers = [ x.strip() for x in
788 (destSettings.getPagerAddresses() or []) ]
789 msg = None
790 fqdn = socket.getfqdn()
791 srcId = self.getUser().getId()
792 testMsg = ('Test sent by %s' % srcId +
793 ' from the Zenoss installation on %s.' % fqdn)
794 for destPager in destPagers:
795 result, errorMsg = Utils.sendPage(destPager, testMsg,
796 self.dmd.snppHost, self.dmd.snppPort)
797 if result:
798 msg = 'Test page sent to %s' % ', '.join(destPagers)
799 else:
800 msg = 'Test failed: %s' % errorMsg
801 break
802 else:
803 msg = 'Test page not sent, user has no pager number.'
804 if REQUEST:
805 REQUEST['message'] = msg
806 return self.callZenScreen(REQUEST)
807 else:
808 return msg
809
816
818 if self.pager.strip():
819 return [self.pager.strip()]
820 return []
821
826
828
829 meta_type = 'GroupSettings'
830
831 factory_type_information = (
832 {
833 'immediate_view' : 'editGroupSettings',
834 'actions' :
835 (
836 {'name' : 'Edit',
837 'action' : 'editGroupSettings',
838 'permissions' : (ZEN_CHANGE_SETTINGS,),
839 },
840 {'name' : 'Administered Objects',
841 'action' : 'administeredDevices',
842 'permissions' : (ZEN_CHANGE_ADMIN_OBJECTS,)
843 },
844 {'name' : 'Alerting Rules',
845 'action' : 'editActionRules',
846 'permissions' : (ZEN_CHANGE_ALERTING_RULES,),
847 },
848 )
849 },
850 )
851
852 security = ClassSecurityInfo()
853
855 return self.zport.acl_users.groupManager
856
858 """ Add user to this group
859 """
860 if type(userids) in types.StringTypes:
861 userids = [userids]
862 for userid in userids:
863 self._getG().addPrincipalToGroup( userid, self.id )
864 if REQUEST:
865 REQUEST['message'] = 'Added %s to Group %s' % (','.join(userids), self.id)
866 return self.callZenScreen(REQUEST)
867
868
870 self._getG().removePrincipalFromGroup( userid, self.id )
871
872
881
885
887 return [ u[0] for u in self._getG().listAssignedPrincipals(self.id) ]
888
891
897
898 InitializeClass(UserSettingsManager)
899 InitializeClass(UserSettings)
900