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

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

项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def forgot(request):
    if request.user.is_authenticated():
        return redirect(_login_redirect_url(request))

    form = forms.ForgotPasswordForm()
    if request.method == 'POST':
        form = forms.ForgotPasswordForm(request.POST)
        if form.is_valid():
            try:
                user = models.User.objects.get(email__iexact=form.cleaned_data['email'])
                if not user.has_usable_password():
                    form.add_error(
                        'email',
                        _('That user does not use a password to log in, and therefore their password cannot be reset. '
                          'Did you sign up with a Google account?'))
                    user = None
            except models.User.DoesNotExist:
                form.add_error('email', _('Sorry, there is no user with that email address.'))
                user = None
            if user:
                _send_forgot_email(request, user)
                signer = Signer('accounts.views.forgot-email')
                email_signed = urlsafe_base64_encode(signer.sign(user.email.encode('utf8')).encode('utf8'))
                return redirect(reverse('accounts:forgot-sent') + '?e=' + email_signed.decode('utf8'))
    return render(request, 'accounts/forgot/step1.html', {'form': form})
项目:healthchecks_asgards    作者:andela    | 项目源码 | 文件源码
def send_report(self):
        # reset next report date first:
        now = timezone.now()
        self.next_report_date = now + timedelta(days=30)
        self.save()

        token = signing.Signer().sign(uuid.uuid4())
        path = reverse("hc-unsubscribe-reports", args=[self.user.username])
        unsub_link = "%s%s?token=%s" % (settings.SITE_ROOT, path, token)

        ctx = {
            "checks": self.user.check_set.order_by("created"),
            "now": now,
            "unsub_link": unsub_link
        }

        emails.report(self.user.email, ctx)
项目:django-tokenauth    作者:skorokithakis    | 项目源码 | 文件源码
def email_login_link(request, email):
    current_site = get_current_site(request)

    # Create the signed structure containing the time and email address.
    email = email.lower().strip()
    data = {"t": int(time.time()), "e": email}
    data = json.dumps(data).encode("utf8")
    data = Signer().sign(base64.b64encode(data).decode("utf8"))

    # Send the link by email.
    send_mail(
        render_to_string("tokenauth_login_subject.txt", {"current_site": current_site}, request=request).strip(),
        render_to_string("tokenauth_login_body.txt", {"current_site": current_site, "data": data}, request=request),
        ta_settings.DEFAULT_FROM_EMAIL,
        [email],
        fail_silently=False,
    )
项目:USTC-Software-2017    作者:igemsoftware2017    | 项目源码 | 文件源码
def __call__(self, view):

        @wraps(view)
        def wrapper(request, *args, **kwargs):

            if 'HTTP_AUTHORIZATION' in request.META:
                auth_info = request.META['HTTP_AUTHORIZATION'].split()

                if len(auth_info) == 2 and auth_info[0].lower() == 'basic':
                    password = base64.b64decode(auth_info[1]).decode().split(':')[1]

                    if ':'.join((self.password, password)) == Signer().sign(self.password):
                        return view(request, *args, **kwargs)

            response = HttpResponse()
            response.status_code = 401
            response['WWW-Authenticate'] = 'Basic realm=%s' % self.realm

            return response
        return wrapper
项目: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
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def change_email(request):
    if request.method == 'POST':
        form = forms.ChangeEmailForm(request.POST, user=request.user)
    else:
        form = forms.ChangeEmailForm(user=request.user)

    if request.method == 'POST' and form.is_valid():
        new_email = form.cleaned_data['new_email']
        _send_change_email(request, request.user, new_email)
        signer = Signer('accounts.views.change-email')
        email_signed = urlsafe_base64_encode(signer.sign(new_email.encode('utf8')).encode('utf8'))
        return redirect(reverse('accounts:change-email-sent') + '?e=' + email_signed.decode('utf8'))

    return render(request, 'accounts/change_email/step1.html', {'form': form})
项目: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})
项目:dart    作者:lmco    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(ListMissionTestsView, self).get_context_data(**kwargs)
        tests = self.get_queryset()

        context['tests'] = tests
        context['this_mission'] = Mission.objects.get(id=self.kwargs['mission'])

        context['server_timestamp'] = Signer().sign(time.time())
        return context
