コード例 #1
0
ファイル: update.py プロジェクト: ringo-framework/ringo
def update(request, callback=None, renderers=None,
           validators=None, values=None):
    """Base method to handle update requests. This view will render a
    update form to update items on (GET) requests.

    It the user submits the data (POST) that the data will be validated.
    If validation is successfull the item will be saved in the datebase
    and the callback method will be called. Finally a redirect to either
    the backurl or the edit or read mode of the item will be triggered.

    If the validation fails, the form will be rendered again.
    :request: Current request
    :callback: Current function which is called after the item has been read.
    :renderers: Dictionary of external renderers which should be used
                for renderering some form elements.
    :validators: List of external formbar validators which should be
                 added to the form for validation
    :values: Dictionary of additional values which will be available in
             the form
    :returns: Dictionary or Redirect.
    """
    handle_history(request)
    handle_params(request)
    if values is None:
        values = {}
    values['_roles'] = [str(r.name) for r in request.user.roles]
    form = get_item_form('update', request, renderers, validators, values)
    if request.POST:
        if handle_POST_request(form, request, callback, 'update', renderers):
            return handle_redirect_on_success(request)

    rvalues = get_return_value(request)
    rvalues['form'] = render_item_form(request, form, values)
    return rvalues
コード例 #2
0
ファイル: ownership.py プロジェクト: mjsorribas/ringo
def ownership(request, callback=None, renderers=None):
    """Base method to handle requests to change the ownership.

    :request: Current request
    :callback: Current function which is called after the item has been read.
    :returns: Dictionary.
    """
    handle_history(request)
    handle_params(request)
    clazz = request.context.__model__
    item_label = get_item_modul(request, clazz).get_label()
    form = get_ownership_form(request)
    if request.POST:
        item = get_item_from_request(request)
        old_gid = str(item.gid)
        old_uid = str(item.uid)
        new_gid = str(request.params.get('group'))
        new_uid = str(request.params.get('owner'))
        if handle_POST_request(form, request, callback, 'update', renderers):
            if old_uid != new_uid:
                log_msg = u'User {user.login} changed uid of {item_label} '\
                          '{item.id} from {old} -> {new}'\
                          .format(item_label=item_label, item=item, 
                                  user=request.user, old=old_uid, new=new_uid)
                log.info(log_msg)
            if old_gid != new_gid:
                log_msg = u'User {user.login} changed gid of {item_label} '\
                          '{item.id} from {old} -> {new}'\
                          .format(item_label=item_label, item=item, 
                                  user=request.user, old=old_gid, new=new_gid)
                log.info(log_msg)
            return handle_redirect_on_success(request)
    rvalues = get_return_value(request)
    rvalues['form'] = get_rendered_ownership_form(request)
    return rvalues
コード例 #3
0
ファイル: users.py プロジェクト: ringo-framework/ringo
def removeaccount(request):
    """Method to remove the useraccout by the user."""

    # Check authentification
    # The view is only available for authenticated users and callable
    # if the user is not the admin unser (id=1)
    id = request.matchdict.get('id')
    if not request.user or id == '1':
        raise HTTPUnauthorized

    clazz = User
    _ = request.translate
    handle_history(request)
    handle_params(request)
    # Load the item return 400 if the item can not be found.
    factory = clazz.get_item_factory()

    try:
        item = factory.load(id, request.db)
        # Check authorisation
        if item.id != request.user.id:
            raise HTTPForbidden()
    except sa.orm.exc.NoResultFound:
        raise HTTPBadRequest()

    form = Form(get_form_config(item, 'removeaccount'),
                item, request.db, translate=_,
                renderers={},
                change_page_callback={'url': 'set_current_form_page',
                                      'item': clazz.__tablename__,
                                      'itemid': id},
                request=request, csrf_token=request.session.get_csrf_token())

    if request.POST:
        mapping = {'item': item}
        if form.validate(request.params):
            # Delete the account and redirect the user to a result page
            request.db.delete(item)
            headers = forget(request)
            target_url = request.route_path('users-accountremoved')
            return HTTPFound(location=target_url, headers=headers)
        else:
            msg = _('Deleting the account of '
                    '"${item}" failed.', mapping=mapping)
            log.info(msg)
            request.session.flash(msg, 'error')

    rvalue = {}
    rvalue['clazz'] = clazz
    rvalue['item'] = item
    rvalue['form'] = form.render(page=get_current_form_page(clazz, request))
    return rvalue
