Exemplo n.º 1
0
class TestLoadCreate(unittest2.TestCase):
    def setUp(self):
        self.dmg = DataManager(alignak_webui.app.app)
        print('Data manager', self.dmg)

    def test_3_1_load(self):
        """ Datamanager load """
        print('test load as admin')

        # Initialize and load ... no reset
        assert self.dmg.user_login('admin', 'admin')
        result = self.dmg.load()
        print("Result:", result)
        # self.assertEqual(result, 0)  # No new objects created ...

        # Initialize and load ... with reset
        result = self.dmg.load(reset=True)
        print("Result:", result)
        # Must not have loaded any objects ... behavior changed, no more objects loading on login
        # self.assertEqual(result, 0)

    def test_3_3_get_errors(self):
        """ Datamanager objects get errors """
        print('test get errors')

        # Initialize and load ... no reset
        assert self.dmg.user_login('admin', 'admin')
        result = self.dmg.load()
        print("Result:", result)
        assert result == 0  # No new objects created ...

        # Get elements error
        item = self.dmg.get_user('unknown')
        assert not item
        item = self.dmg.get_userrestrictrole('unknown')
        assert not item
        item = self.dmg.get_realm('unknown')
        assert not item
        item = self.dmg.get_host('unknown')
        assert not item
        item = self.dmg.get_hostgroup('unknown')
        assert not item
        item = self.dmg.get_hostdependency('unknown')
        assert not item
        item = self.dmg.get_service('unknown')
        assert not item
        item = self.dmg.get_servicegroup('unknown')
        assert not item
        item = self.dmg.get_servicedependency('unknown')
        assert not item
        item = self.dmg.get_command('unknown')
        assert not item
        item = self.dmg.get_history('unknown')
        assert not item
        item = self.dmg.get_logcheckresult('unknown')
        assert not item
        item = self.dmg.get_timeperiod('unknown')
        assert not item
