ERP5UserManager.py 9.4 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
3 4
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights
# Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5
#
6 7 8 9 10 11 12
# 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.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
13 14 15 16 17
#
##############################################################################
""" Classes: ERP5UserManager
"""

18
from Products.ERP5Type.Globals import InitializeClass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
19
from AccessControl import ClassSecurityInfo
20
from AccessControl.AuthEncoding import pw_validate
Jean-Paul Smets's avatar
Jean-Paul Smets committed
21
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
Jérome Perrin's avatar
Jérome Perrin committed
22 23
from Products.PluggableAuthService.PluggableAuthService import \
    _SWALLOWABLE_PLUGIN_EXCEPTIONS
Jean-Paul Smets's avatar
Jean-Paul Smets committed
24 25 26 27
from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin
from Products.PluggableAuthService.utils import classImplements
from Products.PluggableAuthService.interfaces.plugins import IAuthenticationPlugin
from Products.PluggableAuthService.interfaces.plugins import IUserEnumerationPlugin
28
from Products.ERP5Type.Cache import CachingMethod, transactional_cached
29
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
30
from ZODB.POSException import ConflictError
Vincent Pelletier's avatar
Vincent Pelletier committed
31
import sys
32
from DateTime import DateTime
33
from zLOG import LOG, PROBLEM
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34

35 36 37
# This user is used to bypass all security checks.
SUPER_USER = '__erp5security-=__'

