Esempio n. 1
0
    def validate_name(self, field):
        if not valid_username(field.data):
            raise wtforms.ValidationError("Name contains invalid characters.")

        existing = ResourceAction.query.filter_by(name=field.data, resource=self.edit_resource).first()
        if existing and existing.id != self.edit_id:
            raise wtforms.ValidationError("An action with that name already exists for this resource")
Esempio n. 2
0
    def validate_keys(form, field):
        if not field.data:
            return

        expected_keys_count = INCUBATION_PERIOD + SYMPTOMS_TO_VIRUS_NEGATIVE

        key_values = set(key['value'] for key in field.data)

        # All keys should be unique, and should match the expected count
        if len(key_values) != expected_keys_count:
            raise wtforms.ValidationError(
                'Should contain {} daily keys.'.format(expected_keys_count)
            )

        key_dates = sorted(key['date'] for key in field.data)

        # There should not be any missing date
        prev_date = None
        for date in key_dates:
            if prev_date is not None and date != prev_date + datetime.timedelta(days=1):
                raise wtforms.ValidationError('Key dates should not contain gaps.')

            prev_date = date

        if key_dates[0] > datetime.datetime.utcnow().date():
            raise wtforms.ValidationError('Key dates can not all be in the future.')
Esempio n. 3
0
    def pre_validate(self, form):
        if not self._deb_file_input or not isinstance(self._deb_file_input,
                                                      FileStorage):
            return

        # Save the deb file to a tmp file
        _, debtmp = mkstemp()
        with open(debtmp, "wb") as tmp:
            tmp.write(self._deb_file_input.read())
        # Open the deb file and parse control information
        deb_obj = debfile.DebPackage(debtmp)
        tags = TagSection(deb_obj.control_content("control"))
        pkg_name = tags.get('Package', None)

        if pkg_name is None:
            # Remove the tmpfile
            os.unlink(debtmp)
            raise wtf.ValidationError("Invalid deb control file, "
                                      "package name is empty.")

        # Check 'unique' property on pkg_name
        with db_scoped_session() as se:
            obj_t = se.query(Item).filter_by(pkg_name=pkg_name).first()
            if obj_t != None and hasattr(form,
                                         'iid') and obj_t.iid != form.iid.data:
                # obj exists, raise error
                raise wtf.ValidationError("The same package name found in "
                                          "%s" % obj_t)

        # Validation successful, fill the tmpfile path
        self._deb_tmpfile = debtmp
        self.data = debtmp
Esempio n. 4
0
 def validate_phone(self, field):
     existing = UserPhone.query.filter_by(phone=field.data).first()
     if existing is not None:
         if existing.user == g.user:
             raise wtforms.ValidationError(
                 "You have already registered this phone number.")
         else:
             raise wtforms.ValidationError(
                 "That phone number has already been claimed.")
     existing = UserPhoneClaim.query.filter_by(phone=field.data,
                                               user=g.user).first()
     if existing is not None:
         raise wtforms.ValidationError(
             "That phone number is pending verification.")
     # Step 1: Remove punctuation in number
     field.data = strip_phone(field.data)
     # Step 2: Validate number format
     if not valid_phone(field.data):
         raise wtforms.ValidationError(
             "Invalid phone number (must be in international format with a leading + symbol)"
         )
     # Step 3: Check if Indian number (startswith('+91'))
     if not field.data.startswith('+91') or len(field.data) != 13:
         raise wtforms.ValidationError(
             "Only Indian mobile numbers are allowed at this time")
Esempio n. 5
0
    def validate_token_scope(self, field):
        scope = field.data

        try:
            _, scope_kind = scope.split(":", 1)
        except ValueError:
            raise wtforms.ValidationError(f"Unknown token scope: {scope}")

        if scope_kind == "unspecified":
            raise wtforms.ValidationError("Specify the token scope")

        if scope_kind == "user":
            self.validated_scope = scope_kind
            return

        try:
            scope_kind, scope_value = scope_kind.split(":", 1)
        except ValueError:
            raise wtforms.ValidationError(f"Unknown token scope: {scope}")

        if scope_kind != "project":
            raise wtforms.ValidationError(f"Unknown token scope: {scope}")
        if scope_value not in self.project_names:
            raise wtforms.ValidationError(
                f"Unknown or invalid project name: {scope_value}")

        self.validated_scope = {"projects": [scope_value]}
