Beispiel #1
0
def admin_logo(id_: Optional[int] = None) -> Union[str, Response]:
    if g.settings['logo_file_id']:
        abort(418)  # pragma: no cover - Logo already set
    if id_:
        Settings.set_logo(id_)
        return redirect(f"{url_for('admin_index')}#tab-file")
    table = Table([''] + g.table_headers['file'] + ['date'])
    for entity in Entity.get_display_files():
        date = 'N/A'
        if entity.id in g.file_stats:
            date = format_date(
                datetime.datetime.utcfromtimestamp(
                    g.file_stats[entity.id]['date']))
        table.rows.append([
            link(_('set'), url_for('admin_logo', id_=entity.id)), entity.name,
            link(entity.standard_type), g.file_stats[entity.id]['size']
            if entity.id in g.file_stats else 'N/A',
            g.file_stats[entity.id]['ext']
            if entity.id in g.file_stats else 'N/A', entity.description, date
        ])
    return render_template(
        'admin/logo.html',
        table=table,
        title=_('logo'),
        crumbs=[[_('admin'), f"{url_for('admin_index')}#tab-files"],
                _('logo')])
Beispiel #2
0
def admin_settings(category: str) -> Union[str, Response]:
    if category in ['general', 'mail'] and not is_authorized('admin'):
        abort(403)  # pragma: no cover
    form = getattr(importlib.import_module('openatlas.forms.setting'),
                   uc_first(category) + 'Form')()  # Get forms dynamically
    if form.validate_on_submit():
        Transaction.begin()
        try:
            Settings.update(form)
            logger.log('info', 'settings', 'Settings updated')
            Transaction.commit()
            flash(_('info update'), 'info')
        except Exception as e:  # pragma: no cover
            Transaction.rollback()
            logger.log('error', 'database', 'transaction failed', e)
            flash(_('error transaction'), 'error')
        tab = 'data' if category == 'api' else category
        tab = 'email' if category == 'mail' else tab
        return redirect(url_for('admin_index') + '#tab-' + tab)
    set_form_settings(form)
    return render_template('display_form.html',
                           form=form,
                           manual_page='admin/' + category,
                           title=_('admin'),
                           crumbs=[[
                               _('admin'),
                               url_for('admin_index') + '#tab-' +
                               ('data' if category == 'api' else category)
                           ],
                                   _(category)])
Beispiel #3
0
def before_request() -> None:
    from openatlas.models.openatlas_class import (OpenatlasClass,
                                                  view_class_mapping)
    from openatlas.models.cidoc_property import CidocProperty
    from openatlas.models.cidoc_class import CidocClass
    from openatlas.models.type import Type
    from openatlas.models.settings import Settings
    from openatlas.models.reference_system import ReferenceSystem

    if request.path.startswith('/static'):  # pragma: no cover
        return  # Avoid overhead for files if not using Apache with static alias
    open_connection(app.config)
    g.settings = Settings.get_settings()
    session['language'] = get_locale()
    g.cidoc_classes = CidocClass.get_all()
    g.properties = CidocProperty.get_all()
    g.classes = OpenatlasClass.get_all()
    g.types = Type.get_all()
    g.reference_systems = ReferenceSystem.get_all()
    g.view_class_mapping = view_class_mapping
    g.class_view_mapping = OpenatlasClass.get_class_view_mapping()
    g.table_headers = OpenatlasClass.get_table_headers()
    g.file_stats = get_file_stats()

    # Set max file upload in MB
    app.config['MAX_CONTENT_LENGTH'] = \
        g.settings['file_upload_max_size'] * 1024 * 1024

    if request.path.startswith('/api/'):
        ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        if not current_user.is_authenticated \
                and not g.settings['api_public'] \
                and ip not in app.config['ALLOWED_IPS']:
            raise AccessDeniedError  # pragma: no cover
Beispiel #4
0
def admin_settings(category: str) -> Union[str, Response]:
    if category in ['general', 'mail'] and not is_authorized('admin'):
        abort(403)  # pragma: no cover
    form_name = f"{uc_first(category)}Form"
    form = getattr(
        importlib.import_module('openatlas.forms.setting'),
        form_name)()
    if form.validate_on_submit():
        data = {}
        for field in form:
            if field.type in ['CSRFTokenField', 'HiddenField', 'SubmitField']:
                continue
            value = field.data
            if field.type == 'BooleanField':
                value = 'True' if field.data else ''
            data[field.name] = value
        Transaction.begin()
        try:
            Settings.update(data)
            logger.log('info', 'settings', 'Settings updated')
            Transaction.commit()
            flash(_('info update'), 'info')
        except Exception as e:  # pragma: no cover
            Transaction.rollback()
            logger.log('error', 'database', 'transaction failed', e)
            flash(_('error transaction'), 'error')
        return redirect(
            f"{url_for('admin_index')}"
            f"#tab-{category.replace('api', 'data').replace('mail', 'email')}")
    set_form_settings(form)
    return render_template(
        'display_form.html',
        form=form,
        manual_page=f"admin/{category}",
        title=_('admin'),
        crumbs=[
            [
                _('admin'),
                f"{url_for('admin_index')}"
                f"#tab-{'data' if category == 'api' else category}"],
            _(category)])
