Esempio n. 1
0
 def get_managed_fields(self):
     fields = ['username', 'password']
     if(Setting.get_by_name('auth_container_email_header').app_settings_value):
         fields.append('email')
     if(Setting.get_by_name('auth_container_firstname_header').app_settings_value):
         fields.append('firstname')
     if(Setting.get_by_name('auth_container_lastname_header').app_settings_value):
         fields.append('lastname')
     return fields
Esempio n. 2
0
def test_passing_list_setting_value_results_in_string_valued_setting():
    assert Setting.get_by_name(name) is None
    setting = Setting.create_or_update(name, ['spam', 'eggs'])
    Session().flush() # must flush so we can delete it below
    try:
        assert Setting.get_by_name(name) is not None
        # Quirk: list value is stringified.
        assert Setting.get_by_name(name).app_settings_value \
               == "['spam', 'eggs']"
        assert Setting.get_by_name(name).app_settings_type == 'unicode'
    finally:
        Session().delete(setting)
Esempio n. 3
0
 def get_managed_fields(self):
     fields = ['username', 'password']
     if (Setting.get_by_name(
             'auth_container_email_header').app_settings_value):
         fields.append('email')
     if (Setting.get_by_name(
             'auth_container_firstname_header').app_settings_value):
         fields.append('firstname')
     if (Setting.get_by_name(
             'auth_container_lastname_header').app_settings_value):
         fields.append('lastname')
     return fields
Esempio n. 4
0
    def __render(self, defaults, errors):
        c.defaults = {}
        c.plugin_settings = {}
        c.plugin_shortnames = {}

        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"])
                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
        # we want to show , separated list of enabled plugins
        c.defaults['auth_plugins'] = ','.join(c.enabled_plugin_names)

        if defaults:
            c.defaults.update(defaults)

        log.debug(formatted_json(defaults))
        return formencode.htmlfill.render(
            render('admin/auth/auth_settings.html'),
            defaults=c.defaults,
            errors=errors,
            prefix_error=False,
            encoding="UTF-8",
            force_defaults=False)
Esempio n. 5
0
    def __render(self, defaults, errors):
        c.defaults = {}
        c.plugin_settings = {}
        c.plugin_shortnames = {}

        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"])
                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
        # we want to show , separated list of enabled plugins
        c.defaults['auth_plugins'] = ','.join(c.enabled_plugin_names)

        if defaults:
            c.defaults.update(defaults)

        log.debug(formatted_json(defaults))
        return formencode.htmlfill.render(
            render('admin/auth/auth_settings.html'),
            defaults=c.defaults,
            errors=errors,
            prefix_error=False,
            encoding="UTF-8",
            force_defaults=False)
 def get_settings(self):
     """Get plugin settings values."""
     plugin_settings = {}
     for v in self.plugin_settings():
         conf_key = "auth_%s_%s" % (self.name, v["name"])
         setting = Setting.get_by_name(conf_key)
         plugin_settings[v["name"]] = setting.app_settings_value if setting else None
     return plugin_settings
Esempio n. 7
0
def test_list_valued_setting_creation_requires_manual_value_formatting():
    assert Setting.get_by_name(name) is None
    # Quirk: need manual formatting of list setting value.
    setting = Setting.create_or_update(name, 'spam,eggs', type='list')
    Session().flush() # must flush so we can delete it below
    try:
        assert setting.app_settings_value == ['spam', 'eggs']
    finally:
        Session().delete(setting)
Esempio n. 8
0
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 Exception:
            log.exception('Failed to load authentication module %s' %
                          (plugin_name))
        else:
            auth_plugins.append(plugin)
    return auth_plugins
Esempio n. 9
0
    def create_default_options(self, skip_existing=False):
        """Creates default settings"""

        for k, v, t in [('default_repo_enable_locking', False, 'bool'),
                        ('default_repo_enable_downloads', False, 'bool'),
                        ('default_repo_enable_statistics', False, 'bool'),
                        ('default_repo_private', False, 'bool'),
                        ('default_repo_type', 'hg', 'unicode')]:

            if skip_existing and Setting.get_by_name(k) is not None:
                log.debug('Skipping option %s', k)
                continue
            setting = Setting(k, v, t)
            self.sa.add(setting)