Exemplo n.º 2
0
class WebUI(object):
    """
    WebUI application
    """
    def __init__(self, app, name='alignak_webui', config=None):
        """
        Application initialization

        :param: config
        :type: dict
        """
        logger.info("Initializing application...")
        self.reduced_mode = os.environ.get('ALIGNAK_WEBUI_REDUCED', False)
        if self.reduced_mode:
            logger.warning("- reduced mode: %s!", self.reduced_mode)

        # Store all the plugins
        self.plugins = []

        # Store all the widgets
        self.widgets = {}

        # Store all the tables
        self.tables = {}

        # Store all the lists
        self.lists = {}

        # Helper class
        self.helper = Helper()

        # Application configuration
        self.app = app
        self.name = name
        self.config = config

        # Application data manager and connection
        self.datamgr = None
        self.current_user = None

        # Load plugins in the plugins directory ...
        self.plugins_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'plugins')
        self.plugins_count = self.load_plugins(plugins_dir=self.plugins_dir)
        logger.info("loaded %d plugins from: %s", self.plugins_count, self.plugins_dir)

    def load_plugins(self, plugins_dir):
        # pylint: disable=too-many-locals, too-many-nested-blocks, undefined-loop-variable
        """
        Load plugins from the provided directory

        If the plugin has
        - 'pages', declare routes for the pages
        - 'widgets', declare widgets in the main widgets list

        Register the plugin 'views' directory in the Bottle views

        If the plugin has a 'load_config' function, call it
        """
        # ---
        # Reduced mode without authentication
        # ---
        if self.reduced_mode:
            plugins_dir = "%s_reduced" % plugins_dir
        logger.debug("load plugins from: %s", plugins_dir)

        # Get list of sub directories
        try:
            plugin_names = [
                fname for fname in os.listdir(plugins_dir)
                if os.path.isdir(os.path.join(plugins_dir, fname))
            ]
        except OSError as exp:  # pragma: no cover - simple security ...
            logger.error("plugins directory '%s' does not exist!", plugins_dir)
            return 0

        # Try to import all found supposed modules
        i = 0
        for plugin_name in plugin_names:
            logger.debug("trying to load plugin '%s' ...", plugin_name)
            try:
                # Import the module in the package namespace
                plugin = import_module(
                    '.%s.%s.%s' % (plugins_dir.rsplit('/')[-1], plugin_name, plugin_name),
                    __package__
                )

                # Plugin declared classes ...
                classes = inspect.getmembers(plugin, inspect.isclass)

                # Find "Plugin" sub classes in imported module ...
                p_classes = [co for dummy, co in classes if issubclass(co, Plugin) and co != Plugin]
                if p_classes:
                    logger.debug("Found plugins classes: %s", p_classes)
                    cfg_files = [
                        os.path.join(os.path.join(plugins_dir, plugin_name), 'settings.cfg'),
                        '~/%s/plugin_%s.cfg' % (self.name, plugin_name),
                        '/etc/%s/plugin_%s.cfg' % (self.name, plugin_name),
                        '/usr/local/etc/%s/plugin_%s.cfg' % (self.name, plugin_name),
                    ]

                    for p_class in p_classes:
                        # Create a plugin instance
                        plugin_instance = p_class(self, plugin_name, cfg_files)

                        if not plugin_instance.is_enabled():
                            logger.warning("Plugin '%s' is disabled!", plugin_name)
                            continue

                        i += 1
                        self.plugins.append(plugin_instance)

                # Add the views sub-directory of the plugin in the Bottle templates path
                dir_views = os.path.join(
                    os.path.join(plugins_dir, plugin_name), 'views'
                )
                if os.path.isdir(dir_views):
                    TEMPLATE_PATH.append(os.path.join(
                        os.path.join(plugins_dir, plugin_name), 'views'
                    ))
                    logger.debug("registered views directory '%s'", os.path.join(
                        os.path.join(plugins_dir, plugin_name), 'views'
                    ))

                logger.debug("registered plugin '%s'", plugin_name)

            except Exception as exp:  # pragma: no cover - simple security ...
                logger.exception("loading plugin %s, exception: %s", plugin_name, exp)

        return i

    def get_url(self, name):  # pylint:disable=no-self-use
        """
        Get the URL for a named route
        :param name:
        :return:
        """
        return self.app.get_url(name)

    @property
    def js_list(self):
        """
        Get the list of Javascript files
        :return:
        """
        js_list = [
            "/static/js/jquery-1.12.0.min.js",
            "/static/js/jquery-ui-1.11.4.min.js"
        ]

        if self.config.get('bootstrap4', '0') == '1':
            js_list += [
                "/static/js/bootstrap4.min.js"
            ]
        else:
            js_list += [
                "/static/js/bootstrap.min.js"
            ]

        js_list += [
            "/static/js/moment-with-langs.min.js",
            "/static/js/daterangepicker.js",
            "/static/js/jquery.jclock.js",
            "/static/js/jquery.jTruncate.js",
            "/static/js/typeahead.bundle.min.js",
            "/static/js/screenfull.js",
            "/static/js/alertify.min.js",
            "/static/js/BootSideMenu.js",
            "/static/js/selectize.min.js",
            "/static/js/Chart.min.js",
            "/static/js/jstree.min.js",
        ]

        if self.config.get('bootstrap4', '0') == '1':
            js_list += [
                "/static/js/datatables.bootstrap4.min.js"
            ]
        else:
            js_list += [
                "/static/js/datatables.min.js"
                # "/static/js/datatables.js"
            ]

        js_list += [
            "/static/js/material/arrive.min.js",
            "/static/js/material/material.min.js",
            "/static/js/material/ripples.min.js"
        ]

        return js_list

    @property
    def css_list(self):
        """
        Get the list of Javascript files
        :return:
        """
        if self.config.get('bootstrap4', '0') == '1':
            css_list = [
                "/static/css/bootstrap4.min.css"
            ]
        else:
            css_list = [
                "/static/css/bootstrap.min.css"
            ]

        css_list += [
            "/static/css/font-awesome.min.css",
            "/static/css/typeahead.css",
            "/static/css/daterangepicker.css",
            "/static/css/alertify/alertify.min.css",
            "/static/css/alertify/bootstrap.min.css",
            "/static/css/BootSideMenu.css",
            "/static/css/timeline.css",
            "/static/css/selectize.bootstrap3.css",
        ]

        css_list += [
            "/static/css/font-roboto.css",
            "/static/css/material-icons.css",
            "/static/css/material/bootstrap-material-design.min.css",
            "/static/css/material/ripples.min.css"
        ]

        css_list += [
            "/static/css/jstree/style.min.css",
        ]
        if self.config.get('bootstrap4', '0') == '1':
            css_list += [
                "/static/css/datatables.bootstrap4.min.css",
            ]
        else:
            css_list += [
                "/static/css/datatables.min.css",
            ]

        css_list += [
            "/static/css/alignak_webui.css",
            "/static/css/alignak_webui-items.css"
        ]

        return css_list

    # ---------------------------------------------------------------------------------------------
    # User authentication
    # ---------------------------------------------------------------------------------------------
    def user_authentication(self, username, password, session=None):
        """
        Authenticate a user thanks to his username / password

        The authentication is requested near the data manager. This functions uses the data manager
        of the current session, else it creates a new one.

        Stores the authenticated User object in the session to make it available
        """

        logger.warning("user_authentication, authenticating: %s", username)

        # Session...
        # session = request.environ['beaker.session']

        session['login_message'] = None
        # if not session:
        if 'current_user' not in session or not session['current_user'] or \
                not isinstance(session['current_user'], dict):
            # Build DM without any session or user parameter
            self.datamgr = DataManager(self.app)

            # Set user for the data manager and try to log-in.
            if not self.datamgr.user_login(username, password, load=(password is not None)):
                self.datamgr.load()
                session['login_message'] = self.datamgr.connection_message
                session['current_user'] = None

                logger.warning("user authentication refused: %s", session['login_message'])
                return False

            # Update application variables
            # self.current_user = self.datamgr.logged_in_user

            # Update session variables
            # session['current_user'] = self.current_user
            session['current_user'] = self.datamgr.logged_in_user
            session['current_realm'] = self.datamgr.my_realm
            # session['current_ls'] = self.datamgr.my_ls

        logger.debug("user_authentication, current user authenticated")
        return session

    def find_plugin(self, name):
        """Find a plugin with its name or its backend endpoint"""
        for plugin in self.plugins:
            if plugin.name == name:
                return plugin
        for plugin in self.plugins:
            if plugin.backend_endpoint == name:
                return plugin
        return None

    def get_widgets_for(self, place):
        """For a specific place like 'dashboard' or 'external', returns the widgets list
        sorted by the defined widget order property"""
        widgets_list = []
        for plugin in self.plugins:
            logger.debug("WebUI plugin %s", plugin)
            for widget in plugin.widgets.get(place, []):
                logger.debug(" - widget %s, order: %d, %s", widget['name'], widget['order'], widget)
                # Check if the widget requires a specific plugin to be present and enabled
                if widget.get('plugin', None):
                    needed_plugin = self.find_plugin(widget.get('plugin', None))
                    if not needed_plugin or not needed_plugin.is_enabled():
                        logger.debug("Widget '%s' ignored because of missing "
                                     "or disabled plugin: %s", widget['name'], plugin)
                        continue

                widgets_list.append(widget)

        sorted_widgets = sorted(widgets_list, key=lambda x: x['order'], reverse=False)
        return sorted_widgets

    def get_tables_for(self, place):
        """For a specific place like 'external', return the application tables list"""
        tables = []
        for plugin in self.plugins:
            if place in plugin.tables:
                tables = tables + plugin.tables[place]
        return tables

    ##
    # Make responses for browser client requests
    # ------------------------------------------------------------------------------------------
    @staticmethod
    def response_ok(message="Ok"):
        """Request is ok"""
        response.status = 200
        response.content_type = 'application/json'
        return json.dumps(
            {'status': 'ok', 'message': message}
        )

    @staticmethod
    def response_data(data):
        """Request is ok and contains data"""
        response.status = 200
        response.content_type = 'application/json'
        return json.dumps(data)

    @staticmethod
    def response_invalid_parameters(message="Missing parameter"):
        """Request parameters are invalid"""
        response.status = 400
        response.content_type = 'application/json'
        return json.dumps(
            {'status': 'ko', 'message': message}
        )

    @staticmethod
    def response_missing_file(message="No file selected for upload"):
        """File to upload missing parameter"""
        return WebUI.response_ko(message=message, code=412)

    @staticmethod
    def response_ko(message="Error!", code=409):
        """
        Request failed
        """
        response.status = code
        response.content_type = 'application/json'

        return json.dumps(
            {'status': 'ko', 'message': message}
        )
