Exemple #1
0
 def check_xauth(self, key, secret, token_url):
     """Check a generic xAuth provider"""
     auth = OAuth1(key, secret)
     params = {
         'x_auth_username': self.cleaned_data['username'],
         'x_auth_password': self.cleaned_data['password'],
         'x_auth_mode': 'client_auth',
     }
     response = requests.post(token_url, auth=auth, data=params)
     if response.status_code != 200:
         raise forms.ValidationError(
             _("Unable to verify your %s credentials. Please double-check "
               "and try again") % self.service, )
     request_token = dict(urlparse.parse_qsl(response.text))
     self.user.read_later_credentials = json.dumps(request_token)
Exemple #2
0
    def clean_captcha(self):
        """
        Fail form validation if captcha answer is not the expected answer.

        If no expected captcha answer was previously generated (this is the
        request on which they hit the rate limit for the first time) and no
        captcha answer was provided in the POST data, we don't fail them -- if
        they've got the right username and password on the login attempt that
        first hits the rate limit, their login should succeed.

        """
        answer = self.cleaned_data.get("captcha")
        if answer != self.captcha_answer:
            raise forms.ValidationError(
                "Sorry, that's not the answer we were looking for.")
Exemple #3
0
 def clean_parameters(self):
     parameters = self.cleaned_data['parameters']
     policy = self.cleaned_data['policy']
     if policy == 'multiply_purchase_by_ratio':
         try:
             Decimal(parameters)
         except InvalidOperation:
             text = ugettext(
                 '{0} is not a valid decimal'.format(parameters))
             if ',' in parameters:
                 text += ' ' + ugettext(
                     'Did you use coma rather than dot as decimal separator?'
                 )
             raise forms.ValidationError(text)
     return parameters
Exemple #4
0
def user_lock(cache_key, user_id, timeout=None):
    key = "lock:{0}:{1}".format(cache_key, user_id)

    redis = get_redis_connection()
    got_lock = redis.setnx(key, user_id)
    if timeout is not None and got_lock:
        redis.setex(key, timeout, user_id)
    if not got_lock:
        raise forms.ValidationError(
            _("This action can only be done one at a time."))
    try:
        yield
    finally:
        if got_lock:
            redis.delete(key)
Exemple #5
0
    def to_python(self, data):
        f = super(OPMLField, self).to_python(data)
        if f is None:
            return

        if hasattr(data, 'read'):
            content = data.read()
        else:
            content = data['content']
        try:
            opml.from_string(content)
        except XMLSyntaxError:
            raise forms.ValidationError(
                _("This file doesn't seem to be a valid OPML file."))

        if hasattr(f, 'seek') and callable(f.seek):
            f.seek(0)
        return f
Exemple #6
0
 def to_python(self, value):
     """
     Validates that the input is a decimal number. Returns a Decimal
     instance. Returns None for empty values. Ensures that there are no more
     than max_digits in the number, and no more than decimal_places digits
     after the decimal point.
     """
     if value in self.empty_values:
         return None
     if self.localize:
         value = formats.sanitize_separators(value)
         value = smart_text(value).strip()
         try:
             value = Decimal(value)
         except DecimalException:
             raise forms.ValidationError(self.error_messages['invalid'],
                                         code='invalid')
     return value
Exemple #7
0
    def clean(self):
        """Validate that selected elements form valid environment."""
        # only act on category_ items.  There may be other fields
        # like "build" in here if a run series is being executed.
        selected_element_ids = set([
            int(eid) for k, eid in self.cleaned_data.iteritems()
            if k.find("category_") == 0 and eid
        ])
        matches = [
            envid for envid, element_ids in self.elementids_by_envid.items()
            if set([e for e in element_ids
                    if e]).issubset(selected_element_ids)
        ]
        if not matches:
            raise forms.ValidationError(
                "The selected environment is not valid for this test run. "
                "Please select a different combination.")

        self.cleaned_data["environment"] = matches[0]

        return self.cleaned_data
Exemple #8
0
 def clean_recipient(self):
     """ Valider et renvoyer les données du champ destinataire """
     recipient = int(self.data['recipient'])
     if get_user_model().objects.get_or_none(id=recipient) is None:
         raise forms.ValidationError(_("The recipient does not exist."))
     return get_user_model().objects.get(id=recipient)
Exemple #9
0
 def clean_last_name(self):
     if len(self.cleaned_data['last_name'].strip()) == 0:
         raise forms.ValidationError(_('You must provide a last name!'))
     return self.cleaned_data['last_name']
Exemple #10
0
 def clean(self):
     throttle_message = check_throttle(self.foirequest.user, FoiMessage)
     if throttle_message:
         raise forms.ValidationError(throttle_message)