Esempio n. 10
0
def test_list_valued_setting_update():
    assert Setting.get_by_name(name) is None
    setting = Setting.create_or_update(name, 'spam', type='list')
    Session().flush() # must flush so we can delete it below
    try:
        assert setting.app_settings_value == ['spam']
        # Assign back setting value.
        setting.app_settings_value = setting.app_settings_value
        # Quirk: value is stringified on write and listified on read.
        assert setting.app_settings_value == ["['spam']"]
        setting.app_settings_value = setting.app_settings_value
        assert setting.app_settings_value == ["[\"['spam']\"]"]
    finally:
        Session().delete(setting)
Esempio n. 11
0
    def create_auth_plugin_options(self, skip_existing=False):
        """
        Create default auth plugin settings, and make it active

        :param skip_existing:
        """

        for k, v, t in [('auth_plugins', 'kallithea.lib.auth_modules.auth_internal', 'list'),
                     ('auth_internal_enabled', 'True', 'bool')]:
            if skip_existing and Setting.get_by_name(k) != None:
                log.debug('Skipping option %s' % k)
                continue
            setting = Setting(k, v, t)
            self.sa.add(setting)
Esempio n. 12
0
    def create_auth_plugin_options(self, skip_existing=False):
        """
        Create default auth plugin settings, and make it active

        :param skip_existing:
        """

        for k, v, t in [('auth_plugins', 'kallithea.lib.auth_modules.auth_internal', 'list'),
                        ('auth_internal_enabled', 'True', 'bool')]:
            if skip_existing and Setting.get_by_name(k) is not None:
                log.debug('Skipping option %s', k)
                continue
            setting = Setting(k, v, t)
            self.sa.add(setting)
Esempio n. 13
0
    def create_default_options(self, skip_existing=False):
        """Creates default settings"""

        for k, v, t in [
            ('default_repo_enable_locking',  False, 'bool'),
            ('default_repo_enable_downloads', False, 'bool'),
            ('default_repo_enable_statistics', False, 'bool'),
            ('default_repo_private', False, 'bool'),
            ('default_repo_type', 'hg', 'unicode')]:

            if skip_existing and Setting.get_by_name(k) is not None:
                log.debug('Skipping option %s' % k)
                continue
            setting = Setting(k, v, t)
            self.sa.add(setting)
Esempio n. 14
0
    def index(self, defaults=None, errors=None, prefix_error=False):
        self.__load_defaults()
        _defaults = {}
        # default plugins loaded
        formglobals = {
            "auth_plugins": ["kallithea.lib.auth_modules.auth_internal"]
        }
        formglobals.update(Setting.get_auth_settings())
        formglobals["plugin_settings"] = {}
        formglobals["auth_plugins_shortnames"] = {}
        _defaults["auth_plugins"] = formglobals["auth_plugins"]

        for module in formglobals["auth_plugins"]:
            plugin = auth_modules.loadplugin(module)
            plugin_name = plugin.name
            formglobals["auth_plugins_shortnames"][module] = plugin_name
            formglobals["plugin_settings"][module] = plugin.plugin_settings()
            for v in formglobals["plugin_settings"][module]:
                fullname = ("auth_" + plugin_name + "_" + v["name"])
                if "default" in v:
                    _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:
                    _defaults[fullname] = setting.app_settings_value
        # we want to show , separated list of enabled plugins
        _defaults['auth_plugins'] = ','.join(_defaults['auth_plugins'])
        if defaults:
            _defaults.update(defaults)

        formglobals["defaults"] = _defaults
        # set template context variables
        for k, v in formglobals.iteritems():
            setattr(c, k, v)

        log.debug(pprint.pformat(formglobals, indent=4))
        log.debug(formatted_json(defaults))
        return formencode.htmlfill.render(
            render('admin/auth/auth_settings.html'),
            defaults=_defaults,
            errors=errors,
            prefix_error=prefix_error,
            encoding="UTF-8",
            force_defaults=False)
