comparison pylons_app/model/forms.py @ 186:556473ba0399

fixed menu in home page, and added login html with forms that validates username and password.
author Marcin Kuzminski <marcin@python-works.com>
date Sat, 22 May 2010 01:32:30 +0200
parents a886f5eba757
children 7109d15c6813
comparison
equal deleted inserted replaced
185:3380ca40cdba 186:556473ba0399
14 14
15 15
16 <name> = formencode.validators.<name of validator> 16 <name> = formencode.validators.<name of validator>
17 <name> must equal form name 17 <name> must equal form name
18 list=[1,2,3,4,5] 18 list=[1,2,3,4,5]
19 for select use formencode.All(OneOf(list), Int()) 19 for SELECT use formencode.All(OneOf(list), Int())
20 20
21 """ 21 """
22 from formencode.validators import UnicodeString, OneOf, Int, Number, Regex
23 from pylons import session
24 from pylons.i18n.translation import _
25 from pylons_app.lib.auth import get_crypt_password
26 from pylons_app.model import meta
27 from pylons_app.model.db import Users
28 from sqlalchemy.exc import OperationalError
29 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
30 from webhelpers.pylonslib.secure_form import authentication_token
31 import formencode
32 import logging
33 log = logging.getLogger(__name__)
22 34
23 import formencode
24 from formencode.validators import UnicodeString, OneOf, Int, Number, Regex
25 from pylons.i18n.translation import _
26 from webhelpers.pylonslib.secure_form import authentication_token
27 35
36 #this is needed to translate the messages using _() in validators
37 class State_obj(object):
38 _ = staticmethod(_)
39
40 #===============================================================================
41 # VALIDATORS
42 #===============================================================================
28 class ValidAuthToken(formencode.validators.FancyValidator): 43 class ValidAuthToken(formencode.validators.FancyValidator):
29 messages = {'invalid_token':_('Token mismatch')} 44 messages = {'invalid_token':_('Token mismatch')}
30 45
31 def validate_python(self, value, state): 46 def validate_python(self, value, state):
32 47
33 if value != authentication_token(): 48 if value != authentication_token():
34 raise formencode.Invalid(self.message('invalid_token', state, search_number=value), value, state) 49 raise formencode.Invalid(self.message('invalid_token', state,
50 search_number=value), value, state)
35 51
36 52 class ValidAuth(formencode.validators.FancyValidator):
53 messages = {
54 'invalid_password':_('invalid password'),
55 'invalid_login':_('invalid user name'),
56 'disabled_account':_('Your acccount is disabled')
57
58 }
59 #error mapping
60 e_dict = {'username':messages['invalid_login'],
61 'password':messages['invalid_password']}
62
63 def validate_python(self, value, state):
64 sa = meta.Session
65 crypted_passwd = get_crypt_password(value['password'])
66 username = value['username']
67 try:
68 user = sa.query(Users).filter(Users.username == username).one()
69 except (NoResultFound, MultipleResultsFound, OperationalError) as e:
70 log.error(e)
71 user = None
72 print value
73 if user:
74 if user.active:
75 if user.username == username and user.password == crypted_passwd:
76 log.info('user %s authenticated correctly', username)
77 from pylons_app.lib.auth import AuthUser
78 auth_user = AuthUser()
79 auth_user.username = username
80 auth_user.is_authenticated = True
81 auth_user.is_admin = user.admin
82 session['hg_app_user'] = auth_user
83 session.save()
84 return value
85 else:
86 log.warning('user %s not authenticated', username)
87 raise formencode.Invalid(self.message('invalid_password',
88 state=State_obj), value, state,
89 error_dict=self.e_dict)
90 else:
91 log.warning('user %s is disabled', username)
92 raise formencode.Invalid(self.message('disabled_account',
93 state=State_obj),
94 value, state, error_dict=self.e_dict)
95
96
97
98 #===============================================================================
99 # FORMS
100 #===============================================================================
37 class LoginForm(formencode.Schema): 101 class LoginForm(formencode.Schema):
38 allow_extra_fields = True 102 allow_extra_fields = True
39 filter_extra_fields = True 103 filter_extra_fields = True
40 username = UnicodeString( 104 username = UnicodeString(
41 strip=True, 105 strip=True,
54 'empty':_('Please enter a password'), 118 'empty':_('Please enter a password'),
55 'tooShort':_('Enter a value %(min)i characters long or more')} 119 'tooShort':_('Enter a value %(min)i characters long or more')}
56 ) 120 )
57 121
58 122
123 #chained validators have access to all data
124 chained_validators = [ValidAuth]
125
126