Python django.core.signing 模块,BadSignature() 实例源码

我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.core.signing.BadSignature()

项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
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')
项目:pfb-network-connectivity    作者:azavea    | 项目源码 | 文件源码
def post(self, request):
        errors = []
        fatal = False
        token = request.data.get('token')
        password = request.data.get('password')
        if not token:
            errors.append('Invalid reset token.')
            fatal = True
        if not password:
            errors.append('No password provided.')
        signer = TimestampSigner(salt=settings.RESET_SALT)
        if token:
            try:
                user_uuid = signer.unsign(token, max_age=settings.RESET_TOKEN_LENGTH)
            except BadSignature:
                errors.append('Can not reset password because the reset link used was invalid.')
                fatal = True
        if len(errors) == 0:
            # set password
            user = PFBUser.objects.get(uuid=user_uuid)
            user.set_password(password)
            user.save()
            return Response({'status': 'Success'})
        else:
            return Response({'errors': errors, 'fatal': fatal}, status.HTTP_400_BAD_REQUEST)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:nightreads    作者:avinassh    | 项目源码 | 文件源码
def clean(self):
        cleaned_data = super(ConfirmEmailForm, self).clean()
        if self.errors:
            return cleaned_data
        user_id = cleaned_data['user']
        code = cleaned_data['code']
        for_subscription = cleaned_data['subscribe']
        user = User.objects.filter(id=user_id).first()
        if not user:
            raise forms.ValidationError('Invalid Link')
        self.cleaned_data['user'] = user
        try:
            user_service.validate_key(key=code, user=user,
                                      for_subscription=for_subscription)
        except BadSignature:
            raise forms.ValidationError('Invalid Link')
        except SignatureExpired:
            raise forms.ValidationError('Link expired, please regenerate')
        return cleaned_data
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
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
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def do_password_reset(request, token=None):
    try:
        email, timestamp = _password_reset_token_factory.parse_token(token)
    except (signing.BadSignature, signing.SignatureExpired):
        return render(request, 'users/password_reset/reset_token_invalid.html', {})

    try:
        user = get_user(email)
    except User.DoesNotExist:
        raise Http404()
    profile = user.profile
    timestamp = datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc)
    if profile.last_password_change and profile.last_password_change > timestamp:
        return render(request, 'users/password_reset/token_already_used.html', {})

    form = SetPasswordForm(user, request.POST or None)
    if form.is_valid():
        form.save()
        profile.last_password_change = timezone.now()
        profile.save()
        return render(request, 'users/password_reset/reset_complete.html', {})
    return render(request, 'users/password_reset/reset_form.html', {
        'user': user,
        'form': form,
    })
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
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
项目:ComBunqWebApp    作者:OGKevin    | 项目源码 | 文件源码
def store_in_session(data, password, username):
        user = User.objects.get(username=username)
        data = json.loads(data)

        try:
            dec_data = signing.loads(data['secret'], key=password)
        except signing.BadSignature:
            return None

        enc_data = signing.dumps(dec_data)

        s = SessionStore()
        s['api_data'] = enc_data
        s.create()
        user.session.session_token = s.session_key
        user.save()
        return True
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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
项目:waves-demo    作者:lirmm    | 项目源码 | 文件源码
def validate_key(self, activation_key):
        try:
            username = signing.loads(
                activation_key,
                salt=settings.REGISTRATION_SALT,
                max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400
            )
            return username
        # SignatureExpired is a subclass of BadSignature, so this will
        # catch either one.
        except signing.SignatureExpired:
            self.template_name = "accounts/activation_error.html"
            self.error_reason = "Your code has expired"
            return None
        except signing.BadSignature:
            self.template_name = "accounts/activation_error.html"
            self.error_reason = "Bad activation key"
            return None
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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
项目:extrade    作者:aza7    | 项目源码 | 文件源码
def verify_signature(self, signature):
        """
Checks if the signature has been tampered with.

:arg str signature: The signature to check, as generated by
    :func:`make_signature`.
:returns: ``True`` if the signature has not been tampered with,
    ``False`` otherwise.
    :rtype: bool
    """
        signer = Signer()
        value = "%s:%s" % (self.new_email, signature)
        try:
            signer.unsign(value)
        except BadSignature:
            return False
        return True
