Module: Authegy::ControllerHelpers

Defined in:
lib/authegy/controller_helpers.rb

Overview

AuthorizationHelper

Methods that deal with defining access to resources by user roles

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse_given_roles(given_roles = []) ⇒ Object

def match_roles_on

auth_request_env['match_roles_on']

end



55
56
57
58
59
# File 'lib/authegy/controller_helpers.rb', line 55

def self.parse_given_roles(given_roles = [])
  given_roles = [:administrator] unless given_roles.any?
  options = given_roles.last.is_a?(Hash) ? given_roles.pop.with_indifferent_access : {}
  [given_roles, options]
end

Instance Method Details

#authorize_action(*given_roles) ⇒ Object



32
33
34
35
36
# File 'lib/authegy/controller_helpers.rb', line 32

def authorize_action(*given_roles)
  authorize_action!(*given_roles)
rescue
  false
end

#authorize_action!(*given_roles) ⇒ Object

authorize_action! Usage: “‘ class ThingsController < ApplicationController

before_action do
  authorize_action! to: 'thing.owner'
  authorize_action! :administrator, :manager, of: 'thing.other_thing'
  authorize_action! :anyone, from: 'thing.company'
end, only: [:index, :show]

end “‘

Raises:

  • (ActionErrors::Forbidden)


19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/authegy/controller_helpers.rb', line 19

def authorize_action!(*given_roles)
  given_roles, options = AuthorizationHelper.parse_given_roles(given_roles)
  auth_request_env['match_roles_on'] = options[:match_roles_on] if options.key?(:match_roles_on)

  return auth_request_env['authorized_roles'] = Role.all if super_admin_user?
  auth_request_env['authorized_roles'] = current_user_roles.where(name: given_roles)

  # error if only general manager, plant managers can create

  raise ActionErrors::Forbidden if authorized_roles.map(&:name).count == 1 && current_user_roles.first.name == 'manager' && current_user_roles.where(name: 'manager').where.not(target_id: nil).empty?
  raise ActionErrors::Forbidden unless authorized_roles.any?
end

#super_admin_user?Boolean

Returns:

  • (Boolean)


38
39
40
41
42
# File 'lib/authegy/controller_helpers.rb', line 38

def super_admin_user?
  auth_request_env['super_admin_user'] ||= current_user_roles
    .where(name: :administrator, target_id: nil)
    .any?
end