示例#1
0
def login():
    """
    User login ...

    If GET request, display login form
    If POST request, authenticates user and redirects to index page
    """
    # Get configured backend ...
    # frontend = app.config['frontend']

    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        app.logger.info("login request for: %s", username)

        user = User()
        if user.authenticate(username, password):
            if login_user(user, remember=True):
                # Initialize backend
                flash(u"You were successfully logged in.", 'info')
                return redirect(request.args.get('next') or url_for('index'))
            else:  # pragma: no cover - should never happen ...
                error = u"User login failed."
        else:
            error = u"Invalid credentials: username is unknown or password is invalid."

    app.logger.info("show login form ...")
    return render_template(
        'login.html',
        error=error,
        title=u"Login page",
        manifest=manifest
    )
示例#2
0
    def setUp(self):
        print ""
        print "setting up ..."

        alignak_webui.app.config['HOST'] = '127.0.0.1'
        alignak_webui.app.config['PORT'] = 80
        alignak_webui.app.config['DEBUG'] = False

        alignak_webui.app.config['TESTING'] = True

        cfg_file = "settings.cfg"
        print 'Required configuration file:', cfg_file
        sett = Settings(alignak_webui.app)
        found_cfg_files = sett.read(cfg_file, {})
        if not found_cfg_files:
            print "Required configuration file not found."
            sys.exit(1)
        print 'Found configuration file:', cfg_file

        # Initialize backend communication ...
        frontend.configure(alignak_webui.app.config.get('ui.backend', 'http://localhost:5000'))
        print "Frontend: %s", frontend.url_endpoint_root

        # Configure users' management backend
        User.set_backend(frontend)

        helper = Helper(alignak_webui.app)

        self.app = alignak_webui.app.test_client()
示例#3
0
def token_loader(token):  # pragma: no cover - very difficult with unit testing ...
    """
    Called when user login check is required
    """
    # pragma: no cover - very difficult with unit testing ...
    app.logger.debug("token_loader - Try to find user with token: %s", token)
    return User.get_from_token(token)
示例#4
0
    def test_10_livesynthesis(self):
        print "---"

        # Initialize backend communication ...
        frontend.configure(alignak_webui.app.config.get('ui.backend', 'http://localhost:5000'))
        print "Frontend: %s", frontend.url_endpoint_root

        # Configure users' management backend
        User.set_backend(frontend)

        # Force authentication ...
        connection = frontend.login('admin', 'admin', force=True)
        assert_true(frontend.authenticated)
        assert_true(frontend.token)

        connection = frontend.connect(username='******')
        assert_true(frontend.authenticated)
        assert_true(frontend.connected)

        print "Get live synthesis ..."
        synthesis = self.helper.get_livesynthesis()
        print "Result:", synthesis
        assert_true('hosts_synthesis' in synthesis)
        assert_true('nb_elts' in synthesis['hosts_synthesis'])
        assert_true('services_synthesis' in synthesis)
        assert_true('nb_elts' in synthesis['services_synthesis'])

        print "Get HTML live synthesis ..."
        synthesis = self.helper.get_html_livesynthesis()
        print "Result:", synthesis
        assert 'hosts_states_popover' in synthesis
        assert 'host state is UP' in synthesis['hosts_states_popover']
        assert 'host state is DOWN' in synthesis['hosts_states_popover']
        assert 'host state is UNREACHABLE' in synthesis['hosts_states_popover']
        assert 'hosts_state' in synthesis
        # assert False

        assert 'services_states_popover' in synthesis
        assert 'service state is OK' in synthesis['services_states_popover']
        assert 'service state is WARNING' in synthesis['services_states_popover']
        assert 'service state is CRITICAL' in synthesis['services_states_popover']
        assert 'services_state' in synthesis

        # Backend disconnection
        frontend.disconnect()
示例#5
0
    def setUp(self):
        print ""
        print "setting up ..."

        alignak_webui.app.config["HOST"] = "127.0.0.1"
        alignak_webui.app.config["PORT"] = 80
        alignak_webui.app.config["DEBUG"] = False

        alignak_webui.app.config["TESTING"] = True

        sett = Settings(alignak_webui.app)
        found_cfg_files = sett.read("settings.cfg", {})

        self.helper = Helper(alignak_webui.app)

        # Initialize backend communication ...
        frontend.configure(alignak_webui.app.config.get("ui.backend", "http://localhost:5000"))
        print "Frontend: %s", frontend.url_endpoint_root

        # Configure users' management backend
        User.set_backend(frontend)
示例#6
0
def request_loader(req):
    """
    Called when user login check is required
    """
    app.logger.debug("request_loader - Try to find user from request: %s", req)
    token = req.headers.get('Authorization')
    if token is None:
        token = req.args.get('token')

    if token is not None:  # pragma: no cover - very difficult with unit testing ...
        app.logger.debug("load_user - found user token in request")
        return User.get_from_token(token)
    return None