项目:django-learning    作者:adoggie    | 项目源码 | 文件源码
def validate_key(self, activation_key):
        """
        Verify that the activation key is valid and within the
        permitted activation time window, returning the username if
        valid or ``None`` if not.

        """
        try:
            username = signing.loads(
                activation_key,
                salt=REGISTRATION_SALT,
                max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400
            )
            return username
        # SignatureExpired is a subclass of BadSignature, so this will
        # catch either one.
        except signing.BadSignature:
            return None
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
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
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
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
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def get_widget_or_404(self):
        """
        Get and return widget from cache.

        Raises:
            Http404: If if the widget can not be found or no id is provided.

        Returns:
            ModelSelect2Mixin: Widget from cache.

        """
        field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None))
        if not field_id:
            raise Http404('No "field_id" provided.')
        try:
            key = signing.loads(field_id)
        except BadSignature:
            raise Http404('Invalid "field_id".')
        else:
            cache_key = '%s%s' % (settings.SELECT2_CACHE_PREFIX, key)
            widget_dict = cache.get(cache_key)
            if widget_dict is None:
                raise Http404('field_id not found')
            if widget_dict.pop('url') != self.request.path:
                raise Http404('field_id was issued for the view.')
        qs, qs.query = widget_dict.pop('queryset')
        self.queryset = qs.all()
        widget_dict['queryset'] = self.queryset
        widget_cls = widget_dict.pop('cls')
        return widget_cls(**widget_dict)
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def change_email_step1done(request):
    signer = Signer('accounts.views.change-email')
    email_signed = urlsafe_base64_decode(request.GET.get('e', ''))
    try:
        email = signer.unsign(email_signed)
    except BadSignature:
        raise SuspiciousOperation('change_step1done received invalid signed email {}'.format(signer))
    return render(request, 'accounts/change_email/step1done.html', {'email': email})
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def forgot_step1done(request):
    if request.user.is_authenticated():
        return redirect(_login_redirect_url(request))

    signer = Signer('accounts.views.forgot-email')
    email_signed = urlsafe_base64_decode(request.GET.get('e', ''))
    try:
        email = signer.unsign(email_signed)
    except BadSignature:
        raise SuspiciousOperation('forgot_step1done received invalid signed email {}'.format(signer))
    return render(request, 'accounts/forgot/step1done.html', {'email': email})
项目:django-rest-framework-registration    作者:9gix    | 项目源码 | 文件源码
def validate_key(self, activation_key):
        try:
            username = signing.loads(
                activation_key,
                salt=REGISTRATION_SALT,
                max_age=ACCOUNT_ACTIVATION_DAYS * 86400)
        except signing.BadSignature:
            username = None

        return username
项目:healthchecks_asgards    作者:andela    | 项目源码 | 文件源码
def unsubscribe_reports(request, username):
    try:
        signing.Signer().unsign(request.GET.get("token"))
    except signing.BadSignature:
        return HttpResponseBadRequest()

    user = User.objects.get(username=username)
    user.profile.reports_allowed = False
    user.profile.save()

    return render(request, "accounts/unsubscribed.html")
项目:djangocms-comments    作者:Nekmo    | 项目源码 | 文件源码
def value_from_datadict(self, data, files, name):
        value = super(SignedHiddenInput, self).value_from_datadict(data, files, name)
        try:
            value = signer.unsign(value)
        except BadSignature:
            raise SuspiciousOperation()
        if self.include_field_name:
            name_key = '{0}-'.format(name)
            if not value.startswith(name_key):
                raise SuspiciousOperation()
            value = value.replace(name_key, '', 1)
        return value
