Changeset - f58ed40c9a72
[Not reviewed]
default
0 4 0
domruf - 9 years ago 2017-04-02 13:38:08
dominikruf@gmail.com
auth: refactor auth plugin importing

The list of authentication plugins, configured in the database, may contain
plugins which are no longer available. Therefore directly import the plugin in
get_auth_plugins and report the ImportError to the log instead of
breaking kallithea completely.

Patch modified by Mads Kiilerich.
4 files changed with 31 insertions and 35 deletions:
0 comments (0 inline, 0 general)
kallithea/controllers/admin/auth_settings.py
Show inline comments
 
@@ -56,26 +56,26 @@ class AuthSettingsController(BaseControl
 
            'kallithea.lib.auth_modules.auth_internal',
 
            'kallithea.lib.auth_modules.auth_container',
 
            'kallithea.lib.auth_modules.auth_ldap',
 
            'kallithea.lib.auth_modules.auth_crowd',
 
            'kallithea.lib.auth_modules.auth_pam'
 
        ]
 
        c.enabled_plugin_names = Setting.get_auth_plugins()
 
        self.enabled_plugins = auth_modules.get_auth_plugins()
 
        c.enabled_plugin_names = [plugin.__class__.__module__ for plugin in self.enabled_plugins]
 

	
 
    def __render(self, defaults, errors):
 
        c.defaults = {}
 
        c.plugin_settings = {}
 
        c.plugin_shortnames = {}
 

	
 
        for module in c.enabled_plugin_names:
 
            plugin = auth_modules.loadplugin(module)
 
            plugin_name = plugin.name
 
            c.plugin_shortnames[module] = plugin_name
 
        for plugin in self.enabled_plugins:
 
            module = plugin.__class__.__module__
 
            c.plugin_shortnames[module] = plugin.name
 
            c.plugin_settings[module] = plugin.plugin_settings()
 
            for v in c.plugin_settings[module]:
 
                fullname = "auth_%s_%s" % (plugin_name, v["name"])
 
                fullname = "auth_%s_%s" % (plugin.name, v["name"])
 
                if "default" in v:
 
                    c.defaults[fullname] = v["default"]
 
                # Current values will be the default on the form, if there are any
 
                setting = Setting.get_by_name(fullname)
 
                if setting is not None:
 
                    c.defaults[fullname] = setting.app_settings_value
kallithea/lib/auth_modules/__init__.py
Show inline comments
 