コード例 #4
0
ファイル: read.py プロジェクト: ringo-framework/ringo
def read(request, callback=None, renderers=None):
    """Base method to handle read requests. Returns a dictionary of
    values used available in the rendererd template The template to
    render is defined in the view configuration.

    :request: Current request
    :callback: Current function which is called after the item has been read.
    :returns: Dictionary.
    """
    handle_history(request)
    handle_params(request)
    handle_callback(request, callback)
    rvalues = get_return_value(request)
    values = {'_roles': [str(r.name) for r in request.user.roles]}
    form = get_item_form('read', request, renderers, values=values)
    rvalues['form'] = render_item_form(request, form, values)
    return rvalues
コード例 #5
0
ファイル: read.py プロジェクト: reiterl/ringo
def read(request, callback=None, renderers=None):
    """Base method to handle read requests. Returns a dictionary of
    values used available in the rendererd template The template to
    render is defined in the view configuration.

    :request: Current request
    :callback: Current function which is called after the item has been read.
    :returns: Dictionary.
    """
    handle_params(request)
    handle_callback(request, callback, mode="pre,default")
    rvalues = get_return_value(request)
    values = {'_roles': [str(r.name) for r in request.user.roles]}
    form = get_item_form('read', request, renderers, values=values)
    rvalues['form'] = render_item_form(request, form)
    handle_callback(request, callback, mode="post")
    return rvalues
コード例 #6
0
def print_(request):
    handle_history(request)
    handle_params(request)
    item = get_item_from_request(request)
    renderer = PrintDialogRenderer(request, item)
    form = renderer.form
    if (request.method == 'POST' and is_confirmed(request)
            and form.validate(request.params)):
        template = form.data.get('printtemplates')[0]
        out = _render_template(request, template, item)
        return _build_final_response(out, request, template)
    else:
        clazz = item.__class__
        rvalue = {}
        rvalue['dialog'] = renderer.render()
        rvalue['clazz'] = clazz
        rvalue['item'] = item
        return rvalue
コード例 #7
0
def restore(request):
    clazz = request.context.__model__
    _ = request.translate
    handle_params(request)
    handle_history(request)
    item = get_item_from_request(request)
    item_label = get_item_modul(request, clazz).get_label(plural=True)
    mapping = {'item_type': item_label, 'item': item}
    item.trash_state_id = 1
    route_name = get_action_routename(item, 'update')
    url = request.route_path(route_name, id=item.id)

    msg = _('Restored ${item} from trash successfully.', mapping=mapping)
    log_msg = u'User {user.login} restored {item_label} {item.id}'.format(
        item_label=item_label, item=item, user=request.user)
    log.info(log_msg)
    request.session.flash(msg, 'success')

    transaction.commit()
    return HTTPFound(location=url)
コード例 #8
0
ファイル: import_.py プロジェクト: ringo-framework/ringo
def import_(request, callback=None):
    handle_history(request)
    handle_params(request)

    clazz = request.context.__model__
    _ = request.translate
    renderer = ImportDialogRenderer(request, clazz)
    imported_items = []
    form = renderer.form
    if request.method == "POST" and is_confirmed(request) and form.validate(request.params):
        try:
            items = _import(request)
        except (ValueError, AttributeError) as e:
            err_title = _("Import failed")
            err_msg = (
                _(
                    "Bad news! The import could not be finished and "
                    "returns with an error."
                    "No data has been modified in this operation and no "
                    "items has been imported or updated. "
                    "The last message we heard from the importer was: %s"
                )
                % e
            )
            renderer = ErrorDialogRenderer(request, err_title, err_msg)
            rvalue = {}
            ok_url = request.session["history"].pop(2)
            rvalue["dialog"] = renderer.render(ok_url)
            rvalue["clazz"] = clazz
            return rvalue

        imported_items = _handle_save(request, items, callback)
        invalidate_cache()
        redirect = _handle_redirect(request)
        if redirect:
            return redirect
    rvalue = {}
    rvalue["dialog"] = renderer.render(imported_items)
    rvalue["clazz"] = clazz
    return rvalue
