当前位置: 首页>>代码示例>>Python>>正文


Python signing.TimestampSigner类代码示例

本文整理汇总了Python中django.core.signing.TimestampSigner的典型用法代码示例。如果您正苦于以下问题:Python TimestampSigner类的具体用法?Python TimestampSigner怎么用?Python TimestampSigner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TimestampSigner类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: index

def index(request):
    limited = getattr(request, 'limited', False)
    if limited:
        return HttpResponseRedirect(reverse('rate_limited'))

    error_message = None
    reset_request = ResetRequestForm(request.POST or None)
    email_response = False
    
    try:
        if reset_request.is_valid():
            if reset_request.cleaned_data['email'] != '':
                user_data = ContactInformation.objects.get(alternate_email=reset_request.cleaned_data['email'])
                email_response = True
            else:
                user_data = ContactInformation.objects.get(cell_phone=reset_request.cleaned_data['cell'])
    
            signer = TimestampSigner()
            token = signer.sign(user_data.psu_uuid)
            
            if email_response is True:
                r = password_reset_email(user_data.psu_uuid, user_data.alternate_email, token)

            else:
                short_code = TextMessageShortCode()
                short_code.token = token
                short_code.save()
                
                r = password_reset_sms(user_data.cell_phone, short_code.code)

            if r is not True:
                raise APIException("Reset code not sent. Email? " + str(email_response))

            logger.info(
                "service=myinfo page=passwordreset action=reset_request status=success email={0} cell={1}".format(
                    reset_request.cleaned_data['email'], reset_request.cleaned_data['cell']))
            return HttpResponseRedirect(reverse("PasswordReset:reset_notoken"))
            
    except (ContactInformation.DoesNotExist, ContactInformation.MultipleObjectsReturned) as e:
        # Either we couldn't find it or we couldn't uniquely identify it.
        if isinstance(e, ContactInformation.DoesNotExist):
            status = "id_not_found"
        else:
            status = "multiple_matches"
        logger.info(
            "service=myinfo page=passwordreset action=reset_request status={0} email={1} cell={2}".format(
                status, reset_request.cleaned_data['email'], reset_request.cleaned_data['cell']))

        error_message = ("We could not uniquely identify a user with this information. "
                         "Ensure this information is correct and please try again. "
                         "If you continue to have difficulty, contact the Helpdesk (503-725-4357) for assistance.")
    except APIException:

        logger.info(
            "service=myinfo page=passwordreset action=reset_request status=code_not_sent email={0} cell={1}".format(
                reset_request.cleaned_data['email'], reset_request.cleaned_data['cell']))

        error_message = "Sorry, we were unable to send a reset code. Please try again later."
    
    return render(request, 'PasswordReset/index.html', {'form': reset_request, 'error': error_message, })
开发者ID:hhauer,项目名称:myinfo,代码行数:60,代码来源:views.py

示例2: send_restore_password

    def send_restore_password(self):
        signer = TimestampSigner()
        value = signer.sign(self.user.username)
        x = value.index(':')
        key = value[x+1:]
        
        self.password_restore_key = key
        self.save()

        sender = '[email protected]' 
        msg = {}
        msg['subject'] = 'Восстановление пароля' 
        magic_url = 'http://draftwatcher.pythonanywhere.com/'
        msg['body'] = '''
        Вы запросили восстановление пароля. Если Вы хотите
        сбросить пароль, перейдите по ссылке:
        {url}.
        Ссылка будет активна в течение пяти минут.
        
        Если вы не иницировали отправление этого сообщения, 
        просто проигнорируйте его.
        '''.format(
                url=''.join(
                    (magic_url,'restore_password/', key)))

        send_mail(msg['subject'], msg['body'], sender,
            [self.user.email], fail_silently=False)
        return key
开发者ID:redlolgeerf,项目名称:draftwatcher,代码行数:28,代码来源:models.py

示例3: confirmar_permiso

def confirmar_permiso(request):
    """
    ## Confirma un permiso enviado por la url

    Estado=Aprobado
    http://127.0.0.1:8000/confirmar/permiso/?token=4:1ay4mm:xeXW4JDTQqU3JYtVC-l_He1gT08&estado=1

    Estado=No Aprobado
    http://127.0.0.1:8000/confirmar/permiso/?token=4:1ay4mm:xeXW4JDTQqU3JYtVC-l_He1gT08&estado=0

    La utilidad de esta liibreria es para otorgar un permiso via email
    """
    token_mail = request.GET.get("token")
    estado = True if request.GET.get("estado") == "1" else False
    print estado
    print token_mail
    signer = TimestampSigner(salt="4g3t1c")
    try:
        pk_dpermiso = signer.unsign(token_mail, max_age=3600*1)
        designacion_permiso = DesignacionPermiso.objects.filter(pk=pk_dpermiso, token_mail=token_mail, token_confirmation_date__isnull=True)
        if designacion_permiso:
            designacion_permiso.update(aprobado=estado, token_confirmation_date=timezone.now())
            return HttpResponse("El permiso fue aprobado satisfactoriamente")
        else:
            return HttpResponse("El permiso ya fue confirmado")
    except signing.SignatureExpired:
        return HttpResponse("La clave del mensaje a expirado")
    except signing.BadSignature:
        return HttpResponse("Firma de Mensaje Incorrecto")
