"""Input validation helpers shared by every handler.""" import re from errors import NotFoundError, ValidationError MAX_TEXT_LEN = 200 MAX_NOTE_LEN = 4000 EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$") def clean_text(value, field, required=False, max_len=MAX_TEXT_LEN): """Validate an optional text field and return a trimmed string.""" if value is None: if required: raise ValidationError("%s is required" % field) return "" if isinstance(value, bool) or not isinstance(value, str): raise ValidationError("%s must be a string" % field) text = value.strip() if not text: if required: raise ValidationError("%s is required" % field) return "" if len(text) > max_len: raise ValidationError("%s must be at most %d characters" % (field, max_len)) return text def clean_email(value, field="email"): """Validate an optional email address.""" text = clean_text(value, field) if text and not EMAIL_RE.match(text): raise ValidationError("%s is not a valid email address" % field) return text def clean_amount(value, field="amount"): """Validate an optional non-negative number, defaulting to 0.""" if value is None: return 0.0 if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValidationError("%s must be a number" % field) amount = float(value) if amount < 0: raise ValidationError("%s must be greater than or equal to 0" % field) return amount def clean_stage(value, stages, field="stage", default=None): """Validate a deal stage, defaulting when the key is absent.""" if value is None: return default if isinstance(value, bool) or not isinstance(value, str) or value not in stages: raise ValidationError("%s must be one of: %s" % (field, ", ".join(stages))) return value def clean_reference(store, value, table, field, entity="record"): """Validate an optional foreign key against an existing row.""" if value is None or value == "": return None if isinstance(value, bool) or not isinstance(value, int): raise ValidationError("%s must be an integer" % field) if not store.exists(table, value): raise ValidationError("%s does not reference an existing %s" % (field, entity)) return value def require_object(body): """Accept only a parsed JSON object as a request body.""" if body is None: raise ValidationError("request body is required") if not isinstance(body, dict): raise ValidationError("request body must be a JSON object") return body def parse_id(raw_id): """Parse a record id taken from the URL.""" try: value = int(raw_id) except (TypeError, ValueError): raise NotFoundError("invalid id %r" % (raw_id,)) if value < 1: raise NotFoundError("invalid id %r" % (raw_id,)) return value def parse_int_param(raw_value, field, minimum): """Parse an integer query parameter such as limit or offset.""" try: value = int(raw_value) except (TypeError, ValueError): raise ValidationError("%s must be an integer" % field) if value < minimum: raise ValidationError("%s must be greater than or equal to %d" % (field, minimum)) return value