Youngmathimus
Youngmathimus

Reputation: 31

Cancan, allow users to only view or edit their own content

I'm setting up a very basic web application with Rails, I've already got devise set up and working.

My problem as of now is that no matter who I am signed in as I can view and destroy the content of the account I was last signed in on.

I only need 2 types of roles, members, and guests. Members should be only able to view, edit and destroy their own content, and guests should only be able to stare at the register screen.

Can someone help me out? I have cancan installed and have the abilities folder.

I copied some settings from a few other questions on this site and none have worked so far, here is my current users.rb

class User < ActiveRecord::Base
  attr_accessible :name , :email # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

     ROLES = %w[member guest]


  def is?( requested_role )
    self.role == requested_role.to_s
  end
end

and my current abilities

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)

    if user.role == "member"
      can :manage, :user_id => user.id
    elsif user.role == "guest"
      cannot :manage, :all, 
  end
end

Upvotes: 3

Views: 2676

Answers (2)

in ability.rb

user ||= User.new # guest user (not logged in)

  # admin
  if user.has_role? :admin
    can :manage, :all

  # member
  elsif user.has_role? :member
    can :manage, User, id: user.id
    cannot :index, User

  # guest
  else
    cannot :manage, User
  end

And don't forget to include load_and_authorize_resource in the beginning of user controller after before_action line. For example, like this

enter image description here

Proof: It definitely works

User trying to get details of another user, result 401

enter image description here

User trying to get his own details, result 200

enter image description here

User trying to read all users, result 401

enter image description here

Why :manage, User, user_id: user.id won't work?

Bcoz it searches for users.user_id which would definitely be not there

enter image description here

Upvotes: 2

Joel Brewer
Joel Brewer

Reputation: 1652

Hmm. Looks like your syntax might be a little off:

if user.role == "member"
  can :manage, User, :user_id => user.id
elsif user.role == "guest"
  cannot :manage, User, :all
end

Make sure to pass in the model (User) as the second attribute to the can and cannot methods.

Upvotes: 0

Related Questions