开发者ID:Marcelo1180,项目名称:agetic_rrhh,代码行数:29,代码来源:views.py

示例4: politician_hansard_subscribe

def politician_hansard_subscribe(request, signed_key):
    ctx = {
        'key_error': False
    }
    try:
        key = TimestampSigner(salt='alerts_pol_subscribe').unsign(signed_key, max_age=60*60*24*14)
        politician_id, _, email = key.partition(',')
        pol = get_object_or_404(Politician, id=politician_id)
        if not pol.current_member:
            raise Http404

        user, created = User.objects.get_or_create(email=email)
        sub, created = Subscription.objects.get_or_create_by_query(
            _generate_query_for_politician(pol), user)
        if not sub.active:
            sub.active = True
            sub.save()
        ctx.update(
            pol=pol,
            title=u'Email alerts for %s' % pol.name
        )
    except BadSignature:
        ctx['key_error'] = True

    return render(request, 'alerts/activate.html', ctx)
开发者ID:DevinMonroe-HalcyonWebDesign,项目名称:openparliament,代码行数:25,代码来源:views.py

示例5: find

def find(request, token):
    try:
        signer = TimestampSigner(key=request.session.session_key, sep=':')
        id = b64_decode(signer.unsign(token, max_age=Task.TIMEOUT).encode('utf-8'))
        return Task.status(id)
    except:
        return None
开发者ID:jmartign,项目名称:vac-templater,代码行数:7,代码来源:__init__.py

示例6: post

    def post(self, request, *args, **kwargs):
        try:
            data = confirm(request)
        except PaymentError as e:
            messages.error(self.request, str(e))
            self.restore_frozen_basket()
            logger.exception(e)
            return TemplateResponse(request, 'worldpay/worldpay_response.html', {'url': self.request.build_absolute_uri(reverse("worldpay-fail") + "?error=%s" % str(e))})

        basket = Basket.objects.get(pk=data['M_basket'])
        basket.strategy = Selector().strategy()
        
        if data['M_user'] == 'None':
            user = AnonymousUser()
        else:
            user = User.objects.get(pk=data['M_user'])
        
        # Fetch submission data out of session
        order_number = data['cartId']
        total = Decimal(data['amount'])
        
        # Record payment source
        source_type, is_created = SourceType.objects.get_or_create(name='WorldPay')
        source = Source(source_type=source_type,
                        currency=data['currency'],
                        amount_allocated=total,
                        amount_debited=total,
                        reference=data['transId'])
        self.add_payment_source(source)
        self.add_payment_event('paid', total, reference=data['transId'])
        
        shipping_address = ShippingAddress.objects.get(pk=data['M_shipping_address'])
        if data['M_billing_address'] == 'None':
            billing_address = None
        else:
            billing_address = BillingAddress.objects.get(pk=data['M_billing_address'])
        
        shipping_methods = Repository().get_shipping_methods(basket, user=user, shipping_addr=shipping_address)
        shipping_method = [method for method in shipping_methods if method.code == data['M_shipping_method']][0]
        
        order_kwargs = json.loads(data['M_order_kwargs'])
        # Place order
        calc_total = self.get_order_totals(basket, shipping_method.calculate(basket))
        self.handle_order_placement(
            order_number,
            user,
            basket,
            shipping_address,
            shipping_method,
            shipping_method.calculate(basket),
            billing_address,
            calc_total,
            **order_kwargs
        )
        
        signer = TimestampSigner()
        order_number = signer.sign(order_number)
        success_url = self.request.build_absolute_uri(reverse("worldpay-success") + '?order_number=%s' % (order_number))
        
        return TemplateResponse(request, 'worldpay/worldpay_response.html', {'url': success_url})
开发者ID:MatthewWilkes,项目名称:django-oscar-worldpay,代码行数:60,代码来源:views.py

示例7: check_token

def check_token(request, answer, token):
    payload = hashlib.sha1('{}:{}'.format(request.session.session_key, answer.pk).encode()).hexdigest()
    signer = TimestampSigner()
    try:
        return payload == signer.unsign(token, max_age=3600 * 24)
    except BadSignature:
        return False
开发者ID:FlaviaBastos,项目名称:pretix,代码行数:7,代码来源:safedownload.py

