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

# Source Code for Module Products.ZenModel.UserSettings

       1  ##############################################################################
       2  #
       3  # Copyright (C) Zenoss, Inc. 2007, all rights reserved.
       4  #
       5  # This content is made available according to terms specified in
       6  # License.zenoss under the directory where your Zenoss product is installed.
       7  #
       8  ##############################################################################
       9
      10
      11  from DateTime import DateTime
      12  from random import choice
      13  from email.MIMEText import MIMEText
      14  import socket
      15  import logging
      16  log = logging.getLogger("zen.UserSettings")
      17
      18  from Globals import DTMLFile
      19  from Globals import InitializeClass
      20  from AccessControl import ClassSecurityInfo
      21  from AccessControl import getSecurityManager
      22  from Acquisition import aq_base
      23  from Products.PluggableAuthService import interfaces
      24  from Products.PluggableAuthService.PluggableAuthService \
      25      import _SWALLOWABLE_PLUGIN_EXCEPTIONS
      26  from zExceptions import Unauthorized
      27
      28  from Products.ZenEvents.ActionRule import ActionRule
      29  from Products.ZenEvents.CustomEventView import CustomEventView
      30  from Products.ZenRelations.RelSchema import *
      31  from Products.ZenUtils import Time
      32  from Products.ZenUtils.Utils import unused, prepId
      33  from Products.ZenUtils.guid.interfaces import IGUIDManager
      34  from Products.ZenUtils import DotNetCommunication
      35  from Products.ZenUtils.guid.interfaces import IGloballyIdentifiable
      36  from Products.ZenWidgets import messaging
      37  from Products.ZenModel.interfaces import IProvidesEmailAddresses, IProvidesPagerAddresses
      38  from Products.ZenMessaging.audit import audit
      39  from Products.ZenUtils.deprecated import deprecated
      40
      41  from ZenossSecurity import *
      42  from ZenModelRM import ZenModelRM
      43  from Products.ZenUtils import Utils
      44  from zope.interface import implements
      45
      46
      47 -class LocalAndLDAPUserEntries(Exception): pass
      48
      49  UserSettingsId = "ZenUsers"
      50
      51 -def manage_addUserSettingsManager(context, REQUEST=None):
      52      """Create user settings manager."""
      53      ufm = UserSettingsManager(UserSettingsId)
      54      context._setObject(ufm.getId(), ufm)
      55      if REQUEST is not None:
      56          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
      57
      58
      59 -def rolefilter(r): return r not in ("Anonymous", "Authenticated", "Owner")
      60
      61
      62 -class UserSettingsManager(ZenModelRM):
      63      """Manage zenoss user folders.
      64      """
      65      security = ClassSecurityInfo()
      66
      67      meta_type = "UserSettingsManager"
      68
      69      #zPrimaryBasePath = ("", "zport")
      70
      71      sub_meta_types = ("UserSettings",)
      72
      73      factory_type_information = (
      74          {
      75              'id'             : 'UserSettingsManager',
      76              'meta_type'      : 'UserSettingsManager',
      77              'description'    : """Base class for all devices""",
      78              'icon'           : 'UserSettingsManager.gif',
      79              'product'        : 'ZenModel',
      80              'factory'        : 'manage_addUserSettingsManager',
      81              'immediate_view' : 'manageUserFolder',
      82              'actions'        :
      83           (
      84                  { 'id'            : 'settings'
      85                  , 'name'          : 'Settings'
      86                  , 'action'        : '../editSettings'
      87                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
      88                  },
      89                  { 'id'            : 'manage'
      90                  , 'name'          : 'Commands'
      91                  , 'action'        : '../dataRootManage'
      92                  , 'permissions'   : (ZEN_MANAGE_DMD,)
      93                  },
      94                  { 'id'            : 'users'
      95                  , 'name'          : 'Users'
      96                  , 'action'        : 'manageUserFolder'
      97                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
      98                  },
      99                  { 'id'            : 'packs'
     100                  , 'name'          : 'ZenPacks'
     101                  , 'action'        : '../ZenPackManager/viewZenPacks'
     102                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     103                  },
     104                  { 'id'            : 'jobs'
     105                  , 'name'          : 'Jobs'
     106                  , 'action'        : '../joblist'
     107                  , 'permissions'   : ( "Manage DMD", )
     108                  },
     109                  { 'id'            : 'portlets'
     110                  , 'name'          : 'Portlets'
     111                  , 'action'        : '../editPortletPerms'
     112                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     113                  },
     114                  { 'id'            : 'daemons'
     115                  , 'name'          : 'Daemons'
     116                  , 'action'        : '../../About/zenossInfo'
     117                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     118                  },
     119                  { 'id'            : 'versions'
     120                  , 'name'          : 'Versions'
     121                  , 'action'        : '../../About/zenossVersions'
     122                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     123                  },
     124                  { 'id'            : 'backups'
     125                  , 'name'          : 'Backups'
     126                  , 'action'        : '../backupInfo'
     127                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     128                  },
     129                  { 'id'            : 'eventConfig'
     130                  , 'name'          : 'Events'
     131                  , 'action'        : 'eventConfig'
     132                  , 'permissions'   : ( "Manage DMD", )
     133                  },
     134                  { 'id'            : 'userInterfaceConfig'
     135                  , 'name'          : 'User Interface'
     136                  , 'action'        : '../userInterfaceConfig'
     137                  , 'permissions'   : ( "Manage DMD", )
     138                  },
     139             )
     140           },
     141          )
     142
     143
     144 -    def getAllUserSettings(self):
     145          """Return list user settings objects.
     146          """
     147          # This code used to filter out the admin user.
     148          # See ticket #1615 for why it no longer does.
     149          return sorted(self.objectValues(spec="UserSettings"),
     150                      key=lambda a: a.id)
     151
     152 -    def getAllGroupSettings(self):
     153          """Return list group settings objects.
     154          """
     155          return sorted(self.objectValues(spec="GroupSettings"),
     156                      key=lambda a: a.id)
     157
     158 -    def getAllUserSettingsNames(self, filtNames=()):
     159          """Return list of all zenoss usernames.
     160          """
     161          filtNames = set(filtNames)
     162          return [ u.id for u in self.getAllUserSettings()
     163                      if u.id not in filtNames ]
     164
     165 -    def getAllGroupSettingsNames(self, filtNames=()):
     166          """Return list of all zenoss groupnames.
     167          """
     168          filtNames = set(filtNames)
     169          return [ g.id for g in self.getAllGroupSettings()
     170                      if g.id not in filtNames ]
     171
     172 -    def getUsers(self):
     173          """Return list of Users wrapped in their settings folder.
     174          """
     175          users = []
     176          for uset in self.objectValues(spec="UserSettings"):
     177              user = self.acl_users.getUser(uset.id)
     178              if user: users.append(user.__of__(uset))
     179          return users
     180
     181
     182 -    def getUser(self, userid=None):
     183          """Return a user object.  If userid is not passed return current user.
     184          """
     185          if userid is None:
     186              user = getSecurityManager().getUser()
     187          else:
     188              user = self.acl_users.getUser(userid)
     189          if user: return user.__of__(self.acl_users)
     190
     191
     192 -    def getAllActionRules(self):
     193          for u in self.getAllUserSettings() + self.getAllGroupSettings():
     194              for ar in u.getActionRules():
     195                  yield ar
     196
     197 -    def getUserSettings(self, userid=None):
     198          """Return a user folder.  If userid is not passed return current user.
     199          """
     200          user=None
     201          if userid is None:
     202              user = getSecurityManager().getUser()
     203              userid = user.getId()
     204          if not userid: raise Unauthorized
     205          folder = self._getOb(userid,None)
     206          if not folder and userid:
     207              userid = str(userid)
     208              ufolder = UserSettings(userid)
     209              self._setObject(ufolder.getId(), ufolder)
     210              folder = self._getOb(userid)
     211              if not user:
     212                  user = self.getUser(userid)
     213              if user:
     214                  # Load default values from our auth backend
     215                  psheets = user.listPropertysheets()
     216                  psheets.reverse() # Because first sheet should have priority
     217                  for ps in map(lambda ps: user.getPropertysheet(ps), psheets):
     218                      props = {}
     219                      for id in ps.propertyIds():
     220                          props[id] = ps.getProperty(id)
     221                      ufolder.updatePropsFromDict(props)
     222                  folder.changeOwnership(user)
     223                  folder.manage_setLocalRoles(userid, ("Owner",))
     224          return folder
     225
     226
     227 -    def getGroupSettings(self, groupid):
     228          groupid = prepId(groupid)
     229          if not self._getOb(groupid, False):
     230              gfolder = GroupSettings(groupid)
     231              self._setObject(gfolder.getId(), gfolder)
     232          return self._getOb(groupid)
     233
     234
     235 -    def setDashboardState(self, userid=None, REQUEST=None):
     236          """ Store a user's portlets and layout. If userid is not passed
     237              set the state for the current user.
     238          """
     239          user = self.getUserSettings(userid)
     240          posted = Utils.extractPostContent(REQUEST)
     241          if posted:
     242              user.dashboardState = posted
     243              if REQUEST:
     244                  audit('UI.Dashboard.Edit', username=userid)
     245          return True
     246
     247 -    def getUserSettingsUrl(self, userid=None):
     248          """Return the url to the current user's folder.
     249          """
     250          uf = self.getUserSettings(userid)
     251          if uf: return uf.getPrimaryUrlPath()
     252          return ""
     253
     254
     255      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addUser')
     256 -    def manage_addUser(self, userid, password=None,roles=("ZenUser",),
     257                      REQUEST=None,**kw):
     258          """
     259          Add a Zenoss user to the system and set the user's default properties.
     260
     261          @parameter userid: username to add
     262          @parameter password: password for the username
     263          @parameter roles: tuple of role names
     264          @parameter REQUEST: Zope object containing details about this request
     265          """
     266          if not userid: return
     267
     268          userid= userid.strip()
     269
     270          illegal_usernames= [ 'user', ]
     271
     272          user_name= userid.lower()
     273          if user_name in illegal_usernames:
     274              if REQUEST:
     275                  messaging.IMessageSender(self).sendToBrowser(
     276                      'Error',
     277                      'The username "%s" is reserved.' % userid,
     278                      priority=messaging.WARNING
     279                  )
     280                  return self.callZenScreen(REQUEST)
     281              else:
     282                  return None
     283
     284          if password is None:
     285              password = self.generatePassword()
     286
     287          self.acl_users._doAddUser(userid,password,roles,"")
     288          self.acl_users.ZCacheable_invalidate()
     289          user = self.acl_users.getUser(userid)
     290          ufolder = self.getUserSettings(userid)
     291          if REQUEST: kw = REQUEST.form
     292          ufolder.updatePropsFromDict(kw)
     293
     294          if REQUEST:
     295              messaging.IMessageSender(self).sendToBrowser(
     296                  'User Added',
     297                  'User "%s" has been created.' % userid
     298              )
     299              audit('UI.User.Add', username=userid, roles=roles)  # don't send password
     300              return self.callZenScreen(REQUEST)
     301          else:
     302              return user
     303
     304
     305 -    def generatePassword(self):
     306          """ Generate a valid password.
     307          """
     308          # we don't use these to avoid typos: OQ0Il1
     309          chars = 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'
     310          return ''.join(choice(chars) for i in range(6))
     311
     312
     313 -    def authenticateCredentials(self, login, password):
     314          """
     315          Authenticates a given set of credentials against all configured
     316          authentication plugins. Returns True for successful authentication and
     317          False otherwise.
     318          """
     319          if login == 'admin':
     320              acl_users = self.getPhysicalRoot().acl_users
     321          else:
     322              acl_users = self.acl_users
     323
     324          try:
     325              authenticators = acl_users.plugins.listPlugins(
     326                  interfaces.plugins.IAuthenticationPlugin)
     327          except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
     328              authenticators = ()
     329
     330          # try each authenticator until a non-None user_id is returned
     331          for authenticator_id, auth in authenticators:
     332              try:
     333                  uid_and_info = auth.authenticateCredentials(
     334                      {'login':login, 'password':password})
     335
     336                  if isinstance(uid_and_info, tuple):
     337                      # make sure tuple has enough values to unpack
     338                      user_id, info = (uid_and_info + (None,None))[:2]
     339
     340                      # return if authentication was a success
     341                      if user_id is not None:
     342                          return True
     343
     344              except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
     345                  pass
     346
     347          # indicate no successful authentications
     348          return False
     349
     350
     351      security.declareProtected(ZEN_MANAGE_DMD, 'manage_changeUser')
     352 -    def manage_changeUser(self, userid, password=None, sndpassword=None,
     353                            roles=None, domains=None, REQUEST=None, **kw):
     354          """Change a zenoss users settings.
     355          """
     356          user = self.acl_users.getUser(userid)
     357          if not user:
     358              if REQUEST:
     359                  messaging.IMessageSender(self).sendToBrowser(
     360                      'Error',
     361                      'User "%s" was not found.' % userid,
     362                      priority=messaging.WARNING
     363                  )
     364                  return self.callZenScreen(REQUEST)
     365              else:
     366                  return
     367          if password and password != sndpassword:
     368              if REQUEST:
     369                  messaging.IMessageSender(self).sendToBrowser(
     370                      'Error',
     371                      "Passwords didn't match. No change.",
     372                      priority=messaging.WARNING
     373                  )
     374                  return self.callZenScreen(REQUEST)
     375              else:
     376                  raise ValueError("passwords don't match")
     377          if REQUEST:
     378              # TODO: Record all the non-password values.
     379              #updates = dict((k,v) for k,v in kw.items() if 'password' not in k.lower())
     380              updates = {}
     381              if password: updates['password'] = '****'
     382              if roles: updates['roles': roles]
     383              if domains: updates['domains': domains]
     384          if password is None: password = user._getPassword()
     385          if roles is None: roles = user.roles
     386          if domains is None: domains = user.domains
     387          self.acl_users._doChangeUser(userid,password,roles,domains)
     388          self.acl_users.ZCacheable_invalidate()
     389          ufolder = self.getUserSettings(userid)
     390          ufolder.updatePropsFromDict(kw)
     391          if REQUEST:
     392              messaging.IMessageSender(self).sendToBrowser(
     393                  'Settings Saved',
     394                  Time.SaveMessage()
     395              )
     396              audit('UI.User.Edit', username=userid, data_=updates)
     397              return self.callZenScreen(REQUEST)
     398          else:
     399              return user
     400
     401
     402      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteUsers')
     403 -    def manage_deleteUsers(self, userids=(), REQUEST=None):
     404          """Delete a list of zenoss users from the system.
     405          """
     406          # get a list of plugins that can add manage users and then call the
     407          # appropriate methods
     408          #
     409          # XXX this needs to be reviewed when new plugins are added, such as the
     410          # LDAP plugin
     411          if 'admin' in userids:
     412              messaging.IMessageSender(self).sendToBrowser(
     413                  'Error',
     414                  "Cannot delete admin user. No users were deleted.",
     415                  messaging.WARNING
     416              )
     417              return self.callZenScreen(REQUEST)
     418
     419          ifaces = [interfaces.plugins.IUserAdderPlugin]
     420          getPlugins = self.acl_users.plugins.listPlugins
     421          plugins = [ getPlugins(x)[0][1] for x in ifaces ]
     422          for userid in userids:
     423              try:
     424                  for plugin in plugins:
     425                      plugin.removeUser(userid)
     426                  self.acl_users.ZCacheable_invalidate()
     427              except KeyError:
     428                  # this means that there's no user in the acl_users, but that
     429                  # Zenoss still sees the user; we want to pass on this exception
     430                  # so that Zenoss can clean up
     431                  pass
     432              if getattr(aq_base(self), userid, False):
     433                  us = self._getOb(userid)
     434                  us.removeAdminRoles()
     435                  for ar in us.adminRoles():
     436                      ar.userSetting.removeRelation()
     437                      mobj = ar.managedObject().primaryAq()
     438                      mobj.adminRoles._delObject(ar.id)
     439                  self._delObject(userid)
     440
     441          if REQUEST:
     442              messaging.IMessageSender(self).sendToBrowser(
     443                  'Users Deleted',
     444                  "Users were deleted: %s." % (', '.join(userids))
     445              )
     446              for userid in userids:
     447                  audit('UI.User.Delete', username=userid)
     448              return self.callZenScreen(REQUEST)
     449
     450
     451      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addGroup')
     452 -    def manage_addGroup(self, groupid, REQUEST=None):
     453          """Add a zenoss group to the system and set its default properties.
     454          """
     455          if not groupid: return
     456          groupid = prepId(groupid)
     457          try:
     458              self.acl_users.groupManager.addGroup(groupid)
     459              self.acl_users.ZCacheable_invalidate()
     460          except KeyError: pass
     461          self.getGroupSettings(groupid)
     462          if REQUEST:
     463              messaging.IMessageSender(self).sendToBrowser(
     464                  'Group Added',
     465                  'Group "%s" has been created.' % groupid
     466              )
     467              audit('UI.Group.Add', groupid)
     468              return self.callZenScreen(REQUEST)
     469
     470
     471      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteGroups')
     472 -    def manage_deleteGroups(self, groupids=(), REQUEST=None):
     473          """ Delete a zenoss group from the system
     474          """
     475          gm = self.acl_users.groupManager
     476          if isinstance(groupids, basestring):
     477              groupids = [groupids]
     478          for groupid in groupids:
     479              if self._getOb(groupid):
     480                  group = self._getOb(groupid)
     481                  group.removeAdminRoles()
     482                  self._delObject(groupid)
     483              try:
     484                  gm.removeGroup(groupid)
     485                  self.acl_users.ZCacheable_invalidate()
     486              except KeyError: pass
     487          if REQUEST:
     488              messaging.IMessageSender(self).sendToBrowser(
     489                  'Groups Deleted',
     490                  "Groups were deleted: %s." % (', '.join(groupids))
     491              )
     492              for groupid in groupids:
     493                  audit('UI.Group.Delete', groupid)
     494              return self.callZenScreen(REQUEST)
     495
     496
     497      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addUsersToGroups')
     498 -    def manage_addUsersToGroups(self, userids=(), groupids=(), REQUEST=None):
     499          """ Add users to a group
     500          """
     501          if isinstance(userids, basestring):
     502              userids = [userids]
     503          if isinstance(groupids, basestring):
     504              groupids = [groupids]
     505          for groupid in groupids:
     506              self._getOb(groupid).manage_addUsersToGroup(userids)
     507          if REQUEST:
     508              if not groupids:
     509                  messaging.IMessageSender(self).sendToBrowser(
     510                      'Error',
     511                      'No groups were selected.',
     512                      priority=messaging.WARNING
     513                  )
     514              else:
     515                  messaging.IMessageSender(self).sendToBrowser(
     516                      'Groups Modified',
     517                      'Users %s were added to group %s.' % (
     518                          ', '.join(userids), ', '.join(groupids))
     519                  )
     520              for userid in userids:
     521                  for groupid in groupids:
     522                      audit('UI.User.AddToGroup', username=userid, group=groupid)
     523              return self.callZenScreen(REQUEST)
     524
     525
     526      security.declareProtected(ZEN_MANAGE_DMD, 'manage_emailTestAdmin')
     527 -    def manage_emailTestAdmin(self, userid, REQUEST=None):
     528          ''' Do email test for given user
     529          '''
     530          userSettings = self.getUserSettings(userid)
     531          msg = userSettings.manage_emailTest()
     532          if msg:
     533              messaging.IMessageSender(self).sendToBrowser('Email Test', msg)
     534          if REQUEST:
     535              return self.callZenScreen(REQUEST)
     536
     537
     538      security.declareProtected(ZEN_MANAGE_DMD, 'manage_pagerTestAdmin')
     539 -    def manage_pagerTestAdmin(self, userid, REQUEST=None):
     540          ''' Do pager test for given user
     541          '''
     542          userSettings = self.getUserSettings(userid)
     543          msg = userSettings.manage_pagerTest()
     544          if msg:
     545              messaging.IMessageSender(self).sendToBrowser('Pager Test', msg)
     546          if REQUEST:
     547              return self.callZenScreen(REQUEST)
     548
     549
     550 -    def cleanUserFolders(self):
     551          """Delete orphaned user folders.
     552          """
     553          userfolders = self._getOb(UserSettingsId)
     554          userids = self.acl_users.getUserNames()
     555          for fid in userfolders.objectIds():
     556              if fid not in userids:
     557                  userfolders._delObject(fid)
     558          self.acl_users.ZCacheable_invalidate()
     559
     560
     561 -    def getAllRoles(self):
     562          """Get list of all roles without Anonymous and Authenticated.
     563          """
     564          return filter(rolefilter, self.valid_roles())
     565
     566
     567 -    def exportXmlHook(self,ofile, ignorerels):
     568          map(lambda x: x.exportXml(ofile, ignorerels), self.getAllUserSettings())
     569
     570
     571
     572 -def manage_addUserSettings(context, id, title = None, REQUEST = None):
     573      """make a device class"""
     574      dc = UserSettings(id, title)
     575      context._setObject(id, dc)
     576      if REQUEST:
     577          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     578
     579
     580  addUserSettings = DTMLFile('dtml/addUserSettings',globals())
     581
     582
     583 -class UserSettings(ZenModelRM):
     584      """zenoss user folder has users preferences.
     585      """
     586      implements(IProvidesEmailAddresses, IProvidesPagerAddresses, IGloballyIdentifiable)
     587
     588      meta_type = "UserSettings"
     589
     590      sub_meta_types = ("ActionRule",)
     591
     592      email = ""
     593      pager = ""
     594      defaultPageSize = 40
     595      defaultEventPageSize = 30
     596      defaultAdminRole = "ZenUser"
     597      oncallStart = 0
     598      oncallEnd = 0
     599      escalationMinutes = 0
     600      dashboardState = ''
     601      netMapStartObject = ''
     602      eventConsoleRefresh = True
     603      zenossNetUser = ''
     604      zenossNetPassword = ''
     605
     606      _properties = ZenModelRM._properties + (
     607          {'id':'email', 'type':'string', 'mode':'w'},
     608          {'id':'pager', 'type':'string', 'mode':'w'},
     609          {'id':'defaultPageSize', 'type':'int', 'mode':'w'},
     610          {'id':'defaultEventPageSize', 'type':'int', 'mode':'w'},
     611          {'id':'defaultAdminRole', 'type':'string', 'mode':'w'},
     612          {'id':'oncallStart', 'type':'int', 'mode':'w'},
     613          {'id':'oncallEnd', 'type':'int', 'mode':'w'},
     614          {'id':'escalationMinutes', 'type':'int', 'mode':'w'},
     615          {'id':'dashboardState', 'type':'string', 'mode':'w'},
     616          {'id':'netMapStartObject', 'type':'string', 'mode':'w'},
     617          {'id':'eventConsoleRefresh', 'type':'boolean', 'mode':'w'},
     618          {'id':'zenossNetUser', 'type':'string', 'mode':'w'},
     619          {'id':'zenossNetPassword', 'type':'string', 'mode':'w'},
     620      )
     621
     622
     623      _relations =  (
     624          ("adminRoles", ToMany(ToOne, "Products.ZenModel.AdministrativeRole",
     625                                "userSetting")),
     626          ("messages", ToManyCont(ToOne,
     627              "Products.ZenWidgets.PersistentMessage.PersistentMessage",
     628              "messageQueue")),
     629      )
     630
     631      # Screen action bindings (and tab definitions)
     632      factory_type_information = (
     633          {
     634              'immediate_view' : 'editUserSettings',
     635              'actions'        :
     636              (
     637                  {'name'         : 'Edit',
     638                  'action'        : 'editUserSettings',
     639                  'permissions'   : (ZEN_CHANGE_SETTINGS,),
     640                  },
     641                  {'name'         : 'Administered Objects',
     642                  'action'        : 'administeredDevices',
     643                  'permissions'   : (ZEN_CHANGE_ADMIN_OBJECTS,)
     644                  },
     645              )
     646           },
     647          )
     648
     649      security = ClassSecurityInfo()
     650
     651 -    def hasNoGlobalRoles(self):
     652          """This user doesn't have global roles. Used to limit access
     653          """
     654          return self.id != 'admin' and len(self.getUserRoles()) == 0
     655
     656 -    def getUserRoles(self):
     657          """Get current roles for this user.
     658          """
     659          user = self.getUser(self.id)
     660          if user:
     661              # This call will create GroupSettings objects for any externally-
     662              # sourced groups.
     663              self.getAllAdminRoles()
     664              return filter(rolefilter, user.getRoles())
     665          return []
     666
     667 -    def getUserRolesNoCache(self):
     668          """
     669          This is used by the UI to make sure that we are always looking at the
     670          latest version of the roles for this user.
     671          """
     672          # make sure we are always getting the most up-to-date roles
     673          self.acl_users.ZCacheable_invalidate()
     674
     675          return self.getUserRoles()
     676
     677 -    def getUserGroupSettingsNames(self):
     678          """Return group settings objects for user
     679          """
     680          user = self.getUser(self.id)
     681          if user:
     682              return self.acl_users._getGroupsForPrincipal(user)
     683          return ()
     684
     685
     686      security.declareProtected(ZEN_CHANGE_SETTINGS, 'updatePropsFromDict')
     687 -    def updatePropsFromDict(self, propdict):
     688          props = self.propertyIds()
     689          for k, v in propdict.items():
     690              if k in props: setattr(self,k,v)
     691
     692
     693 -    def iseditable(self):
     694          """Can the current user edit this settings object.
     695          """
     696          currentUser = getSecurityManager().getUser()
     697
     698          # Managers can edit any users' settings.
     699          if currentUser.has_role("Manager"):
     700              return True
     701
     702          # thisUser can be None if the plugin that created it is inactive.
     703          thisUser = self.acl_users.getUser(self.id)
     704          if thisUser is None:
     705              return False
     706
     707          # ZenManagers can edit any users' settings except for Managers.
     708          if currentUser.has_role("ZenManager") \
     709              and not thisUser.has_role("Manager"):
     710              return True
     711
     712          # Users can edit their own settings.
     713          if thisUser.getUserName() == currentUser.getUserName():
     714              return True
     715
     716          return False
     717
     718      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_resetPassword')
     719 -    def manage_resetPassword(self):
     720          """
     721          Reset a password.
     722          """
     723          email = self.email.strip()
     724          if not email:
     725              messaging.IMessageSender(self).sendToBrowser(
     726                  'Password Reset Failed',
     727                  'Cannot send password reset email; user has no'+
     728                  ' email address.',
     729                  priority=messaging.WARNING
     730              )
     731              return self.callZenScreen(self.REQUEST)
     732
     733          newpw = self.generatePassword()
     734          body = """
     735          Your Zenoss password has been reset at %s's request.
     736
     737          Your new password is: %s
     738          """ % (self.getUser().getId(), newpw)
     739          msg = MIMEText(body)
     740          msg['Subject'] = 'Zenoss Password Reset Request'
     741          msg['From'] = self.dmd.getEmailFrom()
     742          msg['To'] = email
     743          msg['Date'] = DateTime().rfc822()
     744          result, errorMsg = Utils.sendEmail(msg, self.dmd.smtpHost,
     745                              self.dmd.smtpPort,
     746                              self.dmd.smtpUseTLS, self.dmd.smtpUser,
     747                              self.dmd.smtpPass)
     748          if result:
     749              userManager = self.acl_users.userManager
     750              try:
     751                  userManager.updateUserPassword(self.id, newpw)
     752              except KeyError:
     753                  self.getPhysicalRoot().acl_users.userManager.updateUserPassword(
     754                                  self.id, newpw)
     755              messaging.IMessageSender(self).sendToBrowser(
     756                  'Password reset',
     757                  'An email with a new password has been sent.'
     758              )
     759              audit('UI.User.ResetPassword', username=self.id)
     760              loggedInUser = self.REQUEST['AUTHENTICATED_USER']
     761              # we only want to log out the user if it's *their* password
     762              # they've changed, not, for example, if the admin user is
     763              # changing another user's password
     764              if loggedInUser.getUserName() == self.id:
     765                  self.acl_users.logout(self.REQUEST)
     766          else:
     767              messaging.IMessageSender(self).sendToBrowser(
     768                  'Password reset failed',
     769                  'Unable to send password reset email: %s' % errorMsg,
     770                  priority=messaging.WARNING
     771              )
     772          return self.callZenScreen(self.REQUEST)
     773
     774
     775      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_editUserSettings')
     776 -    def manage_editUserSettings(self, oldpassword=None, password=None,
     777                                  sndpassword=None, roles=None, groups=None,
     778                                  domains=None, REQUEST=None, **kw):
     779          """Update user settings.
     780          """
     781          # get the user object; return if no user
     782          user = self.acl_users.getUser(self.id)
     783          if not user:
     784              user = self.getPhysicalRoot().acl_users.getUser(self.id)
     785          if not user:
     786              if REQUEST:
     787                  messaging.IMessageSender(self).sendToBrowser(
     788                      'Error',
     789                      'User %s not found.' % self.id,
     790                      priority=messaging.WARNING
     791                  )
     792                  return self.callZenScreen(REQUEST)
     793              else:
     794                  return
     795
     796          # Verify existing password
     797          curuser = self.getUser().getId()
     798          if not oldpassword or not self.ZenUsers.authenticateCredentials(
     799              curuser, oldpassword):
     800              if REQUEST:
     801                  messaging.IMessageSender(self).sendToBrowser(
     802                      'Error',
     803                      'Confirmation password is empty or invalid. Please'+
     804                      ' confirm your password for security reasons.',
     805                      priority=messaging.WARNING
     806                  )
     807                  return self.callZenScreen(REQUEST)
     808              else:
     809                  raise ValueError("Current password is incorrect.")
     810
     811          # update role info
     812          roleManager = self.acl_users.roleManager
     813          origRoles = filter(rolefilter, user.getRoles())
     814
     815          if not self.has_role('Manager') and roles and 'Manager' in roles:
     816              if REQUEST:
     817                  messaging.IMessageSender(self).sendToBrowser(
     818                      'Error',
     819                      'Only Managers can make more Managers.',
     820                      priority=messaging.WARNING
     821                  )
     822                  return self.callZenScreen(REQUEST)
     823              else:
     824                  return
     825
     826          if not self.has_role('Manager') and origRoles and \
     827              'Manager' in origRoles:
     828
     829              if REQUEST:
     830                  messaging.IMessageSender(self).sendToBrowser(
     831                      'Error',
     832                      'Only Managers can modify other Managers.',
     833                      priority=messaging.WARNING
     834                  )
     835                  return self.callZenScreen(REQUEST)
     836              else:
     837                  return
     838
     839          # if there's a change, then we need to update
     840          # TODO: Record all the non-password values.
     841          #updates = dict((k,v) for k,v in kw.items() if 'password' not in k.lower())
     842          updates = {}
     843
     844          # update user roles
     845          if roles is None:
     846              roles = ()
     847          origRolesSet = set(origRoles)
     848          rolesSet = set(roles)
     849          if rolesSet != origRolesSet and self.isManager():
     850              # get roles to remove and then remove them
     851              removeRoles = origRolesSet - rolesSet
     852              for role in removeRoles:
     853                  try:
     854                      roleManager.removeRoleFromPrincipal(role, self.id)
     855                  except KeyError:
     856                      # User doesn't actually have that role; ignore
     857                      pass
     858              # get roles to add and then add them
     859              addRoles = rolesSet - origRolesSet
     860              for role in addRoles:
     861                  roleManager.assignRoleToPrincipal(role, self.id)
     862              updates['roles'] = roles
     863
     864          # update group info
     865          if groups is None:
     866              groups = ()
     867          groupManager = self.acl_users.groupManager
     868          origGroupsSet = set(groupManager.getGroupsForPrincipal(user))
     869          groupsSet = set(groups)
     870          # if there's a change, then we need to update
     871          if groupsSet != origGroupsSet and self.isManager():
     872              # get groups to remove and then remove them
     873              removeGroups = origGroupsSet - groupsSet
     874              for groupid in removeGroups:
     875                  groupManager.removePrincipalFromGroup(user.getId(), groupid)
     876              # get groups to add and then add them
     877              addGroups = groupsSet - origGroupsSet
     878              for groupid in addGroups:
     879                  try:
     880                      groupManager.addPrincipalToGroup(user.getId(), groupid)
     881                  except KeyError:
     882                      # This can occur if the group came from an external source.
     883                      pass
     884              updates['groups'] = groups
     885
     886          # we're not managing domains right now
     887          if domains:
     888              msg = 'Zenoss does not currently manage domains for users.'
     889              raise NotImplementedError(msg)
     890
     891          # update Zenoss user folder settings
     892          if REQUEST:
     893              kw = REQUEST.form
     894          self.manage_changeProperties(**kw)
     895
     896          # update password info
     897          if self.id=='admin':
     898              userManager = self.getPhysicalRoot().acl_users.userManager
     899          else:
     900              userManager = self.acl_users.userManager
     901          if password:
     902              if password.find(':') >= 0:
     903                  if REQUEST:
     904                      messaging.IMessageSender(self).sendToBrowser(
     905                          'Error',
     906                          'Passwords cannot contain a ":". Password not updated.',
     907                          priority=messaging.WARNING
     908                      )
     909                      return self.callZenScreen(REQUEST)
     910                  else:
     911                      raise ValueError("Passwords cannot contain a ':' ")
     912              elif password != sndpassword:
     913                  if REQUEST:
     914                      messaging.IMessageSender(self).sendToBrowser(
     915                          'Error',
     916                          'Passwords did not match. Password not updated.',
     917                          priority=messaging.WARNING
     918                      )
     919                      return self.callZenScreen(REQUEST)
     920                  else:
     921                      raise ValueError("Passwords don't match")
     922              else:
     923                  try:
     924                      userManager.updateUserPassword(self.id, password)
     925                      updates['password'] = '****'
     926                  except KeyError:
     927                      self.getPhysicalRoot().acl_users.userManager.updateUserPassword(
     928                                      self.id, password)
     929                  if REQUEST:
     930                      loggedInUser = REQUEST['AUTHENTICATED_USER']
     931                      # we only want to log out the user if it's *their* password
     932                      # they've changed, not, for example, if the admin user is
     933                      # changing another user's password
     934                      if loggedInUser.getUserName() == self.id:
     935                          self.acl_users.logout(REQUEST)
     936
     937          self.acl_users.ZCacheable_invalidate()
     938
     939          # finish up
     940          if REQUEST:
     941              messaging.IMessageSender(self).sendToBrowser(
     942                  'Settings Saved',
     943                  Time.SaveMessage()
     944              )
     945              audit('UI.User.Edit', username=self.id, data_=updates)
     946              return self.callZenScreen(REQUEST)
     947          else:
     948              return user
     949
     950      security.declareProtected(ZEN_CHANGE_ALERTING_RULES, 'manage_addActionRule')
     951      @deprecated
     952 -    def manage_addActionRule(self, id=None, REQUEST=None):
     953          """Add an action rule to this object.
     954          """
     955          if id:
     956              ar = ActionRule(id)
     957              self._setObject(id, ar)
     958              ar = self._getOb(id)
     959              user = getSecurityManager().getUser()   # current user
     960              userid = user.getId()
     961              if userid != self.id:            # if we are not the current user
     962                  userid = self.id
     963                  user = self.getUser(userid)
     964                  ar.changeOwnership(user)     # make us the owner of it
     965                  ar.manage_setLocalRoles(userid, ("Owner",))
     966          if REQUEST:
     967              return self.callZenScreen(REQUEST)
     968
     969 -    def getActionRules(self):
     970          return self.objectValues(spec=ActionRule.meta_type)
     971
     972      security.declareProtected(ZEN_CHANGE_EVENT_VIEWS,
     973          'manage_addCustomEventView')
     974      @deprecated
     975 -    def manage_addCustomEventView(self, id=None, REQUEST=None):
     976          """Add a custom event view to this object.
     977          """
     978          if id:
     979              ar = CustomEventView(id)
     980              self._setObject(id, ar)
     981              ar = self._getOb(id)
     982              user = getSecurityManager().getUser()
     983              userid = user.getId()
     984              if userid != self.id:
     985                  userid = self.id
     986                  user = self.getUser(userid)
     987                  ar.changeOwnership(user)
     988                  ar.manage_setLocalRoles(userid, ("Owner",))
     989          if REQUEST:
     990              return self.callZenScreen(REQUEST)
     991
     992
     993      security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
     994          'manage_addAdministrativeRole')
     995 -    def manage_addAdministrativeRole(self, name=None, type='device', role=None,
     996                                       guid=None, uid=None, REQUEST=None):
     997          "Add a Admin Role to the passed object"
     998          unused(role)
     999          mobj = None
    1000          if guid or uid:
    1001              # look up our object by either guid or uid
    1002              if guid:
    1003                  manager = IGUIDManager(self.dmd)
    1004                  mobj = manager.getObject(guid)
    1005              elif uid:
    1006                  mobj = self.unrestrictedTraverse(uid)
    1007          else:
    1008              # use magic to look up our object
    1009              if not name:
    1010                  name = REQUEST.deviceName
    1011              if type == 'device':
    1012                  mobj =self.getDmdRoot("Devices").findDevice(name)
    1013              else:
    1014                  try:
    1015                      root = type.capitalize()+'s'
    1016                      if type == "deviceClass":
    1017                          mobj = self.getDmdRoot("Devices").getOrganizer(name)
    1018                      else:
    1019                          mobj = self.getDmdRoot(root).getOrganizer(name)
    1020                  except KeyError: pass
    1021          if not mobj:
    1022              if REQUEST:
    1023                  messaging.IMessageSender(self).sendToBrowser(
    1024                      'Error',
    1025                      "%s %s not found"%(type.capitalize(),name),
    1026                      priority=messaging.WARNING
    1027                  )
    1028                  return self.callZenScreen(REQUEST)
    1029              else: return
    1030          roleNames = [ r.id for r in mobj.adminRoles() ]
    1031          if self.id in roleNames:
    1032              if REQUEST:
    1033                  messaging.IMessageSender(self).sendToBrowser(
    1034                      'Error',
    1035                      (("Administrative Role for %s %s "
    1036                       "for user %s already exists.") % (type, name, self.id)),
    1037                      priority=messaging.WARNING
    1038                  )
    1039                  return self.callZenScreen(REQUEST)
    1040              else: return
    1041          mobj.manage_addAdministrativeRole(self.id)
    1042          if REQUEST:
    1043              messaging.IMessageSender(self).sendToBrowser(
    1044                  'Role Added',
    1045                  ("Administrative Role for %s %s for user %s added" %
    1046                      (type, name, self.id))
    1047              )
    1048              audit('UI.User.AddAdministrativeRole', username=self.id,
    1049                    data_={mobj.meta_type:mobj.getPrimaryId()})
    1050              return self.callZenScreen(REQUEST)
    1051
    1052
    1053      security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
    1054          'manage_editAdministrativeRoles')
    1055 -    def manage_editAdministrativeRoles(self, ids=(), role=(), REQUEST=None):
    1056          """Edit list of admin roles.
    1057          """
    1058          if isinstance(ids, basestring):
    1059              ids = [ids]
    1060              role = [role]
    1061          else:
    1062              ids = list(ids)
    1063          for ar in self.adminRoles():
    1064              mobj = ar.managedObject()
    1065              try: i = ids.index(mobj.managedObjectName())
    1066              except ValueError: continue
    1067              mobj = mobj.primaryAq()
    1068              mobj.manage_editAdministrativeRoles(self.id, role[i])
    1069              if REQUEST:
    1070                  audit('UI.User.EditAdministrativeRole', username=self.id,
    1071                        data_={mobj.meta_type:mobj.getPrimaryId()},
    1072                        role=role[i])
    1073          if REQUEST:
    1074              if ids:
    1075                  messaging.IMessageSender(self).sendToBrowser(
    1076                      'Roles Updated',
    1077                      "Administrative roles were updated."
    1078                  )
    1079              return self.callZenScreen(REQUEST)
    1080
    1081
    1082      security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
    1083          'manage_deleteAdministrativeRole')
    1084 -    def manage_deleteAdministrativeRole(self, delids=(), REQUEST=None):
    1085          "Delete admin roles of objects."
    1086          if isinstance(delids, basestring):
    1087              delids = [delids]
    1088          for ar in self.adminRoles():
    1089              mobj = ar.managedObject()
    1090              if mobj.managedObjectName() not in delids: continue
    1091              mobj = mobj.primaryAq()
    1092              mobj.manage_deleteAdministrativeRole(self.id)
    1093              if REQUEST:
    1094                  audit('UI.User.DeleteAdministrativeRole', username=self.id,
    1095                        data_={mobj.meta_type:mobj.getPrimaryId()})
    1096          if REQUEST:
    1097              if delids:
    1098                  messaging.IMessageSender(self).sendToBrowser(
    1099                      'Roles Deleted',
    1100                      "Administrative roles were deleted."
    1101                  )
    1102              return self.callZenScreen(REQUEST)
    1103
    1104
    1105      security.declareProtected(ZEN_CHANGE_SETTINGS, 'getAllAdminRoles')
    1106 -    def getAllAdminRoles(self):
    1107          """Return all admin roles for this user and its groups
    1108          """
    1109          ars = self.adminRoles()
    1110          for group in self.getUser().getGroups():
    1111              gs = self.getGroupSettings(group)
    1112              ars.extend(gs.adminRoles())
    1113          return ars
    1114
    1115
    1116      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_emailTest')
    1117 -    def manage_emailTest(self, REQUEST=None):
    1118          ''' Send a test email to the given userid.
    1119          '''
    1120          destSettings = self.getUserSettings(self.getId())
    1121          destAddresses = destSettings.getEmailAddresses()
    1122          msg = None
    1123          if destAddresses:
    1124              fqdn = socket.getfqdn()
    1125              thisUser = self.getUser()
    1126              srcId = thisUser.getId()
    1127              self.getUserSettings(srcId)
    1128              srcAddress = self.dmd.getEmailFrom()
    1129              # Read body from file probably
    1130              body = ('This is a test message sent by %s' % srcId +
    1131                      ' from the Zenoss installation on %s.' % fqdn)
    1132              emsg = MIMEText(body)
    1133              emsg['Subject'] = 'Zenoss Email Test'
    1134              emsg['From'] = srcAddress
    1135              emsg['To'] = ', '.join(destAddresses)
    1136              emsg['Date'] = DateTime().rfc822()
    1137              result, errorMsg = Utils.sendEmail(emsg, self.dmd.smtpHost,
    1138                                  self.dmd.smtpPort,
    1139                                  self.dmd.smtpUseTLS, self.dmd.smtpUser,
    1140                                  self.dmd.smtpPass)
    1141              if result:
    1142                  msg = 'Test email sent to %s' % ', '.join(destAddresses)
    1143              else:
    1144                  msg = 'Test failed: %s' % errorMsg
    1145          else:
    1146              msg = 'Test email not sent, user has no email address.'
    1147          if REQUEST:
    1148              messaging.IMessageSender(self).sendToBrowser(
    1149                  'Email Test',
    1150                  msg.replace("'", "\\'")
    1151              )
    1152              return self.callZenScreen(REQUEST)
    1153          else:
    1154              return msg
    1155
    1156
    1157      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_pagerTest')
    1158 -    def manage_pagerTest(self, REQUEST=None):
    1159          ''' Send a test page
    1160          '''
    1161          destSettings = self.getUserSettings(self.getId())
    1162          destPagers = [ x.strip() for x in
    1163              (destSettings.getPagerAddresses() or []) ]
    1164          msg = None
    1165          fqdn = socket.getfqdn()
    1166          srcId = self.getUser().getId()
    1167          testMsg = ('Test sent by %s' % srcId +
    1168                  ' from the Zenoss installation on %s.' % fqdn)
    1169          for destPager in destPagers:
    1170              result, errorMsg = Utils.sendPage(destPager, testMsg,
    1171                                      self.dmd.pageCommand)
    1172              if result:
    1173                  msg = 'Test page sent to %s' % ', '.join(destPagers)
    1174              else:
    1175                  msg = 'Test failed: %s' % errorMsg
    1176                  break
    1177          if not destPagers:
    1178              msg = 'Test page not sent, user has no pager number.'
    1179          if REQUEST:
    1180              messaging.IMessageSender(self).sendToBrowser(
    1181                  'Pager Test', msg)
    1182              return self.callZenScreen(REQUEST)
    1183          else:
    1184              return msg
    1185
    1186 -    def exportXmlHook(self, ofile, ignorerels):
    1187          """patch to export all user configuration
    1188          """
    1189          for o in self.objectValues():
    1190              if hasattr(aq_base(o), 'exportXml'):
    1191                  o.exportXml(ofile, ignorerels)
    1192
    1193 -    def getPagerAddresses(self):
    1194          if self.pager.strip():
    1195              return [self.pager.strip()]
    1196          return []
    1197
    1198 -    def getEmailAddresses(self):
    1199          if self.email.strip():
    1200              return [self.email]
    1201          return []
    1202
    1203 -    def isLoggedInUser(self):
    1204          loggedinUser = self.ZenUsers.getUserSettings()
    1205          return loggedinUser.id == self.id
    1206
    1207 -    def getDotNetSession(self):
    1208          """
    1209          Use the Zenoss.net credentials associated with this user to log in to a
    1210          Zenoss.net session.
    1211          """
    1212          session = DotNetCommunication.getDotNetSession(
    1213                                          self.zenossNetUser,
    1214                                          self.zenossNetPassword)
    1215          return session
    1216
    1217 -    def removeAdminRoles(self):
    1218          """
    1219          Call before deleting a user or group this will
    1220          remove this user/group from the list of admin objects for
    1221          everything that the object adminstered before. This
    1222          prevents broken relationships
    1223          """
    1224          for role in self.getAllAdminRoles():
    1225              obj = role.managedObject().primaryAq()
    1226              obj.manage_deleteAdministrativeRole(self.id)
    1227
    1228 -class GroupSettings(UserSettings):
    1229      implements(IProvidesEmailAddresses, IProvidesPagerAddresses)
    1230      meta_type = 'GroupSettings'
    1231
    1232      factory_type_information = (
    1233          {
    1234              'immediate_view' : 'editGroupSettings',
    1235              'actions'        :
    1236              (
    1237                  {'name'         : 'Edit',
    1238                  'action'        : 'editGroupSettings',
    1239                  'permissions'   : (ZEN_CHANGE_SETTINGS,),
    1240                  },
    1241                  {'name'         : 'Administered Objects',
    1242                  'action'        : 'administeredDevices',
    1243                  'permissions'   : (ZEN_CHANGE_ADMIN_OBJECTS,)
    1244                  },
    1245              )
    1246           },
    1247          )
    1248
    1249      security = ClassSecurityInfo()
    1250
    1251 -    def iseditable(self):
    1252          """Can the current user edit this settings object.
    1253          """
    1254          currentUser = getSecurityManager().getUser()
    1255          return currentUser.has_role("Manager") or currentUser.has_role("ZenManager")
    1256
    1257 -    def _getG(self):
    1258          return self.zport.acl_users.groupManager
    1259
    1260
    1261 -    def hasNoGlobalRoles(self):
    1262          """This is a group we never have roles. This is set to false so that
    1263          fuctionality that would normally be taken away for a restricted user is
    1264          left in.
    1265          """
    1266          return False
    1267
    1268
    1269      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addUsersToGroup')
    1270 -    def manage_addUsersToGroup( self, userids, REQUEST=None ):
    1271          """ Add user to this group
    1272          """
    1273          if isinstance(userids, basestring):
    1274              userids = [userids]
    1275          for userid in userids:
    1276              self._getG().addPrincipalToGroup( userid, self.id )
    1277              if REQUEST:
    1278                  audit('UI.User.AddToGroup', username=userid, group=self.id)
    1279          if REQUEST:
    1280              messaging.IMessageSender(self).sendToBrowser(
    1281                  'Users Added',
    1282                  'Added %s to Group %s' % (','.join(userids), self.id)
    1283              )
    1284              return self.callZenScreen(REQUEST)
    1285
    1286      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteUserFromGroup')
    1287 -    def manage_deleteUserFromGroup( self, userid ):
    1288          self._getG().removePrincipalFromGroup( userid, self.id )
    1289
    1290      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteUsersFromGroup')
    1291 -    def manage_deleteUsersFromGroup(self, userids=(), REQUEST=None ):
    1292          """ Delete users from this group
    1293          """
    1294          for userid in userids:
    1295              self.manage_deleteUserFromGroup(userid)
    1296              if REQUEST:
    1297                  audit('UI.User.RemoveFromGroup', username=userid, group=self.id)
    1298          if REQUEST:
    1299              messaging.IMessageSender(self).sendToBrowser(
    1300                  'Users Removed',
    1301                  'Deleted users from Group %s' % self.id
    1302              )
    1303              return self.callZenScreen(REQUEST)
    1304
    1305 -    def getMemberUserSettings(self):
    1306          """
    1307          Returns a list of UserSetting instances that are members of this group.
    1308          """
    1309          members = set()
    1310          # We must using reverse mapping of all users to their groups rather
    1311          # than going directly to the group's assigned principals because
    1312          # some group backends don't support listAssignedPrincipals.
    1313          [ members.add(u) for u in self.ZenUsers.getAllUserSettings()
    1314              if self.id in u.getUserGroupSettingsNames() ]
    1315
    1316          # make sure we get everyone assigned directly to this group (incase they appear in
    1317          # another acl_users as is the case with admin)
    1318          [ members.add(self.getUserSettings(u[0]))
    1319            for u in self._getG().listAssignedPrincipals(self.id) ]
    1320          return members
    1321
    1322 -    def getMemberUserIds(self):
    1323          """
    1324          Returns a list of user ids that are members of this group.
    1325          """
    1326          return [ u.id for u in self.getMemberUserSettings() ]
    1327
    1328 -    def printUsers(self):
    1329          try:
    1330              userIds = self.getMemberUserIds()
    1331          except LocalAndLDAPUserEntries, ex:
    1332              return str(ex)
    1333
    1334          return ", ".join(userIds)
    1335
    1336 -    def getEmailAddresses(self):
    1337          try:
    1338              userIds = self.getMemberUserIds()
    1339          except LocalAndLDAPUserEntries, ex:
    1340              return []
    1341
    1342          result = []
    1343          for username in userIds:
    1344              result.extend(self.getUserSettings(username).getEmailAddresses())
    1345          return result
    1346
    1347 -    def getPagerAddresses(self):
    1348          try:
    1349              userIds = self.getMemberUserIds()
    1350          except LocalAndLDAPUserEntries, ex:
    1351              return []
    1352
    1353          result = []
    1354          for username in userIds:
    1355              result.extend(self.getUserSettings(username).getPagerAddresses())
    1356          return result
    1357
    1358
    1359  InitializeClass(UserSettingsManager)
    1360  InitializeClass(UserSettings)
    1361