def validate_python(self, value, state): if value>self.max: raise Invalid('Too large (maximum %d)'%self.max, value, state) if value<self.min: raise Invalid('Too small (minimum %d)'%self.min, value, state) if int(value) != 0: check_product_availability(self.product, value, state)
def _to_python(self, value, state): value = super(ForEachDict, self)._to_python(value, state) result = {} try: for i, item in enumerate(value): try: key = item[self.key_name] except KeyError: raise Invalid( 'key %s not present in item %d of value' % (self.key_name, i), value, state) try: value = item[self.value_name] except KeyError: raise Invalid( 'key %s not present in item %d of value' % (self.value_name, i), value, state) if key in result: raise Invalid( 'duplicate key %s found at position %d in value' % (key, i), value, state) result[key] = value except TypeError: raise Invalid('value is not iterable', value, state) return result
def validate(self, value, state=None): super(LoginForm, self).validate(value, state=state) auth_provider = plugin.AuthenticationProvider.get(request) # can't use a validator attr on the username TextField, since the antispam encoded name changes and doesn't # match the name used in the form submission auth_provider.username_validator(long_message=False).to_python( value['username']) try: auth_provider.login() except exc.HTTPUnauthorized: msg = 'Invalid login' raise Invalid( msg, dict(username=value['username'], rememberme=value.get('rememberme'), return_to=value.get('return_to')), None) except exc.HTTPBadRequest as e: raise Invalid( e.message, dict(username=value['username'], rememberme=value.get('rememberme'), return_to=value.get('return_to')), None) return value
def login(self, came_from=None, **kwargs): if request.environ.get('repoze.who.identity'): redirect(came_from or '/') # the friendlyform plugin requires that these values are set in the # query string form_url = url_for('/login/submit', came_from=(came_from or '').encode('utf-8'), __logins=str(self._is_failed_login())) login_errors = None if self._is_failed_login(): login_errors = Invalid('dummy', None, {}, error_dict={ '_form': Invalid( _('Invalid username or password.'), None, {}), 'login': Invalid('dummy', None, {}), 'password': Invalid('dummy', None, {}), }) return dict( login_form=login_form, form_action=form_url, form_values=kwargs, login_errors=login_errors, )
def validate_python(self, field_dict, state): challenge = field_dict['recaptcha_challenge_field'] response = field_dict['recaptcha_response_field'] if response == '' or challenge == '': error = Invalid(self.message('missing', state), field_dict, state) error.error_dict = {'recaptcha_response_field':'Missing value'} raise error params = urllib.urlencode({ 'privatekey': self.private_key, 'remoteip' : self.remote_ip, 'challenge': challenge, 'response' : response, }) request = urllib2.Request( url = "http://%s/verify" % self.verify_server, data = params, headers = {"Content-type": "application/x-www-form-urlencoded", "User-agent": "reCAPTCHA Python" } ) httpresp = urllib2.urlopen(request) return_values = httpresp.read().splitlines(); httpresp.close(); return_code = return_values[0] if not return_code == "true": error = Invalid(self.message('incorrect', state), field_dict, state) error.error_dict = {'recaptcha_response_field':self.message('incorrect', state)} raise error return True
def _to_python(self, value_dict, state): if value_dict: return value_dict sl = syslanguage active_cultures = (sl.active_record_cultures() if self.record_cultures else sl.active_cultures()) errors = {} # log.debug('active_cultures: %s', active_cultures) for fieldname, validator in self.targetvalidator.fields.items(): if not validator.not_empty: continue for culture in active_cultures: culture = culture.replace("-", "_") errors[culture + "." + fieldname] = Invalid( self.message("empty", state), value_dict, state) if errors: raise Invalid( schema.format_compound_error(errors), value_dict, state, error_dict=errors, ) return value_dict
def check_product_availability(product, value, state): if product.available(): return elif product.available(stock=False): raise Invalid(product.description + " has unfortunately sold out.", value, state) else: raise Invalid(product.description + " is not available.", value, state)
def validate_python(self, value, state): super(UniqueUserValidator, self).validate_python(value, state) if re.match("^[a-zA-Z0-9_-]*[a-zA-Z_-][a-zA-Z0-9_-]*$", value): user = tg.config['registration_dal'].get_user_by_user_name(value) if user: raise Invalid(_('Username already in use.'), value, state) else: raise Invalid(_('Invalid username'), value, state)
def _to_python(self, value, state): if not ':' in value: raise Invalid('No schema in URL', value, None) schema, url = value.split(':', 1) if not schema.lower().strip() in ['http', 'https', 'ftp']: raise Invalid('Invalid schema: %s' % schema, value, None) # TODO: Introduce normalization and possibly collision detection return value
def _validate_python(self, value, state): user = state.dbsession.query(User).filter( User.email == value['email'].lower()).first() if user: if not user.password_matches(value['password']): raise Invalid(self.message('nologin', state), value, state) else: raise Invalid(self.message('nologin', state), value, state)
def validate_python(self, value, state): if not value in self.generator(): if self.hideList: raise Invalid(self.message('invalid', state), value, state) else: items = '; '.join(map(str, self.list)) raise Invalid( self.message('notIn', state, items=items, value=value), value, state)
def _to_python(self, value, state): parts = value.split('.') if len(parts) != 4: raise Invalid(self.message('invalid_ip', state), value, state) parts = [p for p in parts if (p.isdigit() and 0 <= int(p) <= 255) or p == '*'] if len(parts) != 4: raise Invalid(self.message('invalid_ip', state), value, state) return '.'.join(parts)
def _to_python(self, value, state): entity = Entity.by_id(state.dataset, value) if entity is None: raise Invalid('Entity does not exist.', value, None) if entity == state.entity: raise Invalid('Entities are identical.', value, None) if entity.dataset != state.dataset: raise Invalid('Entity belongs to a different dataset.', value, None) return entity
def _validate_python(self, value, state): """If a :class:`~pyramid.request.Request` is set in the ``state``, then checks whether the ``value`` matches the CSRF token stored in the request. """ if hasattr(state, 'request'): if state.request.session.get_csrf_token() != value: raise Invalid(self.message('invalid_csrf_token', state), value, state) else: raise Invalid(self.message('no_request', state), value, state)
def _validate(self, model, form): super(TalkApi, self)._validate(model, form) if int(form.get('schedule_slot_id', 0)) > 0: schedule_slot = self.schedule_slot_dao.get( form['schedule_slot_id']) if schedule_slot.talk and schedule_slot.talk is not model: exc = Invalid("Schedule slot is already in use", 'schedule_slot_id', None) exc.error_dict = {'schedule_slot_id': exc} raise exc
def validate_python(self, value, state): super(UniqueEmailValidator, self).validate_python(value, state) if re.match( "^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", value): user = tg.config['registration_dal'].get_user_by_email(value) if user: raise Invalid(_('Email address has already been taken'), value, state) else: raise Invalid(_('Invalid email'), value, state)
def _validate(self, model, form): super(TalkApi, self)._validate(model, form) if int(form.get('schedule_slot_id', 0)) > 0: schedule_slot = self.schedule_slot_dao.get( form['schedule_slot_id']) if schedule_slot.talk and schedule_slot.talk is not model: exc = Invalid( "Schedule slot is already in use", 'schedule_slot_id', None) exc.error_dict = {'schedule_slot_id': exc} raise exc
def validate_other(self, values, state): soptions = set([six.text_type(d[0] if isinstance(d, tuple) else d) for d in self.options]) sinvalid = set([six.text_type(d) for d in tolist(self.invalid)]) svalues = set([six.text_type(d) for d in tolist(values)]) if len(sinvalid.intersection(svalues)) != 0: raise Invalid(self.message('invalid', state), values, state) if len(soptions.intersection(svalues)) != len(svalues): raise Invalid(self.message('notthere', state), values, state) return
def _to_python(self, value, state): try: value = json.loads(value.decode('utf-8')) if isinstance(value, dict): if 'data' in value: return value['data'] else: raise Invalid(self.message('nodata', state), value, state) else: raise Invalid(self.message('notdict', state), value, state) except ValueError: raise Invalid(self.message('notjson', state), value, state)
def _to_python(self, value, state): try: dec = Decimal(value) except InvalidOperation: raise Invalid(self.message('amount', state), value, state) else: ret = dec.quantize(Decimal('1.00')) if ret == 0: raise Invalid(self.message('nonzero', state), value, state) elif ret != dec: raise Invalid(self.message('precision', state), value, state) else: return Currency(int(ret * 100))
def _to_python(self, value, state): if isinstance(value, dict): value = value.get('id') entity = Entity.by_id(value) if entity is None: entity = Entity.by_name(state.dataset, value) if entity is None: raise Invalid('Entity does not exist: %s' % value, value, None) if entity == state.entity: return None if entity.dataset != state.dataset: raise Invalid('Entity belongs to a different dataset.', value, None) return entity
def _to_python(self, value_dict, state): fields = self._convert_to_list(self.required) if not any(value_dict.get(m) for m in fields): errors = { x: Invalid(self.message("empty", state), value_dict, state) for x in fields } raise Invalid( schema.format_compound_error(errors), value_dict, state, error_dict=errors, ) return value_dict
def _validate_python(self, value, state=None): if hasattr(state, 'email_domains') and state.email_domains: value = value[value.find('@') + 1:] if isinstance(state.email_domains, list): if value not in state.email_domains: raise Invalid( self.message('wrongdomain', state, domains=', '.join(state.email_domains)), value, state) elif value != state.email_domains: raise Invalid( self.message('wrongdomain', state, domains=state.email_domains), value, state)
def _to_python(self, value, state): if value == "new" and self.allow_new: return value elif value == "new" and not self.allow_new: raise Invalid(self.message('new', state), value, state) elif value == "null" and not self.allow_null: raise Invalid(self.message('null', state), value, state) elif value == "null" and self.allow_null: return self.null_value else: obj_id = v.UnicodeString._to_python(self, value, state) obj = self.getObject(obj_id) if obj is None: raise Invalid(self.message('invalid', state), value, state) return obj
def antispam_hook(remainder, params): '''Converts various errors in validate_request to a single Invalid message''' try: new_params = cls.validate_request(params=params) params.update(new_params) except (ValueError, TypeError, binascii.Error): raise Invalid(error_msg, params, None)
def _to_python(self, name, state): entity = Entity.by_name(state.dataset, name) if entity is None: return name if state.entity and entity.id == state.entity.id: return name raise Invalid('Entity already exists.', name, None)
def validate_python(self, values, state): assertion = values['assertion'] audience = h.url_for(qualified=True, controller='home').strip("/") page = urllib2.urlopen('https://verifier.login.persona.org/verify', urllib.urlencode({ "assertion": assertion, "audience": audience})) data = json.load(page) if data['status'] == 'okay': c.email = data['email'] c.person = Person.find_by_email(c.email) if c.person is None: if not Config.get('account_creation'): error_message = "Your sign-in details are incorrect; try the 'Forgotten your password' link below." message = "Login failed" error_dict = {'email_address': error_message} raise Invalid(message, values, state, error_dict=error_dict) # Create a new account for this email address c.person = Person() c.person.email_address = data['email'] c.person.activated = True meta.Session.add(c.person) meta.Session.commit() if not c.person.activated: # Persona returns verified emails only, so might as well confirm this one... c.person.activated = True meta.Session.commit()
def _to_python(self, value, state): from datahub.logic.account import get existing = get(value) if existing and (state.current_name is None or \ not state.current_name == value): raise Invalid('Name is taken.', value, None) return value
def validate_python(self, values, state): status = values.get(self.status) type = values.get(self.type) if status not in type.status: raise Invalid( "This status is not allowed with this Fulfilment Type", values, state)
def validate_python(self, values, state): total = 0 error_dict = {} for field in self.product_fields: try: value = values.get(field, None) if value is None: pass elif value < 0: error_dict[field] = "Must be positive." else: total += value except: pass if total < self.min_qty: error_dict[ self.error_field_name] = "You must have at least %d %s" % ( self.min_qty, self.category_name, ) if total > self.max_qty: error_dict[ self. error_field_name] = "You can not order more than %d %s" % ( self.max_qty, self.category_name, ) if error_dict: error_message = "Quantities for %s are incorrect" % self.category_name raise Invalid(error_message, values, state, error_dict=error_dict)
def _to_python(self, value, state): nro_doc = Usuario.by_nro_documento(value) id_usuario = UrlParser.parse_id(request.url, "usuarios") if nro_doc != None and id_usuario != nro_doc.id_usuario: raise Invalid('Nro de Documento ya existe en sistema', value, state) return value
def validate_python(self, value, state): p = Product.find_by_id(int(value)) for product in Product.find_by_category(p.category.id): if product.id == int(value): check_product_availability(product, value, state) return # All good! raise Invalid("Product " + value + " is not allowed in category " + self.category.name, value, state)