Sha256: 634f429884bc545eeec47319b057ceda93418aef8508333839d1711ee19837a3

Contents?: true

Size: 1.96 KB

Versions: 5

Compression:

Stored size: 1.96 KB

Contents

module Mks
  module Auth
    class UserRolesController < ApplicationController
      before_action :set_role, only: %i[users]
      before_action :set_user, only: %i[assigned_roles assign_roles]

      # GET /user_roles
      def index
        user_roles = UserRole.joins(:application_module)
                             .where("mks_auth_application_modules.code = '#{app_code}'")
                             .order(:name)
        response = { success: true, data: user_roles }
        render json: response
      end

      def users
        response = { success: true, data: @role.users }
        render json: response
      end

      def assigned_roles
        selected = @user.roles.map { |ur| { id: ur.id, name: ur.name, selected: true }}
        ids = @user.roles.map(&:id)
        user_roles = UserRole.joins(:application_module)
                             .where("mks_auth_application_modules.code = '#{app_code}'")
                             .where.not('mks_auth_user_roles.id IN (?)', ids)

        not_selected = user_roles.map { |ur| { id: ur.id, name: ur.name, selected: false }}
        data = (selected + not_selected).sort_by{ |r| r[:name] }

        response = { success: true, data: data }
        render json: response
      end

      # A method which assigns selected roles to a user.
      # This method expects that only selected roles
      # (i.e. roles with `selected` attribute set to true).
      # It removes all other roles and assigns those selected
      # roles to the user.
      def assign_roles
        selected_roles = params[:roles]&.map { |r| r[:id] }
        user_roles = UserRole.where(id: selected_roles)
        @user.roles.destroy_all
        @user.roles = user_roles

        response = { success: true, message: 'Role assignment successful!' }
        render json: response
      end


      private

      def set_role
        @role = UserRole.find(params[:id])
      end

      def set_user
        @user = User.find(params[:id])
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mks_auth-1.0.8 app/controllers/mks/auth/user_roles_controller.rb
mks_auth-1.0.7 app/controllers/mks/auth/user_roles_controller.rb
mks_auth-1.0.6 app/controllers/mks/auth/user_roles_controller.rb
mks_auth-1.0.5 app/controllers/mks/auth/user_roles_controller.rb
mks_auth-1.0.4 app/controllers/mks/auth/user_roles_controller.rb