local_auth.py 文件源码

python
阅读 20 收藏 0 点赞 0 评论 0

项目:pillar 作者: armadillica 项目源码 文件源码
def generate_and_store_token(user_id, days=15, prefix=b'') -> dict:
    """Generates token based on random bits.

    NOTE: the returned document includes the plain-text token.
    DO NOT STORE OR LOG THIS unless there is a good reason to.

    :param user_id: ObjectId of the owning user.
    :param days: token will expire in this many days.
    :param prefix: the token will be prefixed by these bytes, for easy identification.
    :return: the token document with the token in plain text as well as hashed.
    """

    if not isinstance(prefix, bytes):
        raise TypeError('prefix must be bytes, not %s' % type(prefix))

    import secrets

    random_bits = secrets.token_bytes(32)

    # Use 'xy' as altargs to prevent + and / characters from appearing.
    # We never have to b64decode the string anyway.
    token_bytes = prefix + base64.b64encode(random_bits, altchars=b'xy').strip(b'=')
    token = token_bytes.decode('ascii')

    token_expiry = datetime.datetime.now(tz=tz_util.utc) + datetime.timedelta(days=days)
    token_data = store_token(user_id, token, token_expiry)

    # Include the token in the returned document so that it can be stored client-side,
    # in configuration, etc.
    token_data['token'] = token

    return token_data
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号