Search code examples
ruby-on-railssorcery

Restricting user access on sorcery


i have a rails app with sorcery
everything work .
the problem is when edit a user like :
http://localhost:3000/users/1/edit
its work fine , but when i change the user id to 2 or 3 ..
i can update all users data
how can i restrict the edit page only if the current user is the one that logged in

here is my controller :

skip_before_action :require_login, only: [:new, :create, :show]

def new
 @user = User.new
end

def create
@user = User.new(user_params)
if @user.save
  auto_login(@user)
  flash[:info] = "Welcome."
  redirect_to root_url
else
  render 'new'
end
end

def edit
  @user = User.find(params[:id])
end

def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
  flash[:success] = "Profile updated"
  redirect_to @user
else
  render 'edit'
end
end

def show
 @user = User.find(params[:id])
end

private

def user_params
 params.require(:user).permit(:email, :password, :password_confirmation)
end  

Solution

  • you can also do something like this

    before_action :edit_rights?, only: [:update, :edit]
    
    private
    def edit_rights?
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user == @user
    end
    

    you won't need @user = User.find(params[:id]) in both update and edit actions then