ERP5ExternalAuthenticationPlugin.py 8.18 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Francois-Xavier Algrain <fxalgrain@tiolive.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################

from DateTime import DateTime
from zLOG import LOG, PROBLEM
from Products.ERP5Type.Globals import InitializeClass
from AccessControl import ClassSecurityInfo
from AccessControl.SecurityManagement import getSecurityManager,\
                                             newSecurityManager,\
                                             setSecurityManager

from Products.PageTemplates.PageTemplateFile import PageTemplateFile

from Products.PluggableAuthService.interfaces import plugins
from Products.PluggableAuthService.utils import classImplements
from Products.PluggableAuthService.permissions import ManageUsers
from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin

from Products.ERP5Type.Cache import CachingMethod
from Products.ERP5Security.ERP5UserManager import ERP5UserManager,\
     SUPER_USER, _AuthenticationFailure

#Form for new plugin in ZMI
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
50 51 52
manage_addERP5ExternalAuthenticationPluginForm = PageTemplateFile(
  'www/ERP5Security_addERP5ExternalAuthenticationPlugin', globals(),
  __name__='manage_addERP5ExternalAuthenticationPluginForm')
53

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
54
def addERP5ExternalAuthenticationPlugin(dispatcher, id, title=None, user_id_key='',
55
                              REQUEST=None):
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
56
  """ Add a ERP5ExternalAuthenticationPlugin to a Pluggable Auth Service. """
57

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
58
  plugin = ERP5ExternalAuthenticationPlugin( id, title, user_id_key)
59 60 61 62 63 64
  dispatcher._setObject(plugin.getId(), plugin)

  if REQUEST is not None:
      REQUEST['RESPONSE'].redirect(
          '%s/manage_workspace'
          '?manage_tabs_message='
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
65
          'ERP5ExternalAuthenticationPlugin+added.'
66 67
          % dispatcher.absolute_url())

68
class ERP5ExternalAuthenticationPlugin(ERP5UserManager):
69 70 71 72 73
  """
  External authentification PAS plugin which extracts the user id from HTTP
  request header, like REMOTE_USER, openAMid, etc.
  """

74
  meta_type = "ERP5 External Authentication Plugin"
75 76 77 78
  security = ClassSecurityInfo()
  user_id_key = ''

  manage_options = (({'label': 'Edit',
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
79
                      'action': 'manage_editERP5ExternalAuthenticationPluginForm',},
80 81 82 83
                     )
                    + BasePlugin.manage_options[:]
                    )

84 85 86 87 88 89 90 91 92
  _properties = (({'id':'user_id_key',
                   'type':'string',
                   'mode':'w',
                   'label':'HTTP request header key where the user_id is stored'
                   },
                  )
                 + BasePlugin._properties[:]
                 )

93 94 95 96 97 98 99 100 101 102 103 104 105
  def __init__(self, id, title=None, user_id_key=''):
    #Register value
    self._setId(id)
    self.title = title
    self.user_id_key = user_id_key

  ####################################
  #ILoginPasswordHostExtractionPlugin#
  ####################################
  security.declarePrivate('extractCredentials')
  def extractCredentials(self, request):
    """ Extract credentials from the request header. """
    creds = {}
106
    user_id = request.getHeader(self.user_id_key)
107
    if user_id is not None:
108
      creds['external_login'] = user_id
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

    #Complete credential with some informations
    if creds:
      creds['remote_host'] = request.get('REMOTE_HOST', '')
      try:
        creds['remote_address'] = request.getClientAddr()
      except AttributeError:
        creds['remote_address'] = request.get('REMOTE_ADDR', '')

    return creds

  ################################
  #     IAuthenticationPlugin    #
  ################################
  security.declarePrivate('authenticateCredentials')
  def authenticateCredentials( self, credentials ):
    """Authentificate with credentials"""
126
    login = credentials.get('external_login', None)
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 161 162 163 164 165 166 167 168 169 170 171 172
    # Forbidden the usage of the super user.
    if login == SUPER_USER:
      return None

    #Function to allow cache
    def _authenticateCredentials(login):
      if not login:
        return None

      #Search the user by his login
      user_list = self.getUserByLogin(login)
      if len(user_list) != 1:
        raise _AuthenticationFailure()
      user = user_list[0]

      #We need to be super_user
      sm = getSecurityManager()
      if sm.getUser().getId() != SUPER_USER:
        newSecurityManager(self, self.getUser(SUPER_USER))
        try:
          # get assignment list
          assignment_list = [x for x in user.objectValues(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)

          # validate
          if len(valid_assignment_list) > 0:
            return (login,login)
        finally:
          setSecurityManager(sm)

        raise _AuthenticationFailure()

    #Cache Method for best performance
    _authenticateCredentials = CachingMethod(
      _authenticateCredentials,
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
173
      id='ERP5ExternalAuthenticationPlugin_authenticateCredentials',
174 175 176 177 178 179 180
      cache_factory='erp5_content_short')
    try:
      return _authenticateCredentials(login=login)
    except _AuthenticationFailure:
      return None
    except StandardError,e:
      #Log standard error
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
181
      LOG('ERP5ExternalAuthenticationPlugin.authenticateCredentials', PROBLEM, str(e))
182 183 184 185 186 187 188
      return None

  ################################
  # Properties for ZMI managment #
  ################################

  #'Edit' option form
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
189 190
  manage_editERP5ExternalAuthenticationPluginForm = PageTemplateFile(
      'www/ERP5Security_editERP5ExternalAuthenticationPlugin',
191
      globals(),
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
192
      __name__='manage_editERP5ExternalAuthenticationPluginForm' )
193

194 195
  security.declareProtected( ManageUsers, 'manage_editERP5ExternalAuthenticationPlugin' )
  def manage_editERP5ExternalAuthenticationPlugin(self, user_id_key, RESPONSE=None):
196 197 198 199 200 201 202 203 204 205 206 207 208
    """Edit the object"""
    error_message = ''

    #Save user_id_key
    if user_id_key == '' or user_id_key is None:
      error_message += 'Invalid key value '
    else:
      self.user_id_key = user_id_key

    #Redirect
    if RESPONSE is not None:
      if error_message != '':
        self.REQUEST.form['manage_tabs_message'] = error_message
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
209
        return self.manage_editERP5ExternalAuthenticationPluginForm(RESPONSE)
210 211
      else:
        message = "Updated"
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
212
        RESPONSE.redirect('%s/manage_editERP5ExternalAuthenticationPluginForm'
213 214 215 216 217
                          '?manage_tabs_message=%s'
                          % ( self.absolute_url(), message )
                          )

#List implementation of class
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
218
classImplements(ERP5ExternalAuthenticationPlugin,
219 220 221
                plugins.IAuthenticationPlugin,
                plugins.ILoginPasswordHostExtractionPlugin)

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
222
InitializeClass(ERP5ExternalAuthenticationPlugin)