Esempio n. 6
0
 def validate_field(self, field):
     if not field.data:
         raise wtforms.ValidationError("field is empty")
     supported = ["cwshdr"]
     if field.data.lower() not in supported:
         template = "{} is not supported. Currently supported: {}"
         raise wtforms.ValidationError(template.format(field.data, supported))
Esempio n. 7
0
def file_virus_validator(form, field):
    """ Checks for virus in the file from flask request object,
    raises wtf.ValidationError if virus is found else None. """

    if not pagure_config["VIRUS_SCAN_ATTACHMENTS"]:
        return
    from pyclamd import ClamdUnixSocket

    if (field.name not in flask.request.files
            or flask.request.files[field.name].filename == ""):
        # If no file was uploaded, this field is correct
        return
    uploaded = flask.request.files[field.name]
    clam = ClamdUnixSocket()
    if not clam.ping():
        raise wtforms.ValidationError(
            "Unable to communicate with virus scanner")
    results = clam.scan_stream(uploaded.stream.read())
    if results is None:
        uploaded.stream.seek(0)
        return
    else:
        result = results.values()
        res_type, res_msg = result
        if res_type == "FOUND":
            raise wtforms.ValidationError("Virus found: %s" % res_msg)
        else:
            raise wtforms.ValidationError("Error scanning uploaded file")
Esempio n. 8
0
def file_virus_validator(form, field):
    if not pagure.APP.config['VIRUS_SCAN_ATTACHMENTS']:
        return
    from pyclamd import ClamdUnixSocket

    if field.name not in flask.request.files or \
            flask.request.files[field.name].filename == '':
        # If no file was uploaded, this field is correct
        return
    uploaded = flask.request.files[field.name]
    clam = ClamdUnixSocket()
    if not clam.ping():
        raise wtforms.ValidationError(
            'Unable to communicate with virus scanner')
    results = clam.scan_stream(uploaded.stream.read())
    if results is None:
        uploaded.stream.seek(0)
        return
    else:
        result = results.values()
        res_type, res_msg = result
        if res_type == 'FOUND':
            raise wtforms.ValidationError('Virus found: %s' % res_msg)
        else:
            raise wtforms.ValidationError('Error scanning uploaded file')
Esempio n. 9
0
 def validate_username(self, field):
     if field.data in current_app.config['RESERVED_USERNAMES']:
         raise wtforms.ValidationError, "This name is reserved"
     if not valid_username(field.data):
         raise wtforms.ValidationError(u"Invalid characters in name. Names must be made of ‘a-z’, ‘0-9’ and ‘-’, without trailing dashes")
     existing = User.get(username=field.data)
     if existing is not None:
         raise wtforms.ValidationError("This username is taken")
Esempio n. 10
0
    def validate_name(self, field):
        if not valid_username(field.data):
            raise wtforms.ValidationError("Name contains invalid characters.")

        existing = self.edit_resource.get_action(field.data)
        if existing and existing.id != self.edit_id:
            raise wtforms.ValidationError(
                "An action with that name already exists for this resource")
Esempio n. 11
0
 def validate_id(self, field):
     # Check if user is authorized to edit this expense.
     if field.data:
         expense = Expense.query.get(field.data)
         if not expense:
             raise wtforms.ValidationError("Unknown expense")
         if expense.report.user != g.user:
             raise wtforms.ValidationError("You are not authorized to edit this expense")
Esempio n. 12
0
 def validate_delete_username(self, field):
     user = User.query.filter_by(username=self.delete_username.data).first()
     if user is None:
         raise wtforms.ValidationError("User not found")
     if user == current_user:
         raise wtforms.ValidationError("That's you")
     if user not in current_user.friends:
         raise wtforms.ValidationError("User is not a friend")
