Exemple #1
0
def detect_language():
    if 'lang' in request.args:
        requested_locale = request.args['lang']
        locales = [unicode(l) for l in babel.list_translations()]
        locale = negotiate_locale([requested_locale,], locales)
        session['locale'] = locale
        flask_babel.refresh()
Exemple #2
0
    def put(self, id):
        user = User.get_by_id(id)

        if user is None or not user.can_edit():
            flash(gettext('The user was not found'), 'error')
            return redirect(url_for('UsersView:index'))

        if request.method in ['POST']:
            form = EditUserForm()
            if form.validate_on_submit():
                if form.password.data:
                    user.set_password(form.password.data)
                del form.password
                form.populate_obj(user)
                user.save()
                refresh()
                return resp(url_for('UsersView:get', id=user.id), redirect=True,
                            message=gettext('User was succesfully updated'))
            else:
                return resp('admin/users/edit.html', form=form, user=user,
                            message=gettext('Invalid submission, please check the messages below'))
        else:
            form = EditUserForm(user=user)

        return resp('admin/users/edit.html', form=form, user=user)
Exemple #3
0
 def index(self, locale):
     if locale not in self.appbuilder.bm.languages:
         abort(404, description="Locale not supported.")
     session["locale"] = locale
     refresh()
     self.update_redirect()
     return redirect(self.get_redirect())
