如何使用声明式授权而不总是将用户 ID 保留为 URL 中的参数?
声明性授权似乎需要 params[:id] 进行验证,我想使用 /profile 和 /dashboard 等路径,其中用户存储在会话中而不是 URL 中。但它坏了。关于如何在不破坏宝石本身的情况下做到这一点的任何想法?
Declarative authorization seems to require params[:id] to do its validation and I want to use paths like /profile and /dashboard where the user is stored in the session and not the URL. But it breaks. Any ideas on how I can do this without hacking the gem itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
仅当您依赖
filter_resource_access
在控制器中设置实例变量时,这才是正确的。您可以通过指定filter_access_to
来设置自己的授权方案。这允许您设置自己的自定义方法,这些方法可以基于您喜欢的任何内容——会话变量、模型属性等。简介解释了
filter_access_to
并给出了一些示例。This is only true if you are relying on
filter_resource_access
to set instance variables in the controller. You can set up your own authorization scheme by specifyingfilter_access_to
. This allows you to set up your own custom methods which can be based on whatever you like -- session variables, model attributes, etc.The controller section in this introduction explains
filter_access_to
and gives some examples.如果您的应用程序中有用户,为什么不使用身份验证插件呢?我使用 Restful 身份验证,通过一些工作我就完成了会话管理。对于您的问题,该插件有一个辅助方法
current_user
,可以检索打开会话的用户。我认为它更好地依赖像 Restful Authentication (或 AuthLogic 像响应#1)这样的插件,而不是实现你的解决方案,但你会更好地了解你的需求;)
If you have users in your application, why don't use a authentication plugin? I use Restful authentication and with a few work I have complete session management. For your problem this plugin has a helper method
current_user
that retrieves the user with opened session.I think its better rely on plugins like Restful Authentication (or AuthLogic like the response #1) than implement your solution, but you'll know better your needs ;)
我使用 AuthLogic,但据我所知“current_user”无法通过路由访问。
您需要在控制器中检查 params[:id] == "current_user" (作为字符串),然后基于此执行一些逻辑...即:
一个非常简单的示例,但它应该说明类型您需要从自定义路由获取 current_user 的逻辑。您还可以将 current_user 的命名路由映射到它自己的控制器操作,但这不是很 RESTful,并且[很可能]会重复您已经拥有的功能。
I use AuthLogic, but as far as I know "current_user" is not going to be accessible through a route.
You would need to check, in the controller, if params[:id] == "current_user" (as a string) and then do some logic based on that... i.e:
A very simplistic example, but it should illustrate the type of logic you're going to need to get the current_user from a custom route. You could also just map a named route for current_user to it's own controller action, but that's not very RESTful and would [most likely] duplicate functionality you already have.
使用 devise 这样你就可以获得
current_user
方法。使用
filter_access_to
而不是filter_resource_access
。Use devise so you can get a
current_user
method.Use
filter_access_to
instead offilter_resource_access
.