开发者

Rails 3, how to secure and protect controllers and urls

I'm sort of new to rails, what I want to to is protect users profile

what I mean is if user 1 login and go to edit his profile he can, but also if he change on 开发者_Python百科the url to user to # 2 they can also change their information

localhost:3000/users/2/edit

I'm a little lost, any help will be greatly appreciated, or suggestions of good books/blogs


As part of authentication add a session variable, session[:user_id] = User.Authenticate(params[:user][:username], params[:user][:password) (this is the general pattern, you need to add another resource for authentication).

Then add a before_filter function to your controller and check if session[:user_id] == params[:id]. Look at it here: before_filter


The Rails Security Guide is probably a good place to start


Just in case this is useful to someone, something that I came across when testing my app was although users that hadn't signed in couldn't access restricted content, once a user was signed in, they could change the url to a another users id, eg.

/users/3 and it would then show that users home page. So any user could look at any other user, which wasn't what I wanted.

To get around this, I changed the user controller to secure against this:

class UsersController < ApplicationController

#first call the correct_user function before allowing the show action to proceed

before_filter :correct_user, only: [:show]

...

def show
#do whatever here
end

...

private

def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