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 # 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(), dependencies=create_dependencies(request)) 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
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
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 _ = 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
def handle_POST_request(form, request, callback, event="", renderers=None): """@todo: Docstring for handle_POST_request. :name: @todo :request: @todo :callback: @todo :renderers: @todo :event: Name of the event (update, create...) Used for the event handler :returns: True or False """ _ = request.translate clazz = request.context.__model__ item_label = get_item_modul(request, clazz).get_label() item = get_item_from_request(request) mapping = {"item_type": item_label, "item": item} # Add a *special* validator to the form to trigger rendering a # permanent info pane at the top of the form in case of errors on # validation. This info has been added because users reported data # loss because of formbar/ringo default behaviour of not saving # anything in case of errors. Users seems to expect that the valid # part of the data has been saved. This info should make the user # aware of the fact that nothing has been saved in case of errors. error_message = _( "The information contained errors. " "<strong>All entries (including error-free) were not " "saved!</strong> Please correct your entries in the " "fields marked in red and resave." ) form.add_validator(Validator(None, literal(error_message), callback=form_has_errors, context=form)) # Begin a nested transaction. In case an error occours while saving # the data the nested transaction will be rolled back. The parent # session will be still ok. request.db.begin_nested() if form.validate(request.params) and "blobforms" not in request.params: checker = ValueChecker() try: if event == "create": 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 checker.check(clazz, form.data, request) item = factory.create(request.user, form.data) item.save({}, request) request.context.item = item handle_add_relation(request, item) else: values = checker.check(clazz, form.data, request, item) item.save(values, request) handle_event(request, item, event) handle_callback(request, callback) handle_caching(request) if event == "create": msg = _("Created new ${item_type} successfully.", mapping=mapping) log_msg = u"User {user.login} created {item_label} {item.id}".format( item_label=item_label, item=item, user=request.user ) else: msg = _('Edited ${item_type} "${item}" successfully.', mapping=mapping) log_msg = u"User {user.login} edited {item_label} {item.id}".format( item_label=item_label, item=item, user=request.user ) log.info(log_msg) request.session.flash(msg, "success") # Set next form page. if request.params.get("_submit") == "nextpage": table = clazz.__table__ itemid = item.id page = get_next_form_page(form, get_current_form_page(clazz, request)) set_current_form_page(table, itemid, page, request) # In case all is ok merge the nested session. request.db.merge(item) return True except Exception as error: request.db.rollback() mapping["error"] = unicode(error.message) if event == "create": msg = _("Error while saving new " "${item_type}: ${error}.", mapping=mapping) else: msg = _("Error while saving " '${item_type} "${item}": ${error}.', mapping=mapping) log.exception(msg) request.session.flash(msg, "critical") return False elif "blobforms" in request.params: pass else: request.db.rollback() if event == "create": msg = _("Error on validation new " "${item_type}.", mapping=mapping) else: msg = _("Error on validation " '${item_type} "${item}".', mapping=mapping) log.debug(msg) request.session.flash(msg, "error") return False
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
def handle_POST_request(form, request, callback, event="", renderers=None): """@todo: Docstring for handle_POST_request. :name: @todo :request: @todo :callback: @todo :renderers: @todo :event: Name of the event (update, create...) Used for the event handler :returns: True or False """ _ = request.translate clazz = request.context.__model__ item_label = get_item_modul(request, clazz).get_label() item = get_item_from_request(request) mapping = {'item_type': item_label, 'item': item} # Add a *special* validator to the form to trigger rendering a # permanent info pane at the top of the form in case of errors on # validation. This info has been added because users reported data # loss because of formbar/ringo default behaviour of not saving # anything in case of errors. Users seems to expect that the valid # part of the data has been saved. This info should make the user # aware of the fact that nothing has been saved in case of errors. error_message = _("The information contained errors. " "<strong>All entries (including error-free) were not " "saved!</strong> Please correct your entries in the " "fields marked in red and resave.") form.add_validator( Validator(None, literal(error_message), callback=form_has_errors, context=form)) # Begin a nested transaction. In case an error occours while saving # the data the nested transaction will be rolled back. The parent # session will be still ok. request.db.begin_nested() if form.validate(request.params) and "blobforms" not in request.params: checker = ValueChecker() try: # Handle new callback objects wich are configured to be # called previous the origin action. Old simple callbacks # are ignored. handle_callback(request, callback, mode="pre") if event == "create": 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 checker.check(clazz, form.data, request) item = factory.create(request.user, form.data) handle_add_relation(request, item) item.save({}, request) request.context.item = item else: values = checker.check(clazz, form.data, request, item) item.save(values, request) handle_event(request, item, event) # Maintain old behaviour of callbacks. Callback are called # post the origin action of the view. Therefor the callback # must either be an instance of :class:Callback with mode # "post" or it is a simple callable. handle_callback(request, callback, mode="post,default") handle_caching(request) if event == "create": msg = _('Created new ${item_type} successfully.', mapping=mapping) log_msg = u'User {user.login} created {item_label} {item.id}'\ .format(item_label=item_label, item=item, user=request.user) else: msg = _('Edited ${item_type} "${item}" successfully.', mapping=mapping) log_msg = u'User {user.login} edited {item_label} {item.id}'\ .format(item_label=item_label, item=item, user=request.user) log.info(log_msg) request.session.flash(msg, 'success') # Set next form page. if request.params.get("_submit") == "nextpage": table = clazz.__table__ itemid = item.id page = get_next_form_page( form, get_current_form_page(clazz, request)) set_current_form_page(table, itemid, page, request) # In case all is ok merge the nested session. request.db.merge(item) return True except Exception as error: request.db.rollback() mapping['error'] = unicode(error.message) if event == "create": log_msg = _(u'User {user.login} created' '{item_label}').format(item_label=item_label, user=request.user) msg = _('Error while saving new ' '${item_type}: ${error}.', mapping=mapping) else: log_msg = _(u'User {user.login} edited ' '{item_label} {item.id}').format( item_label=item_label, item=item, user=request.user) msg = _( 'Error while saving ' '${item_type} "${item}": ${error}.', mapping=mapping) log.exception(log_msg) request.session.flash(msg, 'critical') return False elif "blobforms" in request.params: pass else: request.db.rollback() if event == "create": msg = _('Error on validation new ' '${item_type}.', mapping=mapping) else: msg = _('Error on validation ' '${item_type} "${item}".', mapping=mapping) log.debug(msg) request.session.flash(msg, 'error') return False