コード例 #1
0
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
コード例 #2
0
ファイル: helpers.py プロジェクト: ringo-framework/ringo
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
コード例 #3
0
ファイル: test_form.py プロジェクト: ringo-framework/formbar
class TestFormAlchemyForm(unittest.TestCase):

    def _insert_item(self):
        item = User('ed', 'Ed Jones', 'edspassword')
        self.session.add(item)
        self.session.commit()
        return item

    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 tearDown(self):
        Session.remove()

    def test_read(self):
        form_config = self.config.get_form('userform1')
        item = self._insert_item()
        form = Form(form_config, item)
        self.assertEqual(len(form.fields), 2)

    def test_create(self):
        form_config = self.config.get_form('userform2')
        item = User()
        form = Form(form_config, item)
        self.assertEqual(len(form.fields), 3)

    def test_create_save(self):
        form_config = self.config.get_form('userform2')
        item = User()
        # Important! Provide the dbsession if you want to create a new
        # item
        form = Form(form_config, item, self.session)
        values = {"name": "paulpaulpaul", "fullname": "Paul Wright",
                  "password": "******"}
        if form.validate(values):
            saved_item = form.save()
            self.assertEqual(saved_item, item)
        result = self.session.query(User).all()
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].name, "paulpaulpaul")

    def test_edit_save(self):
        form_config = self.config.get_form('userform2')
        item = self._insert_item()
        item = self._insert_item()
        result = self.session.query(User).all()
        form = Form(form_config, item)
        result = self.session.query(User).all()
        values = {"name": "paulpaulpaul", "fullname": "Paul Wright",
                  "password": "******"}
        if form.validate(values):
            form.save()
        result = self.session.query(User).all()
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].name, "ed")
        self.assertEqual(result[1].name, "paulpaulpaul")
コード例 #4
0
class TestFormParser(unittest.TestCase):

    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 test_get_fields(self):
        self.assertTrue(isinstance(self.cform.get_fields(), dict))
        self.assertEqual(len(self.cform.get_fields().items()), 9)

    def test_get_field_e1(self):
        field = self.cform.get_field(self.cform._id2name['e1'])
        self.assertEqual(field.id, 'e1')

    def test_autocomplete_default(self):
        self.assertEqual(self.dform.autocomplete, 'on')

    def test_autocomplete_custom(self):
        self.assertEqual(self.cform.autocomplete, 'off')

    def test_method_default(self):
        self.assertEqual(self.dform.method, 'POST')

    def test_method_custom(self):
        self.assertEqual(self.cform.method, 'GET')

    def test_action_default(self):
        self.assertEqual(self.dform.action, '')

    def test_action_custom(self):
        self.assertEqual(self.cform.action, 'http://')

    def test_enctype_default(self):
        self.assertEqual(self.dform.enctype, '')

    def test_enctype_custom(self):
        self.assertEqual(self.cform.enctype, 'multipart/form-data')

    def test_css_default(self):
        self.assertEqual(self.dform.css, '')

    def test_css_custom(self):
        self.assertEqual(self.cform.css, 'testcss')

    def test_readonly_default(self):
        self.assertEqual(self.dform.readonly, False)

    def test_readonly_custom(self):
        self.assertEqual(self.cform.readonly, False)

    def test_id_default(self):
        self.assertEqual(self.dform.id, 'testform')

    def test_id_custom(self):
        self.assertEqual(self.cform.id, 'customform')
