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