Ticket #5370: ldap_user_filter.patch

File ldap_user_filter.patch, 2.4 KB (added by Sebastian Hugentobler, 9 years ago)
  • mediagoblin/plugins/ldap/tools.py

    From 52b3c07356f0c9cedfbd5d9445d8ec55e828549c Mon Sep 17 00:00:00 2001
    From: Sebastian Hugentobler <shugentobler@vanwa.ch>
    Date: Mon, 7 Dec 2015 13:00:27 +0100
    Subject: [PATCH 1/1] Adds the possibility to filter ldap users at login (eg.
     with groups). Set the *LDAP_USER_FILTER* to use this.
    
    ---
     mediagoblin/plugins/ldap/tools.py | 36 +++++++++++++++++++++++++++++++++++-
     1 file changed, 35 insertions(+), 1 deletion(-)
    
    diff --git a/mediagoblin/plugins/ldap/tools.py b/mediagoblin/plugins/ldap/tools.py
    index 2be2dcd..858b47a 100644
    a b class LDAP(object):  
    4848
    4949        return email
    5050
     51    def is_user_allowed(self, config, username):
     52        """ Apply a configured user filter.
     53
     54        If an user filter is configured apply it and check whether there is
     55        exactly one result.
     56
     57        Do nothing if there is no filter.
     58
     59        Args:
     60            config (dict of str: str): The mediagoblin config dictionary.
     61            username (string): Username to use (replaces '{username}' in the filter).
     62        Returns:
     63            bool: True if the filter yields ecactly one result or if there is
     64                  no filter configured, False otherwise.
     65        """
     66        user_allowed = True
     67        use_user_filter = (config['LDAP_USER_FILTER'] is not None
     68            if 'LDAP_USER_FILTER' in config else False)
     69
     70        if use_user_filter:
     71            _log.info('Applying user filter')
     72
     73            user_filter_result = self.conn.search_s(
     74                config['LDAP_SEARCH_BASE'],
     75                ldap.SCOPE_SUBTREE,
     76                config['LDAP_USER_FILTER'].format(username=username))
     77
     78            user_allowed = len(user_filter_result) == 1
     79
     80        return user_allowed
     81
    5182    def login(self, username, password):
    5283        for k, v in six.iteritems(self.ldap_settings):
    5384            try:
    class LDAP(object):  
    5586                user_dn = v['LDAP_USER_DN_TEMPLATE'].format(username=username)
    5687                self.conn.simple_bind_s(user_dn, password.encode('utf8'))
    5788                email = self._get_email(v, username)
    58                 return username, email
     89
     90                user_allowed = self.is_user_allowed(v, username)
     91
     92                return (username, email) if user_allowed else (False, None)
    5993
    6094            except ldap.LDAPError, e:
    6195                _log.info(e)