2011-07-26 42 views
0

嘿傢伙我創建了一些自定義身份驗證感謝railscasts.com但我有點卡住,因爲我需要限制我的用戶編輯其他用戶的配置文件。需要幫助自定義身份驗證

這裏是我的authenticate_user和CURRENT_USER方法:

private 

def current_user 
    @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] 
end 

def authenticate_user! 
    if current_user.nil? 
    redirect_to login_url, :alert => "You must first log in to access this page" 
    end 
end 

下面是我的UsersController的的before_filter:

before_filter :authenticate_user!, :only => [:edit, :update, :destroy]` 

編輯:固定它歸功於alock27。

我不得不修改我的users_controller和修改編輯動作如下:

@user = User.find(params[:id]  
redirect_to root_url unless current_user == @user  
+0

你在使用Devise嗎? – efoo

+0

不,它是一個使用railscasts.com的教程構建的自定義身份驗證系統:p – imjp

回答

1

我想你想要這樣的:

Adding security on routes in Rails

你需要找到用戶:ID並檢查current_user = @user

+0

我嘗試過'如果current_user == @ user',但它不起作用。 – imjp

+0

甜蜜,該鏈接的帖子修復了它! – imjp

1

您不必爲編輯,更新和銷燬提供一個ID:您已經擁有curren T_USER。 而不是編輯@user = User.find(id),編輯current_user。因此,您的身份驗證功能可確保用戶只能編輯自己的配置文件。

+0

是什麼阻止將用戶名/ my_id /編輯的URL ID更改爲用戶/ your_id/edit? – efoo

+0

在編輯方法中,您將使用current_user,並僅編輯該對象。您不再使用該ID來檢索用戶,因爲您已從認證系統中獲取該用戶,並且可以將路由更改爲「用戶/編輯」。 –