コード例 #5
0
ファイル: test_configparser.py プロジェクト: toirl/formbar
class TestFormParser(unittest.TestCase):
    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 test_get_fields(self):
        self.assertTrue(isinstance(self.cform.get_fields(), dict))
        self.assertEqual(len(self.cform.get_fields().items()), 9)

    def test_get_field_e1(self):
        field = self.cform.get_field(self.cform._id2name['e1'])
        self.assertEqual(field.id, 'e1')

    def test_autocomplete_default(self):
        self.assertEqual(self.dform.autocomplete, 'on')

    def test_autocomplete_custom(self):
        self.assertEqual(self.cform.autocomplete, 'off')

    def test_method_default(self):
        self.assertEqual(self.dform.method, 'POST')

    def test_method_custom(self):
        self.assertEqual(self.cform.method, 'GET')

    def test_action_default(self):
        self.assertEqual(self.dform.action, '')

    def test_action_custom(self):
        self.assertEqual(self.cform.action, 'http://')

    def test_enctype_default(self):
        self.assertEqual(self.dform.enctype, '')

    def test_enctype_custom(self):
        self.assertEqual(self.cform.enctype, 'multipart/form-data')

    def test_css_default(self):
        self.assertEqual(self.dform.css, '')

    def test_css_custom(self):
        self.assertEqual(self.cform.css, 'testcss')

    def test_readonly_default(self):
        self.assertEqual(self.dform.readonly, False)

    def test_readonly_custom(self):
        self.assertEqual(self.cform.readonly, False)

    def test_id_default(self):
        self.assertEqual(self.dform.id, 'testform')

    def test_id_custom(self):
        self.assertEqual(self.cform.id, 'customform')
コード例 #6
0
ファイル: auth.py プロジェクト: mjsorribas/ringo
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)}
コード例 #7
0
class TestConfigParser(unittest.TestCase):

    def setUp(self):
        tree = load(os.path.join(test_dir, 'form.xml'))
        self.config = Config(tree)

    def test_get_ambigous_element_fail(self):
        """ Check if an KeyError is raised on ambigous elements. """
        self.assertRaises(
            KeyError, self.config.get_element, 'form', 'ambigous')

    def test_build_form_fail(self):
        """Check if a ValueError is raised if the Config is not instanciated
        with an ElementTree.Element.
        """
        self.assertRaises(ValueError, Config, None)

    def test_build_form_ok(self):
        pass

    def test_get_form_ok(self):
        """ Check if a Form instance is retrieved. """
        form = self.config.get_form('testform')
        self.assertTrue(isinstance(form, Form))

    def test_get_form_fail(self):
        """ Check if an KeyError is raised. """
        self.assertRaises(KeyError, self.config.get_form, '_testform')
コード例 #8
0
ファイル: auth.py プロジェクト: ringo-framework/ringo
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}
コード例 #9
0
ファイル: test_configparser.py プロジェクト: toirl/formbar
class TestConfigParser(unittest.TestCase):
    def setUp(self):
        tree = load(os.path.join(test_dir, 'form.xml'))
        self.config = Config(tree)

    def test_get_ambigous_element_fail(self):
        """ Check if an KeyError is raised on ambigous elements. """
        self.assertRaises(KeyError, self.config.get_element, 'form',
                          'ambigous')

    def test_build_form_fail(self):
        """Check if a ValueError is raised if the Config is not instanciated
        with an ElementTree.Element.
        """
        self.assertRaises(ValueError, Config, None)

    def test_build_form_ok(self):
        pass

    def test_get_form_ok(self):
        """ Check if a Form instance is retrieved. """
        form = self.config.get_form('testform')
        self.assertTrue(isinstance(form, Form))

    def test_get_form_fail(self):
        """ Check if an KeyError is raised. """
        self.assertRaises(KeyError, self.config.get_form, '_testform')
コード例 #10
0
 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))
コード例 #11
0
ファイル: dialogs.py プロジェクト: mjsorribas/ringo
 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))
コード例 #12
0
 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)
コード例 #13
0
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))
コード例 #14
0
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)
    }
コード例 #15
0
ファイル: auth.py プロジェクト: 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)}
コード例 #16
0
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}
コード例 #17
0
ファイル: api.py プロジェクト: ringo-framework/ringo
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!"})
コード例 #18
0
ファイル: api.py プロジェクト: reiterl/ringo
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!"})
コード例 #19
0
ファイル: home.py プロジェクト: toirl/trainable
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
コード例 #20
0
 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)
