2011-07-26 109 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来检索用户,因为您已从认证系统中获取该用户,并且可以将路由更改为“用户/编辑”。 –