comparison rhodecode/model/forms.py @ 2031:82a88013a3fd

merge 1.3 into stable
author Marcin Kuzminski <marcin@python-works.com>
date Sun, 26 Feb 2012 17:25:09 +0200
parents 0f463fa8b260 7e979933ffec
children 9ab21c5ddb84
comparison
equal deleted inserted replaced
2005:ab0e122b38a7 2031:82a88013a3fd
34 34
35 from rhodecode.config.routing import ADMIN_PREFIX 35 from rhodecode.config.routing import ADMIN_PREFIX
36 from rhodecode.lib.utils import repo_name_slug 36 from rhodecode.lib.utils import repo_name_slug
37 from rhodecode.lib.auth import authenticate, get_crypt_password 37 from rhodecode.lib.auth import authenticate, get_crypt_password
38 from rhodecode.lib.exceptions import LdapImportError 38 from rhodecode.lib.exceptions import LdapImportError
39 from rhodecode.model.user import UserModel 39 from rhodecode.model.db import User, UsersGroup, RepoGroup, Repository
40 from rhodecode.model.repo import RepoModel
41 from rhodecode.model.db import User, UsersGroup, Group, Repository
42 from rhodecode import BACKENDS 40 from rhodecode import BACKENDS
43 41
44 log = logging.getLogger(__name__) 42 log = logging.getLogger(__name__)
43
45 44
46 #this is needed to translate the messages using _() in validators 45 #this is needed to translate the messages using _() in validators
47 class State_obj(object): 46 class State_obj(object):
48 _ = staticmethod(_) 47 _ = staticmethod(_)
48
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(
60 search_number=value), value, state) 60 self.message('invalid_token',
61 state, search_number=value),
62 value,
63 state
64 )
65
61 66
62 def ValidUsername(edit, old_data): 67 def ValidUsername(edit, old_data):
63 class _ValidUsername(formencode.validators.FancyValidator): 68 class _ValidUsername(formencode.validators.FancyValidator):
64 69
65 def validate_python(self, value, state): 70 def validate_python(self, value, state):
66 if value in ['default', 'new_user']: 71 if value in ['default', 'new_user']:
67 raise formencode.Invalid(_('Invalid username'), value, state) 72 raise formencode.Invalid(_('Invalid username'), value, state)
68 #check if user is unique 73 #check if user is unique
69 old_un = None 74 old_un = None
70 if edit: 75 if edit:
71 old_un = UserModel().get(old_data.get('user_id')).username 76 old_un = User.get(old_data.get('user_id')).username
72 77
73 if old_un != value or not edit: 78 if old_un != value or not edit:
74 if User.get_by_username(value, case_insensitive=True): 79 if User.get_by_username(value, case_insensitive=True):
75 raise formencode.Invalid(_('This username already ' 80 raise formencode.Invalid(_('This username already '
76 'exists') , value, state) 81 'exists') , value, state)
77 82
78 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None: 83 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
79 raise formencode.Invalid(_('Username may only contain ' 84 raise formencode.Invalid(
80 'alphanumeric characters ' 85 _('Username may only contain alphanumeric characters '
81 'underscores, periods or dashes ' 86 'underscores, periods or dashes and must begin with '
82 'and must begin with alphanumeric ' 87 'alphanumeric character'),
83 'character'), value, state) 88 value,
89 state
90 )
84 91
85 return _ValidUsername 92 return _ValidUsername
86 93
87 94
88 def ValidUsersGroup(edit, old_data): 95 def ValidUsersGroup(edit, old_data):
100 107
101 if old_ugname != value or not edit: 108 if old_ugname != value or not edit:
102 if UsersGroup.get_by_group_name(value, cache=False, 109 if UsersGroup.get_by_group_name(value, cache=False,
103 case_insensitive=True): 110 case_insensitive=True):
104 raise formencode.Invalid(_('This users group ' 111 raise formencode.Invalid(_('This users group '
105 'already exists') , value, 112 'already exists'), value,
106 state) 113 state)
107 114
108
109 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None: 115 if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
110 raise formencode.Invalid(_('Group name may only contain ' 116 raise formencode.Invalid(
111 'alphanumeric characters ' 117 _('RepoGroup name may only contain alphanumeric characters '
112 'underscores, periods or dashes ' 118 'underscores, periods or dashes and must begin with '
113 'and must begin with alphanumeric ' 119 'alphanumeric character'),
114 'character'), value, state) 120 value,
121 state
122 )
115 123
116 return _ValidUsersGroup 124 return _ValidUsersGroup
117 125
118 126
119 def ValidReposGroup(edit, old_data): 127 def ValidReposGroup(edit, old_data):
139 raise formencode.Invalid('', value, state, 147 raise formencode.Invalid('', value, state,
140 error_dict=e_dict) 148 error_dict=e_dict)
141 149
142 old_gname = None 150 old_gname = None
143 if edit: 151 if edit:
144 old_gname = Group.get( 152 old_gname = RepoGroup.get(old_data.get('group_id')).group_name
145 old_data.get('group_id')).group_name
146 153
147 if old_gname != group_name or not edit: 154 if old_gname != group_name or not edit:
148 155
149 # check group 156 # check group
150 gr = Group.query()\ 157 gr = RepoGroup.query()\
151 .filter(Group.group_name == slug)\ 158 .filter(RepoGroup.group_name == slug)\
152 .filter(Group.group_parent_id == group_parent_id)\ 159 .filter(RepoGroup.group_parent_id == group_parent_id)\
153 .scalar() 160 .scalar()
154 161
155 if gr: 162 if gr:
156 e_dict = { 163 e_dict = {
157 'group_name': _('This group already exists') 164 'group_name': _('This group already exists')
171 raise formencode.Invalid('', value, state, 178 raise formencode.Invalid('', value, state,
172 error_dict=e_dict) 179 error_dict=e_dict)
173 180
174 return _ValidReposGroup 181 return _ValidReposGroup
175 182
183
176 class ValidPassword(formencode.validators.FancyValidator): 184 class ValidPassword(formencode.validators.FancyValidator):
177 185
178 def to_python(self, value, state): 186 def to_python(self, value, state):
179 187
180 if value: 188 if not value:
181 189 return
182 if value.get('password'): 190
183 try: 191 if value.get('password'):
184 value['password'] = get_crypt_password(value['password']) 192 try:
185 except UnicodeEncodeError: 193 value['password'] = get_crypt_password(value['password'])
186 e_dict = {'password':_('Invalid characters in password')} 194 except UnicodeEncodeError:
187 raise formencode.Invalid('', value, state, error_dict=e_dict) 195 e_dict = {'password': _('Invalid characters in password')}
188 196 raise formencode.Invalid('', value, state, error_dict=e_dict)
189 if value.get('password_confirmation'): 197
190 try: 198 if value.get('password_confirmation'):
191 value['password_confirmation'] = \ 199 try:
192 get_crypt_password(value['password_confirmation']) 200 value['password_confirmation'] = \
193 except UnicodeEncodeError: 201 get_crypt_password(value['password_confirmation'])
194 e_dict = {'password_confirmation':_('Invalid characters in password')} 202 except UnicodeEncodeError:
195 raise formencode.Invalid('', value, state, error_dict=e_dict) 203 e_dict = {
196 204 'password_confirmation': _('Invalid characters in password')
197 if value.get('new_password'): 205 }
198 try: 206 raise formencode.Invalid('', value, state, error_dict=e_dict)
199 value['new_password'] = \ 207
200 get_crypt_password(value['new_password']) 208 if value.get('new_password'):
201 except UnicodeEncodeError: 209 try:
202 e_dict = {'new_password':_('Invalid characters in password')} 210 value['new_password'] = \
203 raise formencode.Invalid('', value, state, error_dict=e_dict) 211 get_crypt_password(value['new_password'])
204 212 except UnicodeEncodeError:
205 return value 213 e_dict = {'new_password': _('Invalid characters in password')}
214 raise formencode.Invalid('', value, state, error_dict=e_dict)
215
216 return value
217
206 218
207 class ValidPasswordsMatch(formencode.validators.FancyValidator): 219 class ValidPasswordsMatch(formencode.validators.FancyValidator):
208 220
209 def validate_python(self, value, state): 221 def validate_python(self, value, state):
210 222
211 pass_val = value.get('password') or value.get('new_password') 223 pass_val = value.get('password') or value.get('new_password')
212 if pass_val != value['password_confirmation']: 224 if pass_val != value['password_confirmation']:
213 e_dict = {'password_confirmation': 225 e_dict = {'password_confirmation':
214 _('Passwords do not match')} 226 _('Passwords do not match')}
215 raise formencode.Invalid('', value, state, error_dict=e_dict) 227 raise formencode.Invalid('', value, state, error_dict=e_dict)
228
216 229
217 class ValidAuth(formencode.validators.FancyValidator): 230 class ValidAuth(formencode.validators.FancyValidator):
218 messages = { 231 messages = {
219 'invalid_password':_('invalid password'), 232 'invalid_password':_('invalid password'),
220 'invalid_login':_('invalid user name'), 233 'invalid_login':_('invalid user name'),
221 'disabled_account':_('Your account is disabled') 234 'disabled_account':_('Your account is disabled')
222 } 235 }
223 236
224 # error mapping 237 # error mapping
225 e_dict = {'username':messages['invalid_login'], 238 e_dict = {'username': messages['invalid_login'],
226 'password':messages['invalid_password']} 239 'password': messages['invalid_password']}
227 e_dict_disable = {'username':messages['disabled_account']} 240 e_dict_disable = {'username': messages['disabled_account']}
228 241
229 def validate_python(self, value, state): 242 def validate_python(self, value, state):
230 password = value['password'] 243 password = value['password']
231 username = value['username'] 244 username = value['username']
232 user = User.get_by_username(username) 245 user = User.get_by_username(username)
233 246
234 if authenticate(username, password): 247 if authenticate(username, password):
235 return value 248 return value
236 else: 249 else:
237 if user and user.active is False: 250 if user and user.active is False:
238 log.warning('user %s is disabled', username) 251 log.warning('user %s is disabled' % username)
239 raise formencode.Invalid(self.message('disabled_account', 252 raise formencode.Invalid(
240 state=State_obj), 253 self.message('disabled_account',
241 value, state, 254 state=State_obj),
242 error_dict=self.e_dict_disable) 255 value, state,
256 error_dict=self.e_dict_disable
257 )
243 else: 258 else:
244 log.warning('user %s not authenticated', username) 259 log.warning('user %s failed to authenticate' % username)
245 raise formencode.Invalid(self.message('invalid_password', 260 raise formencode.Invalid(
246 state=State_obj), value, state, 261 self.message('invalid_password',
247 error_dict=self.e_dict) 262 state=State_obj), value, state,
263 error_dict=self.e_dict
264 )
265
248 266
249 class ValidRepoUser(formencode.validators.FancyValidator): 267 class ValidRepoUser(formencode.validators.FancyValidator):
250 268
251 def to_python(self, value, state): 269 def to_python(self, value, state):
252 try: 270 try:
255 except Exception: 273 except Exception:
256 raise formencode.Invalid(_('This username is not valid'), 274 raise formencode.Invalid(_('This username is not valid'),
257 value, state) 275 value, state)
258 return value 276 return value
259 277
278
260 def ValidRepoName(edit, old_data): 279 def ValidRepoName(edit, old_data):
261 class _ValidRepoName(formencode.validators.FancyValidator): 280 class _ValidRepoName(formencode.validators.FancyValidator):
262 def to_python(self, value, state): 281 def to_python(self, value, state):
263 282
264 repo_name = value.get('repo_name') 283 repo_name = value.get('repo_name')
266 slug = repo_name_slug(repo_name) 285 slug = repo_name_slug(repo_name)
267 if slug in [ADMIN_PREFIX, '']: 286 if slug in [ADMIN_PREFIX, '']:
268 e_dict = {'repo_name': _('This repository name is disallowed')} 287 e_dict = {'repo_name': _('This repository name is disallowed')}
269 raise formencode.Invalid('', value, state, error_dict=e_dict) 288 raise formencode.Invalid('', value, state, error_dict=e_dict)
270 289
271
272 if value.get('repo_group'): 290 if value.get('repo_group'):
273 gr = Group.get(value.get('repo_group')) 291 gr = RepoGroup.get(value.get('repo_group'))
274 group_path = gr.full_path 292 group_path = gr.full_path
275 # value needs to be aware of group name in order to check 293 # value needs to be aware of group name in order to check
276 # db key This is an actual just the name to store in the 294 # db key This is an actual just the name to store in the
277 # database 295 # database
278 repo_name_full = group_path + Group.url_sep() + repo_name 296 repo_name_full = group_path + RepoGroup.url_sep() + repo_name
279 297
280 else: 298 else:
281 group_path = '' 299 group_path = ''
282 repo_name_full = repo_name 300 repo_name_full = repo_name
283
284 301
285 value['repo_name_full'] = repo_name_full 302 value['repo_name_full'] = repo_name_full
286 rename = old_data.get('repo_name') != repo_name_full 303 rename = old_data.get('repo_name') != repo_name_full
287 create = not edit 304 create = not edit
288 if rename or create: 305 if rename or create:
289 306
290 if group_path != '': 307 if group_path != '':
291 if RepoModel().get_by_repo_name(repo_name_full,): 308 if Repository.get_by_repo_name(repo_name_full):
292 e_dict = {'repo_name':_('This repository already ' 309 e_dict = {
293 'exists in a group "%s"') % 310 'repo_name': _('This repository already exists in '
294 gr.group_name} 311 'a group "%s"') % gr.group_name
312 }
295 raise formencode.Invalid('', value, state, 313 raise formencode.Invalid('', value, state,
296 error_dict=e_dict) 314 error_dict=e_dict)
297 elif Group.get_by_group_name(repo_name_full): 315 elif RepoGroup.get_by_group_name(repo_name_full):
298 e_dict = {'repo_name':_('There is a group with this' 316 e_dict = {
299 ' name already "%s"') % 317 'repo_name': _('There is a group with this name '
300 repo_name_full} 318 'already "%s"') % repo_name_full
319 }
301 raise formencode.Invalid('', value, state, 320 raise formencode.Invalid('', value, state,
302 error_dict=e_dict) 321 error_dict=e_dict)
303 322
304 elif RepoModel().get_by_repo_name(repo_name_full): 323 elif Repository.get_by_repo_name(repo_name_full):
305 e_dict = {'repo_name':_('This repository ' 324 e_dict = {'repo_name': _('This repository '
306 'already exists')} 325 'already exists')}
307 raise formencode.Invalid('', value, state, 326 raise formencode.Invalid('', value, state,
308 error_dict=e_dict) 327 error_dict=e_dict)
309 328
310 return value 329 return value
311 330
312 return _ValidRepoName 331 return _ValidRepoName
313 332
314 def ValidForkName(): 333
315 class _ValidForkName(formencode.validators.FancyValidator): 334 def ValidForkName(*args, **kwargs):
316 def to_python(self, value, state): 335 return ValidRepoName(*args, **kwargs)
317
318 repo_name = value.get('fork_name')
319
320 slug = repo_name_slug(repo_name)
321 if slug in [ADMIN_PREFIX, '']:
322 e_dict = {'repo_name': _('This repository name is disallowed')}
323 raise formencode.Invalid('', value, state, error_dict=e_dict)
324
325 if RepoModel().get_by_repo_name(repo_name):
326 e_dict = {'fork_name':_('This repository '
327 'already exists')}
328 raise formencode.Invalid('', value, state,
329 error_dict=e_dict)
330 return value
331 return _ValidForkName
332 336
333 337
334 def SlugifyName(): 338 def SlugifyName():
335 class _SlugifyName(formencode.validators.FancyValidator): 339 class _SlugifyName(formencode.validators.FancyValidator):
336 340
337 def to_python(self, value, state): 341 def to_python(self, value, state):
338 return repo_name_slug(value) 342 return repo_name_slug(value)
339 343
340 return _SlugifyName 344 return _SlugifyName
345
341 346
342 def ValidCloneUri(): 347 def ValidCloneUri():
343 from mercurial.httprepo import httprepository, httpsrepository 348 from mercurial.httprepo import httprepository, httpsrepository
344 from rhodecode.lib.utils import make_ui 349 from rhodecode.lib.utils import make_ui
345 350
349 if not value: 354 if not value:
350 pass 355 pass
351 elif value.startswith('https'): 356 elif value.startswith('https'):
352 try: 357 try:
353 httpsrepository(make_ui('db'), value).capabilities 358 httpsrepository(make_ui('db'), value).capabilities
354 except Exception, e: 359 except Exception:
355 log.error(traceback.format_exc()) 360 log.error(traceback.format_exc())
356 raise formencode.Invalid(_('invalid clone url'), value, 361 raise formencode.Invalid(_('invalid clone url'), value,
357 state) 362 state)
358 elif value.startswith('http'): 363 elif value.startswith('http'):
359 try: 364 try:
360 httprepository(make_ui('db'), value).capabilities 365 httprepository(make_ui('db'), value).capabilities
361 except Exception, e: 366 except Exception:
362 log.error(traceback.format_exc()) 367 log.error(traceback.format_exc())
363 raise formencode.Invalid(_('invalid clone url'), value, 368 raise formencode.Invalid(_('invalid clone url'), value,
364 state) 369 state)
365 else: 370 else:
366 raise formencode.Invalid(_('Invalid clone url, provide a ' 371 raise formencode.Invalid(_('Invalid clone url, provide a '
368 state) 373 state)
369 return value 374 return value
370 375
371 return _ValidCloneUri 376 return _ValidCloneUri
372 377
378
373 def ValidForkType(old_data): 379 def ValidForkType(old_data):
374 class _ValidForkType(formencode.validators.FancyValidator): 380 class _ValidForkType(formencode.validators.FancyValidator):
375 381
376 def to_python(self, value, state): 382 def to_python(self, value, state):
377 if old_data['repo_type'] != value: 383 if old_data['repo_type'] != value:
379 'type as original'), value, state) 385 'type as original'), value, state)
380 386
381 return value 387 return value
382 return _ValidForkType 388 return _ValidForkType
383 389
384 class ValidPerms(formencode.validators.FancyValidator): 390
385 messages = {'perm_new_member_name':_('This username or users group name' 391 def ValidPerms(type_='repo'):
386 ' is not valid')} 392 if type_ == 'group':
393 EMPTY_PERM = 'group.none'
394 elif type_ == 'repo':
395 EMPTY_PERM = 'repository.none'
396
397 class _ValidPerms(formencode.validators.FancyValidator):
398 messages = {
399 'perm_new_member_name':
400 _('This username or users group name is not valid')
401 }
402
403 def to_python(self, value, state):
404 perms_update = []
405 perms_new = []
406 # build a list of permission to update and new permission to create
407 for k, v in value.items():
408 # means new added member to permissions
409 if k.startswith('perm_new_member'):
410 new_perm = value.get('perm_new_member', False)
411 new_member = value.get('perm_new_member_name', False)
412 new_type = value.get('perm_new_member_type')
413
414 if new_member and new_perm:
415 if (new_member, new_perm, new_type) not in perms_new:
416 perms_new.append((new_member, new_perm, new_type))
417 elif k.startswith('u_perm_') or k.startswith('g_perm_'):
418 member = k[7:]
419 t = {'u': 'user',
420 'g': 'users_group'
421 }[k[0]]
422 if member == 'default':
423 if value.get('private'):
424 # set none for default when updating to private repo
425 v = EMPTY_PERM
426 perms_update.append((member, v, t))
427
428 value['perms_updates'] = perms_update
429 value['perms_new'] = perms_new
430
431 # update permissions
432 for k, v, t in perms_new:
433 try:
434 if t is 'user':
435 self.user_db = User.query()\
436 .filter(User.active == True)\
437 .filter(User.username == k).one()
438 if t is 'users_group':
439 self.user_db = UsersGroup.query()\
440 .filter(UsersGroup.users_group_active == True)\
441 .filter(UsersGroup.users_group_name == k).one()
442
443 except Exception:
444 msg = self.message('perm_new_member_name',
445 state=State_obj)
446 raise formencode.Invalid(
447 msg, value, state, error_dict={'perm_new_member_name': msg}
448 )
449 return value
450 return _ValidPerms
451
452
453 class ValidSettings(formencode.validators.FancyValidator):
387 454
388 def to_python(self, value, state): 455 def to_python(self, value, state):
389 perms_update = [] 456 # settings form can't edit user
390 perms_new = [] 457 if 'user' in value:
391 #build a list of permission to update and new permission to create 458 del['value']['user']
392 for k, v in value.items():
393 #means new added member to permissions
394 if k.startswith('perm_new_member'):
395 new_perm = value.get('perm_new_member', False)
396 new_member = value.get('perm_new_member_name', False)
397 new_type = value.get('perm_new_member_type')
398
399 if new_member and new_perm:
400 if (new_member, new_perm, new_type) not in perms_new:
401 perms_new.append((new_member, new_perm, new_type))
402 elif k.startswith('u_perm_') or k.startswith('g_perm_'):
403 member = k[7:]
404 t = {'u':'user',
405 'g':'users_group'}[k[0]]
406 if member == 'default':
407 if value['private']:
408 #set none for default when updating to private repo
409 v = 'repository.none'
410 perms_update.append((member, v, t))
411
412 value['perms_updates'] = perms_update
413 value['perms_new'] = perms_new
414
415 #update permissions
416 for k, v, t in perms_new:
417 try:
418 if t is 'user':
419 self.user_db = User.query()\
420 .filter(User.active == True)\
421 .filter(User.username == k).one()
422 if t is 'users_group':
423 self.user_db = UsersGroup.query()\
424 .filter(UsersGroup.users_group_active == True)\
425 .filter(UsersGroup.users_group_name == k).one()
426
427 except Exception:
428 msg = self.message('perm_new_member_name',
429 state=State_obj)
430 raise formencode.Invalid(msg, value, state,
431 error_dict={'perm_new_member_name':msg})
432 return value 459 return value
433 460
434 class ValidSettings(formencode.validators.FancyValidator):
435
436 def to_python(self, value, state):
437 #settings form can't edit user
438 if value.has_key('user'):
439 del['value']['user']
440
441 return value
442 461
443 class ValidPath(formencode.validators.FancyValidator): 462 class ValidPath(formencode.validators.FancyValidator):
444 def to_python(self, value, state): 463 def to_python(self, value, state):
445 464
446 if not os.path.isdir(value): 465 if not os.path.isdir(value):
447 msg = _('This is not a valid path') 466 msg = _('This is not a valid path')
448 raise formencode.Invalid(msg, value, state, 467 raise formencode.Invalid(msg, value, state,
449 error_dict={'paths_root_path':msg}) 468 error_dict={'paths_root_path': msg})
450 return value 469 return value
470
451 471
452 def UniqSystemEmail(old_data): 472 def UniqSystemEmail(old_data):
453 class _UniqSystemEmail(formencode.validators.FancyValidator): 473 class _UniqSystemEmail(formencode.validators.FancyValidator):
454 def to_python(self, value, state): 474 def to_python(self, value, state):
455 value = value.lower() 475 value = value.lower()
456 if old_data.get('email') != value: 476 if old_data.get('email', '').lower() != value:
457 user = User.query().filter(User.email == value).scalar() 477 user = User.get_by_email(value, case_insensitive=True)
458 if user: 478 if user:
459 raise formencode.Invalid( 479 raise formencode.Invalid(
460 _("This e-mail address is already taken"), 480 _("This e-mail address is already taken"), value, state
461 value, state) 481 )
462 return value 482 return value
463 483
464 return _UniqSystemEmail 484 return _UniqSystemEmail
485
465 486
466 class ValidSystemEmail(formencode.validators.FancyValidator): 487 class ValidSystemEmail(formencode.validators.FancyValidator):
467 def to_python(self, value, state): 488 def to_python(self, value, state):
468 value = value.lower() 489 value = value.lower()
469 user = User.query().filter(User.email == value).scalar() 490 user = User.get_by_email(value, case_insensitive=True)
470 if user is None: 491 if user is None:
471 raise formencode.Invalid(_("This e-mail address doesn't exist.") , 492 raise formencode.Invalid(
472 value, state) 493 _("This e-mail address doesn't exist."), value, state
494 )
473 495
474 return value 496 return value
497
475 498
476 class LdapLibValidator(formencode.validators.FancyValidator): 499 class LdapLibValidator(formencode.validators.FancyValidator):
477 500
478 def to_python(self, value, state): 501 def to_python(self, value, state):
479 502
481 import ldap 504 import ldap
482 except ImportError: 505 except ImportError:
483 raise LdapImportError 506 raise LdapImportError
484 return value 507 return value
485 508
509
486 class AttrLoginValidator(formencode.validators.FancyValidator): 510 class AttrLoginValidator(formencode.validators.FancyValidator):
487 511
488 def to_python(self, value, state): 512 def to_python(self, value, state):
489 513
490 if not value or not isinstance(value, (str, unicode)): 514 if not value or not isinstance(value, (str, unicode)):
491 raise formencode.Invalid(_("The LDAP Login attribute of the CN " 515 raise formencode.Invalid(
492 "must be specified - this is the name " 516 _("The LDAP Login attribute of the CN must be specified - "
493 "of the attribute that is equivalent " 517 "this is the name of the attribute that is equivalent "
494 "to 'username'"), 518 "to 'username'"), value, state
495 value, state) 519 )
496 520
497 return value 521 return value
498 522
499 #=============================================================================== 523
524 #==============================================================================
500 # FORMS 525 # FORMS
501 #=============================================================================== 526 #==============================================================================
502 class LoginForm(formencode.Schema): 527 class LoginForm(formencode.Schema):
503 allow_extra_fields = True 528 allow_extra_fields = True
504 filter_extra_fields = True 529 filter_extra_fields = True
505 username = UnicodeString( 530 username = UnicodeString(
506 strip=True, 531 strip=True,
507 min=1, 532 min=1,
508 not_empty=True, 533 not_empty=True,
509 messages={ 534 messages={
510 'empty':_('Please enter a login'), 535 'empty': _('Please enter a login'),
511 'tooShort':_('Enter a value %(min)i characters long or more')} 536 'tooShort': _('Enter a value %(min)i characters long or more')}
512 ) 537 )
513 538
514 password = UnicodeString( 539 password = UnicodeString(
515 strip=True, 540 strip=True,
516 min=3, 541 min=3,
517 not_empty=True, 542 not_empty=True,
518 messages={ 543 messages={
519 'empty':_('Please enter a password'), 544 'empty': _('Please enter a password'),
520 'tooShort':_('Enter %(min)i characters or more')} 545 'tooShort': _('Enter %(min)i characters or more')}
521 ) 546 )
547
548 remember = StringBoolean(if_missing=False)
522 549
523 chained_validators = [ValidAuth] 550 chained_validators = [ValidAuth]
551
524 552
525 def UserForm(edit=False, old_data={}): 553 def UserForm(edit=False, old_data={}):
526 class _UserForm(formencode.Schema): 554 class _UserForm(formencode.Schema):
527 allow_extra_fields = True 555 allow_extra_fields = True
528 filter_extra_fields = True 556 filter_extra_fields = True
529 username = All(UnicodeString(strip=True, min=1, not_empty=True), 557 username = All(UnicodeString(strip=True, min=1, not_empty=True),
530 ValidUsername(edit, old_data)) 558 ValidUsername(edit, old_data))
531 if edit: 559 if edit:
532 new_password = All(UnicodeString(strip=True, min=6, not_empty=False)) 560 new_password = All(UnicodeString(strip=True, min=6, not_empty=False))
533 password_confirmation = All(UnicodeString(strip=True, min=6, not_empty=False)) 561 password_confirmation = All(UnicodeString(strip=True, min=6,
562 not_empty=False))
534 admin = StringBoolean(if_missing=False) 563 admin = StringBoolean(if_missing=False)
535 else: 564 else:
536 password = All(UnicodeString(strip=True, min=6, not_empty=True)) 565 password = All(UnicodeString(strip=True, min=6, not_empty=True))
537 password_confirmation = All(UnicodeString(strip=True, min=6, not_empty=False)) 566 password_confirmation = All(UnicodeString(strip=True, min=6,
538 567 not_empty=False))
568
539 active = StringBoolean(if_missing=False) 569 active = StringBoolean(if_missing=False)
540 name = UnicodeString(strip=True, min=1, not_empty=True) 570 name = UnicodeString(strip=True, min=1, not_empty=False)
541 lastname = UnicodeString(strip=True, min=1, not_empty=True) 571 lastname = UnicodeString(strip=True, min=1, not_empty=False)
542 email = All(Email(not_empty=True), UniqSystemEmail(old_data)) 572 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
543 573
544 chained_validators = [ValidPasswordsMatch, ValidPassword] 574 chained_validators = [ValidPasswordsMatch, ValidPassword]
545 575
546 return _UserForm 576 return _UserForm
561 testValueList=True, 591 testValueList=True,
562 if_missing=None, not_empty=False) 592 if_missing=None, not_empty=False)
563 593
564 return _UsersGroupForm 594 return _UsersGroupForm
565 595
596
566 def ReposGroupForm(edit=False, old_data={}, available_groups=[]): 597 def ReposGroupForm(edit=False, old_data={}, available_groups=[]):
567 class _ReposGroupForm(formencode.Schema): 598 class _ReposGroupForm(formencode.Schema):
568 allow_extra_fields = True 599 allow_extra_fields = True
569 filter_extra_fields = True 600 filter_extra_fields = False
570 601
571 group_name = All(UnicodeString(strip=True, min=1, not_empty=True), 602 group_name = All(UnicodeString(strip=True, min=1, not_empty=True),
572 SlugifyName()) 603 SlugifyName())
573 group_description = UnicodeString(strip=True, min=1, 604 group_description = UnicodeString(strip=True, min=1,
574 not_empty=True) 605 not_empty=True)
575 group_parent_id = OneOf(available_groups, hideList=False, 606 group_parent_id = OneOf(available_groups, hideList=False,
576 testValueList=True, 607 testValueList=True,
577 if_missing=None, not_empty=False) 608 if_missing=None, not_empty=False)
578 609
579 chained_validators = [ValidReposGroup(edit, old_data)] 610 chained_validators = [ValidReposGroup(edit, old_data), ValidPerms('group')]
580 611
581 return _ReposGroupForm 612 return _ReposGroupForm
613
582 614
583 def RegisterForm(edit=False, old_data={}): 615 def RegisterForm(edit=False, old_data={}):
584 class _RegisterForm(formencode.Schema): 616 class _RegisterForm(formencode.Schema):
585 allow_extra_fields = True 617 allow_extra_fields = True
586 filter_extra_fields = True 618 filter_extra_fields = True
587 username = All(ValidUsername(edit, old_data), 619 username = All(ValidUsername(edit, old_data),
588 UnicodeString(strip=True, min=1, not_empty=True)) 620 UnicodeString(strip=True, min=1, not_empty=True))
589 password = All(UnicodeString(strip=True, min=6, not_empty=True)) 621 password = All(UnicodeString(strip=True, min=6, not_empty=True))
590 password_confirmation = All(UnicodeString(strip=True, min=6, not_empty=True)) 622 password_confirmation = All(UnicodeString(strip=True, min=6, not_empty=True))
591 active = StringBoolean(if_missing=False) 623 active = StringBoolean(if_missing=False)
592 name = UnicodeString(strip=True, min=1, not_empty=True) 624 name = UnicodeString(strip=True, min=1, not_empty=False)
593 lastname = UnicodeString(strip=True, min=1, not_empty=True) 625 lastname = UnicodeString(strip=True, min=1, not_empty=False)
594 email = All(Email(not_empty=True), UniqSystemEmail(old_data)) 626 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
595 627
596 chained_validators = [ValidPasswordsMatch, ValidPassword] 628 chained_validators = [ValidPasswordsMatch, ValidPassword]
597 629
598 return _RegisterForm 630 return _RegisterForm
631
599 632
600 def PasswordResetForm(): 633 def PasswordResetForm():
601 class _PasswordResetForm(formencode.Schema): 634 class _PasswordResetForm(formencode.Schema):
602 allow_extra_fields = True 635 allow_extra_fields = True
603 filter_extra_fields = True 636 filter_extra_fields = True
604 email = All(ValidSystemEmail(), Email(not_empty=True)) 637 email = All(ValidSystemEmail(), Email(not_empty=True))
605 return _PasswordResetForm 638 return _PasswordResetForm
639
606 640
607 def RepoForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(), 641 def RepoForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(),
608 repo_groups=[]): 642 repo_groups=[]):
609 class _RepoForm(formencode.Schema): 643 class _RepoForm(formencode.Schema):
610 allow_extra_fields = True 644 allow_extra_fields = True
622 656
623 if edit: 657 if edit:
624 #this is repo owner 658 #this is repo owner
625 user = All(UnicodeString(not_empty=True), ValidRepoUser) 659 user = All(UnicodeString(not_empty=True), ValidRepoUser)
626 660
627 chained_validators = [ValidRepoName(edit, old_data), ValidPerms] 661 chained_validators = [ValidRepoName(edit, old_data), ValidPerms()]
628 return _RepoForm 662 return _RepoForm
629 663
630 def RepoForkForm(edit=False, old_data={}, supported_backends=BACKENDS.keys()): 664
665 def RepoForkForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(),
666 repo_groups=[]):
631 class _RepoForkForm(formencode.Schema): 667 class _RepoForkForm(formencode.Schema):
632 allow_extra_fields = True 668 allow_extra_fields = True
633 filter_extra_fields = False 669 filter_extra_fields = False
634 fork_name = All(UnicodeString(strip=True, min=1, not_empty=True), 670 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True),
635 SlugifyName()) 671 SlugifyName())
672 repo_group = OneOf(repo_groups, hideList=True)
673 repo_type = All(ValidForkType(old_data), OneOf(supported_backends))
636 description = UnicodeString(strip=True, min=1, not_empty=True) 674 description = UnicodeString(strip=True, min=1, not_empty=True)
637 private = StringBoolean(if_missing=False) 675 private = StringBoolean(if_missing=False)
638 repo_type = All(ValidForkType(old_data), OneOf(supported_backends)) 676 copy_permissions = StringBoolean(if_missing=False)
639 677 update_after_clone = StringBoolean(if_missing=False)
640 chained_validators = [ValidForkName()] 678 fork_parent_id = UnicodeString()
679 chained_validators = [ValidForkName(edit, old_data)]
641 680
642 return _RepoForkForm 681 return _RepoForkForm
682
643 683
644 def RepoSettingsForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(), 684 def RepoSettingsForm(edit=False, old_data={}, supported_backends=BACKENDS.keys(),
645 repo_groups=[]): 685 repo_groups=[]):
646 class _RepoForm(formencode.Schema): 686 class _RepoForm(formencode.Schema):
647 allow_extra_fields = True 687 allow_extra_fields = True
650 SlugifyName()) 690 SlugifyName())
651 description = UnicodeString(strip=True, min=1, not_empty=True) 691 description = UnicodeString(strip=True, min=1, not_empty=True)
652 repo_group = OneOf(repo_groups, hideList=True) 692 repo_group = OneOf(repo_groups, hideList=True)
653 private = StringBoolean(if_missing=False) 693 private = StringBoolean(if_missing=False)
654 694
655 chained_validators = [ValidRepoName(edit, old_data), ValidPerms, 695 chained_validators = [ValidRepoName(edit, old_data), ValidPerms(),
656 ValidSettings] 696 ValidSettings]
657 return _RepoForm 697 return _RepoForm
658 698
659 699
660 def ApplicationSettingsForm(): 700 def ApplicationSettingsForm():
664 rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True) 704 rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True)
665 rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True) 705 rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True)
666 rhodecode_ga_code = UnicodeString(strip=True, min=1, not_empty=False) 706 rhodecode_ga_code = UnicodeString(strip=True, min=1, not_empty=False)
667 707
668 return _ApplicationSettingsForm 708 return _ApplicationSettingsForm
709
669 710
670 def ApplicationUiSettingsForm(): 711 def ApplicationUiSettingsForm():
671 class _ApplicationUiSettingsForm(formencode.Schema): 712 class _ApplicationUiSettingsForm(formencode.Schema):
672 allow_extra_fields = True 713 allow_extra_fields = True
673 filter_extra_fields = False 714 filter_extra_fields = False
677 hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False) 718 hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False)
678 hooks_pretxnchangegroup_push_logger = OneOf(['True', 'False'], if_missing=False) 719 hooks_pretxnchangegroup_push_logger = OneOf(['True', 'False'], if_missing=False)
679 hooks_preoutgoing_pull_logger = OneOf(['True', 'False'], if_missing=False) 720 hooks_preoutgoing_pull_logger = OneOf(['True', 'False'], if_missing=False)
680 721
681 return _ApplicationUiSettingsForm 722 return _ApplicationUiSettingsForm
723
682 724
683 def DefaultPermissionsForm(perms_choices, register_choices, create_choices): 725 def DefaultPermissionsForm(perms_choices, register_choices, create_choices):
684 class _DefaultPermissionsForm(formencode.Schema): 726 class _DefaultPermissionsForm(formencode.Schema):
685 allow_extra_fields = True 727 allow_extra_fields = True
686 filter_extra_fields = True 728 filter_extra_fields = True