Rails: how to produce 404 or redirect when dealing with an unwanted url?

I want to hide the URLs for editing users and their profiles behind safer and more meaningful URLs. For example, I want to /user/13/edit

was /settings/account

and /user/13/profile/edit

equal /settings/profile

.

I succeeded in doing this, but in order to do this I had to load the user info from the bit current_user

from the session. For instance:

# users_controller
def edit
  @user = current_user
end

# profiles_controller
def edit
  @user = current_user
  @profile = @user.profile
end

      

But now, since I can not be compared @user.id

with params

with current_user

a session, how can I stop using the old URL-address ( /user/13/edit

and /user/13/profile/edit

)? They always load forms for the current user, so there is no harm, but I would be more comfortable if they just threw a 404 error or something.

Thanks in advance.

+2


a source to share


2 answers


First of all, your authentication mechanism needs to set the current user.

routes.rb

map.account '/settings/account', :controller => 'user', :action => 'edit' 
map.profile '/settings/profile', :controller => 'user', :action => 'edit_profile'

map.resources :users, :only => [:edit, :update, :show],
              :member => { :edit_profile => :get, :update_profile, :put }

      

this creates the following routes:

/settings/account         (get)
/settings/profile         (get)
/users/:id                (get, put)
/users/:id/edit           (get)
/users/:id/edit_profile   (get)
/users/:id/update_profile (put)

      

users_controller.rb



before_filter :redirect_if_unauthorized

def edit
  @user = current_user
end

# profiles_controller
def edit
  @user = current_user
  @profile = @user.profile
end

protected

def redirect_if_unauthorized
  redirect_to some_path if params[:id] or current_user.nil?
end

      

Obviously some_path does not exist, you will need to create a page / path, etc. to display the error.

With this solution, you never show / manipulate the user based on [: id] parameters, but only the current_user stored by your authentication scheme.


I might also suggest looking at the declarative_authorization gem / plugin ( Github , Railscast )

+1


a source


/ edit urls still exist because I'm sure you have map.resources in your routes.rb file for the user model. you can put a line higher than in your route.rb file that explicitly matches the edit lines you want to redirect and point them where you want.



0


a source







All Articles