Example #1
0
def login(request):
    handle_history(request)
    _ = request.translate
    settings = request.registry.settings
    config = Config(load(get_path_to_form_config('auth.xml', 'ringo')))
    form_config = config.get_form('loginform')
    form = Form(form_config, csrf_token=request.session.get_csrf_token(),
                translate=_)
    if request.POST:
        form.validate(request.params)
        username = form.data.get('login')
        password = form.data.get('pass')
        user = user_login(username, password)
        if user is None:
            msg = _("Login failed!")
            request.session.flash(msg, 'error')
        elif not user.activated:
            msg = _("Login failed!")
            request.session.flash(msg, 'error')
            target_url = request.route_path('accountdisabled')
            return HTTPFound(location=target_url)
        else:
            msg = _("Login was successfull")
            request.session.flash(msg, 'success')
            headers = remember(request, user.id)
            target_url = request.route_path('home')
            return HTTPFound(location=target_url, headers=headers)

    return {'form': form.render(),
            'registration_enabled': is_registration_enabled(settings),
            'pwreminder_enabled': is_pwreminder_enabled(settings)}
Example #2
0
def forgot_password(request):
    settings = request.registry.settings
    if not is_pwreminder_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    config = Config(load(get_path_to_form_config('auth.xml')))
    form_config = config.get_form('forgot_password')
    form = Form(form_config, csrf_token=request.session.get_csrf_token(),
                translate=_)
    complete = False
    if request.POST:
        if form.validate(request.params):
            username = form.data.get('login')
            user = request_password_reset(username, request.db)
            if user:
                mailer = Mailer(request)
                recipient = user.profile[0].email
                token = user.reset_tokens[-1]
                subject = _('Password reset request')
                values = {'url': request.route_url('reset_password',
                                                   token=token),
                          'app_name': get_app_title(),
                          'email': settings['mail.default_sender'],
                          '_': _}
                mail = Mail([recipient],
                            subject,
                            template="password_reset_request",
                            values=values)
                mailer.send(mail)
            msg = _("Password reset token has been sent to the users "
                    "email address. Please check your email.")
            request.session.flash(msg, 'success')
            complete = True
    return {'form': form.render(), 'complete': complete}
Example #3
0
File: auth.py Project: toirl/ringo
def reset_password(request):
    settings = request.registry.settings
    if not is_pwreminder_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    success = False
    token = request.matchdict.get('token')
    user, password = password_reset(token, request.db)
    if password:
        mailer = Mailer(request)
        recipient = user.profile[0].email
        subject = _('Password has been reseted')
        values = {'password': password,
                  'app_name': get_app_title(),
                  'email': settings['mail.default_sender'],
                  '_': _}
        mail = Mail([recipient],
                    subject,
                    template="password_reminder",
                    values=values)
        mailer.send(mail)
        msg = _("Password was resetted and sent to the users email address."
                " Please check your email.")
        success = True
    else:
        msg = _("Password was not resetted. Maybe the request"
                " token was not valid?")
    return {'msg': msg, 'success': success}
Example #4
0
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
Example #5
0
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
Example #6
0
def logout(request):
    handle_history(request)
    _ = request.translate
    target_url = request.route_path('home')
    if request.params.get('autologout'):
        target_url = request.route_path('autologout')
    headers = forget(request)
    msg = _("Logout was successfull")
    request.session.flash(msg, 'success')
    return HTTPFound(location=target_url, headers=headers)
Example #7
0
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
Example #8
0
File: auth.py Project: toirl/ringo
def confirm_user(request):
    settings = request.registry.settings
    if not is_registration_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    success = False
    token = request.matchdict.get('token')
    user = activate_user(token, request.db)
    if user:
        success = True
        msg = _("The user has beed successfull confirmed.")
    else:
        msg = _("The user was not confirmed. Maybe the confirmation"
                " token was not valid?")
    return {'msg': msg, 'success': success}
Example #9
0
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
Example #10
0
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
Example #11
0
File: auth.py Project: toirl/ringo
def login(request):
    handle_history(request)
    _ = request.translate
    settings = request.registry.settings
    config = Config(load(get_path_to_form_config('auth.xml')))
    form_config = config.get_form('loginform')
    form = Form(form_config, csrf_token=request.session.get_csrf_token(),
                translate=_)
    if request.POST:
        form.validate(request.params)
        username = form.data.get('login')
        password = form.data.get('pass')
        user = user_login(username, password)
        if user is None:
            msg = _("Login failed!")
            request.session.flash(msg, 'error')
        elif not user.activated:
            msg = _("Login failed!")
            request.session.flash(msg, 'error')
            target_url = request.route_path('accountdisabled')
            return HTTPFound(location=target_url)
        else:

            # Handle authentication callback.
            if is_authcallback_enabled(settings):
                authenticated = False
                try:
                    callback = dynamic_import(settings.get("auth.callback"))
                    callback(request, user)
                    authenticated = True
                except AuthentificationException as e:
                    msg = e.message
                    request.session.flash(msg, 'critical')
            else:
                authenticated = True

            if authenticated:
                msg = _("Login was successfull")
                request.session.flash(msg, 'success')
                headers = remember(request, user.id)
                target_url = request.route_path('home')
                return HTTPFound(location=target_url, headers=headers)

    return {'form': form.render(),
            'registration_enabled': is_registration_enabled(settings),
            'pwreminder_enabled': is_pwreminder_enabled(settings)}