示例#7
0
    def test_11_livestate(self):
        print "---"

        # Initialize backend communication ...
        frontend.configure(alignak_webui.app.config.get('ui.backend', 'http://localhost:5000'))
        print "Frontend: %s", frontend.url_endpoint_root

        # Configure users' management backend
        User.set_backend(frontend)

        # Force authentication ...
        connection = frontend.login('admin', 'admin', force=True)
        assert_true(frontend.authenticated)
        assert_true(frontend.token)

        connection = frontend.connect(username='******')
        assert_true(frontend.authenticated)
        assert_true(frontend.connected)

        print "Get live state ..."
        print "Livestate_age: ", self.helper.livestate_age
        ls = self.helper.get_livestate()
        print "Livestate_age: ", self.helper.livestate_age
        print "Livestate: ", self.helper.livestate
        assert self.helper.livestate_age
        for item in ls:
            print "Item:", item
            assert_true('type' in item)
            assert_true('id' in item)
            assert_true('bi' in item)
            assert_true('name' in item)
            assert_true('friendly_name' in item)
        for item in self.helper.livestate:
            print "Item:", item
            assert_true('type' in item)
            assert_true('id' in item)
            assert_true('bi' in item)
            assert_true('name' in item)
            assert_true('friendly_name' in item)
        assert len(ls) == len(self.helper.livestate)

        print "Get HTML live state ..."
        print "Current user: "******"Items:", len(html['rows'])

        for bi in [0,1,2,3,4,5]:
            print "Get HTML live state (BI = %d) ..." % bi
            html = self.helper.get_html_livestate(bi=bi)
            assert 'bi' in html
            assert 'rows' in html
            assert 'panel_bi' in html
            print "Items:", len(html['rows']) / 2
            # for row in html['rows']:
                # print "Item:", row

        print "Get HTML live state ... filter"
        html = self.helper.get_html_livestate(search_filter="type:host")
        assert 'bi' in html
        assert 'rows' in html
        assert 'panel_bi' in html
        print "Items:", len(html['rows'])

        for bi in [0,1,2,3,4,5]:
            print "Get HTML live state (BI = %d) ...and filter" % bi
            html = self.helper.get_html_livestate(bi=bi, search_filter="type:host")
            assert 'bi' in html
            assert 'rows' in html
            assert 'panel_bi' in html
            print "Items:", len(html['rows'])

        # Backend disconnection
        frontend.disconnect()
示例#8
0
    def test_09_search(self):
        print "---"

        # Initialize backend communication ...
        frontend.configure(alignak_webui.app.config.get('ui.backend', 'http://localhost:5000'))
        print "Frontend: %s", frontend.url_endpoint_root

        # Configure users' management backend
        User.set_backend(frontend)

        # Force authentication ...
        connection = frontend.login('admin', 'admin', force=True)
        assert_true(frontend.authenticated)
        assert_true(frontend.token)

        connection = frontend.connect(username='******')
        assert_true(frontend.authenticated)
        assert_true(frontend.connected)

        ls = self.helper.get_livestate()

        print "Search on element type ..."
        search = self.helper.search_livestate(ls, "type:all")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "type:host")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "type:service")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "host")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "service")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "type:unknown")
        print "Result, found %d elements" % len(search)

        print "---"
        print "Search on element name and content ... "
        print "found in name ..."
        search = self.helper.search_livestate(ls, "charnay")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        print "found in output ..."
        search = self.helper.search_livestate(ls, "time")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        print "not found ..."
        search = self.helper.search_livestate(ls, "test")
        print "Result, found %d elements" % len(search)

        print "---"
        print "Search on element business impact ... "
        search = self.helper.search_livestate(ls, "bi:0")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "bi:=0")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "bi:>0")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "bi:>=0")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "bi:<5")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "bi:<=5")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "bi:>3")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0

        print "---"
        print "Search on element state ... "
        search = self.helper.search_livestate(ls, "is:ack")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "ack:true")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "ack:yes")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "ack:1")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:ack")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "ack:false")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "ack:no")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "ack:0")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:downtime")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "downtime:yes")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "downtime:true")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "downtime:1")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "downtime:false")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "downtime:no")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "downtime:0")
        print "Result, found %d elements" % len(search)
        assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:downtime")
        print "Result, found %d elements" % len(search)
        assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:0")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:1")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:2")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:3")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:up")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "up")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:down")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "down")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:unreachable")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "unreachable")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:ok")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "OK")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:warning")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "WARNING")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:critical")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "CRITICAL")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:unknown")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "UNKNOWN")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "is:pending")
        print "Result, found %d elements" % len(search)
        search = self.helper.search_livestate(ls, "PENDING")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:up")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:down")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:unreachable")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:ok")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:warning")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:critical")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:unknown")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0
        search = self.helper.search_livestate(ls, "isnot:pending")
        print "Result, found %d elements" % len(search)
        # assert len(search) > 0

        # Backend disconnection
        frontend.disconnect()
示例#9
0
def user_loader(user_id):
    """
    Called when user login check is required
    """
    app.logger.debug("user_loader - Try to find user with token: %s", user_id)
    return User.get_from_username(user_id)