Beispiel #5
0
def before_request() -> None:
    from openatlas.models.model import CidocClass, CidocProperty
    from openatlas.models.node import Node
    from openatlas.models.settings import Settings
    from openatlas.models.reference_system import ReferenceSystem
    if request.path.startswith('/static'):  # pragma: no cover
        return  # Only needed if not running with Apache and static alias
    open_connection(app.config)
    session['settings'] = Settings.get_settings()
    session['language'] = get_locale()
    g.cidoc_classes = CidocClass.get_all()
    g.properties = CidocProperty.get_all()

    from openatlas.models import system
    g.table_headers = system.get_table_headers()
    g.classes = system.get_system_classes()
    g.view_class_mapping = system.view_class_mapping
    g.class_view_mapping = system.get_class_view_mapping()
    g.nodes = Node.get_all_nodes()
    g.reference_systems = ReferenceSystem.get_all()

    # Set max file upload in MB
    app.config['MAX_CONTENT_LENGTH'] = session['settings'][
        'file_upload_max_size'] * 1024 * 1024
Beispiel #6
0
def admin_index(action: Optional[str] = None,
                id_: Optional[int] = None) -> Union[str, Response]:
    if is_authorized('manager'):
        if id_ and action == 'delete_user':
            user = User.get_by_id(id_)
            if not user \
                    or user.id == current_user.id \
                    or (user.group == 'admin' and not is_authorized('admin')):
                abort(403)
            User.delete(id_)
            flash(_('user deleted'), 'info')
        elif action == 'remove_logo':
            Settings.set_logo()
            return redirect(f"{url_for('admin_index')}#tab-file")
    tables = {
        'user':
        Table([
            'username', 'name', 'group', 'email', 'newsletter', 'created',
            'last login', 'entities'
        ],
              defs=[{
                  'className': 'dt-body-right',
                  'targets': 7
              }]),
        'content':
        Table(['name'] + list(app.config['LANGUAGES']))
    }
    for user in User.get_all():
        count = User.get_created_entities_count(user.id)
        email = user.email \
            if is_authorized('manager') or user.settings['show_email'] else ''
        tables['user'].rows.append([
            link(user), user.real_name, user.group, email,
            _('yes') if user.settings['newsletter'] else '',
            format_date(user.created),
            format_date(user.login_last_success),
            format_number(count) if count else ''
        ])
    for item, languages in get_content().items():
        content = [uc_first(_(item))]
        for language in app.config['LANGUAGES']:
            content.append(sanitize(languages[language], 'text'))
        content.append(link(_('edit'), url_for('admin_content', item=item)))
        tables['content'].rows.append(content)
    form = None
    if is_authorized('admin'):
        form = TestMailForm()
        if form.validate_on_submit(
        ) and g.settings['mail']:  # pragma: no cover
            subject = _('Test mail from %(site_name)s',
                        site_name=g.settings['site_name'])
            body = _('This test mail was sent by %(username)s',
                     username=current_user.username)
            body += f" {_('at')} '{request.headers['Host']}"
            if send_mail(subject, body, form.receiver.data):
                flash(
                    _('A test mail was sent to %(email)s.',
                      email=form.receiver.data), 'info')
        else:
            form.receiver.data = current_user.email
    tabs = {
        'files':
        Tab(_('files'),
            buttons=[
                manual('entity/file'),
                button(_('edit'), url_for('admin_settings', category='files'))
                if is_authorized('manager') else '',
                button(_('list'), url_for('index', view='file')),
                button(_('file'), url_for('insert', class_='file'))
            ],
            content=render_template('admin/file.html',
                                    info=get_form_settings(FilesForm()),
                                    disk_space_info=get_disk_space_info())),
        'user':
        Tab(_('user'),
            table=tables['user'],
            buttons=[
                manual('admin/user'),
                button(_('activity'), url_for('user_activity')),
                button(_('newsletter'), url_for('admin_newsletter'))
                if is_authorized('manager') and g.settings['mail'] else '',
                button(_('user'), url_for('user_insert'))
                if is_authorized('manager') else ''
            ])
    }
    if is_authorized('admin'):
        tabs['general'] = Tab(
            'general',
            content=display_info(get_form_settings(GeneralForm())),
            buttons=[
                manual('admin/general'),
                button(_('edit'), url_for('admin_settings',
                                          category='general')),
                button(_('system log'), url_for('admin_log'))
            ])
        tabs['email'] = Tab(
            'email',
            content=display_info(get_form_settings(MailForm())),
            buttons=[
                manual('admin/mail'),
                button(_('edit'), url_for('admin_settings', category='mail'))
            ])
        if g.settings['mail']:
            tabs['email'].content += display_form(form)
    if is_authorized('manager'):
        tabs['modules'] = Tab(_('modules'),
                              content=f"""
                <h1>{_('Defaults for new user')}</h1>
                {display_info(get_form_settings(ModulesForm()))}""",
                              buttons=[
                                  manual('admin/modules'),
                                  button(
                                      _('edit'),
                                      url_for('admin_settings',
                                              category='modules'))
                              ])
        tabs['map'] = Tab('map',
                          content=display_info(get_form_settings(MapForm())),
                          buttons=[
                              manual('admin/map'),
                              button(_('edit'),
                                     url_for('admin_settings', category='map'))
                          ])
        tabs['content'] = Tab('content',
                              content=tables['content'].display(),
                              buttons=[manual('admin/content')])
    if is_authorized('contributor'):
        tabs['data'] = Tab('data',
                           content=render_template(
                               'admin/data.html',
                               imports=Import.get_all_projects(),
                               info=get_form_settings(ApiForm())))
    return render_template('tabs.html',
                           tabs=tabs,
                           title=_('admin'),
                           crumbs=[_('admin')])