Example #12
0
def version_view(request):
    # Fetch the versions of some Packages
    # Ringo
    handle_history(request)
    values = {}
    formbar_pkg = pkg_resources.get_distribution('formbar')
    sqla_pkg = pkg_resources.get_distribution('sqlalchemy')
    pyramid_pkg = pkg_resources.get_distribution('pyramid')
    values['app_title'] = get_app_title()
    values['app_version'] = get_app_version()
    values['app_name'] = get_app_name()
    values['ringo_version'] = get_ringo_version()
    values['app_version'] = get_app_version()
    values['formbar_version'] = formbar_pkg.version
    values['sqlalchemy_version'] = sqla_pkg.version
    values['pyramid_version'] = pyramid_pkg.version
    return values
Example #13
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
Example #14
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)
Example #15
0
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
Example #16
0
def register_user(request):
    settings = request.registry.settings
    if not is_registration_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    config = Config(load(get_path_to_form_config('auth.xml', 'ringo')))
    form_config = config.get_form('register_user')
    form = Form(form_config, csrf_token=request.session.get_csrf_token(),
                translate=_)
    # Do extra validation which is not handled by formbar.
    # Is the login unique?
    validator = Validator('login',
                          'There is already a user with this name',
                          is_login_unique)
    form.add_validator(validator)
    if request.POST:
        if form.validate(request.params):
            # 1. Create user. Do not activate him. Default role is user.
            ufac = User.get_item_factory()
            user = ufac.create(None, form.data)
            # Set login from formdata
            user.login = form.data['login']
            # Encrypt password and save
            user.password = encrypt_password(form.data['pass'])
            # Deactivate the user. To activate the user needs to confirm
            # with the activation link
            user.activated = False
            atoken = str(uuid.uuid4())
            user.activation_token = atoken
            # Set profile data
            user.profile[0].email = form.data['_email']

            # 2. Set user group
            gfac = Usergroup.get_item_factory()
            group = gfac.load(USER_GROUP_ID)
            user.groups.append(group)

            # 3. Set user role
            rfac = Role.get_item_factory()
            role = rfac.load(USER_ROLE_ID)
            user.roles.append(role)
            # Set default user group.
            request.db.add(user)

            # 4. Send confirmation email. The user will be activated
            #    after the user clicks on the confirmation link
            mailer = Mailer(request)
            recipient = user.profile[0].email
            subject = _('Confirm user registration')
            values = {'url': request.route_url('confirm_user', token=atoken),
                      'app_name': get_app_title(),
                      'email': settings['mail.default_sender'],
                      '_': _}
            mail = Mail([recipient], subject, template="register_user", values=values)
            mailer.send(mail)

            target_url = request.route_path('login')
            headers = forget(request)
            msg = _("User has been created and a confirmation mail was sent"
                    " to the users email adress. Please check your email.")
            request.session.flash(msg, 'success')
            return HTTPFound(location=target_url, headers=headers)
    return {'form': form.render()}
Example #17
0
def anonymize(request):
    handle_history(request)
    handle_params(request)
    item = get_item_from_request(request)
    return _handle_anonymize_request(request, [item])
Example #18
0
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
Example #19
0
def contact_view(request):
    handle_history(request)
    return {}
Example #20
0
def about_view(request):
    handle_history(request)
    values = {}
    values['app_title'] = get_app_title()
    return values
Example #21
0
def index_view(request):
    handle_history(request)
    values = {}
    return values
Example #22
0
def evaluate(request):
    handle_history(request)
    handle_params(request)
    item = get_item_from_request(request)
    return _handle_evaluation_request(request, [item])
