Package ZenModel :: Module UserSettings
[hide private]
[frames] | no frames]

Source Code for Module ZenModel.UserSettings

  1  ########################################################################### 
  2  # 
  3  # This program is part of Zenoss Core, an open source monitoring platform. 
  4  # Copyright (C) 2007, Zenoss Inc. 
  5  # 
  6  # This program is free software; you can redistribute it and/or modify it 
  7  # under the terms of the GNU General Public License version 2 as published by 
  8  # the Free Software Foundation. 
  9  # 
 10  # For complete information please visit: http://www.zenoss.com/oss/ 
 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   
47 -def manage_addUserSettingsManager(context, REQUEST=None):
48 """Create user settings manager.""" 49 ufm = UserSettingsManager(UserSettingsId) 50 context._setObject(ufm.getId(), ufm) 51 if REQUEST is not None: 52 REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
53 54
55 -def rolefilter(r): return r not in ("Anonymous", "Authenticated", "Owner")
56
57 -class UserSettingsManager(ZenModelRM):
58 """Manage zenoss user folders. 59 """ 60 61 meta_type = "UserSettingsManager" 62 63 #zPrimaryBasePath = ("", "zport") 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
123 - def getAllUserSettings(self):
124 """Return list user settings objects. 125 """ 126 # This code used to filter out the admin user. 127 # See ticket #1615 for why it no longer does. 128 return self.objectValues(spec="UserSettings")
129
130 - def getAllGroupSettings(self):
131 """Return list user settings objects. 132 """ 133 return self.objectValues(spec="GroupSettings")
134 135
136 - def getAllUserSettingsNames(self, filtNames=()):
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
142 - def getAllGroupSettingsNames(self, filtNames=()):
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
148 - def getUsers(self):
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
158 - def getUser(self, userid=None):
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
168 - def getAllActionRules(self):
169 for u in self.getAllUserSettings() + self.getAllGroupSettings(): 170 for ar in u.getActionRules(): 171 yield ar
172
173 - def getUserSettings(self, userid=None):
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
194 - def getGroupSettings(self, groupid):
195 if not self._getOb(groupid, False): 196 gfolder = GroupSettings(groupid) 197 self._setObject(gfolder.getId(), gfolder) 198 return self._getOb(groupid)
199 200
201 - def setDashboardState(self, userid=None, REQUEST=None):
202 """ Store a user's portlets and layout. If userid is not passed 203 set the state for the current user. 204 """ 205 user = self.getUserSettings(userid) 206 user.dashboardState = (Utils.extractPostContent(REQUEST) or 207 user.dashboardState) 208 return True
209
210 - def getUserSettingsUrl(self, userid=None):
211 """Return the url to the current user's folder. 212 """ 213 uf = self.getUserSettings(userid) 214 if uf: return uf.getPrimaryUrlPath() 215 return ""
216 217
218 - def manage_addUser(self, userid, password=None,roles=("ZenUser",), 219 REQUEST=None,**kw):
220 """Add a zenoss user to the system and set its default properties. 221 """ 222 if not userid: return 223 if password is None: 224 password = self.generatePassword() 225 self.acl_users._doAddUser(userid,password,roles,"") 226 user = self.acl_users.getUser(userid) 227 ufolder = self.getUserSettings(userid) 228 if REQUEST: kw = REQUEST.form 229 ufolder.updatePropsFromDict(kw) 230 if REQUEST: 231 REQUEST['message'] = "User added" 232 return self.callZenScreen(REQUEST) 233 else: 234 return user
235 236
237 - def generatePassword(self):
238 """ Generate a valid password. 239 """ 240 # we don't use these to avoid typos: OQ0Il1 241 chars = 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789' 242 return ''.join( [ choice(chars) for i in range(6) ] )
243 244
245 - def manage_changeUser(self, userid, password=None, sndpassword=None, 246 roles=None, domains=None, REQUEST=None, **kw):
247 """Change a zenoss users settings. 248 """ 249 user = self.acl_users.getUser(userid) 250 if not user: 251 if REQUEST: 252 REQUEST['message'] = "user %s not found" % userid 253 return self.callZenScreen(REQUEST) 254 else: 255 return 256 if password and password != sndpassword: 257 if REQUEST: 258 REQUEST['message'] = "passwords didn't match no change: " 259 return self.callZenScreen(REQUEST) 260 else: 261 raise ValueError("passwords don't match") 262 if password is None: password = user._getPassword() 263 if roles is None: roles = user.roles 264 if domains is None: domains = user.domains 265 self.acl_users._doChangeUser(userid,password,roles,domains) 266 ufolder = self.getUserSettings(userid) 267 ufolder.updatePropsFromDict(kw) 268 if REQUEST: 269 REQUEST['message'] = Time.SaveMessage() 270 return self.callZenScreen(REQUEST) 271 else: 272 return user
273 274
275 - def manage_deleteUsers(self, userids=(), REQUEST=None):
276 """Delete a list of zenoss users from the system. 277 """ 278 # get a list of plugins that can add manage users and then call the 279 # appropriate methods 280 # 281 # XXX this needs to be reviewed when new plugins are added, such as the 282 # LDAP plugin 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 # this means that there's no user in the acl_users, but that 296 # Zenoss still sees the user; we want to pass on this exception 297 # so that Zenoss can clean up 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
311 - def manage_addGroup(self, groupid, REQUEST=None):
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
324 - def manage_deleteGroups(self, groupids=(), REQUEST=None):
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
340 - def manage_addUsersToGroup(self, userids, groupid, REQUEST=None):
341 """ Add users to a group 342 """ 343 if type(userids) in types.StringTypes: 344 userids = [userids] 345 self._getOb(groupid).manage_addUsersToGroup(userids) 346 if REQUEST: 347 REQUEST['message'] = \ 348 "User %s added to group %s" % (','.join(userids), groupid) 349 return self.callZenScreen(REQUEST)
350 351
352 - def manage_emailTestAdmin(self, userid, REQUEST=None):
353 ''' Do email test for given user 354 ''' 355 userSettings = self.getUserSettings(userid) 356 msg = userSettings.manage_emailTest() 357 if msg: 358 REQUEST['message'] = msg 359 if REQUEST: 360 return self.callZenScreen(REQUEST)
361 362
363 - def manage_pagerTestAdmin(self, userid, REQUEST=None):
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
374 - def cleanUserFolders(self):
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
384 - def getAllRoles(self):
385 """Get list of all roles without Anonymous and Authenticated. 386 """ 387 return filter(rolefilter, self.valid_roles())
388 389
390 - def exportXmlHook(self,ofile, ignorerels):
391 map(lambda x: x.exportXml(ofile, ignorerels), self.getAllUserSettings())
392 393 394
395 -def manage_addUserSettings(context, id, title = None, REQUEST = None):
396 """make a device class""" 397 dc = UserSettings(id, title) 398 context._setObject(id, dc) 399 if REQUEST: 400 REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
401 402 403 addUserSettings = DTMLFile('dtml/addUserSettings',globals()) 404 405
406 -class UserSettings(ZenModelRM):
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 # Screen action bindings (and tab definitions) 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
479 - def getUserRoles(self):
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')
498 - def updatePropsFromDict(self, propdict):
499 props = self.propertyIds() 500 for k, v in propdict.items(): 501 if k in props: setattr(self,k,v)
502 503
504 - def iseditable(self):
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')
514 - def manage_editUserSettings(self, password=None, sndpassword=None, 515 roles=None, groups=None, domains=None, 516 REQUEST=None, **kw):
517 """Update user settings. 518 """ 519 # get the user object; return if no user 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 # update role info 531 roleManager = self.acl_users.roleManager 532 origRoles = filter(rolefilter, user.getRoles()) 533 # if there's a change, then we need to update 534 if roles != origRoles: 535 # can we use the built-in set? 536 try: 537 set() 538 except NameError: 539 from sets import Set as set 540 # get roles to remove and then remove them 541 removeRoles = list(set(origRoles).difference(set(roles))) 542 for role in removeRoles: 543 roleManager.removeRoleFromPrincipal(role, self.id) 544 # get roles to add and then add them 545 addRoles = list(set(roles).difference(set(origRoles))) 546 for role in addRoles: 547 roleManager.assignRoleToPrincipal(role, self.id) 548 549 # update role info 550 groupManager = self.acl_users.groupManager 551 origGroups = groupManager.getGroupsForPrincipal(user) 552 # if there's a change, then we need to update 553 if groups != origGroups: 554 # can we use the built-in set? 555 try: 556 set() 557 except NameError: 558 from sets import Set as set 559 # get groups to remove and then remove them 560 removeGroups = set(origGroups).difference(set(groups)) 561 for groupid in removeGroups: 562 groupManager.removePrincipalFromGroup(user.getId(), groupid) 563 # get groups to add and then add them 564 addGroups = set(groups).difference(set(origGroups)) 565 for groupid in addGroups: 566 groupManager.addPrincipalToGroup(user.getId(), groupid) 567 568 # we're not managing domains right now 569 if domains: 570 msg = 'Zenoss does not currently manage domains for users.' 571 raise NotImplementedError(msg) 572 573 # update Zenoss user folder settings 574 if REQUEST: 575 kw = REQUEST.form 576 self.updatePropsFromDict(kw) 577 578 # update password info 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 # we only want to log out the user if it's *their* passowrd 602 # they've changed, not, for example, if the admin user is 603 # changing another user's password 604 if loggedInUser.getUserName() == self.id: 605 self.acl_users.logout(REQUEST) 606 607 # finish up 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')
615 - def manage_addActionRule(self, id=None, REQUEST=None):
616 """Add an action rule to this object. 617 """ 618 if id: 619 ar = ActionRule(id) 620 self._setObject(id, ar) 621 ar = self._getOb(id) 622 user = getSecurityManager().getUser() 623 userid = user.getId() 624 if userid != self.id: 625 userid = self.id 626 user = self.getUser(userid) 627 ar.changeOwnership(user) 628 ar.manage_setLocalRoles(userid, ("Owner",)) 629 if REQUEST: 630 return self.callZenScreen(REQUEST)
631
632 - def getActionRules(self):
633 return self.objectValues(spec=ActionRule.meta_type)
634 635 security.declareProtected(ZEN_CHANGE_EVENT_VIEWS, 636 'manage_addCustomEventView')
637 - def manage_addCustomEventView(self, id=None, REQUEST=None):
638 """Add an action rule to this object. 639 """ 640 if id: 641 ar = CustomEventView(id) 642 self._setObject(id, ar) 643 ar = self._getOb(id) 644 user = getSecurityManager().getUser() 645 userid = user.getId() 646 if userid != self.id: 647 userid = self.id 648 user = self.getUser(userid) 649 ar.changeOwnership(user) 650 ar.manage_setLocalRoles(userid, ("Owner",)) 651 if REQUEST: 652 return self.callZenScreen(REQUEST)
653 654 655 security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS, 656 'manage_addAdministrativeRole')
657 - def manage_addAdministrativeRole(self, name=None, type='device', 658 role=None, REQUEST=None):
659 "Add a Admin Role to this device" 660 mobj = None 661 if not name: 662 name = getattr(REQUEST, 'deviceName') 663 if type == 'device': 664 mobj =self.getDmdRoot("Devices").findDevice(name) 665 else: 666 try: 667 root = type.capitalize()+'s' 668 mobj = self.getDmdRoot(root).getOrganizer(name) 669 except KeyError: pass 670 if not mobj: 671 if REQUEST: 672 REQUEST['message'] = "%s %s not found"%(type.capitalize(),name) 673 return self.callZenScreen(REQUEST) 674 else: return 675 roleNames = [ r.id for r in mobj.adminRoles() ] 676 if self.id in roleNames: 677 if REQUEST: 678 REQUEST['message'] = \ 679 "Administrative Role for %s %s for user %s already exists" % \ 680 (type, name, self.id) 681 return self.callZenScreen(REQUEST) 682 else: return 683 mobj.manage_addAdministrativeRole(self.id) 684 if REQUEST: 685 REQUEST['message'] = \ 686 "Administrative Role for %s %s for user %s added" % \ 687 (type, name, self.id) 688 return self.callZenScreen(REQUEST)
689 690 691 security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS, 692 'manage_editAdministrativeRoles')
693 - def manage_editAdministrativeRoles(self, ids=(), role=(), 694 level=(), REQUEST=None):
695 """Edit list of admin roles. 696 """ 697 if type(ids) in types.StringTypes: 698 ids = [ids] 699 level = [level] 700 role = [role] 701 else: 702 ids = list(ids) 703 for ar in self.adminRoles(): 704 mobj = ar.managedObject() 705 try: i = ids.index(mobj.managedObjectName()) 706 except ValueError: continue 707 mobj = mobj.primaryAq() 708 mobj.manage_editAdministrativeRoles(self.id, role[i], level[i]) 709 if REQUEST: 710 if ids: 711 REQUEST['message'] = "Administrative Roles Updated" 712 return self.callZenScreen(REQUEST)
713 714 715 security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS, 716 'manage_deleteAdministrativeRole')
717 - def manage_deleteAdministrativeRole(self, delids=(), REQUEST=None):
718 "Delete a admin role to this device" 719 import types 720 if type(delids) in types.StringTypes: 721 delids = [delids] 722 for ar in self.adminRoles(): 723 mobj = ar.managedObject() 724 if mobj.managedObjectName() not in delids: continue 725 mobj = mobj.primaryAq() 726 mobj.manage_deleteAdministrativeRole(self.id) 727 if REQUEST: 728 if delids: 729 REQUEST['message'] = "Administrative Roles Deleted" 730 return self.callZenScreen(REQUEST)
731 732 733 security.declareProtected(ZEN_CHANGE_SETTINGS, 'getAllAdminRoles')
734 - def getAllAdminRoles(self):
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')
745 - def manage_emailTest(self, REQUEST=None):
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 # Read body from file probably 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')
783 - def manage_pagerTest(self, REQUEST=None):
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
810 - def exportXmlHook(self, ofile, ignorerels):
811 """patch to export all user configuration 812 """ 813 for o in self.objectValues(): 814 if hasattr(aq_base(o), 'exportXml'): 815 o.exportXml(ofile, ignorerels)
816
817 - def getPagerAddresses(self):
818 if self.pager.strip(): 819 return [self.pager.strip()] 820 return []
821
822 - def getEmailAddresses(self):
823 if self.email.strip(): 824 return [self.email] 825 return []
826
827 -class GroupSettings(UserSettings):
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
854 - def _getG(self):
855 return self.zport.acl_users.groupManager
856
857 - def manage_addUsersToGroup( self, userids, REQUEST=None ):
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
869 - def manage_deleteUserFromGroup( self, userid ):
870 self._getG().removePrincipalFromGroup( userid, self.id )
871 872
873 - def manage_deleteUsersFromGroup(self, userids=(), REQUEST=None ):
874 """ Delete users from this group 875 """ 876 for userid in userids: 877 self.manage_deleteUserFromGroup(userid) 878 if REQUEST: 879 REQUEST['message'] = 'Deleted users from Group %s' % self.id 880 return self.callZenScreen(REQUEST)
881
882 - def getMemberUserSettings(self):
883 return [ self.getUserSettings(u[0]) 884 for u in self._getG().listAssignedPrincipals(self.id) ]
885
886 - def getMemberUserIds(self):
887 return [ u[0] for u in self._getG().listAssignedPrincipals(self.id) ]
888
889 - def printUsers(self):
890 return ", ".join(self.getMemberUserIds())
891
892 - def getEmailAddresses(self):
893 result = [] 894 for username in self.getMemberUserIds(): 895 result.extend(self.getUserSettings(username).getEmailAddresses()) 896 return result
897 898 InitializeClass(UserSettingsManager) 899 InitializeClass(UserSettings) 900