before_filter with exception for current user

自闭症网瘾萝莉.ら 提交于 2020-01-14 04:15:04

问题


I have this current before filter in my users_controller

before_filter :authenticate_usergroup, :except => [:edit, :update, :show]

It works great for just allowing a user to edit their information but not being able to see all the users, but i'v found that by just changing their 'id' in the url they could also edit other users information.

How can i only allow :edit, :show and :update functions to the current user for their own record. i have this method in my application_controller to be able to access the current user

def current_user
 return unless session[:user_id]
 @current_user ||= User.find_by_id(session[:user_id])
end

#update from users_controller.rb
def update
@user = User.find(params[:id])

respond_to do |format|
  if @user.update_attributes(params[:user])
    format.html { redirect_to @user, :notice => 'User was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render :action => "edit" }
    format.json { render :json => @user.errors, :status => :unprocessable_entity }
  end
end
end

回答1:


if you "scope" that only the current_user can access their information, then it doesn't matter.

so in show and edit

@user = current_user

in update action something like current_user.update_attributes(params[:user]) should do the trick.




回答2:


I did it this way:

in #show action in the controller:

if current_user.id == Certificate.find(params[:id]).user_id
  @certificate = Certificate.find(params[:id])
else
  redirect_to certificates_url, notice: 'You can only view your own certificates'
end

I know its not using a 'before_filter', but it seems to have the same effect of blocking users from simply typing in different urls to view other users information.



来源:https://stackoverflow.com/questions/13784285/before-filter-with-exception-for-current-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!