如何从金字塔中的模板访问身份验证超时值
设置
在我的 Pyramid(版本 1.10.5)应用程序启动期间,我设置了身份验证超时,以便会话在用户不活动一段时间后过期,这按预期工作。
login_timeout = 60 * 30 # 30 minutes
authn_policy = AuthTktAuthenticationPolicy(auth_secret,
timeout=login_timeout,
reissue_time=reissue_time,
max_age=login_timeout)
config.set_authentication_policy(authn_policy)
现在,我将 Javascript 添加到我的页面模板中,以便在用户的会话即将过期时提醒用户,并且我希望在模板中嵌入相同的 login_timeout
值,而不是在我的代码中重复该值。
问题
如何从 Pyramid 中的模板或视图访问身份验证策略的超时值?
我尝试过的
我已经阅读了几页金字塔文档和源代码(例如https://docs.pylonsproject.org/projects/pyramid/en/latest/api/authentication.html#authentication-policies),我不知道如何根据请求访问该值 -时间。
我使用调试器检查了传递给视图函数的 request
变量。 request.session._timeout
值不是它(我认为它可能是 cookie 过期时间)。
非常感谢任何帮助。
Setup
During start-up of my Pyramid (version 1.10.5) application, I set an authentication timeout so that sessions expire after a duration of inactivity by the user, which works as expected.
login_timeout = 60 * 30 # 30 minutes
authn_policy = AuthTktAuthenticationPolicy(auth_secret,
timeout=login_timeout,
reissue_time=reissue_time,
max_age=login_timeout)
config.set_authentication_policy(authn_policy)
Now I am adding Javascript to my page templates to alert users when their session is about to expire, and I want to embed the same login_timeout
value in the template without duplicating the value in my code.
Question
How can I access the timeout value of the authentication policy from a template or view in Pyramid?
What I've Tried
I have read through several pages of pyramid docs and source code (e.g. https://docs.pylonsproject.org/projects/pyramid/en/latest/api/authentication.html#authentication-policies), and I don't see how this value is accessible at request-time.
I inspected the request
variable passed to the view function using a debugger. The value request.session._timeout
is NOT it (I think that one might be a cookie expiration time).
Any help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是我最终在视图中获得身份验证超时的方法:
仔细研究,我发现
request.registry
是由 Zope 组件注册表,它允许通过指定接口来获取注册的实用程序。由于 Pyramid 的 AuthTktAuthenticationPolicy 实现了 IAuthenticationPolicy,因此这里要使用它。由于我希望该值可用于所有视图/模板中的所有请求,因此我后来将代码从上面移到了自定义根工厂中,因此视图中不再需要它:
根工厂在应用程序启动时设置:
现在我可以在任何模板中访问它:
Here's how I ended up getting the authentication timeout in a view:
Digging around, I found that the
request.registry
is made from a Zope Component Registry, which allows getting registered utilities by specifying the interface. Since Pyramid'sAuthTktAuthenticationPolicy
implements theIAuthenticationPolicy
, that's the one to use here.Since I want this value to be available on all requests in all views/templates, I later moved the code from above into a custom root factory, so it's no longer needed in the view:
The root factory gets set at application startup:
Now I can access it in any template: