AdrienNhm
AdrienNhm

Reputation: 165

Private profile for users | rails 4 | devise

I'm trying to implement a private profile page for each user. It's an learning app so people have access to the courses they paid for on their profile page. So other users can't access profile pages by entering URLs... The http response should be 404.

So far the idea was to create a profiles_controller

def show
    @user = User.find(current_user)
End

So that each user can only access their own page.

Is there a best way of doing that?

Upvotes: 0

Views: 323

Answers (2)

D-side
D-side

Reputation: 9485

Think of an ideal solution. The one where the problem doesn't even exist. Given the problem

"the user should not see other users' profiles"

we can build upon a principle

"there is only one profile for any user"

And we should reflect that mapping in our routes:

resource :profile # < not `resources`!

...and the profile will be available on /profile. No ids in your routes whatsoever, nothing to alter, therefore nothing to check. And it makes sense, why check anything, if we'll be working with the same resource anyway?

# ProfilesController
def show
  @user = current_user
end

Upvotes: 2

Arslan Ali
Arslan Ali

Reputation: 17802

You can before_action for show method in ProfilesController. Basically, you need to check that the profile a user can view - belongs only to that user.

I assume the URL is /users/:user_id/profiles/:id

before_filter :check_profile, only: :show

def check_profile
  user = User.find_by_id params[:user_id]
  unless params[:id] == user.profile.id
    redirect_to users_profiles_path(user, user.profile)
  end
end

This way, user will be redirected to his own profile path, whenever he'd try to access someone else's profile.

Upvotes: 0

Related Questions