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