Make a timestamped one-time-use token that can be used to
    identifying the user.

    By hashing the `last_sign_in` attribute and a snippet of the current
    password hash salt, it produces a token that will be invalidated as soon
    as the user log in again or the is changed.

    A hash of the user ID is used, so the HMAC part of the token is always
    unique for each user.

    It also hash a secret key, so without access to the source code,
    fake tokens cannot be generated even if the database is compromised.

def get_token(user, secret, timestamp=None):
    """Make a timestamped one-time-use token that can be used to
    identifying the user.

    By hashing the `last_sign_in` attribute and a snippet of the current
    password hash salt, it produces a token that will be invalidated as soon
    as the user log in again or the is changed.

    A hash of the user ID is used, so the HMAC part of the token is always
    unique for each user.

    It also hash a secret key, so without access to the source code,
    fake tokens cannot be generated even if the database is compromised.
    """
    timestamp = int(timestamp or time())
    secret = to_bytes(secret)
    key = '|'.join([
        hashlib.sha1(secret).hexdigest(),
        str(user.id),
        get_hash_extract(user.password),
        str(getattr(user, 'last_sign_in', 0)),
        str(timestamp),
    ])
    key = key.encode('utf8', 'ignore')
    mac = hmac.new(key, msg=None, digestmod=hashlib.sha512)
    mac = mac.hexdigest()[:50]
    token = '{0}${1}${2}'.format(user.id, to36(timestamp), mac)
    return token