def get_blobform_config(request, item, formname): """Helper function used in the create_ method to setup the create forms for blogform items. To create a new blogform item the creation is done in three steps: 1. Stage 1: The user selects a form from a list 2. Stage 2: The create dialog is rendered with the selected form 3. Stage 3: The item is validated and saved. :request: current request :item: item to build the form :formname: name of the form in the formconfig :returns: formconfig, item used to build a form. """ # First check if the fid parameter is provided fid = request.params.get('fid') or item.fid blobform = request.params.get('blobforms') if fid: log.debug("Stage 3: User has submitted data to create a new item") setattr(item, 'fid', fid) formfactory = BlobformForm.get_item_factory() formconfig = Config(parse(formfactory.load(fid).definition)) return item, formconfig.get_form(formname) elif blobform: log.debug("Stage 2: User has selected a blobform %s " % blobform) setattr(item, 'fid', blobform) formfactory = BlobformForm.get_item_factory() formconfig = Config(parse(formfactory.load(blobform).definition)) return item, formconfig.get_form(formname) else: log.debug("Stage 1: User is selecting a blobform") modul = get_item_modul(request, item) formconfig = get_form_config(modul, "blobform") return modul, formconfig
def setUp(self): tree = load(os.path.join(test_dir, 'form.xml')) self.config = Config(tree) self.form = self.config.get_form('customform') self.form2 = self.config.get_form('userform2') self.dfield = self.form.get_field('default') self.cfield = self.form.get_field('date') self.ifield = self.form.get_field('integer') self.sfield = self.form2.get_field('name') self.hfield = self.form.get_field('html') self.tfield = self.form.get_field('interval')
def __init__(self, request, clazz): """@todo: to be defined """ DialogRenderer.__init__(self, request, clazz, "import") self.template = template_lookup.get_template("internal/import.mako") config = Config(load(get_path_to_form_config('import.xml', 'ringo'))) form_config = config.get_form('default') self.form = Form(form_config, csrf_token=self._request.session.get_csrf_token(), dbsession=request.db, eval_url=get_eval_url(), url_prefix=get_app_url(request))
def __init__(self, request, clazz): """@todo: to be defined """ DialogRenderer.__init__(self, request, clazz, "evaluate") self.template = template_lookup.get_template("internal/evaluation.mako") config = Config(load(get_path_to_form_config('evaluations.xml', 'ringo_evaluation', location="."))) form_config = config.get_form('dialog') url_prefix = request.application_url self.form = Form(form_config, csrf_token=self._request.session.get_csrf_token(), translate=request.translate, eval_url=get_eval_url(), url_prefix=url_prefix)
def example(request): config = Config(load(os.path.join(example_dir, 'example.xml'))) form_config = config.get_form('example') form = Form(form_config, eval_url="/evaluate", request=request) if request.POST: form.validate(request.POST) else: form.validate({}) template = template_lookup.get_template("index.mako") values = {'form': form.render()} return Response(template.render(**values))
def login(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: # Delete old session data and begin with new fresh session. request.session.invalidate() 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) }
def forgot_password(request): settings = request.registry.settings if not is_pwreminder_enabled(settings): raise exc.exception_response(503) _ = 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 msg = None if request.POST: if form.validate(request.params): username = form.data.get('login') user = request_password_reset(username, request.db) if user and user.profile[0].email: recipient = user.profile[0].email mailer = Mailer(request) 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'], 'username': username, '_': _ } mail = Mail([recipient], subject, template="password_reset_request", values=values) mailer.send(mail) log.info(u"Passwort reset token sent to " u"user {} with email {}".format(username, recipient)) else: log.info(u"Failed sending Passwort reset token for {}. " u"User not found or missing email".format(username)) # Return a message to the user which does not allow to get # information about the existence of a user. msg = _("If the user has been found together with configured " "e-mail, a confirmation mail for resetting the password " "has been sent. Please check your e-mail box.") request.session.flash(msg, 'success') complete = True return {'form': form.render(), 'complete': complete, 'msg': msg}
def render(request): """Will return a JSONResponse with a rendererd form. The form defintion and the formid is provided in the POST request.""" _ = request.translate form_config = request.POST.get("definition") config_name = request.POST.get("formid") out = [] try: config = Config(parse(form_config)) form_config = config.get_form(config_name) form = Form(form_config, None, request.db, csrf_token=request.session.get_csrf_token()) out.append(form.render(buttons=False, outline=False)) except Exception as ex: out.append(_('ERROR: %s' % str(ex))) data = {"form": "".join(out)} return JSONResponse(True, data, {"msg": "Ole!"})
def get_form_config_from_file(name, filename, formname): """Return the file based configuration for a given form. The configuration tried to be loaded from the current application (and its origins) first. If this fails it tries to load it from the extension.""" loaded_config = None try: path = get_path_to_form_config(filename) if os.path.exists(path): loaded_config = load(path) elif name.startswith("ringo_"): loaded_config = load( get_path_to_form_config(filename, name, location=".")) except: pass # If we can't load the config file, raise an IOError. Hint: Maybe # you missed to set the app.base config variable? if loaded_config is None: raise IOError("Could not load form configuration for %s" % filename) return Config(loaded_config).get_form(formname)
def trainable_index_view(request): values = index_view(request) if request.user: client = Client() client_id = request.user.profile[0].strava_client_id redirect_uri = request.route_url("authstrava") url = client.authorization_url(client_id=client_id, redirect_uri=redirect_uri, scope="view_private") _ = request.translate config = Config(load(get_path_to_form_config('strava.xml'))) form_config = config.get_form('syncform') form = Form(form_config, csrf_token=request.session.get_csrf_token(), translate=_, locale="de", eval_url=get_eval_url()) if request.POST and form.validate(request.params): sync(request, form.data.get("sport"), form.data.get("start"), form.data.get("end"), form.data.get("commute")) values["fitness"] = get_fitness(0, 0, get_activities_for_user(request)) values["strava_auth_url"] = url values["strava_syncform"] = form.render() return values
def __init__(self, request, clazz): """@todo: to be defined """ DialogRenderer.__init__(self, request, clazz, "print") self.template = template_lookup.get_template("internal/print.mako") config = Config( load( get_path_to_form_config('print.xml', 'ringo_printtemplate', '.'))) form_config = config.get_form('default') # Load available_printtemplates and put them into the form as # external data. This than later used to render the available # printtemplates. mid = clazz._modul_id values = {} values['printtemplates'] = [(p, p.id) for p in self._item.printtemplates] self.form = Form(form_config, item=clazz, csrf_token=self._request.session.get_csrf_token(), dbsession=request.db, translate=request.translate, url_prefix=get_app_url(request), eval_url=get_eval_url(), values=values)
def register_user(request): settings = request.registry.settings if not is_registration_enabled(settings): raise exc.exception_response(503) _ = 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'], 'login': user.login, '_': _ } 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}
def setUp(self): tree = load(os.path.join(test_dir, 'form.xml')) config = Config(tree) form_config = config.get_form('customform') self.form = Form(form_config)
def setUp(self): tree = load(os.path.join(test_dir, 'form.xml')) self.config = Config(tree)
def setUp(self): tree = load(os.path.join(test_dir, 'form.xml')) self.config = Config(tree) self.dform = self.config.get_form('testform') self.cform = self.config.get_form('customform')
def get_form_config_from_db(fid, formname): """Return the blobform configuration for a given form.""" from ringo.model.form import Form factory = Form.get_item_factory() form = factory.load(fid) return Config(parse(form.definition.encode('utf-8'))).get_form(formname)
def _get_config(config): return Config(parse(config.read()))
def setUp(self): Base.metadata.create_all(engine) tree = load(os.path.join(test_dir, 'form.xml')) self.config = Config(tree) self.session = Session()