コード例 #21
0
class TestFormAlchemyForm(unittest.TestCase):
    def _insert_item(self):
        item = User('ed', 'Ed Jones', 'edspassword')
        self.session.add(item)
        self.session.commit()
        return item

    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 tearDown(self):
        Session.remove()

    def test_read(self):
        form_config = self.config.get_form('userform1')
        item = self._insert_item()
        form = Form(form_config, item)
        self.assertEqual(len(form.fields), 2)

    def test_create(self):
        form_config = self.config.get_form('userform2')
        item = User()
        form = Form(form_config, item)
        self.assertEqual(len(form.fields), 3)

    def test_create_save(self):
        form_config = self.config.get_form('userform2')
        item = User()
        # Important! Provide the dbsession if you want to create a new
        # item
        form = Form(form_config, item, self.session)
        values = {
            "name": "paulpaulpaul",
            "fullname": "Paul Wright",
            "password": "******"
        }
        if form.validate(values):
            saved_item = form.save()
            self.assertEqual(saved_item, item)
        result = self.session.query(User).all()
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].name, "paulpaulpaul")

    def test_edit_save(self):
        form_config = self.config.get_form('userform2')
        item = self._insert_item()
        item = self._insert_item()
        result = self.session.query(User).all()
        form = Form(form_config, item)
        result = self.session.query(User).all()
        values = {
            "name": "paulpaulpaul",
            "fullname": "Paul Wright",
            "password": "******"
        }
        if form.validate(values):
            form.save()
        result = self.session.query(User).all()
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].name, "ed")
        self.assertEqual(result[1].name, "paulpaulpaul")
コード例 #22
0
ファイル: auth.py プロジェクト: 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}
コード例 #23
0
ファイル: test_configparser.py プロジェクト: toirl/formbar
class TestFieldConfig(unittest.TestCase):
    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 test_get_field_mission(self):
        self.assertRaises(KeyError, self.form.get_field, 'missing')

    def test_autocomplete_default(self):
        self.assertEqual(self.dfield.autocomplete, 'on')

    def test_autocomplete_custom(self):
        self.assertEqual(self.cfield.autocomplete, 'off')

    def test_required_default(self):
        self.assertEqual(self.dfield.required, False)

    def test_requried_custom(self):
        ifield = self.form.get_field('integer')
        self.assertEqual(ifield.required, True)

    def test_desired_default(self):
        self.assertEqual(self.dfield.desired, False)

    def test_desired_custom(self):
        ifield = self.form.get_field('float')
        self.assertEqual(ifield.desired, True)

    def test_readonly_default(self):
        self.assertEqual(self.sfield.readonly, False)

    def test_readonly_custom(self):
        self.assertEqual(self.dfield.readonly, False)

    def test_css_default(self):
        self.assertEqual(self.dfield.css, '')

    def test_css_custom(self):
        self.assertEqual(self.cfield.css, 'datefield')

    def test_label_default(self):
        self.assertEqual(self.dfield.label, self.dfield.name.capitalize())

    def test_label_custom(self):
        self.assertEqual(self.cfield.label, 'Date field')

    def test_number_default(self):
        self.assertEqual(self.dfield.number, '')

    def test_number_custom(self):
        self.assertEqual(self.cfield.number, '1')

    def test_type_default(self):
        self.assertEqual(self.dfield.type, None)

    def test_type_custom(self):
        self.assertEqual(self.cfield.type, 'date')

    def test_id_default(self):
        self.assertEqual(self.dfield.id, 'e0')

    def test_id_custom(self):
        self.assertEqual(self.cfield.id, 'e4')

    def test_name_default(self):
        self.assertEqual(self.dfield.name, 'default')

    def test_name_custom(self):
        self.assertEqual(self.cfield.name, 'date')

    def test_renderer_default(self):
        self.assertEqual(self.dfield.renderer, None)

    def test_renderer_custom(self):
        self.assertNotEqual(self.cfield.renderer, None)

    def test_help_default(self):
        self.assertEqual(self.dfield.help, None)

    def test_help_custom(self):
        self.assertEqual(self.cfield.help, 'This is my helptext')

    def test_rules_default(self):
        self.assertEqual(len(self.dfield.get_rules()), 0)

    def test_rules_custom(self):
        self.assertEqual(len(self.ifield.get_rules()), 2)

    def test_validators_default(self):
        self.assertEqual(len(self.dfield.get_validators()), 0)

    def test_validators_custom(self):
        self.assertEqual(len(self.ifield.get_validators()), 1)

    def test_html_renderer_fails(self):
        """Only html renderer have the body attribute set"""
        self.assertEqual(self.cfield.renderer.body, None)

    def test_html_renderer(self):
        self.assertEqual(self.hfield.renderer.body.strip(), "<div>Test</div>")

    def test_tags_default(self):
        self.assertEqual(self.dfield.tags, [])

    def test_tags_custom(self):
        self.assertEqual(self.hfield.tags, ["tag1", "tag2"])
