##// END OF EJS Templates
added dump validation of cloneurl, it can still freeze if server will ask for auth.
marcink -
r1261:30828b1e beta
parent child Browse files
Show More
@@ -1,555 +1,583 b''
1 """ this is forms validation classes
1 """ this is forms validation classes
2 http://formencode.org/module-formencode.validators.html
2 http://formencode.org/module-formencode.validators.html
3 for list off all availible validators
3 for list off all availible validators
4
4
5 we can create our own validators
5 we can create our own validators
6
6
7 The table below outlines the options which can be used in a schema in addition to the validators themselves
7 The table below outlines the options which can be used in a schema in addition to the validators themselves
8 pre_validators [] These validators will be applied before the schema
8 pre_validators [] These validators will be applied before the schema
9 chained_validators [] These validators will be applied after the schema
9 chained_validators [] These validators will be applied after the schema
10 allow_extra_fields False If True, then it is not an error when keys that aren't associated with a validator are present
10 allow_extra_fields False If True, then it is not an error when keys that aren't associated with a validator are present
11 filter_extra_fields False If True, then keys that aren't associated with a validator are removed
11 filter_extra_fields False If True, then keys that aren't associated with a validator are removed
12 if_key_missing NoDefault If this is given, then any keys that aren't available but are expected will be replaced with this value (and then validated). This does not override a present .if_missing attribute on validators. NoDefault is a special FormEncode class to mean that no default values has been specified and therefore missing keys shouldn't take a default value.
12 if_key_missing NoDefault If this is given, then any keys that aren't available but are expected will be replaced with this value (and then validated). This does not override a present .if_missing attribute on validators. NoDefault is a special FormEncode class to mean that no default values has been specified and therefore missing keys shouldn't take a default value.
13 ignore_key_missing False If True, then missing keys will be missing in the result, if the validator doesn't have .if_missing on it already
13 ignore_key_missing False If True, then missing keys will be missing in the result, if the validator doesn't have .if_missing on it already
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 import os
22 import os
23 import re
23 import re
24 import logging
24 import logging
25
25
26 import formencode
26 import formencode
27 from formencode import All
27 from formencode import All
28 from formencode.validators import UnicodeString, OneOf, Int, Number, Regex, \
28 from formencode.validators import UnicodeString, OneOf, Int, Number, Regex, \
29 Email, Bool, StringBoolean, Set
29 Email, Bool, StringBoolean, Set
30
30
31 from pylons.i18n.translation import _
31 from pylons.i18n.translation import _
32 from webhelpers.pylonslib.secure_form import authentication_token
32 from webhelpers.pylonslib.secure_form import authentication_token
33
33
34 from rhodecode.lib.utils import repo_name_slug
34 from rhodecode.lib.utils import repo_name_slug
35 from rhodecode.lib.auth import authenticate, get_crypt_password
35 from rhodecode.lib.auth import authenticate, get_crypt_password
36 from rhodecode.lib.exceptions import LdapImportError
36 from rhodecode.lib.exceptions import LdapImportError
37 from rhodecode.model import meta
37 from rhodecode.model import meta
38 from rhodecode.model.user import UserModel
38 from rhodecode.model.user import UserModel
39 from rhodecode.model.repo import RepoModel
39 from rhodecode.model.repo import RepoModel
40 from rhodecode.model.users_group import UsersGroupModel
40 from rhodecode.model.users_group import UsersGroupModel
41 from rhodecode.model.db import User, UsersGroup
41 from rhodecode.model.db import User, UsersGroup
42 from rhodecode import BACKENDS
42 from rhodecode import BACKENDS
43
43
44 log = logging.getLogger(__name__)
44 log = logging.getLogger(__name__)
45
45
46 #this is needed to translate the messages using _() in validators
46 #this is needed to translate the messages using _() in validators
47 class State_obj(object):
47 class State_obj(object):
48 _ = staticmethod(_)
48 _ = staticmethod(_)
49
49
50 #===============================================================================
50 #===============================================================================
51 # VALIDATORS
51 # VALIDATORS
52 #===============================================================================
52 #===============================================================================
53 class ValidAuthToken(formencode.validators.FancyValidator):
53 class ValidAuthToken(formencode.validators.FancyValidator):
54 messages = {'invalid_token':_('Token mismatch')}
54 messages = {'invalid_token':_('Token mismatch')}
55
55
56 def validate_python(self, value, state):
56 def validate_python(self, value, state):
57
57
58 if value != authentication_token():
58 if value != authentication_token():
59 raise formencode.Invalid(self.message('invalid_token', state,
59 raise formencode.Invalid(self.message('invalid_token', state,
60 search_number=value), value, state)
60 search_number=value), value, state)
61
61
62 def ValidUsername(edit, old_data):
62 def ValidUsername(edit, old_data):
63 class _ValidUsername(formencode.validators.FancyValidator):
63 class _ValidUsername(formencode.validators.FancyValidator):
64
64
65 def validate_python(self, value, state):
65 def validate_python(self, value, state):
66 if value in ['default', 'new_user']:
66 if value in ['default', 'new_user']:
67 raise formencode.Invalid(_('Invalid username'), value, state)
67 raise formencode.Invalid(_('Invalid username'), value, state)
68 #check if user is unique
68 #check if user is unique
69 old_un = None
69 old_un = None
70 if edit:
70 if edit:
71 old_un = UserModel().get(old_data.get('user_id')).username
71 old_un = UserModel().get(old_data.get('user_id')).username
72
72
73 if old_un != value or not edit:
73 if old_un != value or not edit:
74 if UserModel().get_by_username(value, cache=False,
74 if UserModel().get_by_username(value, cache=False,
75 case_insensitive=True):
75 case_insensitive=True):
76 raise formencode.Invalid(_('This username already exists') ,
76 raise formencode.Invalid(_('This username already exists') ,
77 value, state)
77 value, state)
78
78
79
79
80 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
80 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
81 raise formencode.Invalid(_('Username may only contain '
81 raise formencode.Invalid(_('Username may only contain '
82 'alphanumeric characters underscores, '
82 'alphanumeric characters underscores, '
83 'periods or dashes and must begin with '
83 'periods or dashes and must begin with '
84 'alphanumeric character'),
84 'alphanumeric character'),
85 value, state)
85 value, state)
86
86
87
87
88
88
89 return _ValidUsername
89 return _ValidUsername
90
90
91
91
92
92
93 def ValidUsersGroup(edit, old_data):
93 def ValidUsersGroup(edit, old_data):
94
94
95 class _ValidUsersGroup(formencode.validators.FancyValidator):
95 class _ValidUsersGroup(formencode.validators.FancyValidator):
96
96
97 def validate_python(self, value, state):
97 def validate_python(self, value, state):
98 if value in ['default']:
98 if value in ['default']:
99 raise formencode.Invalid(_('Invalid group name'), value, state)
99 raise formencode.Invalid(_('Invalid group name'), value, state)
100 #check if group is unique
100 #check if group is unique
101 old_ugname = None
101 old_ugname = None
102 if edit:
102 if edit:
103 old_ugname = UsersGroupModel()\
103 old_ugname = UsersGroupModel()\
104 .get(old_data.get('users_group_id')).users_group_name
104 .get(old_data.get('users_group_id')).users_group_name
105
105
106 if old_ugname != value or not edit:
106 if old_ugname != value or not edit:
107 if UsersGroupModel().get_by_groupname(value, cache=False,
107 if UsersGroupModel().get_by_groupname(value, cache=False,
108 case_insensitive=True):
108 case_insensitive=True):
109 raise formencode.Invalid(_('This users group already exists') ,
109 raise formencode.Invalid(_('This users group already exists') ,
110 value, state)
110 value, state)
111
111
112
112
113 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
113 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
114 raise formencode.Invalid(_('Group name may only contain '
114 raise formencode.Invalid(_('Group name may only contain '
115 'alphanumeric characters underscores, '
115 'alphanumeric characters underscores, '
116 'periods or dashes and must begin with '
116 'periods or dashes and must begin with '
117 'alphanumeric character'),
117 'alphanumeric character'),
118 value, state)
118 value, state)
119
119
120 return _ValidUsersGroup
120 return _ValidUsersGroup
121
121
122
122
123
123
124 class ValidPassword(formencode.validators.FancyValidator):
124 class ValidPassword(formencode.validators.FancyValidator):
125
125
126 def to_python(self, value, state):
126 def to_python(self, value, state):
127
127
128 if value:
128 if value:
129
129
130 if value.get('password'):
130 if value.get('password'):
131 try:
131 try:
132 value['password'] = get_crypt_password(value['password'])
132 value['password'] = get_crypt_password(value['password'])
133 except UnicodeEncodeError:
133 except UnicodeEncodeError:
134 e_dict = {'password':_('Invalid characters in password')}
134 e_dict = {'password':_('Invalid characters in password')}
135 raise formencode.Invalid('', value, state, error_dict=e_dict)
135 raise formencode.Invalid('', value, state, error_dict=e_dict)
136
136
137 if value.get('password_confirmation'):
137 if value.get('password_confirmation'):
138 try:
138 try:
139 value['password_confirmation'] = \
139 value['password_confirmation'] = \
140 get_crypt_password(value['password_confirmation'])
140 get_crypt_password(value['password_confirmation'])
141 except UnicodeEncodeError:
141 except UnicodeEncodeError:
142 e_dict = {'password_confirmation':_('Invalid characters in password')}
142 e_dict = {'password_confirmation':_('Invalid characters in password')}
143 raise formencode.Invalid('', value, state, error_dict=e_dict)
143 raise formencode.Invalid('', value, state, error_dict=e_dict)
144
144
145 if value.get('new_password'):
145 if value.get('new_password'):
146 try:
146 try:
147 value['new_password'] = \
147 value['new_password'] = \
148 get_crypt_password(value['new_password'])
148 get_crypt_password(value['new_password'])
149 except UnicodeEncodeError:
149 except UnicodeEncodeError:
150 e_dict = {'new_password':_('Invalid characters in password')}
150 e_dict = {'new_password':_('Invalid characters in password')}
151 raise formencode.Invalid('', value, state, error_dict=e_dict)
151 raise formencode.Invalid('', value, state, error_dict=e_dict)
152
152
153 return value
153 return value
154
154
155 class ValidPasswordsMatch(formencode.validators.FancyValidator):
155 class ValidPasswordsMatch(formencode.validators.FancyValidator):
156
156
157 def validate_python(self, value, state):
157 def validate_python(self, value, state):
158
158
159 if value['password'] != value['password_confirmation']:
159 if value['password'] != value['password_confirmation']:
160 e_dict = {'password_confirmation':
160 e_dict = {'password_confirmation':
161 _('Password do not match')}
161 _('Password do not match')}
162 raise formencode.Invalid('', value, state, error_dict=e_dict)
162 raise formencode.Invalid('', value, state, error_dict=e_dict)
163
163
164 class ValidAuth(formencode.validators.FancyValidator):
164 class ValidAuth(formencode.validators.FancyValidator):
165 messages = {
165 messages = {
166 'invalid_password':_('invalid password'),
166 'invalid_password':_('invalid password'),
167 'invalid_login':_('invalid user name'),
167 'invalid_login':_('invalid user name'),
168 'disabled_account':_('Your account is disabled')
168 'disabled_account':_('Your account is disabled')
169
169
170 }
170 }
171 #error mapping
171 #error mapping
172 e_dict = {'username':messages['invalid_login'],
172 e_dict = {'username':messages['invalid_login'],
173 'password':messages['invalid_password']}
173 'password':messages['invalid_password']}
174 e_dict_disable = {'username':messages['disabled_account']}
174 e_dict_disable = {'username':messages['disabled_account']}
175
175
176 def validate_python(self, value, state):
176 def validate_python(self, value, state):
177 password = value['password']
177 password = value['password']
178 username = value['username']
178 username = value['username']
179 user = UserModel().get_by_username(username)
179 user = UserModel().get_by_username(username)
180
180
181 if authenticate(username, password):
181 if authenticate(username, password):
182 return value
182 return value
183 else:
183 else:
184 if user and user.active is False:
184 if user and user.active is False:
185 log.warning('user %s is disabled', username)
185 log.warning('user %s is disabled', username)
186 raise formencode.Invalid(self.message('disabled_account',
186 raise formencode.Invalid(self.message('disabled_account',
187 state=State_obj),
187 state=State_obj),
188 value, state,
188 value, state,
189 error_dict=self.e_dict_disable)
189 error_dict=self.e_dict_disable)
190 else:
190 else:
191 log.warning('user %s not authenticated', username)
191 log.warning('user %s not authenticated', username)
192 raise formencode.Invalid(self.message('invalid_password',
192 raise formencode.Invalid(self.message('invalid_password',
193 state=State_obj), value, state,
193 state=State_obj), value, state,
194 error_dict=self.e_dict)
194 error_dict=self.e_dict)
195
195
196 class ValidRepoUser(formencode.validators.FancyValidator):
196 class ValidRepoUser(formencode.validators.FancyValidator):
197
197
198 def to_python(self, value, state):
198 def to_python(self, value, state):
199 sa = meta.Session()
199 sa = meta.Session()
200 try:
200 try:
201 self.user_db = sa.query(User)\
201 self.user_db = sa.query(User)\
202 .filter(User.active == True)\
202 .filter(User.active == True)\
203 .filter(User.username == value).one()
203 .filter(User.username == value).one()
204 except Exception:
204 except Exception:
205 raise formencode.Invalid(_('This username is not valid'),
205 raise formencode.Invalid(_('This username is not valid'),
206 value, state)
206 value, state)
207 finally:
207 finally:
208 meta.Session.remove()
208 meta.Session.remove()
209
209
210 return self.user_db.user_id
210 return self.user_db.user_id
211
211
212 def ValidRepoName(edit, old_data):
212 def ValidRepoName(edit, old_data):
213 class _ValidRepoName(formencode.validators.FancyValidator):
213 class _ValidRepoName(formencode.validators.FancyValidator):
214
214
215 def to_python(self, value, state):
215 def to_python(self, value, state):
216 slug = repo_name_slug(value)
216 slug = repo_name_slug(value)
217 if slug in ['_admin']:
217 if slug in ['_admin']:
218 raise formencode.Invalid(_('This repository name is disallowed'),
218 raise formencode.Invalid(_('This repository name is disallowed'),
219 value, state)
219 value, state)
220 if old_data.get('repo_name') != value or not edit:
220 if old_data.get('repo_name') != value or not edit:
221 if RepoModel().get_by_repo_name(slug, cache=False):
221 if RepoModel().get_by_repo_name(slug, cache=False):
222 raise formencode.Invalid(_('This repository already exists') ,
222 raise formencode.Invalid(_('This repository already exists') ,
223 value, state)
223 value, state)
224 return slug
224 return slug
225
225
226
226
227 return _ValidRepoName
227 return _ValidRepoName
228
228
229 def ValidCloneUri():
230 from mercurial.httprepo import httprepository, httpsrepository
231 from rhodecode.lib.utils import make_ui
232
233 class _ValidCloneUri(formencode.validators.FancyValidator):
234 def to_python(self, value, state):
235 if not value:
236 pass
237 elif value.startswith('https'):
238 try:
239 httpsrepository(make_ui('db'), value).capabilities()
240 except:
241 raise formencode.Invalid(_('invalid clone url'), value,
242 state)
243 elif value.startswith('http'):
244 try:
245 httprepository(make_ui('db'), value).capabilities()
246 except:
247 raise formencode.Invalid(_('invalid clone url'), value,
248 state)
249 else:
250 raise formencode.Invalid(_('Invalid clone url, provide a '
251 'valid clone http\s url'), value,
252 state)
253
254 return _ValidCloneUri
255
229 def ValidForkType(old_data):
256 def ValidForkType(old_data):
230 class _ValidForkType(formencode.validators.FancyValidator):
257 class _ValidForkType(formencode.validators.FancyValidator):
231
258
232 def to_python(self, value, state):
259 def to_python(self, value, state):
233 if old_data['repo_type'] != value:
260 if old_data['repo_type'] != value:
234 raise formencode.Invalid(_('Fork have to be the same type as original'),
261 raise formencode.Invalid(_('Fork have to be the same '
235 value, state)
262 'type as original'), value, state)
236 return value
263 return value
237 return _ValidForkType
264 return _ValidForkType
238
265
239 class ValidPerms(formencode.validators.FancyValidator):
266 class ValidPerms(formencode.validators.FancyValidator):
240 messages = {'perm_new_member_name':_('This username or users group name'
267 messages = {'perm_new_member_name':_('This username or users group name'
241 ' is not valid')}
268 ' is not valid')}
242
269
243 def to_python(self, value, state):
270 def to_python(self, value, state):
244 perms_update = []
271 perms_update = []
245 perms_new = []
272 perms_new = []
246 #build a list of permission to update and new permission to create
273 #build a list of permission to update and new permission to create
247 for k, v in value.items():
274 for k, v in value.items():
248 #means new added member to permissions
275 #means new added member to permissions
249 if k.startswith('perm_new_member'):
276 if k.startswith('perm_new_member'):
250 new_perm = value.get('perm_new_member', False)
277 new_perm = value.get('perm_new_member', False)
251 new_member = value.get('perm_new_member_name', False)
278 new_member = value.get('perm_new_member_name', False)
252 new_type = value.get('perm_new_member_type')
279 new_type = value.get('perm_new_member_type')
253
280
254 if new_member and new_perm:
281 if new_member and new_perm:
255 if (new_member, new_perm, new_type) not in perms_new:
282 if (new_member, new_perm, new_type) not in perms_new:
256 perms_new.append((new_member, new_perm, new_type))
283 perms_new.append((new_member, new_perm, new_type))
257 elif k.startswith('u_perm_') or k.startswith('g_perm_'):
284 elif k.startswith('u_perm_') or k.startswith('g_perm_'):
258 member = k[7:]
285 member = k[7:]
259 t = {'u':'user',
286 t = {'u':'user',
260 'g':'users_group'}[k[0]]
287 'g':'users_group'}[k[0]]
261 if member == 'default':
288 if member == 'default':
262 if value['private']:
289 if value['private']:
263 #set none for default when updating to private repo
290 #set none for default when updating to private repo
264 v = 'repository.none'
291 v = 'repository.none'
265 perms_update.append((member, v, t))
292 perms_update.append((member, v, t))
266
293
267 value['perms_updates'] = perms_update
294 value['perms_updates'] = perms_update
268 value['perms_new'] = perms_new
295 value['perms_new'] = perms_new
269
296
270 #update permissions
297 #update permissions
271 sa = meta.Session
298 sa = meta.Session
272 for k, v, t in perms_new:
299 for k, v, t in perms_new:
273 try:
300 try:
274 if t is 'user':
301 if t is 'user':
275 self.user_db = sa.query(User)\
302 self.user_db = sa.query(User)\
276 .filter(User.active == True)\
303 .filter(User.active == True)\
277 .filter(User.username == k).one()
304 .filter(User.username == k).one()
278 if t is 'users_group':
305 if t is 'users_group':
279 self.user_db = sa.query(UsersGroup)\
306 self.user_db = sa.query(UsersGroup)\
280 .filter(UsersGroup.users_group_active == True)\
307 .filter(UsersGroup.users_group_active == True)\
281 .filter(UsersGroup.users_group_name == k).one()
308 .filter(UsersGroup.users_group_name == k).one()
282
309
283 except Exception:
310 except Exception:
284 msg = self.message('perm_new_member_name',
311 msg = self.message('perm_new_member_name',
285 state=State_obj)
312 state=State_obj)
286 raise formencode.Invalid(msg, value, state,
313 raise formencode.Invalid(msg, value, state,
287 error_dict={'perm_new_member_name':msg})
314 error_dict={'perm_new_member_name':msg})
288 return value
315 return value
289
316
290 class ValidSettings(formencode.validators.FancyValidator):
317 class ValidSettings(formencode.validators.FancyValidator):
291
318
292 def to_python(self, value, state):
319 def to_python(self, value, state):
293 #settings form can't edit user
320 #settings form can't edit user
294 if value.has_key('user'):
321 if value.has_key('user'):
295 del['value']['user']
322 del['value']['user']
296
323
297 return value
324 return value
298
325
299 class ValidPath(formencode.validators.FancyValidator):
326 class ValidPath(formencode.validators.FancyValidator):
300 def to_python(self, value, state):
327 def to_python(self, value, state):
301
328
302 if not os.path.isdir(value):
329 if not os.path.isdir(value):
303 msg = _('This is not a valid path')
330 msg = _('This is not a valid path')
304 raise formencode.Invalid(msg, value, state,
331 raise formencode.Invalid(msg, value, state,
305 error_dict={'paths_root_path':msg})
332 error_dict={'paths_root_path':msg})
306 return value
333 return value
307
334
308 def UniqSystemEmail(old_data):
335 def UniqSystemEmail(old_data):
309 class _UniqSystemEmail(formencode.validators.FancyValidator):
336 class _UniqSystemEmail(formencode.validators.FancyValidator):
310 def to_python(self, value, state):
337 def to_python(self, value, state):
311 value = value.lower()
338 value = value.lower()
312 if old_data.get('email') != value:
339 if old_data.get('email') != value:
313 sa = meta.Session()
340 sa = meta.Session()
314 try:
341 try:
315 user = sa.query(User).filter(User.email == value).scalar()
342 user = sa.query(User).filter(User.email == value).scalar()
316 if user:
343 if user:
317 raise formencode.Invalid(_("This e-mail address is already taken") ,
344 raise formencode.Invalid(_("This e-mail address is already taken") ,
318 value, state)
345 value, state)
319 finally:
346 finally:
320 meta.Session.remove()
347 meta.Session.remove()
321
348
322 return value
349 return value
323
350
324 return _UniqSystemEmail
351 return _UniqSystemEmail
325
352
326 class ValidSystemEmail(formencode.validators.FancyValidator):
353 class ValidSystemEmail(formencode.validators.FancyValidator):
327 def to_python(self, value, state):
354 def to_python(self, value, state):
328 value = value.lower()
355 value = value.lower()
329 sa = meta.Session
356 sa = meta.Session
330 try:
357 try:
331 user = sa.query(User).filter(User.email == value).scalar()
358 user = sa.query(User).filter(User.email == value).scalar()
332 if user is None:
359 if user is None:
333 raise formencode.Invalid(_("This e-mail address doesn't exist.") ,
360 raise formencode.Invalid(_("This e-mail address doesn't exist.") ,
334 value, state)
361 value, state)
335 finally:
362 finally:
336 meta.Session.remove()
363 meta.Session.remove()
337
364
338 return value
365 return value
339
366
340 class LdapLibValidator(formencode.validators.FancyValidator):
367 class LdapLibValidator(formencode.validators.FancyValidator):
341
368
342 def to_python(self, value, state):
369 def to_python(self, value, state):
343
370
344 try:
371 try:
345 import ldap
372 import ldap
346 except ImportError:
373 except ImportError:
347 raise LdapImportError
374 raise LdapImportError
348 return value
375 return value
349
376
350 class AttrLoginValidator(formencode.validators.FancyValidator):
377 class AttrLoginValidator(formencode.validators.FancyValidator):
351
378
352 def to_python(self, value, state):
379 def to_python(self, value, state):
353
380
354 if not value or not isinstance(value, (str, unicode)):
381 if not value or not isinstance(value, (str, unicode)):
355 raise formencode.Invalid(_("The LDAP Login attribute of the CN "
382 raise formencode.Invalid(_("The LDAP Login attribute of the CN "
356 "must be specified - this is the name "
383 "must be specified - this is the name "
357 "of the attribute that is equivalent "
384 "of the attribute that is equivalent "
358 "to 'username'"),
385 "to 'username'"),
359 value, state)
386 value, state)
360
387
361 return value
388 return value
362
389
363 #===============================================================================
390 #===============================================================================
364 # FORMS
391 # FORMS
365 #===============================================================================
392 #===============================================================================
366 class LoginForm(formencode.Schema):
393 class LoginForm(formencode.Schema):
367 allow_extra_fields = True
394 allow_extra_fields = True
368 filter_extra_fields = True
395 filter_extra_fields = True
369 username = UnicodeString(
396 username = UnicodeString(
370 strip=True,
397 strip=True,
371 min=1,
398 min=1,
372 not_empty=True,
399 not_empty=True,
373 messages={
400 messages={
374 'empty':_('Please enter a login'),
401 'empty':_('Please enter a login'),
375 'tooShort':_('Enter a value %(min)i characters long or more')}
402 'tooShort':_('Enter a value %(min)i characters long or more')}
376 )
403 )
377
404
378 password = UnicodeString(
405 password = UnicodeString(
379 strip=True,
406 strip=True,
380 min=6,
407 min=6,
381 not_empty=True,
408 not_empty=True,
382 messages={
409 messages={
383 'empty':_('Please enter a password'),
410 'empty':_('Please enter a password'),
384 'tooShort':_('Enter %(min)i characters or more')}
411 'tooShort':_('Enter %(min)i characters or more')}
385 )
412 )
386
413
387
414
388 #chained validators have access to all data
415 #chained validators have access to all data
389 chained_validators = [ValidAuth]
416 chained_validators = [ValidAuth]
390
417
391 def UserForm(edit=False, old_data={}):
418 def UserForm(edit=False, old_data={}):
392 class _UserForm(formencode.Schema):
419 class _UserForm(formencode.Schema):
393 allow_extra_fields = True
420 allow_extra_fields = True
394 filter_extra_fields = True
421 filter_extra_fields = True
395 username = All(UnicodeString(strip=True, min=1, not_empty=True),
422 username = All(UnicodeString(strip=True, min=1, not_empty=True),
396 ValidUsername(edit, old_data))
423 ValidUsername(edit, old_data))
397 if edit:
424 if edit:
398 new_password = All(UnicodeString(strip=True, min=6, not_empty=False))
425 new_password = All(UnicodeString(strip=True, min=6, not_empty=False))
399 admin = StringBoolean(if_missing=False)
426 admin = StringBoolean(if_missing=False)
400 else:
427 else:
401 password = All(UnicodeString(strip=True, min=6, not_empty=True))
428 password = All(UnicodeString(strip=True, min=6, not_empty=True))
402 active = StringBoolean(if_missing=False)
429 active = StringBoolean(if_missing=False)
403 name = UnicodeString(strip=True, min=1, not_empty=True)
430 name = UnicodeString(strip=True, min=1, not_empty=True)
404 lastname = UnicodeString(strip=True, min=1, not_empty=True)
431 lastname = UnicodeString(strip=True, min=1, not_empty=True)
405 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
432 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
406
433
407 chained_validators = [ValidPassword]
434 chained_validators = [ValidPassword]
408
435
409 return _UserForm
436 return _UserForm
410
437
411
438
412 def UsersGroupForm(edit=False, old_data={}, available_members=[]):
439 def UsersGroupForm(edit=False, old_data={}, available_members=[]):
413 class _UsersGroupForm(formencode.Schema):
440 class _UsersGroupForm(formencode.Schema):
414 allow_extra_fields = True
441 allow_extra_fields = True
415 filter_extra_fields = True
442 filter_extra_fields = True
416
443
417 users_group_name = All(UnicodeString(strip=True, min=1, not_empty=True),
444 users_group_name = All(UnicodeString(strip=True, min=1, not_empty=True),
418 ValidUsersGroup(edit, old_data))
445 ValidUsersGroup(edit, old_data))
419
446
420 users_group_active = StringBoolean(if_missing=False)
447 users_group_active = StringBoolean(if_missing=False)
421
448
422 if edit:
449 if edit:
423 users_group_members = OneOf(available_members, hideList=False,
450 users_group_members = OneOf(available_members, hideList=False,
424 testValueList=True,
451 testValueList=True,
425 if_missing=None, not_empty=False)
452 if_missing=None, not_empty=False)
426
453
427 return _UsersGroupForm
454 return _UsersGroupForm
428
455
429 def RegisterForm(edit=False, old_data={}):
456 def RegisterForm(edit=False, old_data={}):
430 class _RegisterForm(formencode.Schema):
457 class _RegisterForm(formencode.Schema):
431 allow_extra_fields = True
458 allow_extra_fields = True
432 filter_extra_fields = True
459 filter_extra_fields = True
433 username = All(ValidUsername(edit, old_data),
460 username = All(ValidUsername(edit, old_data),
434 UnicodeString(strip=True, min=1, not_empty=True))
461 UnicodeString(strip=True, min=1, not_empty=True))
435 password = All(UnicodeString(strip=True, min=6, not_empty=True))
462 password = All(UnicodeString(strip=True, min=6, not_empty=True))
436 password_confirmation = All(UnicodeString(strip=True, min=6, not_empty=True))
463 password_confirmation = All(UnicodeString(strip=True, min=6, not_empty=True))
437 active = StringBoolean(if_missing=False)
464 active = StringBoolean(if_missing=False)
438 name = UnicodeString(strip=True, min=1, not_empty=True)
465 name = UnicodeString(strip=True, min=1, not_empty=True)
439 lastname = UnicodeString(strip=True, min=1, not_empty=True)
466 lastname = UnicodeString(strip=True, min=1, not_empty=True)
440 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
467 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
441
468
442 chained_validators = [ValidPasswordsMatch, ValidPassword]
469 chained_validators = [ValidPasswordsMatch, ValidPassword]
443
470
444 return _RegisterForm
471 return _RegisterForm
445
472
446 def PasswordResetForm():
473 def PasswordResetForm():
447 class _PasswordResetForm(formencode.Schema):
474 class _PasswordResetForm(formencode.Schema):
448 allow_extra_fields = True
475 allow_extra_fields = True
449 filter_extra_fields = True
476 filter_extra_fields = True
450 email = All(ValidSystemEmail(), Email(not_empty=True))
477 email = All(ValidSystemEmail(), Email(not_empty=True))
451 return _PasswordResetForm
478 return _PasswordResetForm
452
479
453 def RepoForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(),
480 def RepoForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(),
454 repo_groups=[]):
481 repo_groups=[]):
455 class _RepoForm(formencode.Schema):
482 class _RepoForm(formencode.Schema):
456 allow_extra_fields = True
483 allow_extra_fields = True
457 filter_extra_fields = False
484 filter_extra_fields = False
458 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True),
485 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True),
459 ValidRepoName(edit, old_data))
486 ValidRepoName(edit, old_data))
460 clone_uri = UnicodeString(strip=True, min=1, not_empty=False)
487 clone_uri = All(UnicodeString(strip=True, min=1, not_empty=False),
488 ValidCloneUri()())
461 repo_group = OneOf(repo_groups, hideList=True)
489 repo_group = OneOf(repo_groups, hideList=True)
462 repo_type = OneOf(supported_backends)
490 repo_type = OneOf(supported_backends)
463 description = UnicodeString(strip=True, min=1, not_empty=True)
491 description = UnicodeString(strip=True, min=1, not_empty=True)
464 private = StringBoolean(if_missing=False)
492 private = StringBoolean(if_missing=False)
465 enable_statistics = StringBoolean(if_missing=False)
493 enable_statistics = StringBoolean(if_missing=False)
466 enable_downloads = StringBoolean(if_missing=False)
494 enable_downloads = StringBoolean(if_missing=False)
467
495
468 if edit:
496 if edit:
469 #this is repo owner
497 #this is repo owner
470 user = All(Int(not_empty=True), ValidRepoUser)
498 user = All(Int(not_empty=True), ValidRepoUser)
471
499
472 chained_validators = [ValidPerms]
500 chained_validators = [ValidPerms]
473 return _RepoForm
501 return _RepoForm
474
502
475 def RepoForkForm(edit=False, old_data={}, supported_backends=BACKENDS.keys()):
503 def RepoForkForm(edit=False, old_data={}, supported_backends=BACKENDS.keys()):
476 class _RepoForkForm(formencode.Schema):
504 class _RepoForkForm(formencode.Schema):
477 allow_extra_fields = True
505 allow_extra_fields = True
478 filter_extra_fields = False
506 filter_extra_fields = False
479 fork_name = All(UnicodeString(strip=True, min=1, not_empty=True),
507 fork_name = All(UnicodeString(strip=True, min=1, not_empty=True),
480 ValidRepoName(edit, old_data))
508 ValidRepoName(edit, old_data))
481 description = UnicodeString(strip=True, min=1, not_empty=True)
509 description = UnicodeString(strip=True, min=1, not_empty=True)
482 private = StringBoolean(if_missing=False)
510 private = StringBoolean(if_missing=False)
483 repo_type = All(ValidForkType(old_data), OneOf(supported_backends))
511 repo_type = All(ValidForkType(old_data), OneOf(supported_backends))
484 return _RepoForkForm
512 return _RepoForkForm
485
513
486 def RepoSettingsForm(edit=False, old_data={}):
514 def RepoSettingsForm(edit=False, old_data={}):
487 class _RepoForm(formencode.Schema):
515 class _RepoForm(formencode.Schema):
488 allow_extra_fields = True
516 allow_extra_fields = True
489 filter_extra_fields = False
517 filter_extra_fields = False
490 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True),
518 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True),
491 ValidRepoName(edit, old_data))
519 ValidRepoName(edit, old_data))
492 description = UnicodeString(strip=True, min=1, not_empty=True)
520 description = UnicodeString(strip=True, min=1, not_empty=True)
493 private = StringBoolean(if_missing=False)
521 private = StringBoolean(if_missing=False)
494
522
495 chained_validators = [ValidPerms, ValidSettings]
523 chained_validators = [ValidPerms, ValidSettings]
496 return _RepoForm
524 return _RepoForm
497
525
498
526
499 def ApplicationSettingsForm():
527 def ApplicationSettingsForm():
500 class _ApplicationSettingsForm(formencode.Schema):
528 class _ApplicationSettingsForm(formencode.Schema):
501 allow_extra_fields = True
529 allow_extra_fields = True
502 filter_extra_fields = False
530 filter_extra_fields = False
503 rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True)
531 rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True)
504 rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True)
532 rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True)
505 rhodecode_ga_code = UnicodeString(strip=True, min=1, not_empty=False)
533 rhodecode_ga_code = UnicodeString(strip=True, min=1, not_empty=False)
506
534
507 return _ApplicationSettingsForm
535 return _ApplicationSettingsForm
508
536
509 def ApplicationUiSettingsForm():
537 def ApplicationUiSettingsForm():
510 class _ApplicationUiSettingsForm(formencode.Schema):
538 class _ApplicationUiSettingsForm(formencode.Schema):
511 allow_extra_fields = True
539 allow_extra_fields = True
512 filter_extra_fields = False
540 filter_extra_fields = False
513 web_push_ssl = OneOf(['true', 'false'], if_missing='false')
541 web_push_ssl = OneOf(['true', 'false'], if_missing='false')
514 paths_root_path = All(ValidPath(), UnicodeString(strip=True, min=1, not_empty=True))
542 paths_root_path = All(ValidPath(), UnicodeString(strip=True, min=1, not_empty=True))
515 hooks_changegroup_update = OneOf(['True', 'False'], if_missing=False)
543 hooks_changegroup_update = OneOf(['True', 'False'], if_missing=False)
516 hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False)
544 hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False)
517 hooks_pretxnchangegroup_push_logger = OneOf(['True', 'False'], if_missing=False)
545 hooks_pretxnchangegroup_push_logger = OneOf(['True', 'False'], if_missing=False)
518 hooks_preoutgoing_pull_logger = OneOf(['True', 'False'], if_missing=False)
546 hooks_preoutgoing_pull_logger = OneOf(['True', 'False'], if_missing=False)
519
547
520 return _ApplicationUiSettingsForm
548 return _ApplicationUiSettingsForm
521
549
522 def DefaultPermissionsForm(perms_choices, register_choices, create_choices):
550 def DefaultPermissionsForm(perms_choices, register_choices, create_choices):
523 class _DefaultPermissionsForm(formencode.Schema):
551 class _DefaultPermissionsForm(formencode.Schema):
524 allow_extra_fields = True
552 allow_extra_fields = True
525 filter_extra_fields = True
553 filter_extra_fields = True
526 overwrite_default = StringBoolean(if_missing=False)
554 overwrite_default = StringBoolean(if_missing=False)
527 anonymous = OneOf(['True', 'False'], if_missing=False)
555 anonymous = OneOf(['True', 'False'], if_missing=False)
528 default_perm = OneOf(perms_choices)
556 default_perm = OneOf(perms_choices)
529 default_register = OneOf(register_choices)
557 default_register = OneOf(register_choices)
530 default_create = OneOf(create_choices)
558 default_create = OneOf(create_choices)
531
559
532 return _DefaultPermissionsForm
560 return _DefaultPermissionsForm
533
561
534
562
535 def LdapSettingsForm(tls_reqcert_choices, search_scope_choices):
563 def LdapSettingsForm(tls_reqcert_choices, search_scope_choices):
536 class _LdapSettingsForm(formencode.Schema):
564 class _LdapSettingsForm(formencode.Schema):
537 allow_extra_fields = True
565 allow_extra_fields = True
538 filter_extra_fields = True
566 filter_extra_fields = True
539 pre_validators = [LdapLibValidator]
567 pre_validators = [LdapLibValidator]
540 ldap_active = StringBoolean(if_missing=False)
568 ldap_active = StringBoolean(if_missing=False)
541 ldap_host = UnicodeString(strip=True,)
569 ldap_host = UnicodeString(strip=True,)
542 ldap_port = Number(strip=True,)
570 ldap_port = Number(strip=True,)
543 ldap_ldaps = StringBoolean(if_missing=False)
571 ldap_ldaps = StringBoolean(if_missing=False)
544 ldap_tls_reqcert = OneOf(tls_reqcert_choices)
572 ldap_tls_reqcert = OneOf(tls_reqcert_choices)
545 ldap_dn_user = UnicodeString(strip=True,)
573 ldap_dn_user = UnicodeString(strip=True,)
546 ldap_dn_pass = UnicodeString(strip=True,)
574 ldap_dn_pass = UnicodeString(strip=True,)
547 ldap_base_dn = UnicodeString(strip=True,)
575 ldap_base_dn = UnicodeString(strip=True,)
548 ldap_filter = UnicodeString(strip=True,)
576 ldap_filter = UnicodeString(strip=True,)
549 ldap_search_scope = OneOf(search_scope_choices)
577 ldap_search_scope = OneOf(search_scope_choices)
550 ldap_attr_login = All(AttrLoginValidator, UnicodeString(strip=True,))
578 ldap_attr_login = All(AttrLoginValidator, UnicodeString(strip=True,))
551 ldap_attr_firstname = UnicodeString(strip=True,)
579 ldap_attr_firstname = UnicodeString(strip=True,)
552 ldap_attr_lastname = UnicodeString(strip=True,)
580 ldap_attr_lastname = UnicodeString(strip=True,)
553 ldap_attr_email = UnicodeString(strip=True,)
581 ldap_attr_email = UnicodeString(strip=True,)
554
582
555 return _LdapSettingsForm
583 return _LdapSettingsForm
General Comments 0
You need to be logged in to leave comments. Login now