Esempio n. 13
0
 def Blog_length_limit(form, field):
     soup = BeautifulSoup(field.data, 'html.parser')
     [s.extract() for s in soup('script')]
     length = len(soup.get_text().strip())
     if length < 10:
         raise wtforms.ValidationError(u'文章太短了,多敲几个字吧')
     if length > 20000:
         raise wtforms.ValidationError(u'文章长度超限,不能大于20000')
Esempio n. 14
0
 def validate_username(self, field):
     if Admin.query.filter_by(username=field.data).first():
         password = setPassword(self.password.data)
         if password != Admin.query.filter_by(
                 username=field.data).first().password:
             raise wtforms.ValidationError("您输入的用户名或密码错误!")
     else:
         raise wtforms.ValidationError("您输入的用户名或密码错误!")
Esempio n. 15
0
 def check_valid_timeline(form, field):
     publish_date = form.publish_date.data
     retract_date = form.retract_date.data
     if not publish_date:
         raise wtforms.ValidationError(
             _(u'Cannot retract an un-published form'))
     if retract_date < publish_date:
         raise wtforms.ValidationError(_('Must be after publish date'))
Esempio n. 16
0
 def validate_alias(form, field):
     if form.alias.data == 'new':
         raise wtforms.ValidationError(flask.Markup(
             'The alias cannot be <code>new</code>.'))
     check = Election.search(SESSION, alias=form.alias.data)
     if check:
         if not (form._election_id and form._election_id == check[0].id):
             raise wtforms.ValidationError(
                 'There is already another election with this alias.')
Esempio n. 17
0
    def validate_endpoint(self, field):
        data = field.data.strip()
        if not Infura.is_valid_project_id_or_endpoint(data):
            raise wtforms.ValidationError(
                "Not a valid Infura URL nor Infura Project ID")

        if not (Infura.is_valid_project_id(data)
                or search(self.meta.network, data)):
            raise wtforms.ValidationError(
                f"Infura URL for wrong network, expected {self.meta.network}")
Esempio n. 18
0
 def validate_url(self, field):
     long_url = field.data
     if not is_url(long_url):
         raise wtforms.ValidationError('URL is invalid')
     short_id = g.tinyurl.get_short_id(long_url=long_url)
     if short_id is not None:
         short_url = common.get_short_url_from_short_id(short_id=short_id)
         raise wtforms.ValidationError(
             'URL is already a TinyURL ({short_url}).'.format(
                 short_url=short_url))
Esempio n. 19
0
    def validate_name(self, field):
        if not valid_username(field.data):
            raise wtforms.ValidationError("Name contains invalid characters.")

        if field.data in resource_registry:
            raise wtforms.ValidationError("This name is reserved for internal use")

        existing = Resource.query.filter_by(name=field.data).first()
        if existing and existing.id != self.edit_id:
            raise wtforms.ValidationError("A resource with that name already exists")
Esempio n. 20
0
 def __call__(self, form, field):
     email_domain = get_email_domain(field.data)
     try:
         dns.resolver.query(email_domain, 'MX')
     except dns.resolver.NXDOMAIN:
         raise wtforms.ValidationError(self.message or self.message_domain)
     except dns.resolver.NoAnswer:
         raise wtforms.ValidationError(self.message or self.message_email)
     except (dns.resolver.Timeout, dns.resolver.NoNameservers):
         pass
Esempio n. 21
0
    def validate_username(self, field):
        allowed_characters = string.ascii_lowercase + string.digits + "_"

        if any(c not in allowed_characters for c in self.username.data):
            raise wtforms.ValidationError(
                "Username may only contain lowercase letters, digits, and undescores."
            )

        if User.query.filter_by(username=self.username.data).first():
            raise wtforms.ValidationError("Username already taken")
Esempio n. 22
0
        def validate_dice_report(self, field):
            min_dreport_size = config['MIN_DREPORT_SIZE']
            data = field.data and field.data.strip()
            if not data:
                raise wtforms.ValidationError("Dice-report is required.")
            if len(data) < min_dreport_size:
                raise wtforms.ValidationError(
                    "Dice-report is too short (less than %s char)." %
                    min_dreport_size)

            return data
