Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful routing best practice when referencing current_user from route?

Tags:

I have typical RESTful routes for a user:

/user/:id
/user/:id/edit
/user/:id/newsfeed

However the /user/:id/edit route can only be accessed when the id equals the current_user's id. As I only want the current_user to have access to edit its profile. I don't want other users able to edit profiles that don't belong to them.

What is typically the best practice to handle this situation?

Should I leave the route as is, and thrw an error if the current_user.id != param[:id], forcing the front end client calling the api to track the logged in user's id?

Should I make a special route /user/self/edit and in the controller check to see if param[:id] == 'self'?

like image 275
steve Avatar asked Jun 15 '15 00:06

steve


2 Answers

I would've added special routes for current user profile actions, in this case you don't have to check anything. Just load and display the data of current user. For example:

/my-profile/edit
/my-profile/newsfeed

It's not that RESTful but you don't have to put extra checks keeping your code clean.

If you still have to have (or want to have) a strict RESTful routes then I would use a before_filter and check if the id = current_user.id. If not then return 401 or 403.

like image 102
evgeny.myasishchev Avatar answered Sep 19 '22 06:09

evgeny.myasishchev


I only want the current_user to have access to edit its profile. I don't want other users able to edit profiles that don't belong to them.

What I suggest is to use some authorization gems like pundit

Sample code:

class UserPolicy
  attr_reader :current_user, :model

  def initialize(current_user, model)
    @current_user = current_user
    @user = model
  end

  def edit?
    @current_user == @user
  end
end

Also with an authentication gem like Devise, only the current_user(the users who logged in) can only access and edit their profiles

like image 29
Pavan Avatar answered Sep 20 '22 06:09

Pavan