Example #23
0
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)
Example #24
0
def list_(request):
    clazz = request.context.__model__
    # Important! Prevent any write access on the database for this
    # request. This is needed as transform would modify the items values
    # else.
    handle_history(request)

    # If the user enters the overview page of an item we assume that the
    # user actually leaves any context where a former set backurl is
    # relevant anymore. So delete it.
    backurl = request.session.get('%s.backurl' % clazz)
    if backurl:
        # Redirect to the configured backurl.
        del request.session['%s.backurl' % clazz]
        request.session.save()

    rvalue = {}
    search = get_search(clazz, request)
    sorting = handle_sorting(clazz, request)
    pagination_page, pagination_size = handle_paginating(clazz, request)
    listing = get_item_list(request, clazz, user=request.user)
    listing.sort(sorting[0], sorting[1])
    listing.filter(search)
    listing.paginate(pagination_page, pagination_size)
    # Only save the search if there are items
    if len(listing.items) > 0:
        request.session['%s.list.search' % clazz.__tablename__] = search
        if (request.params.get('form') == "search"):
            if "save" in request.params:
                query_name = request.params.get('save')
                user = BaseFactory(User).load(request.user.id)
                searches_dic = user.settings.get('searches', {})
                searches_dic_search = searches_dic.get(clazz.__tablename__, {})

                # Check if there is already a search saved with the name
                found = False
                for xxx in searches_dic_search.values():
                    if xxx[1] == query_name:
                        found = True
                        break
                if not found:
                    searches_dic_search[str(uuid.uuid1())] = (search, sorting, query_name)
                searches_dic[clazz.__tablename__] = searches_dic_search
                user.settings.set('searches', searches_dic)
                request.db.flush()
            elif "delete" in request.params:
                query_key = request.params.get('delete')
                user = BaseFactory(User).load(request.user.id)
                searches_dic = user.settings.get('searches', {})
                searches_dic_search = searches_dic.get(clazz.__tablename__, {})
                try:
                    del searches_dic_search[query_key]
                except:
                    pass
                searches_dic[clazz.__tablename__] = searches_dic_search
                user.settings.set('searches', searches_dic)
                request.db.flush()
        request.session.save()

    renderer = get_list_renderer(listing, request)
    rendered_page = renderer.render(request)
    rvalue['clazz'] = clazz
    rvalue['listing'] = rendered_page
    rvalue['itemlist'] = listing
    return rvalue
Example #25
0
def export(request):
    handle_history(request)
    handle_params(request)
    item = get_item_from_request(request)
    return _handle_export_request(request, [item])
Example #26
0
File: auth.py Project: toirl/ringo
def register_user(request):
    settings = request.registry.settings
    if not is_registration_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    config = Config(load(get_path_to_form_config('auth.xml')))
    form_config = config.get_form('register_user')
    form = Form(form_config, csrf_token=request.session.get_csrf_token(),
                translate=_)
    # Do extra validation which is not handled by formbar.
    # Is the login unique?
    login_unique_validator = Validator('login',
                                       _('There is already a user with this '
                                         'name'),
                                       is_login_unique)
    pw_len_validator = Validator('pass',
                                 _('Password must be at least 12 characters '
                                   'long.'),
                                 password_minlength_validator)
    pw_nonchar_validator = Validator('pass',
                                     _('Password must contain at least 2 '
                                       'non-letters.'),
                                     password_nonletter_validator)
    form.add_validator(login_unique_validator)
    form.add_validator(pw_len_validator)
    form.add_validator(pw_nonchar_validator)
    registration_complete = False
    if request.POST:
        if form.validate(request.params):
            # 1. Create user. Do not activate him. Default role is user.
            ufac = User.get_item_factory()
            user = ufac.create(None, form.data)
            # Set login from formdata
            user.login = form.data['login']
            # Encrypt password and save
            user.password = encrypt_password(form.data['pass'])
            # Deactivate the user. To activate the user needs to confirm
            # with the activation link
            user.activated = False
            atoken = str(uuid.uuid4())
            user.activation_token = atoken
            # Set profile data
            user.profile[0].email = form.data['_email']

            # 2. Set user group
            gfac = Usergroup.get_item_factory()
            default_grps = settings.get("auth.register_user_default_groups",
                                        str(USER_GROUP_ID))
            for gid in [int(id) for id in default_grps.split(",")]:
                group = gfac.load(gid)
                user.groups.append(group)

            # 3. Set user role
            rfac = Role.get_item_factory()
            default_roles = settings.get("auth.register_user_default_roles",
                                         str(USER_ROLE_ID))
            for rid in [int(id) for id in default_roles.split(",")]:
                role = rfac.load(rid)
                user.roles.append(role)
            # Set default user group.
            request.db.add(user)

            # 4. Send confirmation email. The user will be activated
            #    after the user clicks on the confirmation link
            mailer = Mailer(request)
            recipient = user.profile[0].email
            subject = _('Confirm user registration')
            values = {'url': request.route_url('confirm_user', token=atoken),
                      'app_name': get_app_title(),
                      'email': settings['mail.default_sender'],
                      '_': _}
            mail = Mail([recipient],
                        subject,
                        template="register_user",
                        values=values)
            mailer.send(mail)

            msg = _("User has been created and a confirmation mail was sent"
                    " to the users email adress. Please check your email.")
            request.session.flash(msg, 'success')
            registration_complete = True
    return {'form': form.render(), 'complete': registration_complete}
Example #27
0
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
Example #28
0
def board(request):
    handle_history(request)
    rvalues = get_return_value(request)
    return rvalues
Example #29
0
def delete(request, callback=None):
    item = get_item_from_request(request)
    handle_history(request)
    handle_params(request)
    return _handle_delete_request(request, [item], callback)
Example #30
0
File: home.py Project: toirl/plorma
def index_view(request):
    handle_history(request)
    values = {}
    sprints = get_item_list(request, Sprint, request.user)
    values['sprints'] = [item for item in sprints.items if item.sprint_state_id == 2]
    return values