Esempio n. 23
0
    def __call__(self, form, field):
        challenge = request.form.get('recaptcha_challenge_field', '')
        response = request.form.get('recaptcha_response_field', '')
        remote_ip = request.remote_addr

        if not challenge or not response:
            raise wtforms.ValidationError('This field is required.')

        if not self._validate_recaptcha(challenge, response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise wtforms.ValidationError(self.message)
Esempio n. 24
0
def validate_time(form, field):
    """ Validate if the data set in the given field is a valid time. """
    if isinstance(field.data, time):  # pragma: no cover
        return
    if not re.match(r'\d?\d:\d\d?', field.data):
        raise wtforms.ValidationError(_('Time must be of type "HH:MM"'))
    time_data = field.data.split(':')
    try:
        field.data = time(int(time_data[0]), int(time_data[1]))
    except ValueError:
        raise wtforms.ValidationError(_('Time must be of type "HH:MM"'))
Esempio n. 25
0
 def validate_name(self, field):
     if not valid_username(field.data):
         raise wtforms.ValidationError("Invalid characters in name")
     if field.data in current_app.config['RESERVED_USERNAMES']:
         raise wtforms.ValidationError("That name is reserved")
     existing = User.get(username=field.data)
     if existing is not None:
         raise wtforms.ValidationError("That name is taken")
     existing = Organization.get(name=field.data)
     if existing is not None and existing.id != self.edit_id:
         raise wtforms.ValidationError("That name is taken")
Esempio n. 26
0
 def validate_date(self, field):
     exists = Activity.query.filter_by(venue=self.venue,
                                       date=field.data).first()
     if exists:
         raise wtforms.ValidationError(
             u'You cannot have two activities on the same date. %s already exists.'
             % exists.title)
     if field.data < self.venue.event.from_date or field.data > self.venue.event.to_date:
         raise wtforms.ValidationError(
             u'Activity date should be within the event dates %s & %s.' %
             (self.venue.event.from_date, self.venue.event.to_date))
Esempio n. 27
0
 def check_renders_correctly(form, field):
     try:
         render_url(field.data)
     except NameError as e:
         raise wtforms.ValidationError(
             request.localizer.translate(
                 _(u'Unsupported template variables: ${names}'),
                 mapping={'names': e.message}))
     except Exception as e:
         raise wtforms.ValidationError(
             request.localizer.translate(_(u'Unexpected erorr: ${message}'),
                                         mapping={'message': e.message}))
Esempio n. 28
0
 def validate_namespace(self, field):
     if field.data:
         if not domain_namespace_match(self.website.data, field.data):
             raise wtforms.ValidationError(
                 u"The namespace should be derived from your application’s website domain"
             )
         client = self.edit_model.get(namespace=field.data)
         if client:
             if client == self.edit_obj:
                 return
             raise wtforms.ValidationError(
                 "This namespace has been claimed by another client app")
Esempio n. 29
0
 def validate_long_url(self, field):
     long_url = field.data
     if long_url is None or len(long_url) == 0:
         current_app.logger.debug('Long url is None or empty')
         return
     current_app.logger.debug(
         'Long url: {long_url}'.format(long_url=long_url))
     if not is_url(long_url):
         raise wtforms.ValidationError('Long URL is invalid')
     short_id = g.tinyurl.get_short_id(long_url=long_url)
     if short_id is None:
         raise wtforms.ValidationError(
             'TinyURL does not yet exist for this Long URL')
Esempio n. 30
0
 def validate_short_id(self, field):
     short_id = field.data
     if short_id is None or len(short_id) == 0:
         current_app.logger.debug('Short id is None or empty')
         return
     current_app.logger.debug(
         'Short id: {short_id}'.format(short_id=short_id))
     if not in_alphabet(short_id, BASE62):
         raise wtforms.ValidationError('Short ID is invalid')
     long_url = g.tinyurl.get_long_url(short_id)
     if long_url is None:
         raise wtforms.ValidationError(
             'TinyURL does not yet exist for this Short ID')