本文整理汇总了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, })
示例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
示例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")
示例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)
示例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
示例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})
示例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
示例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)
示例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)
示例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
示例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,})
示例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)
示例13: make_token
def make_token(self):
""" Make timestamped token.
:return string: token
"""
key = TimestampSigner().sign(self.username)
return key.split(":", 1)[1]
示例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,
)
示例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