本文整理汇总了Python中django.core.signing.TimestampSigner.sign方法的典型用法代码示例。如果您正苦于以下问题:Python TimestampSigner.sign方法的具体用法?Python TimestampSigner.sign怎么用?Python TimestampSigner.sign使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.signing.TimestampSigner
的用法示例。
在下文中一共展示了TimestampSigner.sign方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: index
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
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: post
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
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})
示例3: index
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
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,})
示例4: send_restore_password
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
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
示例5: provision
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
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)
示例6: _build_hook_signature
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
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)
示例7: generate_api_token
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
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
示例8: form_valid
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def form_valid(self, form):
'''
'''
user = get_object_or_404(UserProfile, username=form.cleaned_data['username'])
signer = TimestampSigner()
recovery_key = signer.sign(str(user))
self.send_recovery_mail(user)
messages.success(self.request, _('An email has been sent to your email account.'))
response = super(PasswordRecovery, self).form_valid(form)
response.set_signed_cookie('recovery_key', recovery_key, max_age=1200)
return response
示例9: save
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def save(self, *args, **kwargs):
# COLOCAR AQUI CONSUMIR EL REST DE ORGANIGRAMA
# Envio un uid y me devuelve el uid del jefe, si este esta inactivo me devuelve la del superior
self.jefe = User.objects.get(pk=1)
# Crear un Token Para confirmacion de Permiso mediante correo, por temas de la url cambio el separador por -
from django.core.signing import TimestampSigner
signer = TimestampSigner(salt="4g3t1c")
self.token_mail = signer.sign(self.pk)
super(DesignacionPermiso, self).save(*args, **kwargs)
示例10: get_context_data
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
signer = TimestampSigner(settings.SOCKET_SECRET)
channel = signer.sign(1) # el 1 deberia ser el ID de la empresa
url = '{protocol}://{server}/socket?channel={channel}'.format(
protocol = 'wss' if settings.SOCKET_SECURE else 'ws',
server = settings.SOCKET_SERVER,
channel = channel
)
context.update(socket_url=url)
return context
示例11: get_links
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def get_links(self, obj):
request = self.context['request']
signer = TimestampSigner(settings.WEBSOCKET_SECRET)
channel = signer.sign(obj.pk)
return {
'self': reverse('sprint-detail', kwargs={'pk': obj.pk}, request=request),
'tasks': reverse('task-list', request=request) + '?sprint={}'.format(obj.pk),
'channel': '{proto}://{server}/socket?channel={channel}'.format(
proto='wss' if settings.WEBSOCKET_SECURE else 'ws',
server=settings.WEBSOCKET_SERVER, channel=channel),
}
示例12: send_password_reset_email
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def send_password_reset_email(self, request, user):
signer = TimestampSigner()
reset_token = signer.sign(user.get_username())
context = {
"request": request,
"user": user,
"project_name": get_configuration("QS_PROJECT_NAME"),
"project_url": get_configuration("QS_PROJECT_URL"),
"reset_token": reset_token,
}
mails = template_mail.MagicMailBuilder()
email = mails.password_reset(user, context)
email.send()
示例13: send_activation_email
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def send_activation_email(self, request, user):
signer = TimestampSigner()
context = {
'request': request,
'user': user,
'activation_key': signer.sign(user.get_username()),
'project_name': get_configuration("QS_PROJECT_NAME"),
'project_url': get_configuration("QS_PROJECT_URL"),
'expiration_days': get_configuration("QS_SIGNUP_TOKEN_EXPIRATION_DAYS"),
}
mails = template_mail.MagicMailBuilder()
email = mails.activation(user, context)
email.send()
示例14: get_links
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def get_links(self, obj):
request = self.context["request"]
signer = TimestampSigner(settings.WATERCOOLER_SECRET)
channel = signer.sign(obj.pk)
return {
"self": reverse("sprint-detail", kwargs={"pk": obj.pk}, request=request),
"tasks": reverse("task-list", request=request) + "?sprint={}".format(obj.pk),
"channel": "{proto}://{server}/socket?channel={channel}".format(
proto="wss" if settings.WATERCOOLER_SECURE else "ws",
server=settings.WATERCOOLER_SERVER,
channel=channel,
),
}
示例15: get_absolute_file_url
# 需要导入模块: from django.core.signing import TimestampSigner [as 别名]
# 或者: from django.core.signing.TimestampSigner import sign [as 别名]
def get_absolute_file_url(self, authenticated=False):
if not self.name:
return ''
url = reverse('foirequest-auth_message_attachment',
kwargs={
'message_id': self.belongs_to_id,
'attachment_name': self.name
})
if settings.FOI_MEDIA_TOKENS and authenticated:
signer = TimestampSigner()
value = signer.sign(url).split(':', 1)[1]
return '%s?token=%s' % (url, value)
return url