前言:我正在使用设备进行身份验证。
我试图阻止未经授权的用户查看、编辑或更新其他用户的信息。我最关心的是用户将 DOM 中的表单修改为另一个用户的 ID,填写表单,然后单击更新。我已经专门阅读过,像下面这样的东西应该有效,但事实并非如此。 SO 上的一篇文章建议移动validate_current_user
方法进入公共领域,但这也不起作用。
有什么明显的我做错了吗?或者有更好的方法来完成我想做的事情,无论是使用设备还是其他东西?
My UsersController
看起来像这样:
class UsersController < ApplicationController
before_filter :authenticate_admin!, :only => [:new, :create, :destroy]
before_filter :redirect_guests
def index
redirect_to current_user unless current_user.try(:admin?)
if params[:approved] == "false"
@users = User.find_all_by_approved(false)
else
@users = User.all
end
end
def show
@user = User.find(params[:id])
validate_current_user
@user
end
def new
@user = User.new
end
def edit
@user = User.find(params[:id])
validate_current_user
@user
end
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.html { redirect_to @user, :notice => 'User was successfully created.' }
else
format.html { render :action => "new" }
end
end
end
def update
@user = User.find(params[:id])
validate_current_user
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, :notice => 'User was successfully updated.' }
else
format.html { render :action => "edit" }
end
end
end
private
def redirect_guests
redirect_to new_user_session_path if current_user.nil?
end
def validate_current_user
if current_user && current_user != @user && !current_user.try(:admin?)
return redirect_to(current_user)
end
end
end
The authenticate_admin!
方法如下所示:
def authenticate_admin!
return redirect_to new_user_session_path if current_user.nil?
unless current_user.try(:admin?)
flash[:error] = "Unauthorized access!"
redirect_to root_path
end
end
EDIT -- 你是什么意思“它不起作用?”
为了帮助澄清,当我尝试“破解”另一个用户的帐户时,我收到此错误:
在此操作中多次调用渲染和/或重定向。
请注意,您只能调用 render 或 redirect,并且最多
每个动作一次。另请注意,重定向和渲染都不会终止
执行操作,因此如果您想在之后退出操作
重定向,您需要执行类似“redirect_to(...) 和
返回”。
如果我将方法代码内联到各个控制器操作中,它们do工作。但是,我不想这样做,因为它不干。
我还应该指定我已经尝试过:
def validate_current_user
if current_user && current_user != @user && !current_user.try(:admin?)
redirect_to(current_user) and return
end
end