Exemple #4
0
def r_register():
    """ Route for new users to register for accounts

    :return: template, form
    """
    if current_user.is_authenticated:
        flash(_('Sie sind schon eingeloggt.'))
        return redirect(url_for('InstanceNemo.r_index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data,
                    email=form.email.data,
                    default_locale=form.default_locale.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        current_user.default_locale = form.default_locale.data
        refresh()
        flash(_('Sie sind nun registriert.'))
        return redirect(url_for('auth.r_login'))
    return current_app.config['nemo_app'].render(
        template='auth::register.html',
        title=_('Anmelden'),
        form=form,
        url=dict())
Exemple #5
0
    def decorated(*_args, **kwargs):
        config = current_app.config[CONFIG_KEY]
        if str(config.get('secret',
                          '')) == request.headers.get('X-Auth-Token'):
            # Inter services authentication
            from flask_babel import refresh
            setattr(
                flask_g, 'user',
                User(0, 'internal', '*****@*****.**', 'internal',
                     'admin', 'admin', 'pt', ['ADMINISTRATOR']))
            refresh()
            return f(*_args, **kwargs)
        else:
            user_id = request.headers.get('x-user-id')
            permissions = request.headers.get('x-permissions')
            user_data = request.headers.get('x-user-data')

            if all([user_data, user_id]):
                login, email, name, locale = user_data.split(';')
                parts = name.split(' ', 1)
                setattr(
                    flask_g, 'user',
                    User(int(user_id), login, email, name, parts[0],
                         parts[1].strip() if len(parts) > 1 else '', locale,
                         (permissions or '').split(',')))

                return f(*_args, **kwargs)
            else:
                return authenticate(MSG1,
                                    {'message': 'Invalid authentication'})
Exemple #6
0
def r_user(username):
    """ profile page for user. Initially used to change user information (e.g., password, email, etc.)

    :return: template, page title, forms
    :rtype: {str: Any}
    """
    password_form = PasswordChangeForm()
    if password_form.validate_on_submit():
        user = User.query.filter_by(username=username).first_or_404()
        if not user.check_password(password_form.old_password.data):
            flash(_("Das ist nicht Ihr aktuelles Passwort."))
            return redirect(url_for('auth.r_user', username=username))
        user.set_password(password_form.password.data)
        db.session.add(user)
        db.session.commit()
        flash(_("Sie haben Ihr Passwort erfolgreich geändert."))
        return redirect(url_for('auth.r_login'))
    language_form = LanguageChangeForm()
    if language_form.validate_on_submit():
        current_user.default_locale = language_form.new_locale.data
        db.session.commit()
        refresh()
        flash(_("Sie haben Ihre Benutzersprache erfolgreich geändert."))
        return redirect(url_for('auth.r_user', username=username))
    elif request.method == 'GET':
        language_form.new_locale.data = current_user.default_locale
    return current_app.config['nemo_app'].render(
        template="auth::login.html",
        title=_("Benutzerprofil ändern"),
        forms=[password_form, language_form],
        username=username,
        purpose='user',
        url=dict())
Exemple #7
0
 def get(self, server=None, client=None, conf=None):
     """Reads a given client configuration"""
     try:
         conf = unquote(conf)
     except:
         pass
     res = bui.client.read_conf_cli(client, conf, server)
     refresh()
     # Translate the doc and placeholder API side
     doc = bui.client.get_parser_attr('doc', server).copy()
     placeholders = bui.client.get_parser_attr('placeholders', server).copy()
     for key, val in iteritems(doc):
         doc[key] = _(val)
     for key, val in iteritems(placeholders):
         placeholders[key] = _(val)
     return jsonify(
         results=res,
         boolean=bui.client.get_parser_attr('boolean_cli', server),
         string=bui.client.get_parser_attr('string_cli', server),
         integer=bui.client.get_parser_attr('integer_cli', server),
         multi=bui.client.get_parser_attr('multi_cli', server),
         server_doc=doc,
         suggest=bui.client.get_parser_attr('values', server),
         placeholders=placeholders,
         defaults=bui.client.get_parser_attr('defaults', server)
     )
Exemple #8
0
def user_settings() -> ResponseType:
    """
        Show and process a form to edit a user's settings.

        :return: The response for this view.
    """

    settings = current_user.settings
    settings_form = UserSettingsForm(obj=settings)
    if settings_form.validate_on_submit():

        # Get the data from the form and save it.
        settings.language = settings_form.language.data
        db.session.commit()

        # Refresh the language to reflect possible changes to the user's language.
        refresh()

        flash(_('Your changes have been saved.'))
        return redirect(url_for('.user_settings'))

    reset_form = UserSettingsResetForm()
    return render_template('userprofile/user_settings.html',
                           title=_('Settings'),
                           settings_form=settings_form,
                           reset_form=reset_form)
Exemple #9
0
def user_settings(user_id: int) -> ResponseType:
    """
        Show and process a form to edit a user's settings.

        :param user_id: The ID of the user whose settings will be managed.
        :return: The response for this view.
    """

    user = User.load_from_id(user_id)
    if user is None:
        abort(404)

    settings = user.settings
    settings_form = UserSettingsForm(obj=settings)
    if settings_form.validate_on_submit():

        # Get the data from the form and save it.
        settings.language = settings_form.language.data
        db.session.commit()

        # Refresh the language in case the current user is editing themselves and they have changed their language.
        refresh()

        flash(_('Your changes have been saved.'))
        return redirect(url_for('.user_settings', user_id=user_id))

    reset_form = UserSettingsResetForm()
    return render_template('administration/user_settings.html',
                           user=user,
                           settings_form=settings_form,
                           reset_form=reset_form)
Exemple #10
0
def send_email(context, subject, body, params):
    if not with_mail():
        return

    recipients = [context['user']['email']]

    params.update({
        'scheme': context['scheme'],
        'host': context['host'],
        'service': param('title', 'Diamond wiki')
    })

    with app.app_context():
        g.locale = context['locale']

        refresh()

        subject = _(subject)
        body = _(body.strip(), **params)

        message = Message(subject, recipients, body)

        try:
            mail.send(message)
        except:
            app.logger.error(traceback.format_exc().strip())
Exemple #11
0
def lang():
    from flask_babel import refresh
    session['language'] = request.form['language']
    refresh()
    new_language = current_app.config['ACCEPT_LANGUAGES'][
        request.form['language']]
    flash(_('Language changed to ') + new_language, 'success')
    return redirect(url_for('frontend.index'))
    def config(self):
        from flask_babel import refresh

        cfg = super(ConvertDateStructIntoSkGUI, self).config
        cfg["BABEL_DEFAULT_LOCALE"] = "sk"
        cfg["CFG_SITE_LANG"] = "sk"
        refresh()
        return cfg
Exemple #13
0
def set_lang(lang):
    if lang not in LANGUAGES.keys():
        return redirect('page.index')

    rv = make_response(redirect(redirect_url()))
    rv.set_cookie('lang', lang)
    refresh()
    return rv
    def config(self):
        from flask_babel import refresh

        cfg = super(ConvertIntoDateGUITest, self).config
        cfg["BABEL_DEFAULT_LOCALE"] = "en"
        cfg["CFG_SITE_LANG"] = "en"
        refresh()
        return cfg
Exemple #15
0
    def r_set_language(self, code):
        """ Sets the seseion's language code which will be used for all requests

        :param code: The 2-letter language code
        :type code: str
        """
        session['locale'] = code
        refresh()
Exemple #16
0
 def test_refreshing(self):
     app = flask.Flask(__name__)
     b = babel.Babel(app)
     d = datetime(2010, 4, 12, 13, 46)
     with app.test_request_context():
         assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM'
         app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna'
         babel.refresh()
         assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
def init_user_preference(messenger):
    # Localise the bot for the current user
    list_of_globals = globals()
    list_of_globals["user"].update(messenger.get_user())
    logger.debug("Current USER: {}".format(user))

    get_locale()
    get_timezone()
    refresh()
Exemple #18
0
def change_language(lang):
    print "CHANGE LANGUAGE !"
    print lang

    global current_language
    current_language = lang
    refresh()

    return render_template('dummy.html')
Exemple #19
0
 def test_refreshing(self):
     app = flask.Flask(__name__)
     babel.Babel(app)
     d = datetime(2010, 4, 12, 13, 46)
     with app.test_request_context():
         assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM'
         app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna'
         babel.refresh()
         assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
Exemple #20
0
def set_language(lang='english'):
    if lang in ('english', 'french', 'spanish'):
        iso = LANGUAGES_MAP.get(lang, 'en')
        g.language_verbose = lang
    if lang in ('en', 'fr', 'es'):
        iso = lang
        g.language_verbose = LANGUAGES_ISO_MAP.get(lang, 'english')
    g.language = iso
    refresh()
Exemple #21
0
 def mutate(self, info, **kwargs):
     with session_scope():
         user = current_user._get_current_object()
         classic = kwargs.get("classic")
         if current_user.is_authenticated:
             user.settings.classic = classic
         session["classic"] = classic
         refresh()
         return ChangeClassic(ok=True)
Exemple #22
0
def set_locale():
    # define the user location
    user_locale = request.headers.get('Accept-Language')
    print(user_locale)
    # if there is no language set in the header
    if user_locale is None:
        g.user_locale = babel.default_locale
    else:
        g.user_locale = user_locale

    refresh()
Exemple #23
0
 def mutate(self, info, **kwargs):
     locale = kwargs.get("locale")
     if not locale in supported_languages:
         raise GraphQLError(_("Received unsupported locale."))
     with session_scope():
         user = current_user._get_current_object()
         if current_user.is_authenticated:
             user.locale = locale
         session["locale"] = locale
         refresh()
         return ChangeLocale(ok=True)
Exemple #24
0
def set_user_lang(lang=None):
    if lang not in constants.LANGUAGES.keys():
        flash(_('Language unsupported on this site') + ': ' + lang, 'warning')
        return redirect(url_for('home.home'))
    if current_user.is_anonymous:
        flash(_('You need to be logged in to set a permanent language.'))
        return redirect_back()

    current_user.locale = lang
    db.session.add(current_user)
    db.session.commit()
    refresh()
    return redirect_back()
Exemple #25
0
def test_refresh_during_force_locale():
    app = flask.Flask(__name__)
    b = babel.Babel(app)

    @b.localeselector
    def select_locale():
        return 'de_DE'

    with app.test_request_context():
        with babel.force_locale('en_US'):
            assert str(babel.get_locale()) == 'en_US'
            babel.refresh()
            assert str(babel.get_locale()) == 'en_US'
Exemple #26
0
def change_language(language):

    @babel.localeselector
    def get_locale():
        if language in languages:
            return language
        else:
            return request.accept_languages.best_match(languages)
    if current_user.is_authenticated:
        current_user.language = get_locale()
        db.session.commit()
    refresh()
    return redirect(request.referrer)
Exemple #27
0
    def get(self, server=None, client=None, conf=None):
        """Reads a given client configuration"""
        try:
            conf = unquote(conf)
        except:
            pass
        args = self.parser_get.parse_args()
        template = args.get("template", False)
        statictemplate = args.get("statictemplate", False)
        parser = bui.client.get_parser(agent=server)
        res = parser.read_client_conf(client, conf, template, statictemplate)
        refresh()
        # Translate the doc and placeholder API side
        cache_keys = {
            "doc": "_doc_parser_{}-{}".format(server, g.locale),
            "placeholders":
            "_placeholders_parser_{}-{}".format(server, g.locale),
            "boolean_cli": "_boolean_cli_parser_{}".format(server),
            "string_cli": "_string_cli_parser_{}".format(server),
            "integer_cli": "_integer_cli_parser_{}".format(server),
            "multi_cli": "_multi_cli_parser_{}".format(server),
            "values": "_suggest_parser_{}".format(server),
            "defaults": "_defaults_parser_{}".format(server),
        }
        cache_results = {}
        for name, key in cache_keys.items():
            if not cache.cache.has(key):
                if name in ["doc", "placeholders"]:
                    _tmp = bui.client.get_parser_attr(name, server).copy()
                    _tmp2 = {}
                    for k, v in _tmp.items():
                        _tmp2[k] = _(v)
                    cache_results[name] = _tmp2
                else:
                    cache_results[name] = bui.client.get_parser_attr(
                        name, server)
                cache.cache.set(key, cache_results[name], 3600)
            else:
                cache_results[name] = cache.cache.get(key)

        return jsonify(
            results=res,
            boolean=cache_results["boolean_cli"],
            string=cache_results["string_cli"],
            integer=cache_results["integer_cli"],
            multi=cache_results["multi_cli"],
            server_doc=cache_results["doc"],
            suggest=cache_results["values"],
            placeholders=cache_results["placeholders"],
            defaults=cache_results["defaults"],
        )
Exemple #28
0
 def get_locale():
     # Check if user is logged in, if so, use the users stored preferences
     if current_user.is_authenticated:
         if request.args.get('lang'):
             current_user.lang = request.args.get('lang')
             models.db.session.commit()
             flask_babel.refresh()
         return current_user.lang
     # Check the session cookie if the user isn't logged in
     else:
         if request.args.get('lang'):
             session['lang'] = request.args.get('lang')
             flask_babel.refresh()
         return session.get('lang', None)
Exemple #29
0
def edit(user_id: int):
    me = rest.iface.whoami()
    form = UsersForm(default_locale=me._locale, email=me._email)
    if form.validate_on_submit():

        data = prepare_data(request)
        rest.iface.update_user(user_id, data)

        # show the same month as the date of the item which was created/modified
        session["locale"] = data['default_locale']
        refresh()
        return redirect(url_for('users.index'))

    return render_template('users/edit.html', form=form, known_users=[me])
Exemple #30
0
def index(language="zh_Hans_CN"):
    session["language"] = language
    refresh()
    form = MyLoginForm()
    if flask.request.method == "GET":
        return render_template("index.html", form=form)
    else:
        if form.validate_on_submit():
            session["name"] = form.username.data
            return redirect(
                url_for('answer',
                        user=form.username.data,
                        num=form.numbers.data))
        else:
            return render_template("index.html", form=form)
    def r_set_language(self, code):
        """ Sets the session's language code which will be used for all requests

        :param code: The 2-letter language code
        :type code: str
        """
        session['locale'] = code
        refresh()
        if request.headers.get('X-Requested-With') == "XMLHttpRequest":
            return 'OK'
        else:
            flash(
                'Language Changed. You may need to refresh the page in your browser.'
            )
            return redirect(request.referrer)
Exemple #32
0
    def get(self, server=None, client=None, conf=None):
        """Reads a given client configuration"""
        try:
            conf = unquote(conf)
        except:
            pass
        args = self.parser_get.parse_args()
        template = args.get('template', False)
        parser = bui.client.get_parser(agent=server)
        res = parser.read_client_conf(client, conf, template)
        refresh()
        # Translate the doc and placeholder API side
        cache_keys = {
            'doc': '_doc_parser_{}-{}'.format(server, g.locale),
            'placeholders': '_placeholders_parser_{}-{}'.format(server, g.locale),
            'boolean_cli': '_boolean_cli_parser_{}'.format(server),
            'string_cli': '_string_cli_parser_{}'.format(server),
            'integer_cli': '_integer_cli_parser_{}'.format(server),
            'multi_cli': '_multi_cli_parser_{}'.format(server),
            'values': '_suggest_parser_{}'.format(server),
            'defaults': '_defaults_parser_{}'.format(server),
        }
        cache_results = {}
        for name, key in cache_keys.items():
            if not cache.cache.has(key):
                if name in ['doc', 'placeholders']:
                    _tmp = bui.client.get_parser_attr(name, server).copy()
                    _tmp2 = {}
                    for k, v in _tmp.items():
                        _tmp2[k] = _(v)
                    cache_results[name] = _tmp2
                else:
                    cache_results[name] = bui.client.get_parser_attr(name, server)
                cache.cache.set(key, cache_results[name], 3600)
            else:
                cache_results[name] = cache.cache.get(key)

        return jsonify(
            results=res,
            boolean=cache_results['boolean_cli'],
            string=cache_results['string_cli'],
            integer=cache_results['integer_cli'],
            multi=cache_results['multi_cli'],
            server_doc=cache_results['doc'],
            suggest=cache_results['values'],
            placeholders=cache_results['placeholders'],
            defaults=cache_results['defaults']
        )
Exemple #33
0
    def get(self, server=None, client=None, conf=None):
        """Reads a given client configuration"""
        try:
            conf = unquote(conf)
        except:
            pass
        args = self.parser_get.parse_args()
        template = args.get('template', False)
        parser = bui.client.get_parser(agent=server)
        res = parser.read_client_conf(client, conf, template)
        refresh()
        # Translate the doc and placeholder API side
        cache_keys = {
            'doc': '_doc_parser_{}-{}'.format(server, g.locale),
            'placeholders':
            '_placeholders_parser_{}-{}'.format(server, g.locale),
            'boolean_cli': '_boolean_cli_parser_{}'.format(server),
            'string_cli': '_string_cli_parser_{}'.format(server),
            'integer_cli': '_integer_cli_parser_{}'.format(server),
            'multi_cli': '_multi_cli_parser_{}'.format(server),
            'values': '_suggest_parser_{}'.format(server),
            'defaults': '_defaults_parser_{}'.format(server),
        }
        cache_results = {}
        for name, key in cache_keys.items():
            if not cache.cache.has(key):
                if name in ['doc', 'placeholders']:
                    _tmp = bui.client.get_parser_attr(name, server).copy()
                    _tmp2 = {}
                    for k, v in _tmp.items():
                        _tmp2[k] = _(v)
                    cache_results[name] = _tmp2
                else:
                    cache_results[name] = bui.client.get_parser_attr(
                        name, server)
                cache.cache.set(key, cache_results[name], 3600)
            else:
                cache_results[name] = cache.cache.get(key)

        return jsonify(results=res,
                       boolean=cache_results['boolean_cli'],
                       string=cache_results['string_cli'],
                       integer=cache_results['integer_cli'],
                       multi=cache_results['multi_cli'],
                       server_doc=cache_results['doc'],
                       suggest=cache_results['values'],
                       placeholders=cache_results['placeholders'],
                       defaults=cache_results['defaults'])
Exemple #34
0
def load_logged_in_user():
    auth_token = session.get('auth_token')

    if auth_token is None:
        g.user = None
        g.is_superuser = None
    else:
        try:
            user = rest.iface.whoami()
            user.locale = session['locale'] = user._locale
            refresh()
            g.user = user.get_id()
            g.is_superuser = user.is_superuser
        except rest.ApiException:
            session.clear()
            return redirect(url_for('auth.login'))
def language(previous, lang):
    if lang in app.config['LANGUAGES'] and app.config['SELECTED_LANGUAGE'] != lang:
        app.config.pop('ranking', None)
        app.config.pop('query', None)
        app.config.pop('query', None)
        app.config['SELECTED_LANGUAGE'] = lang

        global THEMES, THEME_CHOICES
        THEMES = MODEL.get_themes(app.config['SELECTED_LANGUAGE'])
        THEME_CHOICES.clear()

        for language_theme in THEMES:
            THEME_CHOICES.append((language_theme.id, language_theme.theme))

        refresh()
    return redirect(url_for(previous))
Exemple #36
0
def change_language():
    """
    Changes the session language locale and refreshes the Flask app context
    """
    locale = request.form.get("locale")
    session["language"] = locale
    ractl.locale = session["language"]
    file_cmds.locale = session["language"]
    refresh()

    language = Locale.parse(locale)
    language_name = language.get_language_name(locale)
    flash(
        _("Changed Web Interface language to %(locale)s",
          locale=language_name))
    return redirect(url_for("index"))
Exemple #37
0
def user_settings_reset() -> str:
    """
        Reset the user settings and redirect to the settings page.

        :return: The HTML response.
    """
    settings = current_user.settings
    reset_form = UserSettingsResetForm()
    if reset_form.validate_on_submit():

        # Reset and save.
        settings.reset()
        db.session.commit()

        # Refresh the language in case it changed.
        refresh()

        flash(_('The settings have been set to their default values.'))

    return redirect(url_for('.user_settings'))
Exemple #38
0
def user_settings() -> str:
    """
        Show a page to edit a user's settings. Upon submission, change the account details.

        :return: The HTML response.
    """

    settings = current_user.settings
    settings_form = UserSettingsForm(obj=settings)
    if settings_form.validate_on_submit():

        # Get the data from the form and save it.
        settings.language = settings_form.language.data
        db.session.commit()

        # Refresh the language to reflect possible changes to the user's language.
        refresh()

        flash(_('Your changes have been saved.'))
        return redirect(url_for('.user_settings'))

    reset_form = UserSettingsResetForm()
    return render_template('userprofile/user_settings.html', title=_('Settings'), settings_form=settings_form,
                           reset_form=reset_form)
 def init_request_locale():
     language_code = request.environ.get('LANGUAGE_CODE_FROM_URL')
     if language_code and language_code!=self.get_language_code():
         self.set_language_code(language_code)
         flask_babel.refresh()
def change_locale():
    session['language'] = request.args.get('locale')
    refresh()
    return jsonify(error=0)
Exemple #41
0
    def get(self, conf=None, server=None):
        """Reads the server configuration

        **GET** method provided by the webservice.

        The *JSON* returned is:
        ::

            {
              "boolean": [
                "daemon",
                "fork",
                "..."
              ],
              "defaults": {
                "address": "",
                "autoupgrade_dir": "",
                "ca_burp_ca": "",
                "ca_conf": "",
                "ca_name": "",
                "ca_server_name": "",
                "client_can_delete": true,
                "...": "..."
              },
              "integer": [
                "port",
                "status_port",
                "..."
              ],
              "multi": [
                "keep",
                "restore_client",
                "..."
              ],
              "placeholders": {
                "autoupgrade_dir": "path",
                "ca_burp_ca": "path",
                "ca_conf": "path",
                "ca_name": "name",
                "ca_server_name": "name",
                "client_can_delete": "0|1",
                "...": "..."
              },
              "results": {
                "boolean": [
                  {
                    "name": "hardlinked_archive",
                    "value": false,
                    "reset": false
                  },
                  {
                    "name": "syslog",
                    "value": true,
                    "reset": false
                  },
                  { "...": "..." }
                ],
                "clients": [
                  {
                    "name": "testclient",
                    "value": "/etc/burp/clientconfdir/testclient"
                  }
                ],
                "common": [
                  {
                    "name": "mode",
                    "value": "server",
                    "reset": false
                  },
                  {
                    "name": "directory",
                    "value": "/var/spool/burp",
                    "reset": false
                  },
                  { "...": "..." }
                ],
                "includes": [],
                "includes_ext": [],
                "integer": [
                  {
                    "name": "port",
                    "value": 4971,
                    "reset": false
                  },
                  {
                    "name": "status_port",
                    "value": 4972,
                    "reset": false
                  },
                  { "...": "..." }
                ],
                "multi": [
                  {
                    "name": "keep",
                    "value": [
                      "7",
                      "4"
                    ],
                    "reset": [
                      false,
                      true
                    ]
                  },
                  { "...": "..." }
                ],
                "hierarchy": [
                  {
                    "children": [
                      {
                        "children": [],
                        "dir": "/tmp/burp/conf.d",
                        "full": "/tmp/burp/conf.d/empty.conf",
                        "name": "empty.conf",
                        "parent": "/tmp/burp/burp-server.conf"
                      },
                      {
                        "children": [],
                        "dir": "/tmp/burp/conf.d",
                        "full": "/tmp/burp/conf.d/ipv4.conf",
                        "name": "ipv4.conf",
                        "parent": "/tmp/burp/burp-server.conf"
                      }
                    ],
                    "dir": "/tmp/burp",
                    "full": "/tmp/burp/burp-server.conf",
                    "name": "burp-server.conf",
                    "parent": null
                  }
                ]
              },
              "server_doc": {
                "address": "Defines the main TCP address...",
                "...": "..."
              },
              "string": [
                "mode",
                "address",
                "..."
              ],
              "suggest": {
                "compression": [
                  "gzip1",
                  "gzip2",
                  "gzip3",
                  "gzip4",
                  "gzip5",
                  "gzip6",
                  "gzip7",
                  "gzip8",
                  "gzip9"
                ],
                "mode": [
                  "client",
                  "server"
                ],
                "...": [
                  "..."
                ]
              }
            }


        :param server: Which server to collect data from when in multi-agent mode
        :type server: str

        :returns: The *JSON* described above.
        """
        try:
            conf = unquote(conf)
        except:
            pass
        res = bui.client.read_conf_srv(conf, server)
        refresh()
        # Translate the doc and placeholder API side
        cache_keys = {
            'doc': '_doc_parser_{}-{}'.format(server, g.locale),
            'placeholders': '_placeholders_parser_{}-{}'.format(server, g.locale),
            'boolean_srv': '_boolean_srv_parser_{}'.format(server),
            'string_srv': '_string_srv_parser_{}'.format(server),
            'integer_srv': '_integer_srv_parser_{}'.format(server),
            'multi_srv': '_multi_srv_parser_{}'.format(server),
            'values': '_suggest_parser_{}'.format(server),
            'defaults': '_defaults_parser_{}'.format(server),
            'advanced_type': '_advanced_parser_{}'.format(server),
            'pair_associations': '_pair_associations_parser_{}'.format(server),
        }
        cache_results = {}
        for name, key in cache_keys.items():
            if not cache.cache.has(key):
                if name in ['doc', 'placeholders']:
                    _tmp = bui.client.get_parser_attr(name, server).copy()
                    _tmp2 = {}
                    for k, v in _tmp.items():
                        _tmp2[k] = _(v)
                    cache_results[name] = _tmp2
                else:
                    cache_results[name] = bui.client.get_parser_attr(name, server)
                cache.cache.set(key, cache_results[name], 3600)
            else:
                cache_results[name] = cache.cache.get(key)

        return jsonify(results=res,
                       boolean=cache_results['boolean_srv'],
                       string=cache_results['string_srv'],
                       integer=cache_results['integer_srv'],
                       multi=cache_results['multi_srv'],
                       pair=cache_results['pair_associations'],
                       advanced=cache_results['advanced_type'],
                       server_doc=cache_results['doc'],
                       suggest=cache_results['values'],
                       placeholders=cache_results['placeholders'],
                       defaults=cache_results['defaults'])
Exemple #42
0
 def index(self, locale):
     session['locale'] = locale
     refresh()
     self.update_redirect()
     return redirect(self.get_redirect())
Exemple #43
0
def setlocale(locale):
    session['locale'] = locale
    refresh()
    return redirect(request.referrer)
Exemple #44
0
    template_folder='public/templates',
    static_folder='public/static'
)

app.config.from_object(__name__)
app.secret_key = (
    '9\xecv\xc4\xdb\xf7\x94a\xd1Q\xd1' +
    '\x9a\x10\xfc3\xe8{\\zxp\xa1o\x90'
)

app.config['BABEL_DEFAULT_TIMEZONE'] = 'America/Sao_Paulo'
app.config['BABEL_DEFAULT_LOCALE'] = 'pt'

babel = Babel(app, default_locale='pt')

refresh()

# login
login_manager = LoginManager()
login_manager.init_app(app)

# admin
admin = flask_admin.Admin(app, 'PySOS', index_view=PySOSAdminView())
admin.add_view(AttendantView())
admin.add_view(ClientView())
admin.add_view(DeviceModelView())
admin.add_view(DeviceBrandView())
admin.add_view(MobileOperatorView())
admin.add_view(ServiceOrderStatusView())
admin.add_view(ServiceOrderView())