Exemplo n.º 3
0
class TestBasic(unittest2.TestCase):
    def setUp(self):
        self.dmg = DataManager(alignak_webui.app.app)
        print('Data manager', self.dmg)

        # Initialize and load ... no reset
        assert self.dmg.user_login('admin', 'admin')
        result = self.dmg.load()

    def tearDown(self):
        # Logout
        self.dmg.reset(logout=True)
        assert not self.dmg.my_backend.connected
        assert self.dmg.logged_in_user is None
        assert self.dmg.loaded == False

    def test_5_1_get_simple(self):
        """ Datamanager objects get - simple elements """
        print('test objects get simple objects')

        # Get realms
        items = self.dmg.get_realms()
        for item in items:
            print("Got: ", item)
            assert item.id
            item.get_html_state()
        assert len(items) == 4

        # Get commands
        items = self.dmg.get_commands()
        for item in items:
            print("Got: ", item)
            assert item.id
            icon_status = item.get_html_state()
        assert len(items) == 50  # Backend pagination limit ...

        # Get timeperiods
        items = self.dmg.get_timeperiods()
        for item in items:
            print("Got: ", item)
            assert item.id
            item.get_html_state()
        assert len(items) == 5

    def test_5_1_get_linked(self):
        """ Datamanager objects get - linked elements """
        print('test objects get linked')

        # Get hosts
        items = self.dmg.get_hosts()
        for item in items:
            print("Got: ", item)
            assert item.id
            assert isinstance(item.check_command, Command)  # Must be an object
            assert isinstance(item.check_period,
                              TimePeriod)  # Must be an object
        assert len(items) == 13

        # Get services
        items = self.dmg.get_services()
        for item in items:
            print("Got: ", item)
            assert item.id
            assert isinstance(item.check_command, Command)  # Must be an object
            assert isinstance(item.check_period,
                              TimePeriod)  # Must be an object
        assert len(items) == 50  # Backend pagination limit ...

    def test_5_1_get_linked_groups(self):
        """ Datamanager objects get - group elements """
        print('test objects get self linked')

        # Get hostgroups
        items = self.dmg.get_hostgroups()
        for item in items:
            print("Got: ", item)
            assert item.id
            if item.level != 0:
                assert isinstance(item._parent, HostGroup)  # Must be an object
        assert len(items) == 12

        # Get servicegroups
        items = self.dmg.get_servicegroups()
        for item in items:
            print("Got: ", item)
            assert item.id
            if item.level != 0:
                assert isinstance(item._parent,
                                  ServiceGroup)  # Must be an object
        assert len(items) == 10

        # Get usergroups
        items = self.dmg.get_usergroups()
        for item in items:
            print("Got: ", item)
            assert item.id
            if item.level != 0:
                assert isinstance(item._parent, UserGroup)  # Must be an object
        assert len(items) == 7

    def test_5_3_livesynthesis(self):
        """ Datamanager objects get - livesynthesis """
        print('test livesynthesis')

        self.maxDiff = None

        # Get livesynthesis - user logged-in realm and its sub-realms
        expected_ls = {
            '_id': self.dmg.my_ls['_id'],
            'hosts_synthesis': {
                'nb_elts': 7,
                'nb_not_monitored': 0,
                'pct_not_monitored': 0.0,
                # 'business_impact': 0,
                'warning_threshold': 2.0,
                'global_warning_threshold': 2.0,
                'critical_threshold': 5.0,
                'global_critical_threshold': 5.0,
                'nb_up': 0,
                'pct_up': 0.0,
                'nb_up_hard': 0,
                'nb_up_soft': 0,
                'nb_down': 0,
                'pct_down': 0.0,
                'nb_down_hard': 0,
                'nb_down_soft': 0,
                'nb_unreachable': 7,
                'pct_unreachable': 100.0,
                'nb_unreachable_hard': 7,
                'nb_unreachable_soft': 0,
                'nb_problems': 7,
                'pct_problems': 100.0,
                'nb_flapping': 0,
                'pct_flapping': 0.0,
                'nb_acknowledged': 0,
                'pct_acknowledged': 0.0,
                'nb_in_downtime': 0,
                'pct_in_downtime': 0.0,
            },
            'services_synthesis': {
                'nb_elts': 241,
                'nb_not_monitored': 0,
                'pct_not_monitored': 0.0,
                # 'business_impact': 0,
                'warning_threshold': 2.0,
                'global_warning_threshold': 2.0,
                'critical_threshold': 5.0,
                'global_critical_threshold': 5.0,
                'nb_ok': 0,
                'pct_ok': 0.0,
                'nb_ok_hard': 0,
                'nb_ok_soft': 0,
                'nb_warning': 0,
                'pct_warning': 0.0,
                'nb_warning_hard': 0,
                'nb_warning_soft': 0,
                'nb_critical': 0,
                'pct_critical': 0.0,
                'nb_critical_hard': 0,
                'nb_critical_soft': 0,
                'nb_unknown': 241,
                'pct_unknown': 100.0,
                'nb_unknown_hard': 241,
                'nb_unknown_soft': 0,
                'nb_unreachable': 0,
                'pct_unreachable': 0.0,
                'nb_unreachable_hard': 0,
                'nb_unreachable_soft': 0,
                'nb_problems': 0,
                'pct_problems': 0.0,
                'nb_flapping': 0,
                'pct_flapping': 0.0,
                'nb_acknowledged': 0,
                'pct_acknowledged': 0.0,
                'nb_in_downtime': 0,
                'pct_in_downtime': 0.0
            }
        }
        got_ls = self.dmg.get_livesynthesis({
            'concatenation': '1',
            'where': {
                '_realm': self.dmg.my_realm.id
            }
        })
        assert got_ls['hosts_synthesis'] == expected_ls['hosts_synthesis']
        assert got_ls['services_synthesis'] == expected_ls[
            'services_synthesis']

        # Get livesynthesis - user logged-in realm and no sub realms
        expected_ls = {
            '_id': self.dmg.my_ls['_id'],
            'hosts_synthesis': {
                'nb_elts': 7,
                'nb_not_monitored': 0,
                'pct_not_monitored': 0.0,
                # 'business_impact': 0,
                'warning_threshold': 2.0,
                'global_warning_threshold': 2.0,
                'critical_threshold': 5.0,
                'global_critical_threshold': 5.0,
                'nb_up': 0,
                'pct_up': 0.0,
                'nb_up_hard': 0,
                'nb_up_soft': 0,
                'nb_down': 0,
                'pct_down': 0.0,
                'nb_down_hard': 0,
                'nb_down_soft': 0,
                'nb_unreachable': 7,
                'pct_unreachable': 100.0,
                'nb_unreachable_hard': 7,
                'nb_unreachable_soft': 0,
                'nb_problems': 7,
                'pct_problems': 100.0,
                'nb_flapping': 0,
                'pct_flapping': 0.0,
                'nb_acknowledged': 0,
                'pct_acknowledged': 0.0,
                'nb_in_downtime': 0,
                'pct_in_downtime': 0.0,
            },
            'services_synthesis': {
                'nb_elts': 241,
                'nb_not_monitored': 0,
                'pct_not_monitored': 0.0,
                # 'business_impact': 0,
                'warning_threshold': 2.0,
                'global_warning_threshold': 2.0,
                'critical_threshold': 5.0,
                'global_critical_threshold': 5.0,
                'nb_ok': 0,
                'pct_ok': 0.0,
                'nb_ok_hard': 0,
                'nb_ok_soft': 0,
                'nb_warning': 0,
                'pct_warning': 0.0,
                'nb_warning_hard': 0,
                'nb_warning_soft': 0,
                'nb_critical': 0,
                'pct_critical': 0.0,
                'nb_critical_hard': 0,
                'nb_critical_soft': 0,
                'nb_unknown': 241,
                'pct_unknown': 100.0,
                'nb_unknown_hard': 241,
                'nb_unknown_soft': 0,
                'nb_unreachable': 0,
                'pct_unreachable': 0.0,
                'nb_unreachable_hard': 0,
                'nb_unreachable_soft': 0,
                'nb_problems': 0,
                'pct_problems': 0.0,
                'nb_flapping': 0,
                'pct_flapping': 0.0,
                'nb_acknowledged': 0,
                'pct_acknowledged': 0.0,
                'nb_in_downtime': 0,
                'pct_in_downtime': 0.0
            }
        }
        got_ls = self.dmg.get_livesynthesis(self.dmg.my_ls['_id'])
        assert got_ls['hosts_synthesis'] == expected_ls['hosts_synthesis']
        assert got_ls['services_synthesis'] == expected_ls[
            'services_synthesis']