示例#10
0
def main():
    args = docopt(__doc__, help=True, options_first=True, version=manifest['version'])

    # Set application logger name
    app.logger_name = __pkg_name__

    # Set logging options for the application
    logger = logging.getLogger(app.logger_name)
    logger.setLevel(logging.WARNING)

    # Create a console handler, add a formatter and set level to DEBUG
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

    # Add console handler to logger
    app.logger.addHandler(ch)

    if args['--debug']:
        app.logger.setLevel(logging.DEBUG)
        app.debug = True
        app.config['DEBUG'] = True
    elif args['--verbose']:
        app.logger.setLevel(logging.INFO)

    # Set and read configuration file
    cfg_file = args['--config']
    print 'Required configuration file:', cfg_file
    sett = Settings(app)
    found_cfg_files = sett.read(cfg_file, settings)
    if not found_cfg_files:
        print "Required configuration file not found."
        sys.exit(1)
    print 'Found configuration file:', cfg_file

    # Set logs file
    if args['--logs'] != 'no application log':
        # Store logs in a daily file, keeping 6 days along ... as default!
        # Default configuration may be set in configuration file, section [logs]
        fh = TimedRotatingFileHandler(
            filename=args['--logs'],
            when=settings.get('logs.when', 'D'),
            interval=int(settings.get('logs.interval', 1)),
            backupCount=int(settings.get('logs.backupCount', 6))
        )

        fh.setFormatter(logging.Formatter(
            settings.get('logs.formatter', '[%(asctime)s] - %(name)s - %(levelname)s - %(message)s')
        ))
        app.logger.addHandler(fh)
        print "%s logs stored in rotating file: %s" % (manifest['name'].lower(), args['--logs'])

    if args['--access'] != 'no access log':
        # Store Werkzeug logs  in a daily file, keeping 6 days along ... as default!
        # Default configuration may be set in configuration file, section [logs]
        # Store logs in a daily file, keeping 6 days along ... as default!
        # Default configuration may be set in configuration file, section [logs]
        fh = TimedRotatingFileHandler(
            filename=args['--access'],
            when=settings.get('logs.when', 'D'),
            interval=int(settings.get('logs.interval', 1)),
            backupCount=int(settings.get('logs.backupCount', 6))
        )

        fh.setFormatter(logging.Formatter(
            settings.get('logs.formatter', '[%(asctime)s] - %(name)s - %(levelname)s - %(message)s')
        ))

        logger = logging.getLogger('werkzeug')
        logger.addHandler(fh)
        # Also add the handler to Flask's logger for cases
        #  where Werkzeug isn't used as the underlying WSGI server.
        # app.logger.addHandler(fh)
        # Uncommenting this line makes the application log also available in the access logs file.
        print "server logs stored in rotating file: %s" % args['--access']

    try:
        # Update application manifest
        manifest['fmw_name'] = settings['framework.name']
        manifest['fmw_version'] = settings['framework.version']
        manifest['webui_logo'] = settings.get(
            'ui.webui_logo', '/static/images/logo_webui.png'
        )
        manifest['footer_logo'] = settings.get(
            'ui.footer_logo', '/static/images/logo_webui_xxs.png'
        )
        manifest['company_logo'] = settings.get(
            'ui.company_logo', '/static/images/default_company.png'
        )
        manifest['login_text'] = settings['ui.welcome_text']

        # Application banner in log
        app.logger.info(
            "--------------------------------------------------------------------------------"
        )
        app.logger.info("%s, version %s", manifest['name'], manifest['version'])
        app.logger.info("Copyright %s", manifest['copyright'])
        app.logger.info("License %s", manifest['license'])
        app.logger.info(
            "--------------------------------------------------------------------------------"
        )
        app.logger.debug("Doc: %s", manifest['doc'])
        app.logger.debug("Release notes: %s", manifest['release'])
        app.logger.debug(
            "--------------------------------------------------------------------------------"
        )
        app.logger.debug("Framework: %s, version %s", manifest['fmw_name'], manifest['fmw_version'])
        app.logger.debug(
            "--------------------------------------------------------------------------------"
        )

        # Application configuration in log
        app.logger.info("Configuration file searched in %s", [cfg_file])
        app.logger.info("Configuration files found: %s", found_cfg_files)
        app.logger.info("Application settings: %s", app.config)

        if args['<command>'] == 'start':
            # Initialize backend communication ...
            frontend.configure(app.config.get('ui.backend', 'http://localhost:5000'))
            app.logger.info("Backend used: %s", frontend.url_endpoint_root)

            # Configure users' management backend
            User.set_backend(frontend)

            # Application current directory
            app_dir = os.path.abspath(os.path.dirname(__file__))

            # Load application plugins
            plugins = Plugins(app)
            plugins_dir = os.path.join(
                os.path.join(app_dir, manifest['name'].lower()),
                app.config.get('ui.plugins_dir', 'plugins')
            )
            plugins.load_plugins(plugins_dir)

            app.run(
                host=app.config['HOST'],
                port=app.config['PORT'],
                debug=app.config['DEBUG']
            )
    except Exception as e:
        print("Command '%s' failed, exception: %s / %s", args['<command>'], type(e), str(e))
        app.logger.error("failed to launch command '%s'", args['<command>'])
        app.logger.error("Back trace of this kill: %s", traceback.format_exc())
        sys.exit(3)