Python django.core.signing.BadSignature() Examples

The following are 30 code examples of django.core.signing.BadSignature(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.signing , or try the search function .
Example #1
Source File: verification.py    From django-rest-registration with MIT License 6 votes vote down vote up
def verify(self):
        data = self._data
        signature = data.get(self.SIGNATURE_FIELD, None)
        if signature is None:
            raise BadSignature()
        expected_signature = self.calculate_signature()
        if not constant_time_compare(signature, expected_signature):
            raise BadSignature()

        valid_period = self.get_valid_period()

        if self.USE_TIMESTAMP and valid_period is not None:
            timestamp = data[self.TIMESTAMP_FIELD]
            timestamp = int(timestamp)
            current_timestamp = get_current_timestamp()
            valid_period_secs = valid_period.total_seconds()
            if current_timestamp - timestamp > valid_period_secs:
                raise SignatureExpired() 
Example #2
Source File: request.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
        """
        Attempt to return a signed cookie. If the signature fails or the
        cookie has expired, raise an exception, unless the `default` argument
        is provided,  in which case return that value.
        """
        try:
            cookie_value = self.COOKIES[key]
        except KeyError:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        try:
            value = signing.get_cookie_signer(salt=key + salt).unsign(
                cookie_value, max_age=max_age)
        except signing.BadSignature:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        return value 
Example #3
Source File: views.py    From website with GNU General Public License v3.0 6 votes vote down vote up
def get_object(self):
        # Decode the timestamped data:
        # - the PK of the AlumSurveyTracker
        #
        # If the timestamp is older than 1 month, display an error message.
        #
        # Figure out which model is not null (alumni_info or intern_info) to use.
        # See if we already have an AlumSurvey that points to this survey tracker.
        # If not, create it.
        signer = TimestampSigner()
        try:
            this_pk = signer.unsign(self.kwargs['survey_slug'], max_age=timedelta(days=30))
        except SignatureExpired:
            raise PermissionDenied("The survey link has expired.")
        except BadSignature:
            raise PermissionDenied("Bad survey link.")

        try:
            return AlumSurvey.objects.get(survey_tracker__pk=this_pk)
        except AlumSurvey.DoesNotExist:
            tracker = get_object_or_404(AlumSurveyTracker, pk=this_pk)
            return AlumSurvey(survey_tracker=tracker, survey_date=datetime.now())

    # No need to override get_context because we can get everything from
    # form.instance.survey_tracker 
Example #4
Source File: views.py    From website with GNU General Public License v3.0 6 votes vote down vote up
def survey_opt_out(request, survey_slug):
    signer = TimestampSigner()
    try:
        this_pk = signer.unsign(survey_slug)
    except BadSignature:
        raise PermissionDenied("Bad survey opt-out link.")

    try:
        survey_tracker = AlumSurveyTracker.objects.get(pk=this_pk)
    except AlumSurveyTracker.DoesNotExist:
        raise PermissionDenied("Bad survey opt-out link.")

    if survey_tracker.alumni_info != None:
        survey_tracker.alumni_info.survey_opt_out = True
        survey_tracker.alumni_info.save()
    elif survey_tracker.intern_info != None:
        survey_tracker.intern_info.survey_opt_out = True
        survey_tracker.intern_info.save()

    return render(request, 'home/survey_opt_out_confirmation.html') 
Example #5
Source File: models.py    From django-db-mailer with GNU General Public License v2.0 6 votes vote down vote up
def track(cls, http_meta, encrypted):
        class Request(object):
            META = http_meta

        try:
            request = Request()

            mail_log_id = signing.loads(encrypted)
            mail_log = MailLog.objects.get(log_id=mail_log_id)

            track_log = MailLogTrack.objects.filter(mail_log=mail_log)
            if not track_log.exists():
                MailLogTrack.objects.create(
                    mail_log=mail_log,
                    ip=get_ip(request),
                    ua=request.META.get('HTTP_USER_AGENT'),
                    is_read=True,
                )
            else:
                track_log[0].save()
        except (signing.BadSignature, MailLog.DoesNotExist):
            pass 
Example #6
Source File: models.py    From lego with MIT License 6 votes vote down vote up
def validate_token(token):
        """
        Validate token.

        returns MeetingInvitation or None
        """

        try:
            # Valid in 7 days
            valid_in = 60 * 60 * 24 * 7
            data = signing.loads(TimestampSigner().unsign(token, max_age=valid_in))

            return MeetingInvitation.objects.filter(
                user=int(data["user_id"]), meeting=int(data["meeting_id"])
            )[0]
        except (BadSignature, SignatureExpired):
            return None 
Example #7
Source File: request.py    From python with Apache License 2.0 6 votes vote down vote up
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
        """
        Attempts to return a signed cookie. If the signature fails or the
        cookie has expired, raises an exception... unless you provide the
        default argument in which case that value will be returned instead.
        """
        try:
            cookie_value = self.COOKIES[key]
        except KeyError:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        try:
            value = signing.get_cookie_signer(salt=key + salt).unsign(
                cookie_value, max_age=max_age)
        except signing.BadSignature:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        return value 
Example #8
Source File: request.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
        """
        Attempts to return a signed cookie. If the signature fails or the
        cookie has expired, raises an exception... unless you provide the
        default argument in which case that value will be returned instead.
        """
        try:
            cookie_value = self.COOKIES[key]
        except KeyError:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        try:
            value = signing.get_cookie_signer(salt=key + salt).unsign(
                cookie_value, max_age=max_age)
        except signing.BadSignature:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        return value 
Example #9
Source File: request.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
        """
        Attempts to return a signed cookie. If the signature fails or the
        cookie has expired, raises an exception... unless you provide the
        default argument in which case that value will be returned instead.
        """
        try:
            cookie_value = self.COOKIES[key]
        except KeyError:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        try:
            value = signing.get_cookie_signer(salt=key + salt).unsign(
                cookie_value, max_age=max_age)
        except signing.BadSignature:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        return value 
Example #10
Source File: spam_util.py    From Bitpoll with GNU General Public License v3.0 6 votes vote down vote up
def check_anti_spam_challange(key: str, answer: str, poll_id: int) -> bool:
    """Checks if the anti spam cheallenge was solved and not expired"""
    try:
        spam_data = signing.loads(key)
        if spam_data.get('type') != 'anti_spam':
            raise ValidationError(_("Error while checking response"))
    except BadSignature:
        raise ValidationError(_("Error while checking response"))
    if spam_data['poll_id'] != poll_id:
        raise ValidationError(_("Error while checking response"))
    if spam_data['time'] <= time.time() - django_settings.ANTI_SPAM_CHALLENGE_TTL:
        raise ValidationError(_("Question Expired, please solve the new question."))
    if answer is None:
        raise ValidationError(_('Field is required'))
    op = spam_data['op']
    x = spam_data['x']
    y = spam_data['y']

    if op == '+':
        return answer == x + y
    if op == '-':
        return answer == x - y
    if op == '*':
        return answer == x * y
    raise ValidationError(_("Error while checking response")) 
Example #11
Source File: views.py    From Bitpoll with GNU General Public License v3.0 6 votes vote down vote up
def change_email(request, token):
    try:
        data = signing.loads(token, max_age=TOKEN_MAX_AGE)
    except signing.SignatureExpired:
        return TemplateResponse(request, 'registration/token_expired.html')
    except signing.BadSignature:
        return TemplateResponse(request, 'registration/token_invalid.html')
    if request.user.username != data.get('username'):
        return TemplateResponse(request, 'registration/token_invalid.html')
    email = data.get('email')
    try:
        validate_email(email)
    except ValidationError:
        return TemplateResponse(request, 'registration/token_invalid.html')
    request.user.email = email
    request.user.save()

    messages.success(request, _('Your email address has been changed.'))
    return redirect('registration_account') 
Example #12
Source File: request.py    From python2017 with MIT License 6 votes vote down vote up
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
        """
        Attempts to return a signed cookie. If the signature fails or the
        cookie has expired, raises an exception... unless you provide the
        default argument in which case that value will be returned instead.
        """
        try:
            cookie_value = self.COOKIES[key]
        except KeyError:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        try:
            value = signing.get_cookie_signer(salt=key + salt).unsign(
                cookie_value, max_age=max_age)
        except signing.BadSignature:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        return value 
Example #13
Source File: utils.py    From django-elevate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def has_elevated_privileges(request):
    """
    Check if a request is allowed to perform Elevate actions
    """
    if getattr(request, '_elevate', None) is None:
        try:
            request._elevate = (
                is_authenticated(request.user) and
                constant_time_compare(
                    request.get_signed_cookie(COOKIE_NAME, salt=COOKIE_SALT, max_age=COOKIE_AGE),
                    request.session[COOKIE_NAME]
                )
            )
        except (KeyError, BadSignature):
            request._elevate = False
    return request._elevate 
Example #14
Source File: request.py    From bioforum with MIT License 6 votes vote down vote up
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
        """
        Attempt to return a signed cookie. If the signature fails or the
        cookie has expired, raise an exception, unless the `default` argument
        is provided,  in which case return that value.
        """
        try:
            cookie_value = self.COOKIES[key]
        except KeyError:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        try:
            value = signing.get_cookie_signer(salt=key + salt).unsign(
                cookie_value, max_age=max_age)
        except signing.BadSignature:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        return value 
Example #15
Source File: views.py    From django-register-sample with MIT License 6 votes vote down vote up
def get(self, request, **kwargs):
        token = kwargs.get('token')
        try:
            new_email = loads(token, max_age=self.timeout_seconds)

        # 期限切れ
        except SignatureExpired:
            return HttpResponseBadRequest()

        # tokenが間違っている
        except BadSignature:
            return HttpResponseBadRequest()

        # tokenは問題なし
        else:
            User.objects.filter(email=new_email, is_active=False).delete()
            request.user.email = new_email
            request.user.save()
            return super().get(request, **kwargs) 
Example #16
Source File: request.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
        """
        Attempts to return a signed cookie. If the signature fails or the
        cookie has expired, raises an exception... unless you provide the
        default argument in which case that value will be returned instead.
        """
        try:
            cookie_value = self.COOKIES[key]
        except KeyError:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        try:
            value = signing.get_cookie_signer(salt=key + salt).unsign(
                cookie_value, max_age=max_age)
        except signing.BadSignature:
            if default is not RAISE_ERROR:
                return default
            else:
                raise
        return value 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_decode_detects_tampering(self):
        "loads should raise exception for tampered objects"
        transforms = (
            lambda s: s.upper(),
            lambda s: s + 'a',
            lambda s: 'a' + s[1:],
            lambda s: s.replace(':', ''),
        )
        value = {
            'foo': 'bar',
            'baz': 1,
        }
        encoded = signing.dumps(value)
        self.assertEqual(value, signing.loads(encoded))
        for transform in transforms:
            with self.assertRaises(signing.BadSignature):
                signing.loads(transform(encoded)) 
Example #18
Source File: api_views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def verify_secret(secret, module):
    data = {}
    if "$" in secret:
        #
        # There is no $ in the signed secret produced by the django signing module (base64 + :)
        # Try to verify a simple structure:
        #
        # secret = signed_secret$id_attribute$id_value
        #
        # Only used for now with id_attribute == SERIAL and id_value == machine serial number
        # Usefull to get the machine serial number when the signed_secret is shared
        # among a fleet of machines for easy deployment
        #
        try:
            secret, method, value = secret.split('$', 2)
        except ValueError:
            raise APIAuthError('Malformed secret')
        if method != 'SERIAL':
            raise APIAuthError('Invalid secret method')
        if not value:
            raise APIAuthError('Invalid secret value')
        data['machine_serial_number'] = value.strip().splitlines()[0]  # NOT VERIFIED
    try:
        data.update(signing.loads(secret, key=API_SECRET))
    except signing.BadSignature:
        raise APIAuthError('Bad secret signature')
    if data['module'] != module:
        raise APIAuthError('Invalid module')
    bu_k = data.pop('bu_k', None)
    if bu_k:
        # TODO: cache
        qs = BusinessUnit.objects.select_related('source')
        bu_list = list(qs.filter(key__startswith=bu_k,
                                 source__module='zentral.contrib.inventory').order_by('-id'))
        if not bu_list:
            logger.error('Unknown BU %s', bu_k)
        else:
            if len(bu_list) > 1:
                logger.error('Found multiple BU for key %s', bu_k)
            data['business_unit'] = bu_list[0]
    return data 
Example #19
Source File: user.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def validate_reset_token(cls, token):
        try:
            data = signer.unsign_t(token)
            user_id = data.get('reset', None)
            user_email = data.get('email', '')
            user = cls.objects.get(id=user_id, email=user_email)

        except (signing.BadSignature, cls.DoesNotExist):
            user = None
        return user 
Example #20
Source File: conf.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get_instance_with_secret(self, secret):
        try:
            data = signing.loads(secret, key=API_SECRET)
        except signing.BadSignature:
            raise APIAuthError("Bad secret signature")
        else:
            return self.instances[data["url"]] 
Example #21
Source File: views.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def validate_key(self, activation_key):
        try:
            dump = signing.loads(activation_key, salt=REGISTRATION_SALT,
                                 max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400)
            return dump
        except signing.BadSignature:
            return None 
Example #22
Source File: activation_service.py    From della with MIT License 5 votes vote down vote up
def validate_key(key, user):
    signer = TimestampSigner(settings.SECRET_KEY)
    try:
        value = signer.unsign(key, max_age=settings.EMAIL_LINK_EXPIRY_DAYS)
        return str(user.id) == value
    except (BadSignature, SignatureExpired):
        return False 
Example #23
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_can_use_salt(self):
        response = HttpResponse()
        response.set_signed_cookie('a', 'hello', salt='one')
        request = HttpRequest()
        request.COOKIES['a'] = response.cookies['a'].value
        value = request.get_signed_cookie('a', salt='one')
        self.assertEqual(value, 'hello')
        with self.assertRaises(signing.BadSignature):
            request.get_signed_cookie('a', salt='two') 
Example #24
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_unsign_detects_tampering(self):
        "unsign should raise an exception if the value has been tampered with"
        signer = signing.Signer('predictable-secret')
        value = 'Another string'
        signed_value = signer.sign(value)
        transforms = (
            lambda s: s.upper(),
            lambda s: s + 'a',
            lambda s: 'a' + s[1:],
            lambda s: s.replace(':', ''),
        )
        self.assertEqual(value, signer.unsign(signed_value))
        for transform in transforms:
            with self.assertRaises(signing.BadSignature):
                signer.unsign(transform(signed_value)) 
Example #25
Source File: models.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get_with_token(self, token):
        from zentral.utils.api_views import API_SECRET
        try:
            pk = int(signing.loads(token, salt="monolith", key=API_SECRET)["pk"])
        except (AttributeError, KeyError, signing.BadSignature):
            logger.error("Bad ppd download URL signature")
            raise ValueError
        else:
            return self.get(pk=pk) 
Example #26
Source File: tokens.py    From Spirit with MIT License 5 votes vote down vote up
def is_valid(self, user, signed_value):
        try:
            self.data = signing.loads(signed_value.replace(".", ":"), salt=__name__)
        except signing.BadSignature:
            return False

        if self.data['uid'] != self._uid(user):
            return False

        return True 
Example #27
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_detects_tampering(self):
        response = HttpResponse()
        response.set_signed_cookie('c', 'hello')
        request = HttpRequest()
        request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$'
        with self.assertRaises(signing.BadSignature):
            request.get_signed_cookie('c') 
Example #28
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_can_use_salt(self):
        response = HttpResponse()
        response.set_signed_cookie('a', 'hello', salt='one')
        request = HttpRequest()
        request.COOKIES['a'] = response.cookies['a'].value
        value = request.get_signed_cookie('a', salt='one')
        self.assertEqual(value, 'hello')
        with self.assertRaises(signing.BadSignature):
            request.get_signed_cookie('a', salt='two') 
Example #29
Source File: spam_util.py    From Bitpoll with GNU General Public License v3.0 5 votes vote down vote up
def get_spam_challenge_from_key(key: str, poll_id: int) -> Dict:
    """Returns the anti spam challenge from the key, or generates a new if it is not valid"""
    try:
        spam_data = signing.loads(key)
        if spam_data.get('type') != 'anti_spam' or spam_data['time'] <= time.time() - django_settings.ANTI_SPAM_CHALLENGE_TTL:
            return create_anti_spam_challenge(poll_id)
        spam_data['key'] = key
        return spam_data
    except BadSignature:
        return create_anti_spam_challenge(poll_id) 
Example #30
Source File: views.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def verify_token(self, request, *args, **kwargs):
        """
        Use `token` to allow one-time access to a view.

        Set the user as a class attribute or raise an `InvalidExpiredToken`.

        Token expiry can be set in `settings` with `VERIFY_ACCOUNT_EXPIRY` and is
        set in seconds.
        """
        User = get_user_model()

        try:
            max_age = settings.VERIFY_ACCOUNT_EXPIRY
        except AttributeError:
            max_age = self.DEFAULT_VERIFY_ACCOUNT_EXPIRY

        try:
            email_data = signing.loads(kwargs['token'], max_age=max_age)
        except signing.BadSignature:
            raise self.invalid_exception_class

        email = email_data['email']

        try:
            self.user = User.objects.get_by_natural_key(email)
        except User.DoesNotExist:
            raise self.invalid_exception_class

        if self.user.email_verified:
            raise self.permission_denied_class