mitsuhiko/itsdangerous — pull request #39 by RussellLuo (2014-11-13 12:07:02+00:00)
Title: enhance `TimedJSONWebSignatureSerializer` to support never-expire

Motivation
-------------

In `itsdangerous`, you can generate tokens without expiry time based on `JSONWebSignatureSerializer`:

from itsdangerous import JSONWebSignatureSerializer as JWSSerializer

def make_normal_token(secret_key, data):
s = JWSSerializer(secret_key)
return s.dumps(data)

and you can generate tokens with expiry time based on `TimedJSONWebSignatureSerializer`:

from itsdangerous import TimedJSONWebSignatureSerializer as TimedJWSSerializer

def make_timed_token(secret_key, data, expires=None):
s = TimedJWSSerializer(secret_key, expires_in=expires)
return s.dumps(data)

Then, you can merge the above two functions as one:

from itsdangerous import JSONWebSignatureSerializer as JWSSerializer
from itsdangerous import TimedJSONWebSignatureSerializer as TimedJWSSerializer

def make_token(secret_key, data, expires=None):
if expires == 0:
s = JWSSerializer(secret_key)
else:
s = TimedJWSSerializer(secret_key, expires_in=expires)
return s.dumps(data)

But there's no easy way (neither `JSONWebSignatureSerializer.loads()` nor `TimedJSONWebSignatureSerializer.loads()`) to load tokens generated by `make_token`. (Maybe any suggestions?)

def load_token(secret_key, token):
pass # how to load?

Advantage
-------------

With the enhanced version of `TimedJSONWebSignatureSerializer`, everything above can be implemented as follows:

from itsdangerous import TimedJSONWebSignatureSerializer as TimedJWSSerializer

def make_token(secret_key, data, expires=None):
s = TimedJWSSerializer(secret_key, expires_in=expires)
return s.dumps(data)

def load_data(secret_key, token):
s = TimedJWSSerializer(secret_key)
try:
data = s.loads(token)
return data
except SignatureExpired: # valid token, but expired
return None
except BadSignature: # invalid token
return None