Rails,你能帮我 DRY 这个常见的“是 current_user 允许的”吗?检查我的控制器

发布于 2024-12-28 10:05:43 字数 819 浏览 2 评论 0原文

我是一个相对 Rails 的新手,刚刚开始学习如何干燥我的代码,并且不确定我是否需要创建一个助手,或装饰器,或模型方法,或某种重载类来执行一些非常常见的操作“该用户是否被允许访问这些数据?”检查....

其他用户的个人资料)

我的rails 3.1应用程序使用devise进行用户身份验证,并且我(根据devise文档)添加了一个简单的admin:boolean标志,可以让某些用户执行其他用户无法执行的操作(例如查看/编辑 防止网址欺骗等我在很多方法的顶部附近使用它:

if current_user.nil?
  redirect_to root_path, :alert => "You must sign in to do XXXX" and return
end
if !current_user.admin? && (current_user.id != MYMODEL.user_id)
  redirect_to MYMODEL_path, :alert => "The ZZZZ you tried to XXXXX is not yours" and return
end
if current_user.admin? && (current_user.id != MYMODEL.user_id)
  flash[:alert] = "Hey ADMIN: You know you are XXXX another user's ZZZZ, right?"
end

每种情况下的消息都不同,但逻辑是相同的。

有人可以向我展示将该逻辑放在一个地方(对于一个控制器)的最简单方法吗?控制器中的所有方法都可以使用它(可选)传递 3 个自定义消息?

I'm a relative rails newbie, just getting started on learning how to DRY my code, and am not sure if I need to be creating a helper, or decorator, or model method, or some kind overloading class to do some very common "is this user allowed to access this data?" checking....

My rails 3.1 app uses devise for user authentication, and I have (per devise docs) added a simple admin:boolean flag that lets certain users do things other users cannot (like view/edit other users' profile)

to prevent url spoofing etc I use this near the top of a LOT of my methods:

if current_user.nil?
  redirect_to root_path, :alert => "You must sign in to do XXXX" and return
end
if !current_user.admin? && (current_user.id != MYMODEL.user_id)
  redirect_to MYMODEL_path, :alert => "The ZZZZ you tried to XXXXX is not yours" and return
end
if current_user.admin? && (current_user.id != MYMODEL.user_id)
  flash[:alert] = "Hey ADMIN: You know you are XXXX another user's ZZZZ, right?"
end

The message in each case is different, but the logic is the same.

Can someone show me the easiest way to put that logic in one place (for one controller) that all methods in a controller can use it (optionally) passing in the 3 custom messages?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤城病女 2025-01-04 10:05:44

before_filter 怎么样?

我建议反对明确告诉用户有一个不允许他们编辑的有效对象;他们不需要知道这一点——只需告诉他们没有找到即可。

您还可以探索“康康舞”等宝石。

How about a before_filter?

I'd recommend against explicitly telling the user there's a valid object they're not allowed to edit; they don't need to know that--just tell them it's not found.

You could also explore gems like "cancan".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文