2010-04-16 5 views
0

리소스가 1 레벨보다 깊게 중첩되어서는 안됩니다. 나는이 같은 3 개 모델이있는 경우 그래서레일 - 다양한 중첩 리소스와 호환되는 건식 인증 방법 찾기

사용자 has_many 주택 has_many 입주자

및 준수하기 위해 내가

map.resources :users, :has_many => :houses 
map.resorces :houses, :has_many => :tenants 

을 위 지금은 사용자가 원하는 (아래 단지 가상의 상황) 집과 세입자 세부 정보를 모두 편집 할 수는 있지만 URL의 user_id 부분을 위조하여 다른 사용자 주택 및 임차인을 편집하지 못하도록하고 싶습니다. 그래서 USER_ID가

edit_user_house_path(@user, @house) 

통해하지만 tenents 케이스

tenant house_tenent_path(@house) 

에는 사용자 ID가 전달되는 전달되기 때문에 쉽게 주택이

def prevent_user_acting_as_other_user 
     if User.find_by_id(params[:user_id]) != current_user() 
      @current_user_session.destroy 
      flash[:error] = "Stop screwing around wiseguy" 
      redirect_to login_url() 
      return 
     end 
    end 

같은 before_filter를 만듭니다. 그러나 @ house.user.id를 수행하여 사용자 ID를 얻을 수 있지만 ID는 위의 코드를 변경해야합니다.

def prevent_user_acting_as_other_user 
    if params[:user_id] 
     @user = User.find(params[:user_id] 
    elsif params[:house_id] 
     @user = House.find(params[:house_id]).user 
    end 
    if @user != current_user() 
     #kick em out 
    end 
end 

더 좋은 방법이 있는지 궁금합니다. 사용자가 위조를 방지해야하는 새로운 리소스를 추가 할 때마다 조건을 계속 추가해야합니다. 나는 많은 경우가 있다고 생각하지 않지만 더 좋은 접근법을 알고 싶습니다.

답변

1

는 다음을 수행 필터에서

class User < ActiveRecord::Base 
    has_many :houses 
    has_many :tenants 
end 

class House < ActiveRecord::Base 
    belongs_to :user 
    has_many :tenants 
end 

class Tenant < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :house 
end 

는 다음을 수행하십시오

def kill_session(message) 
    @current_user_session.destroy 
    flash[:error] = message 
    redirect_to login_url() 
end 

def prevent_user_acting_as_other_user 
    if params[:user_id] and params[:user_id] != @current_user.id 
    kill_session("You don't have access to this page") 
    elsif params[:house_id] and [email protected]_user.houses.exists?(params[:house_id]) 
    kill_session("You don't have access to this page") 
    elsif params[:tenant_id] and [email protected]_user.tenants.exists?(params[:tanant_id]) 
    kill_session("You don't have access to this page") 
    end 
end 
+0

협회를 해결하는 답을 업데이트했습니다. –

+0

최근 질문에 대한 답변과 답변을 해주셔서 감사합니다. – robodisco