检查 current_user 是否是资源的所有者并允许编辑/删除操作 [英] Check if current_user is the owner of a resource and allow edit/delete actions

查看:13
本文介绍了检查 current_user 是否是资源的所有者并允许编辑/删除操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

用户A (id=10) 创建了一个照片资源

User A (id=10) has created a photo resource

photo: (id: 1 user_id = 10, url: "http://...")

现在,如果用户 B (id=20) 转到这个 url: /photos/1/edit 它可以编辑用户 A 的照片!!!

Now, if User B (id=20) go to this url: /photos/1/edit it can edit photo of user A!!!

Rails+Devise 默认为此提供了一些东西?这似乎是一个很常见的问题

Rails+Devise provides something for this by default? It seems it's a very common issue

我只需要允许任何用户只能编辑/删除它创建的资源(其中 current_user == resource.user)

I just need to allow that any user can edit/delete ONLY resource it has created (where current_user == resource.user)

使用:Rails 4,设计

更新:

我认为 CanCan 太先进了.我不需要角色或限制某些用户的某些操作

I think CanCan it's something too advanced. I don't need roles or restrict some actions to certain users

推荐答案

在你的 PhotosController 中:

In your PhotosController:

before_filter :require_permission, only: :edit

def require_permission
  if current_user != Photo.find(params[:id]).user
    redirect_to root_path
    #Or do something else here
  end
end

这篇关于检查 current_user 是否是资源的所有者并允许编辑/删除操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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