Esempio n. 15
0
    def index(self, defaults=None, errors=None, prefix_error=False):
        self.__load_defaults()
        _defaults = {}
        # default plugins loaded
        formglobals = {
            "auth_plugins": ["kallithea.lib.auth_modules.auth_internal"]
        }
        formglobals.update(Setting.get_auth_settings())
        formglobals["plugin_settings"] = {}
        formglobals["auth_plugins_shortnames"] = {}
        _defaults["auth_plugins"] = formglobals["auth_plugins"]

        for module in formglobals["auth_plugins"]:
            plugin = auth_modules.loadplugin(module)
            plugin_name = plugin.name
            formglobals["auth_plugins_shortnames"][module] = plugin_name
            formglobals["plugin_settings"][module] = plugin.plugin_settings()
            for v in formglobals["plugin_settings"][module]:
                fullname = ("auth_" + plugin_name + "_" + v["name"])
                if "default" in v:
                    _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:
                    _defaults[fullname] = setting.app_settings_value
        # we want to show , separated list of enabled plugins
        _defaults['auth_plugins'] = ','.join(_defaults['auth_plugins'])
        if defaults:
            _defaults.update(defaults)

        formglobals["defaults"] = _defaults
        # set template context variables
        for k, v in formglobals.iteritems():
            setattr(c, k, v)

        log.debug(pprint.pformat(formglobals, indent=4))
        log.debug(formatted_json(defaults))
        return formencode.htmlfill.render(
            render('admin/auth/auth_settings.html'),
            defaults=_defaults,
            errors=errors,
            prefix_error=prefix_error,
            encoding="UTF-8",
            force_defaults=False)
Esempio n. 16
0
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()
    log.debug('Authentication against %s plugins', auth_plugins)
    for module in auth_plugins:
        try:
            plugin = loadplugin(module)
        except (ImportError, AttributeError, TypeError) as e:
            raise ImportError('Failed to load authentication module %s : %s'
                              % (module, str(e)))
        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"])
            setting = Setting.get_by_name(conf_key)
            plugin_settings[v["name"]] = setting.app_settings_value if setting else None
        log.debug('Plugin settings \n%s', formatted_json(plugin_settings))

        if not str2bool(plugin_settings["enabled"]):
            log.info("Authentication plugin %s is disabled, skipping for %s",
                     module, username)
            continue

        # use plugin's method of user extraction.
        user = plugin.get_user(username, environ=environ,
                               settings=plugin_settings)
        log.debug('Plugin %s extracted user is `%s`', module, user)
        if not plugin.accepts(user):
            log.debug('Plugin %s does not accept user `%s` for authentication',
                      module, user)
            continue
        else:
            log.debug('Plugin %s accepted user `%s` for authentication',
                      module, user)
            # The user might have tried to authenticate using their email address,
            # then the username variable wouldn't contain a valid username.
            # But as the plugin has accepted the user, .username field should
            # have a valid username, so use it for authentication purposes.
            if user is not None:
                username = user.username

        log.info('Authenticating user using %s plugin', plugin.__module__)

        # _authenticate is a wrapper for .auth() method of plugin.
        # it checks if .auth() sends proper data. For KallitheaExternalAuthPlugin
        # it also maps users to Database and maps the attributes returned
        # from .auth() to Kallithea database. If this function returns data
        # then auth is correct.
        user_data = plugin._authenticate(user, username, password,
                                           plugin_settings,
                                           environ=environ or {})
        log.debug('PLUGIN USER DATA: %s', user_data)

        if user_data is not None:
            log.debug('Plugin returned proper authentication data')
            return user_data

        # we failed to Auth because .auth() method didn't return the user
        if username:
            log.warning("User `%s` failed to authenticate against %s",
                        username, plugin.__module__)
    return None
