我目前已经设置了我的应用程序,以便在成功登录应用程序时将用户重定向到他们的个人资料,localhost:3000/users/id
但是如果我是第一个用户id => 1
并且类型users/2
我可以完全访问此个人资料。我一直在尝试找到如何使用设计来阻止这种情况。我对 Rails 很陌生,所以我确定我遗漏了一些简单的东西,我使用过,before_filter :authenticate_user!
但这显然只是检查用户是否登录,但不限制对其他用户个人资料的访问。我已经阅读了一些关于 CanCan 的内容,但这对于我想要实现的目标来说似乎有点矫枉过正。任何指针都非常感谢。
users_controller.rb
class UsersController < ApplicationController
before_filter :authenticate_user!
before_filter :user_authorization
def index
@users = User.all
end
def show
@user = User.find(current_user[:id])
end
private
def user_authorization
redirect_to(root_url) unless current_user.id == params[:id]
end
end
这是从服务器报告的:
Started GET "/users/2" for 127.0.0.1 at 2012-06-24 13:00:38 +0200
Processing by UsersController#show as HTML
Parameters: {"id"=>"2"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
Redirected to http://localhost:3000/
Filter chain halted as :user_authorization rendered or redirected
Completed 302 Found in 20ms (ActiveRecord: 0.8ms)