Beispiel #7
0
def admin_index(action: Optional[str] = None,
                id_: Optional[int] = None) -> Union[str, Response]:
    if is_authorized('manager'):
        if id_ and action == 'delete_user':
            user = User.get_by_id(id_)
            if not user \
                    or user.id == current_user.id \
                    or (user.group == 'admin' and not is_authorized('admin')):
                abort(403)  # pragma: no cover
            User.delete(id_)
            flash(_('user deleted'), 'info')
        elif action == 'remove_logo':
            Settings.set_logo()
            return redirect(url_for('admin_index') + '#tab-file')
    dirs = {
        'uploads':
        True if os.access(app.config['UPLOAD_DIR'], os.W_OK) else False,
        'export/sql':
        True if os.access(app.config['EXPORT_DIR'] /
                          'sql', os.W_OK) else False,
        'export/csv':
        True if os.access(app.config['EXPORT_DIR'] / 'csv', os.W_OK) else False
    }
    tables = {
        'user':
        Table([
            'username', 'name', 'group', 'email', 'newsletter', 'created',
            'last login', 'entities'
        ]),
        'content':
        Table(['name'] +
              [language for language in app.config['LANGUAGES'].keys()])
    }
    for user in User.get_all():
        count = User.get_created_entities_count(user.id)
        email = user.email if is_authorized(
            'manager') or user.settings['show_email'] else ''
        tables['user'].rows.append([
            link(user), user.real_name, user.group, email,
            _('yes') if user.settings['newsletter'] else '',
            format_date(user.created),
            format_date(user.login_last_success),
            format_number(count) if count else ''
        ])
    for item, languages in Content.get_content().items():
        content = [uc_first(_(item))]
        for language in app.config['LANGUAGES'].keys():
            content.append(sanitize(languages[language], 'text'))
        content.append(link(_('edit'), url_for('admin_content', item=item)))
        tables['content'].rows.append(content)
    form = None
    if is_authorized('admin'):
        form = TestMailForm()
        if form.validate_on_submit(
        ) and session['settings']['mail']:  # pragma: no cover
            subject = _('Test mail from %(site_name)s',
                        site_name=session['settings']['site_name'])
            body = _('This test mail was sent by %(username)s',
                     username=current_user.username)
            body += ' ' + _('at') + ' ' + request.headers['Host']
            if send_mail(subject, body, form.receiver.data):
                flash(
                    _('A test mail was sent to %(email)s.',
                      email=form.receiver.data), 'info')
        else:
            form.receiver.data = current_user.email
    return render_template('admin/index.html',
                           form=form,
                           tables=tables,
                           settings=session['settings'],
                           writeable_dirs=dirs,
                           disk_space_info=get_disk_space_info(),
                           imports=Import.get_all_projects(),
                           title=_('admin'),
                           crumbs=[_('admin')],
                           info={
                               'file': get_form_settings(FilesForm()),
                               'general': get_form_settings(GeneralForm()),
                               'mail': get_form_settings(MailForm()),
                               'map': get_form_settings(MapForm()),
                               'api': get_form_settings(ApiForm()),
                               'modules': get_form_settings(ModulesForm())
                           })