【问题标题】:Rails 3 authorization with default authRails 3 授权与默认身份验证
【发布时间】:2011-12-25 13:14:23
【问题描述】:
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
authentication
authorization
【解决方案1】:
由于您在应用程序控制器中定义current_user,这很容易。您可以在用户控制器中像这样使用before_filter:
class ItemsController < ApplicationController
before_filter :check_if_owner, :only => [:edit, :update, :show, :destroy]
def check_if_owner
unless current_user.admin? # check whether the user is admin, preferably by a method in the model
unless # check whether the current user is the owner of the item (or whether it is his account) like 'current_user.id == params[:id].to_i'
flash[:notice] = "You dont have permission to modify this item"
redirect_to # some path
return
end
end
end
###
end
你应该在 UsersController 中添加一个类似的方法来检查它是否是他的个人资料,他正在编辑。
另外,请查看Devise,这是推荐用于身份验证的插件。
【解决方案2】:
为此,我不会使用设计。对于这个简单的用途来说,这是非常重要的。
我会为公共视图创建一个单独的控制器并始终引用 current_user
请记住为 PublicController 中的操作创建路由
class PublicController < ApplicationController
before_filter :login_required?
def list
@list = current_user.list
end
def user
@user = current_user
end
def user_delete
@user = current_user
# do your magic
end
def user_update
@user = current_user
# do your magic
end
# and so on...
end