Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Enable the rich text editor, if dictated by the settings:
if tiny_mce_condition():
if 'css_classes' in kwargs:
kwargs['css_classes'].append('tinymcearea')
else:
kwargs['css_classes'] = ['tinymcearea']
return TextArea.display(self, value, **kwargs)
email_validator = Email(messages={
'badUsername': N_('The portion of the email address before the @ is invalid'),
'badDomain': N_('The portion of this email address after the @ is invalid')
})
class email_list_validator(FancyValidator):
def __init__(self, *args, **kwargs):
FancyValidator.__init__(self, *args, **kwargs)
self.email = Email()
def _to_python(self, value, state=None):
"""Validate a comma separated list of email addresses."""
emails = [x.strip() for x in value.split(',')]
good_emails = []
messages = []
for addr in emails:
try:
good_emails.append(self.email.to_python(addr, state))
except Invalid, e:
messages.append(str(e))
template_dictionary[KEY_CURRENT_VERSION_FULL] = TvbProfile.current.version.CURRENT_VERSION
return template_dictionary
class LoginForm(formencode.Schema):
"""
Validate for Login UI Form
"""
empty_msg = 'Please enter a value'
username = validators.UnicodeString(not_empty=True, use_builtins_gettext=False, messages={'empty': empty_msg})
password = validators.UnicodeString(not_empty=True, use_builtins_gettext=False, messages={'empty': empty_msg})
class UniqueUsername(formencode.FancyValidator):
"""
Custom validator to check that a given user-name is unique.
"""
def _convert_to_python(self, value, state):
""" Fancy validate for Unique user-name """
if not UserService().is_username_valid(value):
raise formencode.Invalid('Please choose another user-name, this one is already in use!', value, state)
return value
class RegisterForm(formencode.Schema):
"""
Validate Register Form
"""
def __init__(self, *args, **kwargs):
FancyValidator.__init__(self, *args, **kwargs)
self.email = Email()
state = 'CONFLICT'
raise formencode.Invalid('conflict', value, state)
else:
return value
class UniqueCertDN(formencode.FancyValidator):
"""Use this class to define what makes a unique user."""
def _to_python(self, value, state):
cert_q = meta.Session.query(model.Certificate)
if cert_q.filter(model.Certificate.client_dn==value).first():
state = 'CONFLICT'
raise formencode.Invalid('conflict', value, state)
else:
return value
class UniqueEmail(formencode.FancyValidator):
def _to_python(self, value, state):
user_q = meta.Session.query(model.User)
if value != None and user_q.filter(model.User.email==value).first():
state = 'CONFLICT'
raise formencode.Invalid('conflict', value, state)
else:
return value
class ModifyUserForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
# What fields should be editable by the user?
full_name = formencode.validators.String(if_missing=None)
cert_dn = formencode.All(formencode.validators.String(if_missing=None),
UniqueCertDN())
values).setResultsName('query')
query = domain + CaselessKeyword("where").suppress() + subdomain + \
operator + values + StringEnd()
self.statement = (query | expression | (values + StringEnd()))
def parse_string(self, text):
'''
'''
return self.statement.parseString(text)
class OperatorValidator(formencode.FancyValidator):
to_operator_map = {}
def _to_python(self, value, state=None):
if value in self.to_operator_map:
return self.to_operator_map[value]
else:
return value
def _from_python(self, value, state=None):
return value
class SQLOperatorValidator(OperatorValidator):
from formencode import Schema, validators, FancyValidator, All, Invalid
from models import DBSession, User
class UniqueEmail(FancyValidator):
def to_python(self, value, state):
if DBSession.query(User).filter(User.email == value).count():
raise Invalid(
'That email already exists', value, state
)
return value
class EmailExists(FancyValidator):
def to_python(self, value, state):
if not DBSession.query(User).filter(User.email == value).count():
raise Invalid(
'That email doesnt exist', value, state
)
return value
class PasswordCorrect(FancyValidator):
def to_python(self, value, state):
if not state.user.check_password(value):
raise Invalid(
'Current password is not correct', value, state
)
return value
schema.to_python(kwargs)
except Invalid as ex:
for arg, error in ex.error_dict.items():
errors.append("%s: %s ('%s')" % (arg,error.msg,error.value))
# custom validators
for arg in vKwargs.keys():
validator = vKwargs[arg]
if arg in kwargs:
val = kwargs[arg]
try:
validator.to_python(val)
except Invalid as ex:
errors.append("%s: %s ('%s')" % (arg,ex,val))
else:
if isinstance(validator,FancyValidator) and validator.not_empty:
raise TypeError("Missing mandatory argument '%s'" % arg)
# fire error if anything failed validation
if len(errors) > 0:
raise TypeError('\n'.join(errors))
# all OK
return realfn(*args,**kwargs)
return wrap
def _convert_to_python(self, value, _):
"""
Validation required method.
"""
try:
value = int(value)
except ValueError:
raise formencode.Invalid('Invalid number %s. Should be number between 1 and 16.' % value, value, None)
if 0 < value < 17:
return value
else:
raise formencode.Invalid('Invalid number %d. Should be in interval [1, 16]' % value, value, None)
class SurfaceVerticesNrValidator(formencode.FancyValidator):
"""
Custom validator for the number of vertices allowed for a surface
"""
# This limitation is given by our Max number of colors in pick mechanism
MAX_VALUE = 256 * 256 * 256 + 1
def _convert_to_python(self, value, _):
"""
Validation required method.
"""
msg = 'Invalid value: %s. Should be a number between 1 and %d.'
try:
value = int(value)
if 0 < value < self.MAX_VALUE:
return value
# validate lengths on String and Unicode types, but not Text b/c it shouldn't have a
# length
if validate_length and isinstance(col.type, sa.types.String) \
and not isinstance(col.type, sa.types.Text):
fmeta = FEVMeta(fev.MaxLength(col.type.length), colname)
self.fev_metas.append(fmeta)
if validate_type and isinstance(col.type, sa.types.Numeric):
fmeta = FEVMeta(NumericValidator(col.type.precision, col.type.scale), colname)
self.fev_metas.append(fmeta)
# handle fields that are not nullable
if validate_nullable and not col.nullable:
if not col.default and not col.server_default:
validator = formencode.FancyValidator(not_empty=True)
event = 'before_flush'
if col.foreign_keys:
event = 'before_exec'
fmeta = FEVMeta(validator, colname, event)
self.fev_metas.append(fmeta)
# data-type validation
if validate_type:
for sa_type, fe_validator in six.iteritems(SA_FORMENCODE_MAPPING):
if isinstance(col.type, sa_type):
self.create_fev_meta(fe_validator, colname, auto_not_empty=False)
break
from pylons import request
from pylons.decorators import validate
from pylons.decorators.secure import authenticate_form
from formencode import validators, Schema, FancyValidator, Invalid
log = logging.getLogger(__name__)
class EmailSchema(AuthFormSchema):
"Validate email updates."
allow_extra_fields = False
new_email = validators.Email()
class UniqueUsername(FancyValidator):
def _to_python(self, value, state):
u = meta.Session.query(model.User).\
filter(model.User.username == value).\
first()
if u:
raise Invalid(
'That username already exists',
value, state)
return value
class NewUserSchema(AuthFormSchema):
"Validate new users."
allow_extra_fields = False
username = UniqueUsername(not_empty=True)
password = validators.String(if_missing=None)