コード例 #9
0
ファイル: create.py プロジェクト: mjsorribas/ringo
def create(request, callback=None, renderers=None, validators=None):
    """Base method to handle create requests. This view will render a
    create form to update items on (GET) requests.

    It the user submits the data (POST) that the data will be validated.
    If validation is successfull the item will be saved in the datebase
    and the callback method will be called. Finally a redirect to either
    the backurl or the edit or read mode of the item will be triggered.

    If the validation fails, the form will be rendered again.

    :request: Current request
    :callback: Current function which is called after the item has been read.
    :renderers: Dictionary of external renderers which should be used
                for renderering some form elements.
    :validators: List of external formbar validators which should be
                 added to the form for validation
    :returns: Dictionary or Redirect.
    """
    handle_history(request)
    params = handle_params(request)

    # Create a new item
    clazz = request.context.__model__
    try:
        factory = clazz.get_item_factory(request)
    except TypeError:
        # Old version of get_item_factory method which does not take an
        # request parameter.
        factory = clazz.get_item_factory()
        factory._request = request
    # Only create a new item if there isn't already an item in the
    # request.context. This can happen if we define a custom view for
    # create where the item gets created before to set some default
    # values e.g (See create function of forms)
    if not request.context.item:
        request.context.item = factory.create(request.user, {})
    form = get_item_form(params.get("form", "create"),
                         request, renderers, validators)
    if request.POST and 'blobforms' not in request.params:
        if handle_POST_request(form, request, callback, 'create', renderers):
            return handle_redirect_on_success(request)
    rvalues = get_return_value(request)
    values = {'_roles': [str(r.name) for r in request.user.roles]}
    values.update(params.get('values', {}))
    rvalues['form'] = render_item_form(request, form, values, False)
    return rvalues
コード例 #10
0
def anonymize(request):
    handle_history(request)
    handle_params(request)
    item = get_item_from_request(request)
    return _handle_anonymize_request(request, [item])
コード例 #11
0
ファイル: create.py プロジェクト: toirl/ringo
def create(request, callback=None, renderers=None,
           validators=None, values=None):
    """Base method to handle create requests. This view will render a
    create form to update items on (GET) requests.

    It the user submits the data (POST) that the data will be validated.
    If validation is successfull the item will be saved in the datebase
    and the callback method will be called. Finally a redirect to either
    the backurl or the edit or read mode of the item will be triggered.

    If the validation fails, the form will be rendered again.

    :request: Current request
    :callback: Current function which is called after the item has been read.
    :renderers: Dictionary of external renderers which should be used
                for renderering some form elements.
    :validators: List of external formbar validators which should be
                 added to the form for validation
    :values: Dictionary of additional values which will be available in
             the form
    :returns: Dictionary or Redirect.
    """
    handle_history(request)
    params = handle_params(request)

    # Create a new item
    clazz = request.context.__model__
    try:
        factory = clazz.get_item_factory(request)
    except TypeError:
        # Old version of get_item_factory method which does not take an
        # request parameter.
        factory = clazz.get_item_factory()
        factory._request = request
    # Only create a new item if there isn't already an item in the
    # request.context. This can happen if we define a custom view for
    # create where the item gets created before to set some default
    # values e.g (See create function of forms)
    if not request.context.item:
        request.context.item = factory.create(request.user, {})
    if values is None:
        values = {}
    values['_roles'] = [str(r.name) for r in request.user.roles]
    values.update(params.get('values', {}))

    #  FIXME: "form_values" seems to be only used in one single
    #  application (efa). For now we will leave this here to not break
    #  any things but it should be removed.
    #  See https://github.com/ringo-framework/ringo/issues/31
    #  (ti) <2016-10-18 21:51>
    form_values = request.session.get("form_values") or {}
    values.update(form_values)
    request.session["form_values"] = None
    request.session.save()

    form = get_item_form(params.get("form", "create"),
                         request, renderers, validators, values=values)
    if request.POST and 'blobforms' not in request.params:
        if handle_POST_request(form, request, callback, 'create', renderers):
            return handle_redirect_on_success(request)
    rvalues = get_return_value(request)
    rvalues['form'] = render_item_form(request, form, validate=False)
    return rvalues
コード例 #12
0
ファイル: delete.py プロジェクト: ringo-framework/ringo
def delete(request, callback=None):
    item = get_item_from_request(request)
    handle_history(request)
    handle_params(request)
    return _handle_delete_request(request, [item], callback)
コード例 #13
0
ファイル: export.py プロジェクト: ringo-framework/ringo
def export(request):
    handle_history(request)
    handle_params(request)
    item = get_item_from_request(request)
    return _handle_export_request(request, [item])