Esempio n. 17
0
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, plugin_user dict if auth is correct
    """

    auth_plugins = Setting.get_auth_plugins()
    log.debug('Authentication against %s plugins' % (auth_plugins, ))
    for module in auth_plugins:
        try:
            plugin = loadplugin(module)
        except (ImportError, AttributeError, TypeError), e:
            raise ImportError('Failed to load authentication module %s : %s' %
                              (module, str(e)))
        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"])
            setting = Setting.get_by_name(conf_key)
            plugin_settings[
                v["name"]] = setting.app_settings_value if setting else None
        log.debug('Plugin settings \n%s' % formatted_json(plugin_settings))

        if not str2bool(plugin_settings["enabled"]):
            log.info("Authentication plugin %s is disabled, skipping for %s" %
                     (module, username))
            continue

        # use plugin's method of user extraction.
        user = plugin.get_user(username,
                               environ=environ,
                               settings=plugin_settings)
        log.debug('Plugin %s extracted user is `%s`' % (module, user))
        if not plugin.accepts(user):
            log.debug(
                'Plugin %s does not accept user `%s` for authentication' %
                (module, user))
            continue
        else:
            log.debug('Plugin %s accepted user `%s` for authentication' %
                      (module, user))

        log.info('Authenticating user using %s plugin' % plugin.__module__)
        # _authenticate is a wrapper for .auth() method of plugin.
        # it checks if .auth() sends proper data. For KallitheaExternalAuthPlugin
        # it also maps users to Database and maps the attributes returned
        # from .auth() to Kallithea database. If this function returns data
        # then auth is correct.
        plugin_user = plugin._authenticate(user,
                                           username,
                                           password,
                                           plugin_settings,
                                           environ=environ or {})
        log.debug('PLUGIN USER DATA: %s' % plugin_user)

        if plugin_user:
            log.debug('Plugin returned proper authentication data')
            return plugin_user

        # we failed to Auth because .auth() method didn't return proper the user
        if username:
            log.warning("User `%s` failed to authenticate against %s" %
                        (username, plugin.__module__))
Esempio n. 18
0
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 = get_auth_plugins()
    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"])
            setting = Setting.get_by_name(conf_key)
            plugin_settings[
                v["name"]] = setting.app_settings_value if setting else None
        log.debug('Settings for auth plugin %s:\n%s', plugin_name,
                  formatted_json(plugin_settings))

        if not str2bool(plugin_settings["enabled"]):
            log.info("Authentication plugin %s is disabled, skipping for %s",
                     module, username)
            continue

        # use plugin's method of user extraction.
        user = plugin.get_user(username,
                               environ=environ,
                               settings=plugin_settings)
        log.debug('Plugin %s extracted user `%s`', module, user)
        if not plugin.accepts(user):
            log.debug('Plugin %s does not accept user `%s` for authentication',
                      module, user)
            continue
        else:
            log.debug('Plugin %s accepted user `%s` for authentication',
                      module, user)
            # The user might have tried to authenticate using their email address,
            # then the username variable wouldn't contain a valid username.
            # But as the plugin has accepted the user, .username field should
            # have a valid username, so use it for authentication purposes.
            if user is not None:
                username = user.username

        log.info('Authenticating user using %s plugin', module)

        # _authenticate is a wrapper for .auth() method of plugin.
        # it checks if .auth() sends proper data. For KallitheaExternalAuthPlugin
        # it also maps users to Database and maps the attributes returned
        # from .auth() to Kallithea database. If this function returns data
        # then auth is correct.
        user_data = plugin._authenticate(user,
                                         username,
                                         password,
                                         plugin_settings,
                                         environ=environ or {})
        log.debug('Plugin user data: %s', user_data)

        if user_data is not None:
            log.debug('Plugin returned proper authentication data')
            return user_data

        # we failed to Auth because .auth() method didn't return the user
        if username:
            log.warning("User `%s` failed to authenticate against %s",
                        username, module)
    return None