Exemplo n.º 4
0
class TestNotAdmin(unittest2.TestCase):
    def setUp(self):
        self.dmg = DataManager(alignak_webui.app.app)
        print('Data manager', self.dmg)

    @unittest2.skip(
        "Skipped because creating a new user do not allow him to get its own data (timeperiod get is 404)!"
    )
    def test_4_1_load(self):
        """ Datamanager load, not admin user """
        print('test load not admin user')

        # Initialize and load ... no reset
        assert self.dmg.user_login('admin', 'admin')
        result = self.dmg.load()
        print("Result:", result)
        assert result == 0  # No new objects created ...

        # Get main realm
        realm_all = self.dmg.get_realm({'where': {'name': 'All'}})

        # Get main TP
        tp_all = self.dmg.get_timeperiod({'where': {'name': '24x7'}})

        # Create a non admin user ...
        # Create a new user
        print('create a user')
        data = {
            "name": "not_admin",
            "alias": "Testing user - not administrator",
            "min_business_impact": 0,
            "email": "*****@*****.**",
            "is_admin": False,
            "expert": False,
            "can_submit_commands": False,
            "host_notifications_enabled": True,
            "host_notification_period": tp_all.id,
            "host_notification_commands": [],
            "host_notification_options": ["d", "u", "r"],
            "service_notifications_enabled": True,
            "service_notification_period": tp_all.id,
            "service_notification_commands": [],
            "service_notification_options": ["w", "u", "c", "r"],
            "definition_order": 100,
            "address1": "",
            "address2": "",
            "address3": "",
            "address4": "",
            "address5": "",
            "address6": "",
            "pager": "",
            "notificationways": [],
            "_realm": realm_all.id
        }
        new_user_id = self.dmg.add_user(data)
        print("New user id: %s" % new_user_id)

        # Logout
        # self.dmg.reset(logout=True)
        # assert not self.dmg.backend.connected
        # assert self.dmg.logged_in_user is None
        # assert self.dmg.loaded == False

        # Login as not_admin created user
        assert self.dmg.user_login('admin', 'admin', load=False)
        print("-----")

        assert self.dmg.user_login('not_admin', 'NOPASSWORDSET', load=False)
        assert self.dmg.my_backend.connected
        assert self.dmg.logged_in_user
        print("Logged-in user: %s" % self.dmg.logged_in_user)
        assert self.dmg.logged_in_user.get_username() == 'not_admin'
        print('logged in as not_admin')

        # Initialize and load ...
        result = self.dmg.load()
        print("Result:", result)
        print("Objects count:", self.dmg.get_objects_count())
        print("Objects count:", self.dmg.get_objects_count('host'))
        print("Objects count:", self.dmg.get_objects_count('service'))
        print("Objects count (log):", self.dmg.get_objects_count(log=True))
        # assert result == 0                          # Only the newly created user, so no new objects loaded
        # assert self.dmg.get_objects_count() == 1    # not_admin user

        # Initialize and load ... with reset
        result = self.dmg.load(reset=True)
        print("Result:", result)
        print("Objects count:", self.dmg.get_objects_count())
        print("Objects count:", self.dmg.get_objects_count('host'))
        print("Objects count:", self.dmg.get_objects_count('service'))
        print("Objects count (log):", self.dmg.get_objects_count(log=True))
        # assert result == 3                          # not_admin user + test_service + relation
        # assert self.dmg.get_objects_count() == 3    # not_admin user + test_service + relation

        # Not admin user can see only its own data, ...
        # -------------------------------------------

        # Do not check the length because the backend contains more elements than needed ...
        # dump_backend(not_admin_user=True, test_service=True)

        # Get users
        items = self.dmg.get_users()
        print("Users:", items)
        # assert len(items) == 1
        # 1 user only ...

        # Get commands
        items = self.dmg.get_commands()
        print("Commands:", items)
        # assert len(items) == 1

        # Get realms
        items = self.dmg.get_realms()
        print("Commands:", items)
        # assert len(items) == 1

        # Get timeperiods
        items = self.dmg.get_timeperiods()
        print("Commands:", items)
        # assert len(items) == 1

        # Get hosts
        items = self.dmg.get_hosts()
        print("Hosts:", items)
        # assert len(items) == 1

        # Get services
        items = self.dmg.get_services()
        print("Services:", items)
        # assert len(items) == 1

        result = self.dmg.delete_user(new_user_id)
        # Cannot delete the current logged-in user
        assert not result

        # Logout
        self.dmg.reset(logout=True)
        assert not self.dmg.my_backend.connected
        assert self.dmg.logged_in_user is None
        assert self.dmg.loaded == False

        # Login as admin
        assert self.dmg.user_login('admin', 'admin', load=False)
        assert self.dmg.my_backend.connected
        assert self.dmg.logged_in_user.get_username() == 'admin'

        result = self.dmg.delete_user(new_user_id)
        # Can delete the former logged-in user
        assert result