コード例 #24
0
ファイル: test_form.py プロジェクト: ringo-framework/formbar
 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)
コード例 #25
0
class TestFieldConfig(unittest.TestCase):

    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 test_get_field_mission(self):
        self.assertRaises(KeyError, self.form.get_field, 'missing')

    def test_autocomplete_default(self):
        self.assertEqual(self.dfield.autocomplete, 'on')

    def test_autocomplete_custom(self):
        self.assertEqual(self.cfield.autocomplete, 'off')

    def test_required_default(self):
        self.assertEqual(self.dfield.required, False)

    def test_requried_custom(self):
        ifield = self.form.get_field('integer')
        self.assertEqual(ifield.required, True)

    def test_desired_default(self):
        self.assertEqual(self.dfield.desired, False)

    def test_desired_custom(self):
        ifield = self.form.get_field('float')
        self.assertEqual(ifield.desired, True)

    def test_readonly_default(self):
        self.assertEqual(self.sfield.readonly, False)

    def test_readonly_custom(self):
        self.assertEqual(self.dfield.readonly, False)

    def test_css_default(self):
        self.assertEqual(self.dfield.css, '')

    def test_css_custom(self):
        self.assertEqual(self.cfield.css, 'datefield')

    def test_label_default(self):
        self.assertEqual(self.dfield.label, self.dfield.name.capitalize())

    def test_label_custom(self):
        self.assertEqual(self.cfield.label, 'Date field')

    def test_number_default(self):
        self.assertEqual(self.dfield.number, '')

    def test_number_custom(self):
        self.assertEqual(self.cfield.number, '1')

    def test_type_default(self):
        self.assertEqual(self.dfield.type, None)

    def test_type_custom(self):
        self.assertEqual(self.cfield.type, 'date')

    def test_id_default(self):
        self.assertEqual(self.dfield.id, 'e0')

    def test_id_custom(self):
        self.assertEqual(self.cfield.id, 'e4')

    def test_name_default(self):
        self.assertEqual(self.dfield.name, 'default')

    def test_name_custom(self):
        self.assertEqual(self.cfield.name, 'date')

    def test_renderer_default(self):
        self.assertEqual(self.dfield.renderer, None)

    def test_renderer_custom(self):
        self.assertNotEqual(self.cfield.renderer, None)

    def test_help_default(self):
        self.assertEqual(self.dfield.help, None)

    def test_help_custom(self):
        self.assertEqual(self.cfield.help, 'This is my helptext')

    def test_rules_default(self):
        self.assertEqual(len(self.dfield.get_rules()), 0)

    def test_rules_custom(self):
        self.assertEqual(len(self.ifield.get_rules()), 2)

    def test_validators_default(self):
        self.assertEqual(len(self.dfield.get_validators()), 0)

    def test_validators_custom(self):
        self.assertEqual(len(self.ifield.get_validators()), 1)

    def test_html_renderer_fails(self):
        """Only html renderer have the body attribute set"""
        self.assertEqual(self.cfield.renderer.body, None)

    def test_html_renderer(self):
        self.assertEqual(self.hfield.renderer.body.strip(), "<div>Test</div>")

    def test_tags_default(self):
        self.assertEqual(self.dfield.tags, [])

    def test_tags_custom(self):
        self.assertEqual(self.hfield.tags, ["tag1", "tag2"])
コード例 #26
0
ファイル: auth.py プロジェクト: mjsorribas/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', '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()}
コード例 #27
0
 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)
コード例 #28
0
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}