D
D
dexdev2015-09-22 16:35:56
Ruby on Rails
dexdev, 2015-09-22 16:35:56

How to properly organize rails permissions?

Good afternoon!
In my application, a user can have many companies, and different rights in companies, in one he can do whatever he wants, and in the other he can only exchange messages, in connection with this, the question arose of how to correctly distinguish rights to more accurately determine the company, using cancancan for authorization and got the following

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :companies, through: :users_companies
  has_many :users_companies
  has_many :users_roles, dependent: :destroy
  has_many :roles, through: :users_roles

  validates :first_name, :last_name, presence: true

  def has_role?(role_sym)
    roles.any? { |r| r.name.underscore.to_sym == role_sym }
  end
end

class Role < ActiveRecord::Base
  has_many :users_roles
  has_many :users, through: :users_roles
end

class UsersRole < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
  #belongs_to :company
end

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # in case of guest
  if user.has_role? :admin
    can :manage, :all
  else
    can :read, :all
  end
  if user.has_role? :moderator
    can :manage, Company
  else
    can :read, :all
  end
    end
end

How to correctly define a company? that it was possible to distinguish correctly the rights? so that the moderator of the Horn and Hoof company who part-time works as a cleaner in the Pistachio company could not clean in the Horn and Hoof company
Please advise something!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zaporozhchenko Oleg, 2015-09-22
@c3gdlk

In user_roles add a link to the company company_id
In cancancan check access for a specific company. To pass the company to ability from the controller, you need to override the current_ability method as far as I remember.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question