@@ -293,16 +293,16 @@ class KallitheaExternalAuthPlugin(Kallit
 
            groups = user_data['groups'] or []
 
            UserGroupModel().enforce_groups(user, groups, self.name)
 
            Session().commit()
 
        return user_data
 

	
 

	
 
def importplugin(plugin):
 
def loadplugin(plugin):
 
    """
 
    Imports and returns the authentication plugin in the module named by plugin
 
    (e.g., plugin='kallithea.lib.auth_modules.auth_internal'). Returns the
 
    Imports, instantiates, and returns the authentication plugin in the module named by plugin
 
    (e.g., plugin='kallithea.lib.auth_modules.auth_internal'). Returns an instance of the
 
    KallitheaAuthPluginBase subclass on success, raises exceptions on failure.
 

	
 
    raises:
 
        AttributeError -- no KallitheaAuthPlugin class in the module
 
        TypeError -- if the KallitheaAuthPlugin is not a subclass of ours KallitheaAuthPluginBase
 
        ImportError -- if we couldn't import the plugin at all
 
@@ -326,48 +326,49 @@ def importplugin(plugin):
 
              plugin, module.__name__, module.__file__)
 

	
 
    pluginclass = getattr(module, PLUGIN_CLASS_NAME)
 
    if not issubclass(pluginclass, KallitheaAuthPluginBase):
 
        raise TypeError("Authentication class %s.KallitheaAuthPlugin is not "
 
                        "a subclass of %s" % (plugin, KallitheaAuthPluginBase))
 
    return pluginclass
 

	
 

	
 
def loadplugin(plugin):
 
    """
 
    Loads and returns an instantiated authentication plugin.
 

	
 
        see: importplugin
 
    """
 
    plugin = importplugin(plugin)()
 
    plugin = pluginclass()
 
    if plugin.plugin_settings.im_func != KallitheaAuthPluginBase.plugin_settings.im_func:
 
        raise TypeError("Authentication class %s.KallitheaAuthPluginBase "
 
                        "has overridden the plugin_settings method, which is "
 
                        "forbidden." % plugin)
 
    return plugin
 

	
 

	
 
def get_auth_plugins():
 
    """Return a list of instances of plugins that are available and enabled"""
 
    auth_plugins = []
 
    for plugin_name in Setting.get_by_name("auth_plugins").app_settings_value:
 
        try:
 
            plugin = loadplugin(plugin_name)
 
        except ImportError as e:
 
            log.exception('Failed to load authentication module %s' % (plugin_name))
 
        else:
 
            auth_plugins.append(plugin)
 
    return auth_plugins
 

	
 

	
 
def authenticate(username, password, environ=None):
 
    """
 
    Authentication function used for access control,
 
    It tries to authenticate based on enabled authentication modules.
 

	
 
    :param username: username can be empty for container auth
 
    :param password: password can be empty for container auth
 
    :param environ: environ headers passed for container auth
 
    :returns: None if auth failed, user_data dict if auth is correct
 
    """
 

	
 
    auth_plugins = Setting.get_auth_plugins()
 
    auth_plugins = get_auth_plugins()
 
    log.debug('Authentication against %s plugins', auth_plugins)
 
    for module in auth_plugins:
 
        try:
 
            plugin = loadplugin(module)
 
        except (ImportError, AttributeError, TypeError) as e:
 
            log.error('Failed to load authentication module %s : %s' % (module, str(e)))
 
            continue
 
    for plugin in auth_plugins:
 
        module = plugin.__class__.__module__
 
        log.debug('Trying authentication using ** %s **', module)
 
        # load plugin settings from Kallithea database
 
        plugin_name = plugin.name
 
        plugin_settings = {}
 
        for v in plugin.plugin_settings():
 
            conf_key = "auth_%s_%s" % (plugin_name, v["name"])
 
@@ -421,14 +422,14 @@ def authenticate(username, password, env
 
    return None
 

	
 
def get_managed_fields(user):
 
    """return list of fields that are managed by the user's auth source, usually some of
 
    'username', 'firstname', 'lastname', 'email', 'active', 'password'
 
    """
 
    auth_plugins = Setting.get_auth_plugins()
 
    for module in auth_plugins:
 
    auth_plugins = get_auth_plugins()
 
    for plugin in auth_plugins:
 
        module = plugin.__class__.__module__
 
        log.debug('testing %s (%s) with auth plugin %s', user, user.extern_type, module)
 
        plugin = loadplugin(module)
 
        if plugin.name == user.extern_type:
 
            return plugin.get_managed_fields()
 
    log.error('no auth plugin %s found for %s', user.extern_type, user)
 
    return [] # TODO: Fail badly instead of allowing everything to be edited?
kallithea/lib/base.py
Show inline comments
 
@@ -479,14 +479,14 @@ class BaseController(WSGIController):
 
                # exception object.
 
                from kallithea.lib import helpers as h
 
                h.flash(e, 'error', logf=log.error)
 

	
 
        # Authenticate by auth_container plugin (if enabled)
 
        if any(
 
            auth_modules.importplugin(name).is_container_auth
 
            for name in Setting.get_auth_plugins()
 
            plugin.is_container_auth
 
            for plugin in auth_modules.get_auth_plugins()
 
        ):
 
            try:
 
                user_info = auth_modules.authenticate('', '', request.environ)
 
            except UserCreationError as e:
 
                from kallithea.lib import helpers as h
 
                h.flash(e, 'error', logf=log.error)
kallithea/model/db.py
Show inline comments
 
@@ -297,17 +297,12 @@ class Setting(Base, BaseDbModel):
 
            settings[each.app_settings_name] = \
 
                each.app_settings_value
 

	
 
        return settings
 

	
 
    @classmethod
 
    def get_auth_plugins(cls, cache=False):
 
        auth_plugins = cls.get_by_name("auth_plugins").app_settings_value
 
        return auth_plugins
 

	
 
    @classmethod
 
    def get_auth_settings(cls, cache=False):
 
        ret = cls.query() \
 
                .filter(cls.app_settings_name.startswith('auth_')).all()
 
        fd = {}
 
        for row in ret:
 
            fd[row.app_settings_name] = row.app_settings_value
0 comments (0 inline, 0 general)