对于我的 webapp,我使用烧杯和 sessionauthenticationpolicy。在查看 pyramid.security 时,我注意到“sessionauthenticationpolicy”的“记住”功能返回一个空列表,因此我无法在返回给用户的响应上设置 cookie(在登录视图中)以根据他的“ userid”在他下次提出请求时。
谢谢
您可以从服务器端的会话存储中读取用户 ID。通常应用程序还公开request.user
属性:https : //github.com/websauna/websauna/blob/master/websauna/system/init .py#L201
以下是add_request_method
(原始来源https://github.com/websauna/websauna/blob/master/websauna/system/auth/authentication.py)的示例
"""The user authentication helper functions."""
from pyramid.settings import aslist
from pyramid.security import unauthenticated_userid
from websauna.system.http import Request
from websauna.system.user.models import User
from websauna.system.user.utils import get_user_registry
def get_user(session_token: str, request: Request) -> User:
"""Extract the logged in user from the request object using Pyramid's authentication framework."""
# user_id = unauthenticated_userid(request)
# TODO: Abstract this to its own service like in Warehouse?
user_registry = get_user_registry(request)
if session_token is not None:
user = user_registry.get_user_by_session_token(session_token)
# Check through conditions why this user would no longer be valid
if user:
if not user.can_login():
# User account disabled while in mid-session
return None
return user
return None
def get_request_user(request:Request) -> User:
"""Reify method for request.user"""
user_id = unauthenticated_userid(request)
return get_user(user_id, request) if user_id else None