Changeset - ebdd1a89cdd9
[Not reviewed]
default
0 3 0
Marcin Kuzminski - 15 years ago 2010-07-24 00:46:29
marcin@python-works.com
Added extra validation in creating users.
new style errors for users
3 files changed with 47 insertions and 29 deletions:
0 comments (0 inline, 0 general)
pylons_app/controllers/admin/repos.py
Show inline comments
 
@@ -63,7 +63,7 @@ class ReposController(BaseController):
 
        # url('repos')
 
        repo_model = RepoModel()
 
        _form = RepoForm()()
 
        form_result = None
 
        form_result = {}
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            repo_model.create(form_result, c.hg_app_user)
 
@@ -82,11 +82,8 @@ class ReposController(BaseController):
 

	
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            if form_result:
 
                msg = _('error occured during creation of repository %s') \
 
                    % form_result['repo_name']
 
            else:
 
                msg = _('error occured during creation of repository') 
 
            msg = _('error occured during creation of repository %s') \
 
                    % form_result.get('repo_name')
 
            h.flash(msg, category='error')
 
            
 
        return redirect('repos')
pylons_app/controllers/admin/users.py
Show inline comments
 
@@ -2,7 +2,7 @@
 
# encoding: utf-8
 
# users controller for pylons
 
# Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
 
 
 
# 
 
# This program is free software; you can redistribute it and/or
 
# modify it under the terms of the GNU General Public License
 
# as published by the Free Software Foundation; version 2
 
@@ -17,11 +17,6 @@
 
# along with this program; if not, write to the Free Software
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
# MA  02110-1301, USA.
 
"""
 
Created on April 4, 2010
 
users controller for pylons
 
@author: marcink
 
"""
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url
 
from pylons.controllers.util import abort, redirect
 
@@ -34,6 +29,12 @@ from pylons_app.model.forms import UserF
 
from pylons_app.model.user_model import UserModel, DefaultUserException
 
import formencode
 
import logging
 
import traceback
 
"""
 
Created on April 4, 2010
 
users controller for pylons
 
@author: marcink
 
"""
 

	
 
log = logging.getLogger(__name__)
 

	
 
@@ -70,13 +71,15 @@ class UsersController(BaseController):
 
            h.flash(_('created user %s') % form_result['username'],
 
                    category='success')
 
        except formencode.Invalid as errors:
 
            c.form_errors = errors.error_dict
 
            return htmlfill.render(
 
                 render('admin/users/user_add.html'),
 
                render('admin/users/user_add.html'),
 
                defaults=errors.value,
 
                encoding="UTF-8")
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8") 
 
        except Exception:
 
            h.flash(_('error occured during creation of user') \
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occured during creation of user %s') \
 
                    % request.POST.get('username'), category='error')            
 
        return redirect(url('users'))
 
    
 
@@ -94,7 +97,8 @@ class UsersController(BaseController):
 
        #           method='put')
 
        # url('user', id=ID)
 
        user_model = UserModel()
 
        _form = UserForm(edit=True)()
 
        _form = UserForm(edit=True, old_data={'user_id':id})()
 
        form_result = {}
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            user_model.update(id, form_result)
 
@@ -102,14 +106,16 @@ class UsersController(BaseController):
 
                           
 
        except formencode.Invalid as errors:
 
            c.user = user_model.get_user(id)
 
            c.form_errors = errors.error_dict
 
            return htmlfill.render(
 
                 render('admin/users/user_edit.html'),
 
                render('admin/users/user_edit.html'),
 
                defaults=errors.value,
 
                encoding="UTF-8")
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8") 
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occured during update of user %s') \
 
                    % form_result['username'], category='error')
 
                    % form_result.get('username'), category='error')
 
            
 
        return redirect(url('users'))
 
    
pylons_app/model/forms.py
Show inline comments
 
@@ -52,11 +52,26 @@ class ValidAuthToken(formencode.validato
 
        if value != authentication_token():
 
            raise formencode.Invalid(self.message('invalid_token', state,
 
                                            search_number=value), value, state)
 
class ValidUsername(formencode.validators.FancyValidator):
 

	
 
    def validate_python(self, value, state):
 
        if value in ['default', 'new_user']:
 
            raise formencode.Invalid(_('Invalid username'), value, state)
 
            
 
def ValidUsername(edit, old_data):             
 
    class _ValidUsername(formencode.validators.FancyValidator):
 
    
 
        def validate_python(self, value, state):
 
            if value in ['default', 'new_user']:
 
                raise formencode.Invalid(_('Invalid username'), value, state)
 
            #check if user is uniq
 
            sa = meta.Session
 
            old_un = None
 
            if edit:
 
                old_un = sa.query(User).get(old_data.get('user_id')).username
 
                
 
            if old_un != value or not edit:    
 
                if sa.query(User).filter(User.username == value).scalar():
 
                    raise formencode.Invalid(_('This username already exists') ,
 
                                             value, state)
 
            meta.Session.remove()
 
                            
 
    return _ValidUsername   
 
    
 
class ValidPassword(formencode.validators.FancyValidator):
 
    
 
@@ -233,16 +248,16 @@ class LoginForm(formencode.Schema):
 
    #chained validators have access to all data
 
    chained_validators = [ValidAuth]
 
    
 
def UserForm(edit=False):
 
def UserForm(edit=False, old_data={}):
 
    class _UserForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = True
 
        username = All(UnicodeString(strip=True, min=3, not_empty=True), ValidUsername)
 
        username = All(UnicodeString(strip=True, min=3, not_empty=True), ValidUsername(edit, old_data))
 
        if edit:
 
            new_password = All(UnicodeString(strip=True, min=3, not_empty=False), ValidPassword)
 
            admin = StringBoolean(if_missing=False)
 
        else:
 
            password = All(UnicodeString(strip=True, min=3, not_empty=False), ValidPassword)
 
            password = All(UnicodeString(strip=True, min=8, not_empty=True), ValidPassword)
 
        active = StringBoolean(if_missing=False)
 
        name = UnicodeString(strip=True, min=3, not_empty=True)
 
        lastname = UnicodeString(strip=True, min=3, not_empty=True)
0 comments (0 inline, 0 general)