项目: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")
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def make_token(self, user):
        '''
        makes a verification token for a user

        Student account verification is spam prevention,
        rather than a security concern. So we can
        make the token the user's signed username

        pls dont spam us??? thanks
        '''
        return Signer().sign(str(user.username)).split(':')[-1]
项目:multiuploader    作者:vinaypost    | 项目源码 | 文件源码
def media_type(context, media_type):
    mu_forms = getattr(settings, "MULTIUPLOADER_FORMS_SETTINGS", settings.MULTIUPLOADER_FORMS_SETTINGS)

    signer = Signer()

    if media_type:
        import warnings

        if media_type == '' or media_type not in mu_forms:
            if settings.DEBUG:
                warnings.warn("A {% media_type %} was used in a template but such media_type ({}) was not provided"
                              "in settings, default used instead".format(media_type))

            return mark_safe(
                u"<div style='display:none'><input type='hidden' name='media_type' value='{}' /></div>".format(signer.sign(
                    'default')))

        else:
            return mark_safe(
                u"<div style='display:none'><input type='hidden' name='media_type' value='{}' /></div>".format(signer.sign(
                    media_type)))
    else:
        # It's very probable that the media_type is missing because of
        # misconfiguration, so we raise a warning
        import warnings
        if settings.DEBUG:
            warnings.warn("A {% media_type %} was used in a template but form_type was not provided")

        return mark_safe(u"")
项目:django-qr-code    作者:dprog-philippe-docourt    | 项目源码 | 文件源码
def get_qr_url_protection_signed_token(size, border, version, image_format):
    """Generate a signed token to handle view protection."""
    url_protection_options = get_url_protection_options()
    signer = Signer(key=url_protection_options['SIGNING_KEY'], salt=url_protection_options['SIGNING_SALT'])
    token = signer.sign(get_qr_url_protection_token(size, border, version, image_format, RANDOM_TOKEN))
    return token
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def from_instance(cls, identifier):
        """
        :param identifier: any object identifier
        :rtype: WebKey
        """
        payload = json.dumps({'t': time.time(), 'identifier': identifier})
        token = signing.Signer().sign(urlsafe_base64_encode(
            force_bytes(payload)))
        return cls(token)
项目: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')
项目:django-tokenauth    作者:skorokithakis    | 项目源码 | 文件源码
def authenticate(self, token=None):
        """Authenticate a user given a signed token."""
        try:
            data = Signer().unsign(token)
        except:
            return

        data = json.loads(base64.b64decode(data).decode("utf8"))
        if data["t"] < time.time() - ta_settings.TOKEN_DURATION:
            return

        User = get_user_model()

        user, created = User.objects.get_or_create(email=data["e"])
        return user
项目:TigerHost    作者:naphatkrit    | 项目源码 | 文件源码
def get_password(self):
        """Get the password for this user/backend combination

        :rtype: str
        :returns: the password
        """
        signer = Signer()
        return signer.sign(self.password_seed)
项目:TigerHost    作者:naphatkrit    | 项目源码 | 文件源码
def get_secret(username):
    """Get the secret for this user.

    :param str username: str

    :rtype: str
    :returns: a base64 encoded string, or None if the user does not exist.
    """
    from wsse.models import WsseProfile
    try:
        profile = WsseProfile.objects.get(user__username__iexact=username)
    except WsseProfile.DoesNotExist:
        return None
    signer = Signer()
    return base64.standard_b64encode(signer.sign(profile.secret))
项目:extrade    作者:aza7    | 项目源码 | 文件源码
def make_signature(self):
        """
Generates a signature to use in one-time secret URL's
to confirm the email address change request.

:returns: A signature.
:rtype: str
"""
        signer = Signer()
        value = signer.sign(self.new_email)
        email, signature = value.split(':',  1)
        return signature
项目:django-mongo-rest    作者:TrueSkills    | 项目源码 | 文件源码
def _signature(querystring, salt):
    return signing.Signer(key=settings.SECRET_KEY, salt=salt).signature(querystring)
项目: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