Module: NexusCqrs::Auth

Includes:
Pundit::Authorization
Included in:
BaseCommandHandler, BaseQueryHandler
Defined in:
lib/nexus_cqrs/auth/auth.rb,
lib/nexus_cqrs/auth/ownable.rb,
lib/nexus_cqrs/auth/user_context.rb,
lib/nexus_cqrs/auth/permission_provider.rb

Overview

Concern used to provide authorisation abilities to handlers and other classes. Overrides pundit’s ‘authorize` method and creates helpers for the permission_provider

Defined Under Namespace

Modules: Ownable Classes: OwnableRelationshipNotSet, PermissionProvider, UserContext

Instance Method Summary collapse

Instance Method Details

#authorize(message, record, query = nil, policy_class: nil) ⇒ Object

Overrides pundit’s ‘authorize` method, allowing the message to be passed

Parameters:

Raises:

  • (Pundit::NotAuthorizedError)

See Also:

  • Pundit#authorize


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/nexus_cqrs/auth/auth.rb', line 15

def authorize(message, record, query = nil, policy_class: nil)
  # Populate the query from the command, or the params if it's being overriden
  query ||= Strings::Case.snakecase(message.demodularised_class_name) + '?'

  # Retreive the policy class object from the type of record we are passing in
  policy_class ||= Pundit::PolicyFinder.new(record).policy

  # Pull context variables from command
  user = message.[:current_user]
  global_permissions = message.[:global_permissions]

  # Instantiate new policy class, with context
  policy = policy_class.new(UserContext.new(user, global_permissions), record)
  raise Pundit::NotAuthorizedError, query: query, record: record, policy: policy unless policy.public_send(query)

  record.is_a?(Array) ? record.last : record
end

#current_userObject



46
47
48
49
50
# File 'lib/nexus_cqrs/auth/auth.rb', line 46

def current_user
  return super if defined?(super)

  nil
end

#permission_provider(message) ⇒ PermissionProvider

Helper method for creating a permissions provider object from a query object. This allows certain permissions to be checked inside the command handler, as opposed to inside the policy

Parameters:

Returns:



38
39
40
# File 'lib/nexus_cqrs/auth/auth.rb', line 38

def permission_provider(message)
  PermissionProvider.new(message.[:current_user], message.[:global_permissions])
end

#pundit_userObject



42
43
44
# File 'lib/nexus_cqrs/auth/auth.rb', line 42

def pundit_user
  nil
end