Jean-Paul Smets's avatar
Jean-Paul Smets committed
38
manage_addERP5UserManagerForm = PageTemplateFile(
39 40
  'www/ERP5Security_addERP5UserManager', globals(),
  __name__='manage_addERP5UserManagerForm' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
41 42

def addERP5UserManager(dispatcher, id, title=None, REQUEST=None):
43
  """ Add a ERP5UserManager to a Pluggable Auth Service. """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
44

45 46
  eum = ERP5UserManager(id, title)
  dispatcher._setObject(eum.getId(), eum)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
47

48 49 50 51 52 53
  if REQUEST is not None:
    REQUEST['RESPONSE'].redirect(
      '%s/manage_workspace'
      '?manage_tabs_message='
      'ERP5UserManager+added.'
      % dispatcher.absolute_url())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
54

55 56 57 58 59 60 61
class _AuthenticationFailure(Exception):
  """Raised when authentication failed, to prevent caching the fact that a user
  does not exist (yet), which happens when someone try to login before the user
  account is ready (like when the indexing not finished, an assignment not open
  etc...)
  """

62 63 64 65 66 67 68 69
@transactional_cached(lambda portal, *args: args)
def getUserByLogin(portal, login, exact_match=True):
  if isinstance(login, basestring):
    login = login,
  if exact_match:
    reference_key = 'ExactMatch'
  else:
    reference_key = 'Keyword'
70 71
  if not (portal.portal_catalog.hasColumn('portal_type') and portal.portal_catalog.hasColumn('reference')):
    raise RuntimeError('Catalog does not have column information. Make sure RDB is working and disk is not full.')
72
  result = portal.portal_catalog.unrestrictedSearchResults(
73 74 75
    select_expression='reference',
    portal_type="Person",
    reference=dict(query=login, key=reference_key))
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  # XXX: Here, we filter catalog result list ALTHOUGH we did pass
  # parameters to unrestrictedSearchResults to restrict result set.
  # This is done because the following values can match person with
  # reference "foo":
  # "foo " because of MySQL (feature, PADSPACE collation):
  #  mysql> SELECT reference as r FROM catalog
  #      -> WHERE reference="foo      ";
  #  +-----+
  #  | r   |
  #  +-----+
  #  | foo |
  #  +-----+
  #  1 row in set (0.01 sec)
  # "bar OR foo" because of ZSQLCatalog tokenizing searched strings
  #  by default (feature).
  return [x.getObject() for x in result if not exact_match
                                           or x['reference'] in login]

Łukasz Nowak's avatar
Łukasz Nowak committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
@transactional_cached(lambda portal, *args: args)
def getValidAssignmentList(user):
  """Returns list of valid assignments."""
  assignment_list = [x for x in user.contentValues(portal_type="Assignment") if x.getValidationState() == "open"]
  valid_assignment_list = []
  # check dates if exist
  login_date = DateTime()
  for assignment in assignment_list:
    if assignment.getStartDate() is not None and \
           assignment.getStartDate() > login_date:
      continue
    if assignment.getStopDate() is not None and \
           assignment.getStopDate() < login_date:
      continue
    valid_assignment_list.append(assignment)
  return valid_assignment_list
110

Jean-Paul Smets's avatar
Jean-Paul Smets committed
111
class ERP5UserManager(BasePlugin):
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  """ PAS plugin for managing users in ERP5
  """

  meta_type = 'ERP5 User Manager'

  security = ClassSecurityInfo()

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

  #
  #   IAuthenticationPlugin implementation
  #
  security.declarePrivate( 'authenticateCredentials' )
  def authenticateCredentials(self, credentials):
    """ See IAuthenticationPlugin.

    o We expect the credentials to be those returned by
      ILoginPasswordExtractionPlugin.
    """
    login = credentials.get('login')
    ignore_password = False
    if not login:
      # fallback to support plugins using external tools to extract login
      # those are not using login/password pair, they just extract login
      # from remote system (eg. SSL certificates)
      login = credentials.get('external_login')
      ignore_password = True
    # Forbidden the usage of the super user.
    if login == SUPER_USER:
      return None

    @UnrestrictedMethod
    def _authenticateCredentials(login, password, path,
      ignore_password=False):
      if not login or not (password or ignore_password):
        return None

      user_list = self.getUserByLogin(login)

      if not user_list:
        raise _AuthenticationFailure()

      user = user_list[0]

      try:

        if (ignore_password or pw_validate(user.getPassword(), password)) and \
Łukasz Nowak's avatar
Łukasz Nowak committed
161
            len(getValidAssignmentList(user)) and user  \
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
            .getValidationState() != 'deleted': #user.getCareerRole() == 'internal':
          return login, login # use same for user_id and login
      finally:
        pass
      raise _AuthenticationFailure()

    _authenticateCredentials = CachingMethod(
      _authenticateCredentials,
      id='ERP5UserManager_authenticateCredentials',
      cache_factory='erp5_content_short')
    try:
      authentication_result = _authenticateCredentials(
        login=login,
        password=credentials.get('password'),
        path=self.getPhysicalPath(),
        ignore_password=ignore_password)

    except _AuthenticationFailure:
      authentication_result = None

    if not self.getPortalObject().portal_preferences.isAuthenticationPolicyEnabled():
      # stop here, no authentication policy enabled
      # so just return authentication check result
      return authentication_result

    # authentication policy enabled, we need person object anyway
    user_list = self.getUserByLogin(credentials.get('login'))
    if not user_list:
      # not an ERP5 Person object
      return None
    user = user_list[0]

    if authentication_result is None:
      # file a failed authentication attempt
      user.notifyLoginFailure()
      return None

    # check if password is expired
    if user.isPasswordExpired():
      user.notifyPasswordExpire()
      return None

    # check if user account is blocked
    if user.isLoginBlocked():
      return None

    return authentication_result

  #
  #   IUserEnumerationPlugin implementation
  #
  security.declarePrivate( 'enumerateUsers' )
  def enumerateUsers(self, id=None, login=None, exact_match=False,
             sort_by=None, max_results=None, **kw):
    """ See IUserEnumerationPlugin.
    """
    if id is None:
      id = login
    if isinstance(id, str):
      id = (id,)
    if isinstance(id, list):
      id = tuple(id)

    user_info = []
    plugin_id = self.getId()

    id_list = []
    for user_id in id:
      if SUPER_USER == user_id:
231
        info = { 'id' : SUPER_USER
232 233
             , 'login' : SUPER_USER
             , 'pluginid' : plugin_id
234 235
        }
        user_info.append(info)
236
      else:
237
        id_list.append(user_id)
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

    if id_list:
      for user in self.getUserByLogin(tuple(id_list), exact_match=exact_match):
        info = { 'id' : user.getReference()
               , 'login' : user.getReference()
               , 'pluginid' : plugin_id
               }

        user_info.append(info)

    return tuple(user_info)

  def getUserByLogin(self, login, exact_match=True):
    # Search the Catalog for login and return a list of person objects
    # login can be a string or a list of strings
    # (no docstring to prevent publishing)
    if not login:
      return []
    if isinstance(login, list):
      login = tuple(login)
    elif not isinstance(login, tuple):
      login = str(login)
    try:
      return getUserByLogin(self.getPortalObject(), login, exact_match)
    except ConflictError:
      raise
    except:
      LOG('ERP5Security', PROBLEM, 'getUserByLogin failed', error=sys.exc_info())
      # Here we must raise an exception to prevent callers from caching
      # a result of a degraded situation.
      # The kind of exception does not matter as long as it's catched by
      # PAS and causes a lookup using another plugin or user folder.
      # As PAS does not define explicitely such exception, we must use
      # the _SWALLOWABLE_PLUGIN_EXCEPTIONS list.
      raise _SWALLOWABLE_PLUGIN_EXCEPTIONS[0]
273

274

Jean-Paul Smets's avatar
Jean-Paul Smets committed
275 276 277 278 279 280
classImplements( ERP5UserManager
               , IAuthenticationPlugin
               , IUserEnumerationPlugin
               )

InitializeClass(ERP5UserManager)