Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Limiting Access so user can update only their data

This seems like something that should be fairly simple since it would be needed a lot. I check to see if a user is logged in fine but once a user is logged in they could potentially alter other peoples accounts. For example: say user with ID 1 was logged in and they put /users/2/edit as the url. This would show them user 2s data and allow them to modify it. Of course I can alter the edit action in the controller to use something like this...

  def edit
    @user = User.find(current_user.id)
  end

where current_user is set in the controller so the user is always that person who is logged in. This is fine if you only have a couple controllers with a couple actions but could be a pain if you have many. It seems like there should be a way to limit this globally so the user can only update their own data no matter what action or controller they use.

Is there a way to restrict the user to their own data for all actions?

like image 954
Xaxum Avatar asked Sep 07 '11 20:09

Xaxum


1 Answers

In your application_controller.rb you can try this:

class ApplicationController < ActionController::Base
  before_filter :validate_user

  private

  def validate_user() #might need to pass id and current_user
    if current_user.id == params[:id]
      # continue to current_user url
    else
        flash[:error] = "Please access one of your own pages"
        redirect_to(:back)
    end
  end
end

by putting the stuff in the application controller it should be available in all the controllers, however if you do not need to confirm that this is the current user (say maybe home page) then you may need to use a skip_before_filter in any specific controller(for a specific action) that needs it, like this in the pages controller for example

class PagesController < ApplicationController
  skip_before_filter :validate_user, :only => [:home, :about]
end

For more info checkout this link to rails guides on filters. There could be more efficient ways of achieving this as well.

Hope it helps

like image 139
Hishalv Avatar answered Sep 28 '22 03:09

Hishalv