josh
josh

Reputation: 10348

How to handle current user in routes

(This is for a single-page Javascript application where certain user information is embedded in the layout)

I'm looking to constrain my routes depending on the user's permissions and allow them to view their own information via the route /current. That is, if they're a user, they can access only routes that a user can access, and while they cannot view other user information, they are allowed to view their own. I'm setting this up using constraints:

scope :users, constraints: UserConstraint.new do
    get '/:id/' => 'users#show'
end

This works when a user wants to visit the route with their id, but I don't want to embed their id into the page; I would like the user to be able to access /users/current and access their information. I thought of doing something like

scope :users, constraints: ->(req) {
    req.params[:id] = RequestCurrentUser.new(req).user.id if req.params[:id] == 'current'
} do
    get '/:id/' => 'users#show'
end

But the controller sees id=current rather than id=1. Is it possible to accomplish this, or is there a better way?

Upvotes: 1

Views: 735

Answers (1)

davidcelis
davidcelis

Reputation: 3347

As opposed to handling this in the routing layer with complicated constraints, why not simply provide some sort of UsersController#current endpoint that just returns the current_user as json?

class UsersController
  # ...

  def current # or def show
    render json: current_user
  end

  # ...
end

Best to simply have some sort of endpoint that requires authentication and renders the authenticated user rather than dynamically route based on authentication.

Upvotes: 1

Related Questions