示例8: lookup

    def lookup(self, signed):
        if signed is None:
            raise NonceException("No nonce was provided.")

        signer = TimestampSigner()
        try:
            payload = signer.unsign(signed, max_age=NONCE_MAX_AGE)
        except BadSignature:
            raise NonceException("The nonce signature was invalid.")
        except SignatureExpired:
            raise NonceException("The nonce has expired.")

        nonce, user_id = payload.split(":")

        User = get_user_model()
        user = User.objects.get(pk=user_id) if user_id else None

        nonce_list = list(Nonce.objects.filter(key=nonce)[:1])

        if nonce_list:
            nonce_obj = nonce_list[0]
            if nonce_obj.user == user:
                return nonce_obj
            else:
                raise NonceException("The current user does not have access to the specified nonce.")
        else:
            return Nonce(key=nonce, user=user)
开发者ID:chalkchisel,项目名称:django-uploadifive,代码行数:27,代码来源:models.py

示例9: provision

    def provision(self, prefix="", user=None):
        nonce = self.random_nonce(prefix)
        user_id = user.pk if user else ""
        payload = "%s:%s" % (nonce, user_id)

        signer = TimestampSigner()
        return signer.sign(payload)
开发者ID:chalkchisel,项目名称:django-uploadifive,代码行数:7,代码来源:models.py

示例10: find

def find(request, token):
    try:
        signer = TimestampSigner(key=request.session.session_key, sep=':')
        id = b64_decode(signer.unsign(token, max_age=86400).encode('utf-8'))
        return AsyncResult(id)
    except:
        return None
开发者ID:BillTheBest,项目名称:varnish-bans-manager,代码行数:7,代码来源:__init__.py

示例11: index

def index(request):
    error_message = None
    reset_request = ResetRequestForm(request.POST or None)
    email_response = False
    
    try:
        if reset_request.is_valid():
            if reset_request.cleaned_data['email'] != '':
                user_data = ContactInformation.objects.get(alternate_email=reset_request.cleaned_data['email'])
                email_response = True
            else:
                user_data = ContactInformation.objects.get(cell_phone=reset_request.cleaned_data['cell'])
    
            signer = TimestampSigner()
            token = signer.sign(user_data.psu_uuid)
            
            if email_response == True:
                password_reset_email(user_data.psu_uuid, user_data.alternate_email, token)
            else:
                shortcode = TextMessageShortCode()
                shortcode.token = token
                shortcode.save()
                
                password_reset_sms(user_data.cell_phone, shortcode.code)
            
            return HttpResponseRedirect(reverse("PasswordReset:reset_notoken"))
            
    except (ContactInformation.DoesNotExist, ContactInformation.MultipleObjectsReturned):
        # Either we couldn't find it or we couldn't uniquely identify it.
        logger.info("service=myinfo email=" + reset_request.cleaned_data['email'] + " cell=" + reset_request.cleaned_data['cell'] + "error = \"Unable to identify.\"")
        error_message = "We were unable to find an identity that matched your information."
    
    return render(request, 'PasswordReset/index.html', {'form' : reset_request, 'error' : error_message,})
开发者ID:kfarr2,项目名称:myinfo,代码行数:33,代码来源:views.py

示例12: _build_hook_signature

 def _build_hook_signature(self, method, url, body):
     signer = TimestampSigner(settings.WATERCOOLER_SECRET)
     value = '{method}:{url}:{body}'.format(
         method=method.lower(),
         url=url,
         body=hashlib.sha256(body or b'').hexdigest()
     )
     return signer.sign(value)
开发者ID:cheshire-howe,项目名称:scrumboard,代码行数:8,代码来源:views.py

示例13: make_token

    def make_token(self):
        """ Make timestamped token.

        :return string: token

        """
        key = TimestampSigner().sign(self.username)
        return key.split(":", 1)[1]
开发者ID:emil2k,项目名称:joltem,代码行数:8,代码来源:__init__.py

示例14: find_temporary_file

def find_temporary_file(token):
    signer = TimestampSigner(sep=':')
    filename, attachment_filename, mimetype = b64_decode(signer.unsign(
        token, max_age=TEMPORARY_FILE_TTL).encode('utf-8')).split(',')
    return (
        secure_join(settings.MEDIA_ROOT, 'temporary', filename),
        attachment_filename,
        mimetype,
    )
开发者ID:allenta,项目名称:varnish-bans-manager,代码行数:9,代码来源:__init__.py

示例15: generate_api_token

    def generate_api_token(user, expiry_seconds=EXPIRY_SECONDS):
        signer = TimestampSigner()
        token = signer.sign(user.username)

        api_token = ApiToken(user=user,
                             expiry_seconds=expiry_seconds,
                             token=token)
        api_token.save()
        return api_token
开发者ID:hloganathan,项目名称:secondhand,代码行数:9,代码来源:models.py


注:本文中的django.core.signing.TimestampSigner类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。