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

# Source Code for Module Products.ZenModel.ZentinelPortal

      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  """ Portal class
     14
     15  $Id: ZentinelPortal.py,v 1.17 2004/04/08 15:35:25 edahl Exp $
     16  """
     17
     18  import urllib, urlparse
     19  import re
     20
     21  import Globals
     22
     23  from zExceptions import Redirect
     24  from AccessControl import getSecurityManager, ClassSecurityInfo
     25
     26  from Products.Sessions.BrowserIdManager import constructBrowserIdManager
     27  from Products.Sessions.SessionDataManager import constructSessionDataManager
     28
     29  from Products.CMFCore.PortalObject import PortalObjectBase
     30  from Products.CMFCore.utils import getToolByName
     31
     32  from Products.ZenUtils import Security, Time
     33  from Products.ZenUtils.Utils import prepId
     34
     35  from ZenossSecurity import *
     36
     37  from Products.AdvancedQuery import MatchGlob, Eq, Or
     38
     39 -class ZentinelPortal ( PortalObjectBase ):
     40      """
     41      The *only* function this class should have is to help in the setup
     42      of a new ZentinelPortal. It should not assist in the functionality at all.
     43      """
     44      meta_type = 'ZentinelPortal'
     45
     46      _properties = (
     47          {'id':'title', 'type':'string'},
     48          {'id':'description', 'type':'text'},
     49          )
     50      title = ''
     51      description = ''
     52
     53      security = ClassSecurityInfo()
     54
     55 -    def __init__( self, id, title='' ):
     56          PortalObjectBase.__init__( self, id, title )
     57
     58 -    def server_time(self):
     59          return Time.isoDateTime()
     60
     61 -    def _additionalQuery(self):
     62          return None
     63
     64      security.declareProtected(ZEN_COMMON, 'searchDevices')
     65 -    def searchDevices(self, queryString='', REQUEST=None):
     66          """Returns the concatenation of a device name, ip and mac
     67          search on the list of devices.
     68          """
     69          zcatalog = self.dmd.Devices.deviceSearch
     70          glob = queryString.rstrip('*') + '*'
     71          idGlob = MatchGlob('id', glob)
     72          titleGlob = MatchGlob('titleOrId', glob)
     73          idOrTitleQuery = Or(idGlob,titleGlob)
     74          query = Or(idOrTitleQuery, Eq('getDeviceIp', queryString))
     75          additionalQuery = self._additionalQuery()
     76          if additionalQuery:
     77              query = And( query, additionalQuery )
     78          brains = zcatalog.evalAdvancedQuery(query)
     79          if REQUEST and len(brains) == 1:
     80              raise Redirect(urllib.quote(brains[0].getPrimaryId))
     81          if additionalQuery:
     82              idGlob = And( idGlob, additionalQuery )
     83          brains += self.dmd.Networks.ipSearch.evalAdvancedQuery(idGlob)
     84          return [ b.getObject() for b in brains ]
     85
     86      security.declareProtected(ZEN_COMMON, 'searchComponents')
     87 -    def searchComponents(self, device='', component='', REQUEST=None):
     88          """
     89          Redirect to the component of a device. Hopefully.
     90          """
     91          catalog = self.dmd.Devices.componentSearch
     92          brains = []
     93          if device and component:
     94              brains = catalog(getParentDeviceName=device)
     95          matchingBrains = []
     96          if brains:
     97              component = prepId(component)
     98              for brain in brains:
     99                  if brain.getPath().split('/')[-1]==component:
    100                      if REQUEST:
    101                          raise Redirect(urllib.quote(
    102                              brain.getPath()+'/viewEvents'))
    103                      else:
    104                          matchingBrains.append(brain)
    105              if REQUEST and len(matchingBrains) == 0:
    106                  return self.searchDevices(device, REQUEST)
    107          return [b.getObject() for b in matchingBrains]
    108
    109      security.declareProtected(ZEN_COMMON, 'dotNetProxy')
    110 -    def dotNetProxy(self, path='', params={}, REQUEST=None):
    111          """
    112          Logs in to Zenoss.net using the user's credentials and retrieves data,
    113          thereby putting it in the current domain
    114          """
    115          session = self.dmd.ZenUsers.getUserSettings().getDotNetSession()
    116          response = session.open(path.lstrip('/'))
    117          if response:
    118              data = response.read()
    119              headers = response.headers.dict
    120              url = response.geturl()
    121              response.close()
    122          else:
    123              return response
    124          localbase = 'http://localhost:8080/zport/dotNetProxy?path='
    125          allrefs = re.compile(r"""(href *= *["']|src *= *["'])(.*?)(["'])""")
    126          proxyrefs = re.compile(
    127              r"""((<a[^<>]*?|location\.)href *= *["'])(.*?)(['"])""")
    128
    129          def mod_rewrite(matchobj):
    130              start, path, end = matchobj.groups()
    131              if not path.startswith('javascript'):
    132                  path = urlparse.urljoin(url, path)
    133              return start + path + end
    134
    135          def make_proxied(matchobj):
    136              start, trash, path, end = matchobj.groups()
    137              path = path.replace(session.base_url, localbase)
    138              return start + path + end
    139
    140          data = re.sub(allrefs, mod_rewrite, data)
    141          data = re.sub(proxyrefs, make_proxied, data)
    142          for header in headers:
    143              REQUEST.RESPONSE.setHeader(header, headers[header])
    144          return data
    145
    146 -    def isManager(self, obj=None):
    147          """
    148          Return true if user is authenticated and has Manager role.
    149          """
    150          user = self.dmd.ZenUsers.getUser()
    151          if user:
    152              return user.has_role((MANAGER_ROLE, ZEN_MANAGER_ROLE), obj)
    153
    154
    155 -    def has_role(self, role, obj=None):
    156          """Check to see of a user has a role.
    157          """
    158          if obj is None: obj = self
    159          user = getSecurityManager().getUser()
    160          if user: return user.has_role(role, obj)
    161
    162
    163 -    def has_permission(self, perm, obj=None):
    164          """Check to see of a user has a permission.
    165          """
    166          if obj is None: obj = self
    167          user = getSecurityManager().getUser()
    168          if user: return user.has_permission(perm, obj)
    169
    170 -    def getZenossVersionShort(self):
    171          return self.About.getZenossVersionShort()
    172
    173 -    def getExtraLoginFormContents(self):
    174          """
    175          On first run, log us in as admin automatically.
    176
    177          This is done via a proxy form with hidden fields, so that the browser
    178          doesn't ask to save the password (which will be changed on the next
    179          screen).
    180          """
    181          if not self.dmd._rq:
    182              return """
    183              <form id="_proxy_form">
    184              <input type="hidden" name="__ac_name"/>
    185              <input type="hidden" name="__ac_password"/>
    186              </form>
    187              <script>
    188              var origform=document.forms[0];
    189              var newform = document.getElementById('_proxy_form');
    190              newform.__ac_name.value = 'admin';
    191              newform.__ac_password.value = 'zenoss';
    192              newform.action = origform.action;
    193              newform.method = origform.method;
    194              newform.submit()
    195              </script>
    196              """
    197
    198
    199  Globals.InitializeClass(ZentinelPortal)
    200
    201
    202 -class PortalGenerator:
    203
    204      klass = ZentinelPortal
    205
    206 -    def setupTools(self, p):
    207          """Set up initial tools"""
    208          addCMFCoreTool = p.manage_addProduct['CMFCore'].manage_addTool
    209          addCMFCoreTool('CMF Skins Tool', None)
    210
    211
    212 -    def setupMailHost(self, p):
    213          p.manage_addProduct['MailHost'].manage_addMailHost(
    214              'MailHost', smtp_host='localhost')
    215
    216
    217 -    def setupUserFolder(self, p):
    218          #p.manage_addProduct['OFSP'].manage_addUserFolder()
    219          Security.createPASFolder(p)
    220          Security.setupPASFolder(p)
    221
    222
    223 -    def setupCookieAuth(self, p):
    224          # XXX PAS is handling this now, right?
    225          #p.manage_addProduct['CMFCore'].manage_addCC(
    226          #    id='cookie_authentication')
    227          pass
    228
    229
    230 -    def setupRoles(self, p):
    231          # Set up the suggested roles.
    232          p.__ac_roles__ += (ZEN_USER_ROLE, ZEN_MANAGER_ROLE,)
    233
    234
    235 -    def setupPermissions(self, p):
    236          # Set up some suggested role to permission mappings.
    237          mp = p.manage_permission
    238          mp(ZEN_CHANGE_SETTINGS,[ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    239          mp(ZEN_CHANGE_DEVICE, [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    240          mp(ZEN_CHANGE_DEVICE_PRODSTATE,
    241              [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    242          mp(ZEN_MANAGE_DMD, [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    243          mp(ZEN_DELETE, [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    244          mp(ZEN_ADD, [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    245          mp(ZEN_VIEW, [ZEN_USER_ROLE, ZEN_MANAGER_ROLE,
    246                          MANAGER_ROLE, OWNER_ROLE])
    247          mp(ZEN_COMMON, ["Authenticated", ZEN_USER_ROLE, ZEN_MANAGER_ROLE,
    248                          MANAGER_ROLE, OWNER_ROLE], 1)
    249
    250          # Events
    251          mp(ZEN_MANAGE_EVENTMANAGER,
    252              [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    253          mp(ZEN_MANAGE_EVENTS,
    254              [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    255          mp(ZEN_SEND_EVENTS,
    256              [ZEN_MANAGER_ROLE, OWNER_ROLE, MANAGER_ROLE,], 1)
    257
    258          mp(ZEN_CHANGE_ALERTING_RULES,
    259              [ZEN_MANAGER_ROLE, MANAGER_ROLE, OWNER_ROLE], 1)
    260          mp(ZEN_CHANGE_ADMIN_OBJECTS, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    261          mp(ZEN_CHANGE_EVENT_VIEWS, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    262          mp(ZEN_ADMIN_DEVICE, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    263          mp(ZEN_MANAGE_DEVICE, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    264          mp(ZEN_ZPROPERTIES_EDIT, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    265          mp(ZEN_ZPROPERTIES_VIEW,
    266              [ZEN_MANAGER_ROLE, MANAGER_ROLE, ZEN_USER_ROLE], 1)
    267          mp(ZEN_EDIT_LOCAL_TEMPLATES, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    268          mp(ZEN_RUN_COMMANDS, [ZEN_USER_ROLE, ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    269          mp(ZEN_DEFINE_COMMANDS_EDIT, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    270          mp(ZEN_DEFINE_COMMANDS_VIEW,
    271              [ZEN_MANAGER_ROLE, MANAGER_ROLE, ZEN_USER_ROLE], 1)
    272          mp(ZEN_MAINTENANCE_WINDOW_EDIT, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    273          mp(ZEN_MAINTENANCE_WINDOW_VIEW,
    274              [ZEN_MANAGER_ROLE, MANAGER_ROLE, ZEN_USER_ROLE], 1)
    275          mp(ZEN_ADMINISTRATORS_EDIT, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    276          mp(ZEN_ADMINISTRATORS_VIEW,
    277              [ZEN_MANAGER_ROLE, MANAGER_ROLE, ZEN_USER_ROLE], 1)
    278          #mp(ZEN_EDIT_USER, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    279          #mp(ZEN_EDIT_USERGROUP, [ZEN_MANAGER_ROLE, MANAGER_ROLE], 1)
    280
    281 -    def setupDefaultSkins(self, p):
    282          from Products.CMFCore.DirectoryView import addDirectoryViews
    283          ps = getToolByName(p, 'portal_skins')
    284          addDirectoryViews(ps, 'skins', globals())
    285          ps.manage_addProduct['OFSP'].manage_addFolder(id='custom')
    286          ps.addSkinSelection('Basic', "custom, zenmodel", make_default=1)
    287          p.setupCurrentSkin()
    288
    289
    290 -    def setupSessionManager(self, p):
    291          """build a session manager and brower id manager for zport"""
    292          constructBrowserIdManager(p, cookiepath="/zport")
    293          constructSessionDataManager(p, "session_data_manager",
    294                      title="Session Data Manager",
    295                      path='/temp_folder/session_data')
    296
    297
    298 -    def setup(self, p, create_userfolder):
    299          if create_userfolder:
    300              self.setupUserFolder(p)
    301          #self.setupCookieAuth(p)
    302          self.setupTools(p)
    303          self.setupMailHost(p)
    304          self.setupRoles(p)
    305          self.setupPermissions(p)
    306          self.setupDefaultSkins(p)
    307          self.setupSessionManager(p)
    308
    309
    310 -    def create(self, parent, id, create_userfolder):
    311          id = str(id)
    312          portal = self.klass(id=id)
    313          parent._setObject(id, portal)
    314          # Return the fully wrapped object.
    315          p = parent.this()._getOb(id)
    316          self.setup(p, create_userfolder)
    317          return p
    318
    319
    320 -    def setupDefaultProperties(self, p, title, description,
    321                                 email_from_address, email_from_name,
    322                                 validate_email,
    323                                 ):
    324          p._setProperty('email_from_address', email_from_address, 'string')
    325          p._setProperty('email_from_name', email_from_name, 'string')
    326          p._setProperty('validate_email', validate_email and 1 or 0, 'boolean')
    327          p.title = title
    328          p.description = description
    329
    330
    331  manage_addZentinelPortal = Globals.HTMLFile('dtml/addPortal', globals())
    332  manage_addZentinelPortal.__name__ = 'addPortal'
    333
    334 -def manage_addZentinelPortal(obj, id="zport", title='Zentinel Portal',
    335                           description='',
    336                           create_userfolder=True,
    337                           email_from_address='postmaster@localhost',
    338                           email_from_name='Portal Administrator',
    339                           validate_email=0, RESPONSE=None):
    340      '''
    341      Adds a portal instance.
    342      '''
    343      gen = PortalGenerator()
    344      from string import strip
    345      id = strip(id)
    346      p = gen.create(obj, id, create_userfolder)
    347      gen.setupDefaultProperties(p, title, description,
    348                                 email_from_address, email_from_name,
    349                                 validate_email)
    350      if RESPONSE is not None:
    351          RESPONSE.redirect(obj.absolute_url()+'/manage_main')
    352