Beispiel #1
0
def is_valid_jabber(message=None):
    """Check if the string passed is a valid Jabber ID.

    This does neither check the domain nor the ressource id because we
    require an address similar to a email address with a nodeid set.

    Since that nodeid is optional in the real-world we'd have to check
    the domain and ressource id if it's not specified.  To avoid that
    we require that nodeid.

    Examples::

        >>> check(is_valid_jabber, '*****@*****.**')
        True
        >>> check(is_valid_jabber, 'boy_you_suck@') # we don't check the domain
        True
        >>> check(is_valid_jabber, "yea, that's invalid")
        False
    """
    if message is None:
        message = lazy_gettext(u'You have to enter a valid Jabber ID')
    def validator(form, field):
        if _jabber_re.match(field.data) is None:
            raise ValidationError(message)
    return validator
Beispiel #2
0
def is_user(message=None, key='username', negative=False):
    """
    Try to get an user either by name or by email (use the `key` parameter to
    specify this).
    Raises a validation error if no user was found. You can change this
    behaviour by setting `negative`.
    """
    if message is None:
        if key == 'username':
            message = negative and lazy_gettext(u'This user does already exist'
                             ) or lazy_gettext(u'This user doesn\'t exist')
        else:
            message = negative and lazy_gettext(u'This email address is already'
                  u' used') or lazy_gettext(u'There\'s no user with this email')

    def validator(form, field):
        user = User.query.filter_by(**{key: field.data}).first()
        if (negative and user) or (not negative and not user):
            raise ValidationError(message)

    return validator
Beispiel #3
0
def is_valid_recaptcha(message=None):
    """Check if the captcha was filled correctly."""
    if message is None:
        message = lazy_gettext(u'You entered an invalid captcha.')
    def validator(form, field):
        from inyoka.utils.captcha import validate_recaptcha
        req = ctx.current_request
        valid = validate_recaptcha(ctx.cfg['recaptcha.private_key'],
            req.form.get('recaptcha_challenge_field'),
            req.form.get('recaptcha_response_field'),
            req.environ['REMOTE_ADDR'] if req else None)

        if not valid:
            raise ValidationError(message)
    return validator
Beispiel #4
0
def timedeltaformat(datetime_or_timedelta, threshold=0.85, granularity="second"):
    """Special locale aware timedelta format function

    Usage Example::

        >>> timedeltaformat(timedelta(weeks=12))
        u'three mths ago'
        >>> timedeltaformat(timedelta(seconds=30))
        u'30 secs ago'
        >>> timedeltaformat(timedelta(seconds=0))
        u'just now'

        The granularity parameter can be provided to alter the lowest unit
        presented, which defaults to a second.

        >>> timedeltaformat(timedelta(hours=3), granularity='day')
        u'one day ago'

        The threshold parameter can be used to determine at which value the
        presentation switches to the next higher unit. A higher threshold factor
        means the presentation will switch later. For example:

        >>> timedeltaformat(timedelta(hours=23), threshold=0.9)
        u'one day ago'
        >>> timedeltaformat(timedelta(hours=23), threshold=1.1)
        u'23 hrs ago'

    :param datetime_or_timedelta: Either a datetime or timedelta object.
                                  If it's a datetime object we caclculate the
                                  timedelta from this object to now (using UTC)
    :param threshold: factor that determines at which point the presentation
                      switches to the next higher unit
    :param granularity: determines the smallest unit that should be displayed,
                        the value can be one of "year", "month", "week", "day",
                        "hour", "minute" or "second"

    """
    if isinstance(datetime_or_timedelta, datetime):
        datetime_or_timedelta = datetime.utcnow() - datetime_or_timedelta

    if datetime_or_timedelta <= timedelta(seconds=3):
        return _(u"just now")

    timedelta_ = _format_timedelta(datetime_or_timedelta, granularity, threshold=threshold)
    return lazy_gettext(u"%(timedelta)s ago") % {"timedelta": timedelta_}
Beispiel #5
0
def is_valid_url(message=None):
    """Check if the string passed is a valid URL.  We also blacklist some
    url schemes like javascript for security reasons.

    >>> check(is_valid_url, 'http://pocoo.org/')
    True
    >>> check(is_valid_url, 'http://zine.pocoo.org/archive')
    True
    >>> check(is_valid_url, 'zine.pocoo.org/archive')
    False
    >>> check(is_valid_url, 'javascript:alert("Zine rocks!");')
    False
    """
    if message is None:
        message = lazy_gettext(u'You have to enter a valid URL.')
    def validator(form, field):
        protocol = urlparse(field.data)[0]
        if not protocol or protocol == 'javascript':
            raise ValidationError(message)
    return validator
Beispiel #6
0
def is_valid_email(message=None):
    """Check if the string passed is a valid mail address.

    >>> check(is_valid_email, '*****@*****.**')
    True
    >>> check(is_valid_email, 'somebody AT example DOT com')
    False
    >>> check(is_valid_email, 'some random string')
    False

    Because e-mail validation is painfully complex we just check the first
    part of the email if it looks okay (comments are not handled!) and ignore
    the second.
    """
    if message is None:
        message = lazy_gettext(u'You have to enter a valid email address.')
    def validator(form, field):
        value = field.data
        if len(value) > 250 or _mail_re.match(value) is None:
            raise ValidationError(message)
    return validator
Beispiel #7
0
class AnswerQuestionForm(Form):

    text = TextField(lazy_gettext(u'Text'), [validators.required()],
                     widget=widgets.TextArea())
Beispiel #8
0
 def validate_parent(self, field):
     message = lazy_gettext(u"You can't choose the forum itself or one of its subforums as parent")
     forum = Forum.query.filter_by(slug=self.slug.data).first()
     forums = Forum.query.filter_by(slug=self.slug.data).subforums()
     if field.data in forums or field.data == forum:
         raise ValidationError(message)
Beispiel #9
0
 def validator(form, field):
     if not _tag_re.match(field.data):
         raise ValidationError(
             lazy_gettext(u'Tag Names should only contain '
                          u'ascii characters and numbers.'))
Beispiel #10
0
 def validator(form, field):
     if u'/' in field.data:
         raise ValidationError(
             lazy_gettext(u'The name must not contain '
                          u'slashes.'))
Beispiel #11
0
class DeactivateProfileForm(Form):
    password = PasswordField(lazy_gettext(u'Password'),
                             [validators.required()],
                             widget=widgets.PasswordInput(False))
Beispiel #12
0
class EditTagForm(Form):
    name = TextField(lazy_gettext(u'Name'), [
        validators.required(),
        validators.length(max=20),
        validators.is_valid_tag_name()
    ])
Beispiel #13
0
 def validator(form, field):
     if not _tag_re.match(field.data):
         raise ValidationError(lazy_gettext(u'Tag Names should only contain '
                                            u'ascii characters and numbers.'))
Beispiel #14
0
 def validator(form, field):
     if u'/' in field.data:
         raise ValidationError(lazy_gettext(u'The name must not contain '
                                            u'slashes.'))