module Authegy::ControllerHelpers

AuthorizationHelper

Methods that deal with defining access to resources by user roles

Public Instance Methods

authorize_action(*given_roles) click to toggle source
# File lib/authegy/controller_helpers.rb, line 32
def authorize_action(*given_roles)
  authorize_action!(*given_roles)
rescue
  false
end
authorize_action!(*given_roles) click to toggle source

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 “`

# 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?() click to toggle source
# 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