Source

trac-apacheuserinfo-plugin / ApacheUserInfo.py

Full commit
"""
Apache User Info plugin

Enable it in trac.ini:

  [components]
  apacheuserinfo.* = enabled

  [apacheuserinfo]
  email_override = true
  email_var = AUTHENTICATE_MAIL
  name_override = true
  name_var = AUTHENTICATE_DISPLAYNAME

The attributes used for mapping must be present in AuthLDAPURL:

  ldap://host:port/basedn?sAMAccountName,displayName,mail?scope?filter
"""


from trac.core import *
from trac.web.api import IRequestFilter


class ApacheUserInfo(Component):

    implements(IRequestFilter)

    def __init__(self):

        cfg = self.config
        self.email_override = cfg.getbool('apacheuserinfo', 'email_override')
        self.email_var = cfg.get('apacheuserinfo', 'email_var')
        self.name_override = cfg.getbool('apacheuserinfo', 'name_override')
        self.name_var = cfg.get('apacheuserinfo', 'name_var')

        dbg = self.log.debug
        dbg('email_override: ' + repr(self.email_override))
        dbg('email_var: ' + repr(self.email_var))
        dbg('name_override : ' + repr(self.name_override))
        dbg('name_var : ' + repr(self.name_var))

        if self.name_var or self.email_var:
            self.enabled = True
            self.log.info('Apache User Info plugin loaded')
        else:
            self.enabled = False
            self.log.info('Apache User Info plugin is not configured')

    # IRequestFilter method
    def pre_process_request(self, req, handler):

        if req.path_info != '/login' or not self.enabled:
            return handler

        self._update(req, 'user name',
                     self.name_override, self.name_var, 'name')
        self._update(req, 'email address',
                     self.email_override, self.email_var, 'email')

        return handler

    # IRequestFilter method
    def post_process_request(self, req, template, data, content_type):
        return template, data, content_type

    def _update(self, req, target, override, apachekey, sessionkey):

        if not apachekey:
            self.log.debug('Skipping %s check', target)
            return

        if apachekey not in req.environ.keys():
            self.log.debug('Missing Apache variable: %s' % repr(apachekey))
            return

        value = req.environ[apachekey].strip()
        self.log.debug('Apache provided %s: %s' % (target, value))

        if (value
            and (override or not sessionkey in req.session.keys())):
            req.session[sessionkey] = value
            self.log.info('The %s was set to: %s' % (target, value))