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 first. If this fails it tries to load it from the extension or orign application and finally from the ringo application.""" loaded_config = None for appname in get_app_inheritance_path(): try: # Always first try to load from the current application. No # matter what the current name is as name can be different from # the appname in case of loading forms for an extension. In this # case first try to load the form configuration from the # application to be able to overwrite the forms. loaded_config = load(get_path_to_form_config(filename, appname)) break except IOError: # Silently ignore IOErrors here as is Ok when trying to load the # configurations files while iterating over the possible config # file locations. If the file can finally not be loaded an IOError # is raised at the end. pass else: if name.startswith("ringo_"): loaded_config = load(get_path_to_form_config(filename, name, location=".")) # If we can't load the config file after searching in all locations, 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 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}
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)}
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 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 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 __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 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)}
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 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 setUp(self): Base.metadata.create_all(engine) tree = load(os.path.join(test_dir, 'form.xml')) self.config = Config(tree) self.session = Session()
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}
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 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')) config = Config(tree) form_config = config.get_form('customform') self.form = Form(form_config)
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 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()}