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