ERP5UserFactory.py 9.09 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights
# Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this
# distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Classes: ERP5User, ERP5UserFactory
"""

18
from Products.ERP5Type.Globals import InitializeClass
19 20 21
from Acquisition import aq_inner, aq_parent
from AccessControl import ClassSecurityInfo
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
22
from App.config import getConfiguration
23 24 25 26 27 28
from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin
from Products.PluggableAuthService.utils import classImplements
from Products.PluggableAuthService.interfaces.plugins import IUserFactoryPlugin
from Products.PluggableAuthService.PropertiedUser import PropertiedUser
from Products.PluggableAuthService.PropertiedUser import \
                                            _what_not_even_god_should_do
29
from Products import ERP5Security
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

manage_addERP5UserFactoryForm = PageTemplateFile(
    'www/ERP5Security_addERP5UserFactory', globals(),
    __name__='manage_addERP5UserFactoryForm' )

def addERP5UserFactory( dispatcher, id, title=None, REQUEST=None ):
  """ Add a ERP5UserFactory to a Pluggable Auth Service. """

  euf = ERP5UserFactory(id, title)
  dispatcher._setObject(euf.getId(), euf)

  if REQUEST is not None:
    REQUEST['RESPONSE'].redirect( '%s/manage_workspace'
                                  '?manage_tabs_message='
                                  'ERP5UserFactory+added.'
                                     % dispatcher.absolute_url())


class ERP5User(PropertiedUser):
  """ User class that checks the object allows acquisition of local roles the
  ERP5Type way.
  """
52 53
  _user_path = None
  _login_path = None
54 55 56 57 58 59 60 61 62 63 64 65

  def getRolesInContext( self, object ):
    """ Return the list of roles assigned to the user.
    For ERP5, we check if a _getAcquireLocalRoles is defined on the object.
    """
    user_id = self.getId()
    # [ x.getId() for x in self.getGroups() ]
    group_ids = self.getGroups()

    principal_ids = list( group_ids )
    principal_ids.insert( 0, user_id )

66
    local = {}
67 68 69 70 71 72 73 74 75 76 77 78
    object = aq_inner( object )

    while 1:
      local_roles = getattr( object, '__ac_local_roles__', None )
      if local_roles:
        if callable( local_roles ):
          local_roles = local_roles()

        dict = local_roles or {}
        for principal_id in principal_ids:
          for role in dict.get( principal_id, [] ):
            local[ role ] = 1
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
      # patch by Klaus for LocalRole blocking
      if getattr(object, '_getAcquireLocalRoles', None) is not None:
        if not object._getAcquireLocalRoles():
          break

      inner = aq_inner( object )
      parent = aq_parent( inner )

      if parent is not None:
        object = parent
        continue

      new = getattr( object, 'im_self', None )
      if new is not None:
        object = aq_inner( new )
        continue
      break
97

98 99
    # Patched: Developer role should not never be available as local role
    local.pop('Developer', None)
100 101 102
    return list( self.getRoles() ) + local.keys()

  def allowed( self, object, object_roles=None ):
103 104 105 106
    """ Check whether the user has access to object.
    As for getRolesInContext, we take into account _getAcquireLocalRoles for
    ERP5.
    """
107
    if self.getUserName() == ERP5Security.SUPER_USER:
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
      # super user is allowed to accesss any object
      return 1

    if object_roles is _what_not_even_god_should_do:
      return 0

    # Short-circuit the common case of anonymous access.
    if object_roles is None or 'Anonymous' in object_roles:
      return 1

    # Check for Developer Role, see patches.User for rationale
    # XXX-arnau: copy/paste
    object_roles = set(object_roles)
    if 'Developer' in object_roles:
      object_roles.remove('Developer')
      product_config = getattr(getConfiguration(), 'product_config', None)
      if product_config:
        config = product_config.get('erp5')
        if config and self.getId() in config.developer_list:
          return 1
128

129 130 131 132 133 134 135 136 137 138 139
    # Provide short-cut access if object is protected by 'Authenticated'
    # role and user is not nobody
    if 'Authenticated' in object_roles and (
      self.getUserName() != 'Anonymous User'):
      return 1

    # Check for ancient role data up front, convert if found.
    # This should almost never happen, and should probably be
    # deprecated at some point.
    if 'Shared' in object_roles:
      object_roles = self._shared_roles(object)
140 141 142
      if object_roles is None or 'Anonymous' in object_roles:
        return 1

143 144 145 146 147 148 149
    # Check for a role match with the normal roles given to
    # the user, then with local roles only if necessary. We
    # want to avoid as much overhead as possible.
    user_roles = self.getRoles()
    for role in object_roles:
      if role in user_roles:
        if self._check_context(object):
150
          return 1
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        return None

    # Still have not found a match, so check local roles. We do
    # this manually rather than call getRolesInContext so that
    # we can incur only the overhead required to find a match.
    inner_obj = aq_inner( object )
    user_id = self.getId()
    # [ x.getId() for x in self.getGroups() ]
    group_ids = self.getGroups()

    principal_ids = list( group_ids )
    principal_ids.insert( 0, user_id )

    while 1:
      local_roles = getattr( inner_obj, '__ac_local_roles__', None )
      if local_roles:
        if callable( local_roles ):
          local_roles = local_roles()

        dict = local_roles or {}
        for principal_id in principal_ids:
          local_roles = dict.get( principal_id, [] )
          for role in object_roles:
            if role in local_roles:
              if self._check_context( object ):
                return 1
              return 0

      # patch by Klaus for LocalRole blocking
      if getattr(inner_obj, '_getAcquireLocalRoles', None) is not None:
        if not inner_obj._getAcquireLocalRoles():
          break

      inner = aq_inner( inner_obj )
      parent = aq_parent( inner )

      if parent is not None:
        inner_obj = parent
        continue

      new = getattr( inner_obj, 'im_self', None )

      if new is not None:
        inner_obj = aq_inner( new )
        continue
      break
197

198
    return None
199

200 201 202 203 204
  def getUserValue(self):
    """ -> user document

    Return the document (ex: Person) corresponding to current user.
    """
205
    result = self._user_path
206
    if result is not None:
207
      return self.getPortalObject().restrictedTraverse(result)
208 209 210
    # user id may match in more than one PAS plugin, but fail if more than one
    # underlying path is found.
    user_path_set = {x['path'] for x in self.aq_parent.searchUsers(
211 212
      exact_match=True,
      id=self.getId(),
213 214 215 216
    ) if 'path' in x}
    if user_path_set:
      user_path, = user_path_set
      self._user_path = user_path
217
      return self.getPortalObject().restrictedTraverse(user_path)
218 219 220 221 222 223

  def getLoginValue(self):
    """ -> login document

    Return the document (ex: ERP5 Login) corresponding to current user's login.
    """
224
    result = self._login_path
225
    if result is not None:
226
      return self.getPortalObject().restrictedTraverse(result)
227
    # user name may match at most once, or there can be endless ambiguity.
228 229 230 231 232 233 234
    user_list = [x for x in self.aq_parent.searchUsers(
      exact_match=True,
      login=self.getUserName(),
    ) if 'login_list' in x]
    if user_list:
      user, = user_list
      login, = user['login_list']
235
      result = self._login_path = login['path']
236
      return self.getPortalObject().restrictedTraverse(result)
237 238 239 240 241 242

  def getLoginValueList(self, portal_type=None, limit=None):
    """ -> list of login documents

    Return the list of login documents belonging to current user.
    """
243 244 245 246 247 248 249 250 251 252 253
    # Aggregate all login paths.
    user_path_set = {
      login['path']
      for user in self.aq_parent.searchUsers(
        exact_match=True,
        id=self.getId(),
        login_portal_type=portal_type,
        max_results=limit,
      ) if 'login_list' in user
      for login in user['login_list']
    }
254 255
    restrictedTraverse = self.getPortalObject().restrictedTraverse
    return [restrictedTraverse(x) for x in user_path_set]
256

257 258 259 260 261 262 263 264 265 266 267 268 269 270
InitializeClass(ERP5User)


class ERP5UserFactory(BasePlugin):
  """ PAS plugin for creating users that understand local roles blocking based
  on type information's acquire_local_roles
  """
  meta_type = 'ERP5 User Factory'
  security = ClassSecurityInfo()

  def __init__(self, id, title=None):
    self._id = self.id = id
    self.title = title

271
  security.declarePrivate('createUser')
272 273 274 275 276 277 278 279 280 281 282
  def createUser( self, user_id, name ):
    """ See IUserFactoryPlugin
    """
    return ERP5User(user_id, name)


classImplements( ERP5UserFactory
               , IUserFactoryPlugin
               )

InitializeClass(ERP5UserFactory)