コード例 #14
0
ファイル: list_.py プロジェクト: mjsorribas/ringo
def bundle_(request):
    clazz = request.context.__model__
    module = get_item_modul(request, clazz)
    handle_history(request)
    handle_params(request)
    _ = request.translate

    # Handle bundle params. If the request has the bundle_action param
    # the request is the intial request for a bundled action. In this
    # case we can delete all previous selected and stored item ids in
    # the session.
    params = request.params.mixed()
    if params.get('bundle_action'):
        request.session['%s.bundle.action' % clazz] = params.get('bundle_action')
        try:
            del request.session['%s.bundle.items' % clazz]
        except KeyError:
            pass
        request.session['%s.bundle.items' % clazz] = params.get('id', [])
    bundle_action = request.session.get('%s.bundle.action' % clazz)
    ids = request.session.get('%s.bundle.items' % clazz)

    # Check if the user selected at least one item. If not show an
    # dialog informing that the selection is empty.
    if not ids:
        title =  _("Empty selection")
        body =  _("You have not selected any item in the list. "
                  "Click 'OK' to return to the overview.")
        renderer = WarningDialogRenderer(request, title, body)
        rvalue = {}
        rvalue['dialog'] = literal(renderer.render(url=request.referrer))
        return rvalue

    # If the user only selects one single item it is not a list. So
    # convert it to a list with one item.
    if not isinstance(ids, list):
        ids = [ids]

    factory = clazz.get_item_factory()
    items = []
    ignored_items = []
    for id in ids:
        # Check if the user is allowed to call the requested action on
        # the loaded item. If so append it the the bundle, if not ignore
        # it.
        item = factory.load(id)
        if has_permission(bundle_action.lower(), item, request):
            items.append(item)
        else:
            ignored_items.append(item)

    # After checking the permissions the list of items might be empty.
    # If so show a warning to the user to inform him that the selected
    # action is not applicable.
    if not items:
        title = _("${action} not applicable",
                  mapping={"action": bundle_action})
        body = _("After checking the permissions no items remain "
                 "for which an '${action}' can be performed. "
                 "(${num} items were filtered out.)",
                 mapping={"action": bundle_action,
                          "num": len(ignored_items)})
        renderer = WarningDialogRenderer(request, title, body)
        rvalue = {}
        rvalue['dialog'] = literal(renderer.render(url=request.referrer))
        return rvalue

    handler = get_bundle_action_handler(_bundle_request_handlers,
                                        bundle_action.lower(),
                                        module.name)
    return handler(request, items, None)
コード例 #15
0
def evaluate(request):
    handle_history(request)
    handle_params(request)
    item = get_item_from_request(request)
    return _handle_evaluation_request(request, [item])
コード例 #16
0
ファイル: users.py プロジェクト: ringo-framework/ringo
def changepassword(request):
    """Method to change the users password by the user. The user user
    musst provide his old and the new pasword. Users are only allowed to
    change their own password."""

    # Check authentification
    # As this view has now security configured it is
    # generally callable by all users. For this reason we first check if
    # the user is authenticated. If the user is not authenticated the
    # raise an 401 (unauthorized) exception.
    if not request.user:
        raise HTTPUnauthorized

    clazz = User
    handle_history(request)
    handle_params(request)
    _ = request.translate
    rvalue = {}
    # Load the item return 400 if the item can not be found.
    id = request.matchdict.get('id')
    factory = clazz.get_item_factory()
    try:
        item = factory.load(id, request.db)
        # Check authorisation
        # User are only allowed to set their own password.
        if item.id != request.user.id:
            raise HTTPForbidden()
    except sa.orm.exc.NoResultFound:
        raise HTTPBadRequest()

    form = Form(get_form_config(item, 'changepassword'),
                item, request.db, translate=_,
                renderers={},
                change_page_callback={'url': 'set_current_form_page',
                                      'item': clazz.__tablename__,
                                      'itemid': id},
                request=request, csrf_token=request.session.get_csrf_token())

    if request.POST:
        mapping = {'item': item}
        # Do extra validation which is not handled by formbar.
        # Is the provided old password correct?
        validator = Validator('oldpassword',
                              _('The given password is not correct'),
                              check_password)
        pw_len_validator = Validator('password',
                                     _('Password must be at least 12 '
                                       'characters long.'),
                                     password_minlength_validator)
        pw_nonchar_validator = Validator('password',
                                         _('Password must contain at least 2 '
                                           'non-letters.'),
                                         password_nonletter_validator)

        form.add_validator(validator)
        form.add_validator(pw_len_validator)
        form.add_validator(pw_nonchar_validator)
        if form.validate(request.params):
            form.save()
            # Actually save the password. This is not done in the form
            # as the password needs to be encrypted.
            encrypt_password_callback(request, item)
            msg = _('Changed password for "${item}" successfull.',
                    mapping=mapping)
            log.info(msg)
            request.session.flash(msg, 'success')
            route_name = get_action_routename(item, 'changepassword')
            url = request.route_path(route_name, id=item.id)
            # Invalidate cache
            invalidate_cache()
            return HTTPFound(location=url)
        else:
            msg = _('Error on changing the password for '
                    '"${item}".', mapping=mapping)
            log.info(msg)
            request.session.flash(msg, 'error')

    rvalue['clazz'] = clazz
    rvalue['item'] = item
    rvalue['form'] = form.render(page=get_current_form_page(clazz, request))
    return rvalue