Exemple #11
0
 def clean(self, *args, **kwargs):
     password1 = self.cleaned_data.get('password1', "")
     password2 = self.cleaned_data.get('password2', "")
     if password1 and (password1 != password2):
         raise forms.ValidationError(ugettext('Passwords are not the same'))
     return super(UserRegistrationForm, self).clean(*args, **kwargs)
Exemple #12
0
 def clean_valor_venda(self):
     valor_venda = self.cleaned_data.get('valor_venda')
     if int(valor_venda) <= 0:
         raise forms.ValidationError('Valor inválido')
     return self.cleaned_data['valor_venda']
Exemple #13
0
 def clean(self, value):
     ''' Permitir somente numeros, mesmo os exponencias como, 10e1 '''
     if value and (re.search(u'[A-z]', value)
                   or not (re.match(u'[0-9]', value))):
         raise forms.ValidationError("Somente Números")
Exemple #14
0
 def clean_confirmation(self):
     confirmation = self.cleaned_data['confirmation']
     if confirmation != self.CONFIRMATION_PHRASE:
         raise forms.ValidationError(
             _('You did not type the confirmation phrase exactly right!'))
     return ''
Exemple #15
0
 def clean_password(self):
     password = self.cleaned_data['password']
     user = auth.authenticate(username=self.user.email, password=password)
     if not user:
         raise forms.ValidationError(_('You provided the wrong password!'))
     return ''
Exemple #16
0
 def clean_user_id(self):
     user_id = self.cleaned_data['user_id']
     if user_id != self.user.pk:
         raise forms.ValidationError(
             _('Logged in user does not match this link!'))
     return user_id
Exemple #17
0
 def clean(self):
     cleaned = super(NewUserWithPasswordForm, self).clean()
     if cleaned['password'] != cleaned['password2']:
         raise forms.ValidationError(_("Passwords do not match!"))
     return cleaned
Exemple #18
0
 def clean_name(self):
     if (self.cleaned_data.get('subscribe', False)
             and not self.cleaned_data['name']):
         raise forms.ValidationError(_('This field is required.'))
     return self.cleaned_data['name']
Exemple #19
0
 def clean_tipo_imovel(self):
     if self.cleaned_data.get('eh_comercial') and self.cleaned_data.get('tipo_imovel') == 'apartamento':
         raise forms.ValidationError('Apartamento não pode ser comercial.')
     return self.cleaned_data.get('tipo_imovel')
Exemple #20
0
 def clean_message(self):
     message = self.cleaned_data['message']
     if len(message) > 10000:
         raise forms.ValidationError(ugettext('Message is too long'))
     return message
Exemple #21
0
    def _clean_fields(self):
        boolean_field_names = self.boolean_field_names()
        for name, field in self.fields.items():
            # value_from_datadict() gets the data from the data dictionaries.
            # Each widget type knows how to retrieve its own data, because some
            # widgets split data over several HTML fields.
            value = field.widget.value_from_datadict(self.data, self.files,
                                                     self.add_prefix(name))
            try:
                if isinstance(field, forms.FileField):
                    initial = self.initial.get(name, field.initial)
                    value = field.clean(value, initial)
                else:
                    value = field.clean(value)
                self.cleaned_data[name] = value

                if name in boolean_field_names and value is None:
                    mfield = self.instance._meta.get_field_by_name(name)[0]
                    if not mfield.allow_blank:
                        msg = otree.constants_internal.field_required_msg
                        raise forms.ValidationError(msg)

                lower, upper = self._get_field_boundaries(name)

                # allow blank=True and min/max to be used together
                # the field is optional, but
                # if a value is submitted, it must be within [min,max]
                if lower is None or value is None:
                    pass
                elif value < lower:
                    msg = _('Value must be greater than or equal to {}.')
                    raise forms.ValidationError(msg.format(lower))

                if upper is None or value is None:
                    pass
                elif value > upper:
                    msg = _('Value must be less than or equal to {}.')
                    raise forms.ValidationError(msg.format(upper))

                if hasattr(self.view, '%s_choices' % name):
                    choices = getattr(self.view, '%s_choices' % name)()
                    choices_values = (
                        otree.common_internal.contract_choice_tuples(choices))
                    if value not in choices_values:
                        # Translators: for multiple-choice fields,
                        # show the valid choices.
                        # e.g. "Value must be one of: A, B, C"
                        msg = _('Value must be one of: {}'.format(", ".join(
                            map(str, choices))))
                        raise forms.ValidationError(msg)

                if hasattr(self.view, '%s_error_message' % name):
                    error_string = getattr(self.view,
                                           '%s_error_message' % name)(value)
                    if error_string:
                        raise forms.ValidationError(error_string)

                if hasattr(self, 'clean_%s' % name):
                    value = getattr(self, 'clean_%s' % name)()
                    self.cleaned_data[name] = value

            except forms.ValidationError as e:
                self.add_error(name, e)
        if not self.errors and hasattr(self.view, 'error_message'):
            error_string = self.view.error_message(self.cleaned_data)
            if error_string:
                e = forms.ValidationError(error_string)
                self.add_error(None, e)