项目:djamazing    作者:sunscrapers    | 项目源码 | 文件源码
def check_signature(signature, filename, username):
    try:
        SIGNER.unsign(':'.join([filename, username, signature]))
    except BadSignature:
        return False
    return True
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except (signing.BadSignature, ValueError):
            self.create()
        return {}
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def activate(request, token=None):
    try:
        data = _registration_token_factory.parse_token(token)
    except (signing.BadSignature, signing.SignatureExpired):
        return render(request, 'users/registration/registration_token_invalid.html', {})

    try:
        existing_user = get_user(data['email'])
        return render(request, 'users/registration/already_activated.html', {
            'existing_user': existing_user,
        })
    except User.DoesNotExist:
        pass

    form = ActivationForm(request.POST or None)
    if form.is_valid():
        user = create_user(data['email'], first_name=data['first_name'], last_name=data['last_name'])
        user.set_password(form.cleaned_data['password'])
        user.save()
        # the userprofile is auto-created, we only have to update some fields.
        profile = user.profile
        profile.gender = data['gender']
        profile.forward_messages_after_minutes = 5
        profile.save()

        return render(request, 'users/registration/activation_complete.html', {
            'activated_user': user,
        })

    return render(request, 'users/registration/activation_form.html', {
        'form': form,
        'data': data,
    })
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def get_identifier(self):
        """ Gets the instance, if token is valid.

        :param klass: the class (must be model.Model instance)
        May throw DoesNotExist
        :returns: instance if signature is ok, None else.
        """
        try:
            payload = signing.Signer().unsign(self.token)
        except signing.BadSignature:
            return None
        else:
            d = json.loads(force_text(urlsafe_base64_decode(payload)))
            return d.get('identifier')
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except (signing.BadSignature, ValueError):
            self.create()
        return {}
项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def from_key(cls, key):
        try:
            max_age = (
                60 * 60 * 24 * app_settings.EMAIL_CONFIRMATION_EXPIRE_DAYS)
            pk = signing.loads(
                key,
                max_age=max_age,
                salt=app_settings.SALT)
            ret = EmailConfirmationHMAC(EmailAddress.objects.get(pk=pk))
        except (signing.SignatureExpired,
                signing.BadSignature,
                EmailAddress.DoesNotExist):
            ret = None
        return ret
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except (signing.BadSignature, ValueError):
            self.create()
        return {}
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def load_data(self):
        try:
            data = self.request.get_signed_cookie(self.prefix)
        except KeyError:
            data = None
        except BadSignature:
            raise SuspiciousOperation('WizardView cookie manipulated')
        if data is None:
            return None
        return json.loads(data, cls=json.JSONDecoder)
项目:USTC-Software-2017    作者:igemsoftware2017    | 项目源码 | 文件源码
def validate_sign(self, value):
        try:
            self.signed_data = signing.loads(value, max_age=PASSWORD_RESET_SIGNING_EXPIRATION)
        except signing.SignatureExpired:
            raise serializers.ValidationError('Signature expired.')
        except signing.BadSignature:
            raise serializers.ValidationError('Bad signature.')

        try:
            self.user = User.objects.get(pk=self.signed_data.get('user_id', None))
        except User.DoesNotExist:
            raise serializers.ValidationError('User does not exist.')

        return value
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except (signing.BadSignature, ValueError):
            self.create()
        return {}
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def load_data(self):
        try:
            data = self.request.get_signed_cookie(self.prefix)
        except KeyError:
            data = None
        except BadSignature:
            raise WizardViewCookieModified('WizardView cookie manipulated')
        if data is None:
            return None
        return json.loads(data, cls=json.JSONDecoder)
项目:django-learning    作者:adoggie    | 项目源码 | 文件源码
def activate(self, *args, **kwargs):
        # This is safe even if, somehow, there's no activation key,
        # because unsign() will raise BadSignature rather than
        # TypeError on a value of None.
        username = self.validate_key(kwargs.get('activation_key'))
        if username is not None:
            user = self.get_user(username)
            if user is not None:
                user.is_active = True
                user.save()
                return user
        return False
项目:geekpoint    作者:Lujinghu    | 项目源码 | 文件源码
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except (signing.BadSignature, ValueError):
            self.create()
        return {}
项目:Sentry    作者:NetEaseGame    | 项目源码 | 文件源码
def unsign(self, signed_value):
        # This unsign is identical to subclass except for the lowercasing
        # See: https://github.com/django/django/blob/1.6.11/django/core/signing.py#L165-L172
        signed_value = force_str(signed_value)
        if self.sep not in signed_value:
            raise BadSignature('No "%s" found in value' % self.sep)
        value, sig = signed_value.rsplit(self.sep, 1)
        if constant_time_compare(sig.lower(), self.signature(value)):
            return force_text(value)
        raise BadSignature('Signature "%s" does not match' % sig)
项目:perdiem-django    作者:RevolutionTech    | 项目源码 | 文件源码
def check_token(user_id, token):
    try:
        key = '%s:%s' % (user_id, token)
        TimestampSigner().unsign(key, max_age=60 * 60 * 48)  # Valid for 2 days
    except (BadSignature, SignatureExpired):
        return False
    return True
