D
D
dexdev2015-09-26 13:25:29
Ruby on Rails
dexdev, 2015-09-26 13:25:29

How to organize an authorization system?

Hi all! Got me in a dead end! Please help!
I do not know how to differentiate access rights for users in different organizations!
The situation is the following. There are many organizations and users, a user can belong to several organizations, a user can have many organizations
User.rb

class User < ActiveRecord::Base
  has_many :companies, through: :users_companies
  has_many :users_companies
end

Company.rb
class Company < ActiveRecord::Base
  has_many :users_companies
  has_many :users, through: :users_companies
end

Created the model Role
Role.rb
class Role < ActiveRecord::Base
  has_many :users_roles
  has_many :users, through: :users_roles
end

with the help of gem'a cancancan distributed the rights (I think the solution for such a task is wrong), but I just don't have enough brains how to check the company correctly. Added the company_id column to the join table users_roles , but with the action update UsersController , the company_id column becomes Null
The following user can be an administrator, secretary and director
The same user can be an administrator in one organization and a secretary in another.
The whole point is that if Vasya Pupkin is an administrator in the Rog and Kopyt company, then he is an administrator in other companies, Google is silent on such issues, tell me how to properly organize a database with this task?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Nikiforov, 2015-09-26
@eoffsock

You can do this: you need to be able to get a list of roles for it from Company. For example, in Role add a reference to Company, and in Company has_many :roles.
Also in Role you need a column with the type of role - admin, secretary, director. Something like admin, secretary, director. Let the column be role.
Then write abilities like this:

Companies.each do |company|
    role = company.roles.where(user: user).first
    can role.role.to_sym, company, id: company.id if role.present?
end

And check where necessary:
if can? :admin, @company
# do smth
end

Experiment, it should work according to the documentation.
By the way, you can replace has_many through with has_and_belongs_to_many if the join table contains only the id of both tables and no other data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question