def validate_token(key, credits=1):
"""
Validate that a token is valid to authorize a setup/register operation:
* Check it's not expired
* Check it has some credits
:param credits: number of credits to decrement if valid
:return 2-tuple (<http response if error, else None>, <registration token if valid, else None>)
"""
try:
with transaction.commit_on_success():
token = RegistrationToken.objects.get(secret = key)
if not token.credits:
log.warning("Attempt to register with exhausted token %s" % key)
return HttpForbidden(), None
else:
# Decrement .credits
RegistrationToken.objects.filter(secret = key).update(credits = token.credits - credits)
except RegistrationToken.DoesNotExist:
log.warning("Attempt to register with non-existent token %s" % key)
return HttpForbidden(), None
else:
now = IMLDateTime.utcnow()
if token.expiry < now:
log.warning("Attempt to register with expired token %s (now %s, expired at %s)" % (key, now, token.expiry))
return HttpForbidden(), None
elif token.cancelled:
log.warning("Attempt to register with cancelled token %s" % key)
return HttpForbidden(), None
return None, token
评论列表
文章目录