Rails中的模型级授权 [英] Model-level authorization in Rails

查看:63
本文介绍了Rails中的模型级授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Rails应用程序中在模型级别(而不是控制器)上实现授权,就像在模型上进行验证一样.最好的方法是什么?

I want to implement authorization in my Rails application on a model level (not controller), in a similar way that validation on models is done. What is the best way to do this?

如果在模型本身中实现,则主要问题是模型无法访问当前用户.我见过类似的解决方案: Thread.current [:user_id] = session [:user_id] ,但这似乎不是一个好主意.

If it is implemented in the models itself, the main problem is that the models don't have access to the current user. I've seen solutions like: Thread.current[:user_id] = session[:user_id], but that doesn't seem like a good idea.

我看到了一种不同的方法,其中创建了诸如create,find和new之类的方法的变体,并为当前用户接受了一个附加参数.

I've seen a different approach where variants of the methods like create, find and new are created, accepting an additional parameter for the current user.

另一种方法是在User/role类中实现所有方法,例如,将使用 user.posts.create user.izable_posts.find 而不是 Post.create Post.find .

Another approach would be to implement all the methods in the User/role class, so for example user.posts.create or user.readable_posts.find would be used instead of Post.create or Post.find.

将建议使用这些方法中的哪些?有没有更好的方法来实现授权?是否有任何插件可以使此操作更容易?我需要一种适合多个角色和模型的方法.

Which of these approaches would be suggested? Are there any better ways to implement the authorization? Are there any plugins that makes this easier? I need an approach that scales well for multiple roles and models.

推荐答案

我建议您查看声明性授权.它适用于模型和控制器.

I would recommend you to look at declarative authorization. It works with both models and controllers.

它要做什么的方法是在applicationController中使用一个before_filter来设置 Authorization.current_user = current_user ,其中Authorization是一个模块.

The way it do what you are asking is having a before_filter in the applicationController that sets Authorization.current_user = current_user where Authorization is a module.

我认为这种方法是最好的方法,它可以使模型保持整洁,并且您不必记住要在任何地方都包括用户,但是可以在模型回调函数中对其进行过滤.

I think that approach is the best one, it keeps the models clean and you don't have to remember to include the user everywhere, but can filter it in the models callback functions instead.

这篇关于Rails中的模型级授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