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

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