Exemplo n.º 5
0
    def test_2_1_creation_load(self):
        """ Datamanager creation and load """
        print('------------------------------')
        print('test creation')

        datamanager = DataManager(alignak_webui.app.app)
        assert datamanager.my_backend
        assert datamanager.loaded == False
        assert datamanager.logged_in_user is None
        print('Data manager', datamanager)
        # Got known managed elements classes
        assert len(datamanager.known_classes) == COUNT_KNOWN_CLASSES

        # Initialize and load fail ...
        print('DM load failed')
        result = datamanager.load()
        # Refused because no backend logged-in user
        assert not result

        # Login error
        print('DM logging bad password')
        assert not datamanager.user_login('admin', 'fake')
        print(datamanager.connection_message)
        assert datamanager.connection_message == 'Access denied! Check your username and password.'
        print(datamanager.logged_in_user)
        assert not datamanager.logged_in_user

        # Create new datamanager - do not use default backend address
        print('DM initialization')
        datamanager = DataManager(alignak_webui.app.app)
        assert datamanager.my_backend
        assert datamanager.loaded == False
        assert datamanager.logged_in_user is None
        print('Data manager', datamanager)

        # Initialize and load fail ...
        print('DM load fail')
        result = datamanager.load()
        # Refused because no backend logged-in user
        assert not result

        # Login error
        print('DM logging bad password')
        assert not datamanager.user_login('admin', 'fake')
        print(datamanager.connection_message)
        assert datamanager.connection_message == 'Access denied! Check your username and password.'
        print(datamanager.logged_in_user)
        assert not datamanager.logged_in_user

        # User login but do not load yet
        print('DM login ok')
        assert datamanager.user_login('admin', 'admin', load=False)
        assert datamanager.connection_message == 'Access granted'
        print("Logged user: %s" % datamanager.logged_in_user)
        assert datamanager.logged_in_user
        assert datamanager.logged_in_user is not None
        assert datamanager.logged_in_user.id is not None
        assert datamanager.logged_in_user.get_username() == 'admin'
        assert datamanager.logged_in_user.authenticated
        user_token = datamanager.logged_in_user.token
        print(User._cache[datamanager.logged_in_user.id].__dict__)

        print('DM reset')
        datamanager.reset()
        # Still logged-in...
        assert datamanager.logged_in_user
        assert datamanager.logged_in_user is not None

        print('DM reset - logout')
        datamanager.reset(logout=True)
        # Logged-out...
        assert not datamanager.logged_in_user
        assert datamanager.logged_in_user is None

        # User login with an authentication token
        print('DM login - token')
        assert datamanager.user_login(user_token)
        # When user authentication is made thanks to a token, DM is not loaded ... it is assumed that load already occured!

        print('DM login')
        assert datamanager.user_login('admin', 'admin', load=False)
        print(datamanager.logged_in_user)
        print(datamanager.logged_in_user.token)
        user_token = datamanager.logged_in_user.token
        assert datamanager.user_login(user_token)
        assert datamanager.connection_message == 'Access granted'

        assert datamanager.logged_in_user
        assert datamanager.logged_in_user is not None
        assert datamanager.logged_in_user.id is not None
        assert datamanager.logged_in_user.get_username() == 'admin'
        assert datamanager.logged_in_user.authenticated