Exemple #22
0
    def clean_url(self):
        url = URLObject(self.cleaned_data['url'])

        # URLObject doesn't handle ipv6 very well yet. In the meantime, ...
        if url.netloc.count(':') > 3:
            raise forms.ValidationError(_("Enter a valid URL."))

        URLValidator()(url.without_auth())
        if url.scheme not in ['http', 'https']:
            raise forms.ValidationError(
                _("Invalid URL scheme: '%s'. Only HTTP and HTTPS are "
                  "supported.") % url.scheme)

        if url.netloc.hostname in ['localhost', '127.0.0.1', '::1']:
            raise forms.ValidationError(_("Enter a valid URL."))

        try:
            validate_ipv46_address(url.netloc.hostname)
        except forms.ValidationError:
            pass
        else:
            raise forms.ValidationError(_("Enter a valid URL."))

        existing = self.user.feeds.filter(url=url)
        if self.instance is not None:
            existing = existing.exclude(pk=self.instance.pk)

        if existing.exists():
            raise forms.ValidationError(
                _("It seems you're already subscribed to this feed."))

        auth = None
        if url.auth != (None, None):
            auth = url.auth

        # Check this is actually a feed
        with user_lock("feed_check", self.user.pk, timeout=30):
            headers = {
                'User-Agent': USER_AGENT % 'checking feed',
                'Accept': feedparser.ACCEPT_HEADER,
            }
            try:
                response = requests.get(six.text_type(url.without_auth()),
                                        headers=headers, timeout=10,
                                        auth=auth)
            except Exception:
                if 'SENTRY_DSN' in os.environ:
                    client = Client()
                    client.captureException()
                raise forms.ValidationError(_("Error fetching the feed."))
            if response.status_code != 200:
                raise forms.ValidationError(_(
                    "Invalid response code from URL: "
                    "HTTP %s.") % response.status_code)
        try:
            parsed = feedparser.parse(response.content)
        except Exception:
            raise forms.ValidationError(_("Error parsing the feed."))
        if not is_feed(parsed):
            raise forms.ValidationError(
                _("This URL doesn't seem to be a valid feed."))
        self.cleaned_data['title'] = parsed.feed.title
        # Cache this in case update_favicon needs it and it's not in the
        # scheduler data yet.
        if hasattr(parsed.feed, 'link'):
            cache.set(u'feed_link:{0}'.format(url), parsed.feed.link, 600)
        return url
Exemple #23
0
 def clean_current_password(self):
     password = self.cleaned_data['current_password']
     if not self.user.check_password(password):
         raise forms.ValidationError(_('Incorrect password'))
     return password
Exemple #24
0
 def clean_action_type(self):
     action_type = self.cleaned_data['action_type']
     try:
         return models.ActionType.objects.get(id=action_type)
     except models.ActionType.DoesNotExist:
         raise forms.ValidationError(_("Invalid type"))
Exemple #25
0
 def clean(self):
     if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
         if self.cleaned_data['password1'] != self.cleaned_data['password2']:
             raise forms.ValidationError(
                 _("The password fields did not match"))
     return self.cleaned_data
Exemple #26
0
 def clean_username(self):
     username = self.cleaned_data['username']
     if User.objects.exclude(pk=self.instance.pk).filter(
             username__iexact=username, ).exists():
         raise forms.ValidationError(_('This username is already taken.'))
     return username
 def clean_rsvp(self):
     if self.cleaned_data['rsvp'] == RSVP.vazio:
         raise forms.ValidationError('Responda aqui!!!')
     return self.cleaned_data['rsvp']
Exemple #28
0
 def clean_new_password2(self):
     password_1 = self.cleaned_data.get('new_password', '')
     if self.cleaned_data['new_password2'] != password_1:
         raise forms.ValidationError(_("The two passwords didn't match"))
     return password_1
Exemple #29
0
 def clean_email(self):
     """Make sure the email doesn't exist already."""
     data = self.cleaned_data['email']
     if SchoolUser.objects.filter(email=data).exists():
         raise forms.ValidationError("This email already used")
     return data