Assign roles in an intranet

0

Good morning, I am currently developing an intranet with different tools, I am using devise and cancan to assign roles to users, however I have a problem which is that the same user will have a different role in each tool of the intranet so you can do or see different things, I read several tutorials and look for different gems but I can not find one that allows me to manage that versatility with the same user login.

If anyone knows a way to achieve this or if it is not possible to thank them for helping me to know it, I will keep looking.

Thank you in advance.

  

Edited:

Create the following structure:

class CreateUserDetails < ActiveRecord::Migration[5.0]
def change
  create_table :user_details do |t|
    t.integer :user_id
    t.integer :app_role_id
    t.integer :role_id
    t.integer :company_id
    t.timestamps
  end
end
end

class CreateAppRoles < ActiveRecord::Migration[5.0]
  def change
    create_table :app_roles do |t|
      t.string :nombre

      t.timestamps
    end
  end
end

class CreateRoles < ActiveRecord::Migration[5.0]
  def change
    create_table :roles do |t|
      t.string :nombre

      t.timestamps
    end
  end
end

However, I can not get current_user to get the role and the app that will use from UserDetails that references the Devise User table.

Likewise try to create a model devise by app but I can not find how to make it work with a single login.

    
asked by Daniel Romero 12.10.2017 в 16:31
source

1 answer

1

I'll tell you how I use CanCan and Devise and adapt it the way you need to

I have the User, Rol and RolUser models

class User < ActiveRecord::Base
  has_many :roles, through: :roles_users
end

class RolUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :rol
end

class Rol < ActiveRecord::Base
  has_many :users, through: :roles_users
end

In Roles I have records as id: 1, nombre: 'admin'; id: 2, nombre: 'editor', id: 3, nombre: 'read_only'; etc

RolesUsers relates a user with multiple roles

And then I have my class Ability as follows

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new
    user.roles.each do |rol|
    self.send(rol.to_sym) # llama al método de igual nombre que el rol
  end

  def admin
    can :manage, :all
  end

  def editor
    can :edit, HerramientaUno
    can :update, HerramientaUno
    # otros permisos
  end
end

So each role (admin, editor, etc) has the permissions defined within a method with the name of that role. When Ability is initialized, the roles of that user are retrieved from the database, and for each role the method that generates the permissions is called. The name of the role must match the name of the method.
And you should also add load_and_authorize_resource in the controllers so CanCan can check if the user has permission or not to execute the action.

    
answered by 16.10.2017 / 19:03
source