python - Python Google App Engine 中的密码重置 token

标签 python google-app-engine

我想为我使用 Google App Engine 的用户模型生成密码重置 token 。显然我们不允许在 GAE 中轻松使用 Django,因此 Django 生成 token 方法的原始代码是:

def _make_token_with_timestamp(self, user, timestamp):
    # timestamp is number of days since 2001-1-1.  Converted to
    # base 36, this gives us a 3 digit string until about 2121
    ts_b36 = int_to_base36(timestamp)

    # By hashing on the internal state of the user and using state
    # that is sure to change (the password salt will change as soon as
    # the password is set, at least for current Django auth, and
    # last_login will also change), we produce a hash that will be
    # invalid as soon as it is used.
    # We limit the hash to 20 chars to keep URL short
    key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"

    # Ensure results are consistent across DB backends
    login_timestamp = user.last_login.replace(microsecond=0, tzinfo=None)

    value = (unicode(user.id) + user.password +
            unicode(login_timestamp) + unicode(timestamp))
    hash = salted_hmac(key_salt, value).hexdigest()[::2]
    return "%s-%s" % (ts_b36, hash)

Python 不是我的专业语言,因此我需要一些帮助来编写与上面类似的自定义方法。我只有几个问题。首先,时间戳的目的是什么? Django 有自己的用户系统,而我使用的是我自己的简单自定义用户模型。我需要保留上述代码的哪些方面,以及我可以删除哪些方面?

最佳答案

嗯,check_token -方法如下所示:

def check_token(self, user, token):
    """
    Check that a password reset token is correct for a given user.
    """
    # Parse the token
    try:
        ts_b36, hash = token.split("-")
    except ValueError:
        return False

    try:
        ts = base36_to_int(ts_b36)
    except ValueError:
        return False

    # Check that the timestamp/uid has not been tampered with
    if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
        return False

    # Check the timestamp is within limit
    if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
        return False

    return True
  • 首先将 token 的时间戳部分转换回整数
  • 然后使用该时间戳生成一个新 token ,并与旧 token 进行比较。
    请注意,生成 token 时,上次登录的时间戳是用于计算哈希的参数之一。这意味着用户登录后旧 token 将变得无效,这对于密码重置 token 来说是有意义的。
  • 最后执行检查以查看 token 是否尚未超时。

这是一个相当简单的过程,而且也相当安全。如果您想使用重置系统闯入帐户,则必须知道用户的密码和上次登录时间戳才能计算哈希值。如果您知道那就不需要闯入该帐户...

因此,如果你想创建一个这样的系统,那么在生成 hast 时使用不易猜测的参数非常重要,当然还要使用良好的加盐哈希函数。 Django uses sha1 ,使用其他 hashlib 摘要当然是很容易实现的。

另一种方法是生成随 secret 码重置 token 并将其存储在数据库中,但这可能会浪费大量空间,因为 token 列对于大多数用户来说可能是空的。

关于python - Python Google App Engine 中的密码重置 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10667723/

相关文章:

python - 是否可以在 python 函数中强制数据不变性?

java - 如何将后端模块类导入android studio中的应用程序模块

java - GWT:使用 RPC 从数据存储填充页面太慢

google-app-engine - Google App Engine PHP,无法解析主机

python - 如何在模块中导入 lib 文件夹

python - 在 OpenCV 中检测由图案包围的形状

python - 类型错误 : cannot unpack non-iterable NoneType object Error

python - 为什么不能迭代?

python - 使用 wxpython 查找文本对话框

python - 使用各种区域设置对 Python 中的字符串集合进行排序