ERP5ExternalAuthenticationPlugin.py 8.1 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-
##############################################################################
#
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
4
# Copyright (c) 2010 Nexedi SA and Contributors. All Rights Reserved.
5 6
#
# WARNING: This program as such is intended to be used by professional
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
7
# programmers who take the whole responsibility of assessing all potential
8 9
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
10
# guarantees and support are strongly adviced to contract a Free Software
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
# 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
49 50 51
manage_addERP5ExternalAuthenticationPluginForm = PageTemplateFile(
  'www/ERP5Security_addERP5ExternalAuthenticationPlugin', globals(),
  __name__='manage_addERP5ExternalAuthenticationPluginForm')
52

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

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
57
  plugin = ERP5ExternalAuthenticationPlugin(id, title, user_id_key)
58 59 60 61 62 63
  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
64
          'ERP5ExternalAuthenticationPlugin+added.'
65 66
          % dispatcher.absolute_url())

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

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

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

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

92 93 94 95 96 97 98 99 100 101 102 103 104
  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 = {}
105
    user_id = request.getHeader(self.user_id_key)
106
    if user_id is not None:
107
      creds['external_login'] = user_id
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

    #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')
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
123
  def authenticateCredentials(self, credentials):
124
    """Authentificate with credentials"""
125
    login = credentials.get('external_login', None)
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 161 162 163 164 165 166 167 168 169 170 171
    # 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
172
      id='ERP5ExternalAuthenticationPlugin_authenticateCredentials',
173 174 175 176 177 178 179
      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
180
      LOG('ERP5ExternalAuthenticationPlugin.authenticateCredentials', PROBLEM, str(e))
181 182 183 184 185 186 187
      return None

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

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

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
193
  security.declareProtected(ManageUsers, 'manage_editERP5ExternalAuthenticationPlugin')
194
  def manage_editERP5ExternalAuthenticationPlugin(self, user_id_key, RESPONSE=None):
195 196 197 198 199 200 201 202 203 204 205 206 207
    """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
208
        return self.manage_editERP5ExternalAuthenticationPluginForm(RESPONSE)
209 210
      else:
        message = "Updated"
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
211
        RESPONSE.redirect('%s/manage_editERP5ExternalAuthenticationPluginForm'
212
                          '?manage_tabs_message=%s'
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
213
                          % (self.absolute_url(), message)
214 215 216
                          )

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

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