How can I allow a user to only visit their own display page using cancan?

I am browsing railscast using cancan gem, but I am stuck in allowing the user to visit their own display page.

My code is as follows:

Ability model

class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.role == "admin" can :manage, :all else can :read, :all if user.role == "author" can :create, Review can :update, Review do |review| review.try(:user) == user end can :update, User do |user| user.try(:current_user) == current_user end end if user.role == "owner" can :update, Venue end end end end 

User controller

 class UsersController < ApplicationController load_and_authorize_resource end 

The user (author) can only update his own reviews, but currently he can view the pages of all users by changing the URL.

What am I missing here?

Thanks so much for any help he really appreciates!

+6
source share
2 answers

Constraints can be passed directly to your feature class, even easier than you are trying. I am sure that this is lacking in some of the abilities you want to have, but this should make you start. I accept reviews :belong_to Users with foreign key :user_id . It also looks like you need some kind of similar restriction for objects, but you did not have it in the code, so I did not add it to this.

 class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.role == "admin" can :manage, :all elsif user.role == "author" can :create, Review can :update, Review, :user_id => user.id can [:show, :update], User, :id => user.id elsif user.role == "owner" can :update, Venue can [:show, :update], User, :id => user.id else can [:show, :update], User, :id => user.id end end end 
+10
source

Try adding control information to the controller when a / show request is requested to verify that current_user is the owner of the page / profile. Sort of:

 def show @user = User.find(params[:id]) #show_page unless current_user.id != @user.id end 

Perhaps start a notification that "you do not have this page" or something like that if it crashes.

0
source

Source: https://habr.com/ru/post/890351/


All Articles