项目:della    作者:avinassh    | 项目源码 | 文件源码
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
项目:SciReg    作者:hms-dbmi    | 项目源码 | 文件源码
def email_confirm(request, template_name='registration/confirmed.html'):
    user = request.user

    email_confirm_value = request.GET.get('email_confirm_value', '-')
    email_confirm_value = user.email + ":" + email_confirm_value.replace(".", ":")
    success_url = request.GET.get('success_url', None)

    signer = TimestampSigner(salt=settings.EMAIL_CONFIRM_SALT)

    try:
        signer.unsign(email_confirm_value, max_age=timedelta(seconds=300))
        registration, created = Registration.objects.get_or_create(user_id=user.id)

        # If this is a new registration make sure we at least save the email/username.
        if created:
            registration.email = user.username

        registration.email_confirmed = True
        registration.save()

        # Set a message.
        messages.success(request, 'Email has been confirmed.',
                         extra_tags='success', fail_silently=True)

    except SignatureExpired:
        messages.error(request, 'This email confirmation code has expired, please try again.',
                       extra_tags='danger', fail_silently=True)

    except BadSignature:
        messages.error(request, 'This email confirmation code is invalid, please try again.',
                       extra_tags='danger', fail_silently=True)

    # Continue on to the next page, if passed. Otherwise render a default page.
    if success_url:
        return redirect(success_url)
    else:
        return render(request, template_name)
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except (signing.BadSignature, ValueError):
            self.create()
        return {}
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def create_account(request, info_token):
    if request.user.is_authenticated():
        return redirect('home')
    try:
        info = signing.loads(info_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')

    username = info['username']

    if BitpollUser.objects.filter(username=username).exists():
        messages.warning(request,_("This User already exists"))
        return redirect('login')

    if request.method == 'POST':
        form = PasswordForm(request.POST)
        if form.is_valid():
            first_name = info.get('first_name')
            last_name = info.get('last_name')
            if not (first_name and last_name):
                return TemplateResponse(request, 'registration/token_invalid.html')
            email = info['email']
            user = BitpollUser(username=username,
                               email=email,
                               first_name=first_name,
                               last_name=last_name,
                               email_invitation=info['email_invitation'],
                               #TODO: weitere felder??
                               )
            user.set_password(form.cleaned_data['password1'])
            user.save()
            user.backend='django.contrib.auth.backends.ModelBackend'

            login(request, user)
            return redirect('home')
    else:
        form = PasswordForm()

    return TemplateResponse(request, 'registration/create_account.html', {
        'form': form,
        'username': username
    })
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def setup_totp(request):
    if twofa.models.TOTPDevice.objects.active_for_user(request.user).exists():
        messages.error(request, _('You may not have multiple Google Authenticators attached to your account.'))
        return redirect('twofa:list')

    setup_signer = TimestampSigner('twofa.views.setup_totp:{}'.format(request.user.pk))

    if request.method == 'POST' and 'secret' in request.POST:
        try:
            b32_secret = setup_signer.unsign(request.POST['secret'], max_age=600)
        except SignatureExpired:
            messages.error(request, _('That took too long and your challenge expired. Here\'s a new one.'))
            return redirect('twofa:setup-totp')
        except BadSignature:
            messages.error(request, _('Whoops - something went wrong. Please try again.'))
            return redirect('twofa:setup-totp')
    else:
        b32_secret = base64.b32encode(secrets.token_bytes(10))
    signed_secret = setup_signer.sign(b32_secret)

    url = 'otpauth://totp/Sponge:{}?{}'.format(
        urlquote(request.user.username),
        urlencode({
            'secret': b32_secret,
            'issuer': 'Sponge'}))
    img = qrcode.make(url, image_factory=qrcode.image.svg.SvgPathFillImage)
    img_buf = io.BytesIO()
    img.save(img_buf)

    device = twofa.models.TOTPDevice(base32_secret=b32_secret, owner=request.user)
    device.activated_at = timezone.now()  # this won't be saved unless the form is valid
    form = device.verify_form(secret=signed_secret)
    if request.method == 'POST':
        form = device.verify_form(request.POST, secret=signed_secret)

        if form.is_valid():
            # relying on verify_form to save the new device
            request.user.twofa_enabled = True
            request.user.save()

            messages.success(request, _('Your authenticator has been added to your account.'))
            return _generate_paper_codes_if_needed(request.user, reverse('twofa:list'))

    return render(request, 'twofa/setup/totp.html', {
        'form': form, 'qr_code_svg': img_buf.getvalue(), 'b32_secret': b32_secret})
项目:django-qr-code    作者:dprog-philippe-docourt    | 项目源码 | 文件源码
def serve_qr_code_image(request):
    """Serve an image that represents the requested QR code."""
    text = base64.urlsafe_b64decode(request.GET.get('text', ''))
    size = request.GET.get('size', DEFAULT_MODULE_SIZE)
    border = request.GET.get('border', DEFAULT_BORDER_SIZE)
    version = request.GET.get('version', DEFAULT_VERSION)
    image_format = request.GET.get('image_format', DEFAULT_IMAGE_FORMAT)
    image_format = get_supported_image_format(image_format)

    # Handle view protection (we do not allow external requests for anyone).
    url_protection_options = get_url_protection_options(request.user)
    if not url_protection_options['ALLOWS_EXTERNAL_REQUESTS']:
        token = request.GET.get('token', '')
        signer = Signer(key=url_protection_options['SIGNING_KEY'], salt=url_protection_options['SIGNING_SALT'])
        try:
            # Check signature.
            url_protection_string = signer.unsign(token)
            # Check that the given token matches the request parameters.
            random_token = url_protection_string.split('.')[-1]
            if get_qr_url_protection_token(size, border, version, image_format, random_token) != url_protection_string:
                raise PermissionDenied("Request query does not match protection token.")
        except BadSignature:
            raise PermissionDenied("Wrong token signature.")

    img = make_qr_code_image(text, image_factory=SvgPathImage if image_format == SVG_FORMAT_NAME else PilImageOrFallback, size=size,
                             border=border, version=version)

    # Warning: The largest QR codes, in version 40, with a border of 4 modules, and rendered in SVG format, are ~800
    # KB large. This can be handled in memory but could cause troubles if the server needs to generate thousands of
    # those QR codes within a short interval! Note that this would also be a problem for the CPU. Such QR codes needs
    # 0.7 second to be generated on a powerful machine (2017), and probably more than one second on a cheap hosting.
    stream = BytesIO()
    if image_format == SVG_FORMAT_NAME:
        img.save(stream, kind=SVG_FORMAT_NAME.upper())
        mime_type = 'image/svg+xml'
    else:
        img.save(stream, format=PNG_FORMAT_NAME.upper())
        mime_type = 'image/png'

    # Go to the beginning of the stream.
    stream.seek(0)

    # Build the response.
    response = HttpResponse(content=stream, content_type=mime_type)
    return response
项目:django-authlib    作者:matthiask    | 项目源码 | 文件源码
def decode(code, *, max_age):
    """
    Decodes the code from the registration link and returns a tuple consisting
    of the verified email address and the associated user instance or ``None``
    if no user was passed to ``send_registration_mail``

    Pass the maximum age in seconds of the link as ``max_age``.

    This method raises ``ValidationError`` exceptions containing an translated
    message what went wrong suitable for presenting directly to the user.
    """
    try:
        data = get_signer().unsign(code, max_age=max_age)
    except signing.SignatureExpired:
        raise ValidationError(_(
            'The link is expired. Please request another registration link.'
        ), code='email_registration_expired')

    except signing.BadSignature:
        raise ValidationError(_(
            'Unable to verify the signature. Please request a new'
            ' registration link.'
        ), code='email_registration_signature')

    parts = data.split(':')
    if len(parts) != 3:
        raise ValidationError(_(
            'Something went wrong while decoding the'
            ' registration request. Please try again.'
        ), code='email_registration_broken')

    email, uid, timestamp = parts
    if uid and timestamp:
        try:
            user = User.objects.get(pk=uid)
        except (User.DoesNotExist, TypeError, ValueError):
            raise ValidationError(_(
                'Something went wrong while decoding the'
                ' registration request. Please try again.'
            ), code='email_registration_invalid_uid')

        if timestamp != int_to_base36(get_last_login_timestamp(user)):
            raise ValidationError(_(
                'The link has already been used.'
            ), code='email_registration_used')

    else:
        user = None

    return email, user