lesli_shield 1.1.7 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. checksums.yaml +4 -4
  2. data/app/assets/stylesheets/lesli_shield/application.css +1036 -32
  3. data/app/assets/stylesheets/lesli_shield/confirmations.css +89 -557
  4. data/app/assets/stylesheets/lesli_shield/invitations.css +544 -0
  5. data/app/assets/stylesheets/lesli_shield/passwords.css +76 -542
  6. data/app/assets/stylesheets/lesli_shield/registrations.css +66 -539
  7. data/app/assets/stylesheets/lesli_shield/sessions.css +98 -564
  8. data/app/controllers/lesli_shield/invites_controller.rb +100 -49
  9. data/app/controllers/lesli_shield/profiles_controller.rb +9 -3
  10. data/app/controllers/lesli_shield/role/actions_controller.rb +134 -38
  11. data/app/controllers/lesli_shield/roles_controller.rb +114 -141
  12. data/app/controllers/lesli_shield/users_controller.rb +11 -4
  13. data/app/controllers/users/confirmations_controller.rb +2 -2
  14. data/app/controllers/users/invitations_controller.rb +101 -0
  15. data/app/controllers/users/passwords_controller.rb +1 -1
  16. data/app/controllers/users/registrations_controller.rb +2 -2
  17. data/app/controllers/users/sessions_controller.rb +3 -1
  18. data/app/jobs/lesli_shield/invitation_delivery_job.rb +123 -0
  19. data/app/mailers/lesli_shield/devise_mailer.rb +3 -3
  20. data/app/mailers/lesli_shield/invitation_mailer.rb +58 -0
  21. data/app/models/concerns/lesli_shield/role_management.rb +70 -0
  22. data/app/models/concerns/lesli_shield/user_security.rb +22 -19
  23. data/app/models/lesli_shield/invite.rb +183 -12
  24. data/app/services/lesli_shield/invitation_audit.rb +34 -0
  25. data/app/services/lesli_shield/invitation_email_policy.rb +64 -0
  26. data/app/services/lesli_shield/invitation_service.rb +405 -0
  27. data/app/services/lesli_shield/invite_service.rb +34 -5
  28. data/app/services/lesli_shield/profile_service.rb +1 -0
  29. data/app/services/lesli_shield/role_action_service.rb +37 -92
  30. data/app/services/lesli_shield/role_audit.rb +42 -0
  31. data/app/services/lesli_shield/role_permission_service.rb +347 -0
  32. data/app/services/lesli_shield/role_privilege_deployment_service.rb +79 -0
  33. data/app/services/lesli_shield/role_privilege_service.rb +69 -105
  34. data/app/services/lesli_shield/role_service.rb +431 -0
  35. data/app/services/lesli_shield/user_registration_service.rb +1 -1
  36. data/app/services/lesli_shield/user_validator_service.rb +9 -9
  37. data/app/views/devise/confirmations/new.html.erb +6 -6
  38. data/app/views/devise/confirmations/show.html.erb +6 -6
  39. data/app/views/devise/passwords/edit.html.erb +8 -8
  40. data/app/views/devise/passwords/new.html.erb +9 -9
  41. data/app/views/devise/registrations/new.html.erb +16 -16
  42. data/app/views/devise/sessions/new.html.erb +9 -9
  43. data/app/views/devise/shared/_application-devise-simple.erb +1 -1
  44. data/app/views/devise/shared/_application-devise.html.erb +4 -4
  45. data/app/views/devise/shared/_demo.html.erb +5 -5
  46. data/app/views/devise/shared/_error_messages.html.erb +5 -5
  47. data/app/views/devise/shared/_links.html.erb +12 -15
  48. data/app/views/lesli_shield/invites/_form.html.erb +64 -7
  49. data/app/views/lesli_shield/invites/_invite.html.erb +55 -2
  50. data/app/views/lesli_shield/invites/_invite_actions.html.erb +34 -0
  51. data/app/views/lesli_shield/invites/_status_badge.html.erb +13 -0
  52. data/app/views/lesli_shield/invites/index.html.erb +119 -63
  53. data/app/views/lesli_shield/invites/new.html.erb +11 -36
  54. data/app/views/lesli_shield/invites/show.html.erb +13 -52
  55. data/app/views/lesli_shield/profiles/_information-form.html.erb +11 -0
  56. data/app/views/lesli_shield/profiles/_password-form.html.erb +1 -1
  57. data/app/views/lesli_shield/profiles/show.html.erb +1 -4
  58. data/app/views/lesli_shield/role/actions/_custom_actions.html.erb +24 -0
  59. data/app/views/lesli_shield/role/actions/_deployment_status.html.erb +14 -0
  60. data/app/views/lesli_shield/role/actions/_matrix.html.erb +69 -0
  61. data/app/views/lesli_shield/role/actions/_permissions.html.erb +95 -0
  62. data/app/views/lesli_shield/role/actions/_toggle.html.erb +34 -0
  63. data/app/views/lesli_shield/role/actions/index.html.erb +13 -10
  64. data/app/views/lesli_shield/roles/_deployment_badge.html.erb +15 -0
  65. data/app/views/lesli_shield/roles/_empty_state.html.erb +20 -0
  66. data/app/views/lesli_shield/roles/_field_errors.html.erb +5 -0
  67. data/app/views/lesli_shield/roles/_filters.html.erb +66 -0
  68. data/app/views/lesli_shield/roles/_form.html.erb +149 -18
  69. data/app/views/lesli_shield/roles/_management_menu.html.erb +37 -0
  70. data/app/views/lesli_shield/roles/_pagination.html.erb +43 -0
  71. data/app/views/lesli_shield/roles/_role_list.html.erb +116 -0
  72. data/app/views/lesli_shield/roles/_status_badge.html.erb +11 -0
  73. data/app/views/lesli_shield/roles/_type_badge.html.erb +9 -0
  74. data/app/views/lesli_shield/roles/index.html.erb +15 -38
  75. data/app/views/lesli_shield/roles/new.html.erb +11 -0
  76. data/app/views/lesli_shield/roles/show.html.erb +79 -7
  77. data/app/views/lesli_shield/users/_information-card.html.erb +3 -3
  78. data/app/views/lesli_shield/users/_information-form.html.erb +6 -0
  79. data/app/views/lesli_shield/users/_management-privileges.html.erb +2 -2
  80. data/app/views/users/invitations/show.html.erb +142 -0
  81. data/app/views/users/invitations/unavailable.html.erb +19 -0
  82. data/config/locales/devise.en.yml +8 -0
  83. data/config/locales/devise.es.yml +8 -0
  84. data/config/locales/translations.en.yml +313 -78
  85. data/config/locales/translations.es.yml +313 -78
  86. data/config/routes.rb +10 -3
  87. data/db/migrate/v1/0801120110_create_lesli_shield_invites.rb +40 -6
  88. data/lib/lesli_shield/engine.rb +4 -0
  89. data/lib/lesli_shield/router.rb +10 -0
  90. data/lib/lesli_shield/version.rb +2 -2
  91. data/lib/tasks/lesli_shield_tasks.rake +1 -1
  92. data/readme.md +13 -1
  93. metadata +35 -11
  94. data/app/assets/stylesheets/lesli_shield/confirmations.tailwind.css +0 -918
  95. data/app/assets/stylesheets/lesli_shield/devise/oauth.css +0 -33
  96. data/app/assets/stylesheets/lesli_shield/passwords.tailwind.css +0 -873
  97. data/app/assets/stylesheets/lesli_shield/registrations.tailwind.css +0 -908
  98. data/app/assets/stylesheets/lesli_shield/sessions.tailwind.css +0 -984
  99. data/app/assets/stylesheets/lesli_shield/users.css +0 -31
  100. data/app/mailers/lesli_shield/invitation.html.erb +0 -23
  101. data/app/views/lesli_shield/invites/edit.html.erb +0 -12
  102. data/app/views/lesli_shield/role/actions/_form.html.erb +0 -75
@@ -0,0 +1,347 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LesliShield
4
+ # Manages a role's selected permission catalog. Saving selections stays
5
+ # intentionally separate from the heavier effective-cache compilation,
6
+ # which is performed on demand by RolePrivilegeDeploymentService.
7
+ class RolePermissionService
8
+ STANDARD_ACTION_ORDER = %w[
9
+ index
10
+ show
11
+ new
12
+ edit
13
+ create
14
+ update
15
+ destroy
16
+ ].freeze
17
+
18
+ class Error < StandardError; end
19
+
20
+ class UnknownActionsError < Error
21
+ attr_reader :action_ids
22
+
23
+ def initialize(action_ids)
24
+ @action_ids = action_ids
25
+ super(
26
+ I18n.t(
27
+ "lesli_shield.roles.errors_unknown_actions",
28
+ action_ids: action_ids.join(", ")
29
+ )
30
+ )
31
+ end
32
+ end
33
+
34
+ def initialize(actor)
35
+ @role_service = RoleService.new(actor)
36
+ end
37
+
38
+ def matrix(role_or_id)
39
+ role = manageable_role!(role_or_id)
40
+ records = permission_catalog_for(role)
41
+
42
+ build_matrix(records)
43
+ end
44
+
45
+ # Validate navigation without building the complete permission matrix.
46
+ # Slugs are the catalog engine names with underscores replaced by hyphens.
47
+ def engine_available?(slug)
48
+ active_catalog.where(
49
+ "REPLACE(parents_lesli_resources.engine, '_', '-') = ?",
50
+ slug
51
+ ).exists?
52
+ end
53
+
54
+ # Persists one checkbox change. The role lock keeps simultaneous
55
+ # requests from losing changes made to other permissions.
56
+ def set!(role:, action_id:, enabled:)
57
+ role = manageable_role!(role)
58
+
59
+ role.with_lock do
60
+ # Account ownership and permission levels may have changed
61
+ # while this request waited for the lock.
62
+ manageable_role!(role.id)
63
+
64
+ action_id = validate_action_id!(action_id)
65
+ timestamp = Time.current
66
+ changed = if enabled
67
+ enable_action!(role, action_id, timestamp)
68
+ else
69
+ disable_action!(role, action_id, timestamp)
70
+ end
71
+
72
+ next unless changed
73
+
74
+ role.update_columns(
75
+ modified_at: timestamp,
76
+ updated_at: timestamp
77
+ )
78
+ end
79
+
80
+ role
81
+ end
82
+
83
+ def duplicate_from!(source_role_or_id, target_role_or_id)
84
+ source = visible_role!(source_role_or_id)
85
+ target = manageable_role!(target_role_or_id)
86
+ selected_ids = active_catalog
87
+ .where(id: source.actions.select(:action_id))
88
+ .order(:id)
89
+ .pluck(:id)
90
+
91
+ target.with_lock do
92
+ manageable_role!(target.id)
93
+ timestamp = Time.current
94
+
95
+ if synchronize_actions!(target, selected_ids, timestamp)
96
+ target.update_columns(
97
+ modified_at: timestamp,
98
+ updated_at: timestamp
99
+ )
100
+ end
101
+ end
102
+
103
+ target
104
+ end
105
+
106
+ # Returns only permissions that currently authorize requests. An
107
+ # inactive role has no effective permissions even if its cache remains.
108
+ def effective_permissions(role_or_id)
109
+ role = visible_role!(role_or_id)
110
+ return [] unless role.active?
111
+
112
+ role.privileges
113
+ .where(active: true)
114
+ .order(:controller, :action)
115
+ .pluck(:controller, :action)
116
+ .map do |controller, action|
117
+ { controller: controller, action: action }
118
+ end
119
+ end
120
+
121
+ private
122
+
123
+ attr_reader :role_service
124
+
125
+ def visible_role!(role_or_id)
126
+ role_service.find!(record_id(role_or_id))
127
+ end
128
+
129
+ def manageable_role!(role_or_id)
130
+ role_service.find!(record_id(role_or_id), manageable: true)
131
+ end
132
+
133
+ def record_id(role_or_id)
134
+ role_or_id.respond_to?(:id) ? role_or_id.id : role_or_id
135
+ end
136
+
137
+ def active_catalog
138
+ Lesli::Resource.actions.joins(:parent)
139
+ end
140
+
141
+ def permission_catalog_for(role)
142
+ role_id = ActiveRecord::Base.connection.quote(role.id)
143
+ join = <<~SQL.squish
144
+ LEFT JOIN lesli_shield_role_actions selected_actions
145
+ ON selected_actions.action_id = lesli_resources.id
146
+ AND selected_actions.role_id = #{role_id}
147
+ SQL
148
+
149
+ active_catalog
150
+ .joins(join)
151
+ .select(
152
+ "lesli_resources.id AS action_id",
153
+ "lesli_resources.action AS action_name",
154
+ "lesli_resources.identifier AS action_identifier",
155
+ "lesli_resources.label AS action_label",
156
+ "parents_lesli_resources.id AS resource_id",
157
+ "parents_lesli_resources.engine AS engine_name",
158
+ "parents_lesli_resources.identifier AS resource_identifier",
159
+ "parents_lesli_resources.label AS resource_label",
160
+ "parents_lesli_resources.route AS resource_route",
161
+ "selected_actions.id AS role_action_id",
162
+ "selected_actions.deleted_at AS role_action_deleted_at"
163
+ )
164
+ .to_a
165
+ end
166
+
167
+ def build_matrix(records)
168
+ engines = records.group_by { |record| record[:engine_name].to_s }
169
+
170
+ engines.map do |engine_name, engine_records|
171
+ build_engine(engine_name, engine_records)
172
+ end.sort_by { |engine| [engine[:label].downcase, engine[:engine]] }
173
+ end
174
+
175
+ def build_engine(engine_name, records)
176
+ resources = records.group_by { |record| record[:resource_id] }
177
+ .map { |_resource_id, resource_records| build_resource(resource_records) }
178
+ .sort_by { |resource| [resource[:label].downcase, resource[:route]] }
179
+
180
+ {
181
+ engine: engine_name,
182
+ label: engine_label(engine_name),
183
+ resources: resources
184
+ }
185
+ end
186
+
187
+ def build_resource(records)
188
+ resource = records.first
189
+
190
+ {
191
+ id: resource[:resource_id],
192
+ identifier: resource[:resource_identifier],
193
+ label: readable_label(
194
+ resource[:resource_label],
195
+ resource[:resource_identifier],
196
+ resource[:resource_route]
197
+ ),
198
+ route: resource[:resource_route],
199
+ actions: records
200
+ .sort_by { |record| action_sort_key(record[:action_name]) }
201
+ .map { |record| build_action(record) }
202
+ }
203
+ end
204
+
205
+ def build_action(record)
206
+ assigned = record[:role_action_id].present? &&
207
+ record[:role_action_deleted_at].nil?
208
+ action_name = record[:action_name].to_s
209
+ standard = STANDARD_ACTION_ORDER.include?(action_name)
210
+ label = readable_label(
211
+ record[:action_label],
212
+ record[:action_identifier],
213
+ action_name
214
+ )
215
+
216
+ {
217
+ id: record[:action_id],
218
+ identifier: record[:action_identifier],
219
+ label: label,
220
+ display_label: standard_action_label(action_name, label),
221
+ action: action_name,
222
+ standard: standard,
223
+ assigned: assigned,
224
+ role_action_id: record[:role_action_id]
225
+ }
226
+ end
227
+
228
+ def standard_action_label(action_name, fallback)
229
+ return fallback unless STANDARD_ACTION_ORDER.include?(action_name)
230
+
231
+ I18n.t(
232
+ "lesli_shield.roles.permissions_standard_actions_#{action_name}",
233
+ default: fallback
234
+ )
235
+ end
236
+
237
+ def action_sort_key(action_name)
238
+ action_name = action_name.to_s
239
+ standard_position = STANDARD_ACTION_ORDER.index(action_name)
240
+
241
+ return [0, standard_position] if standard_position
242
+
243
+ [1, action_name]
244
+ end
245
+
246
+ def readable_label(label, identifier, fallback)
247
+ label.presence || identifier.to_s.demodulize.humanize.presence ||
248
+ fallback.to_s.humanize
249
+ end
250
+
251
+ def engine_label(engine_name)
252
+ metadata = LesliSystem.engines.values.find do |engine|
253
+ engine[:code].to_s == engine_name
254
+ end
255
+
256
+ metadata&.dig(:name).presence || engine_name.to_s.camelize
257
+ end
258
+
259
+ def validate_action_id!(action_id)
260
+ normalized_id = Integer(action_id, exception: false)
261
+ valid = normalized_id && active_catalog.exists?(id: normalized_id)
262
+
263
+ raise UnknownActionsError, [action_id] unless valid
264
+
265
+ normalized_id
266
+ end
267
+
268
+ def synchronize_actions!(role, selected_ids, timestamp)
269
+ existing_actions = role.actions.with_deleted
270
+ current_ids = existing_actions
271
+ .where(deleted_at: nil)
272
+ .order(:action_id)
273
+ .pluck(:action_id)
274
+ return false if current_ids == selected_ids
275
+
276
+ existing_ids = existing_actions.pluck(:action_id)
277
+ insert_actions!(role, selected_ids - existing_ids, timestamp)
278
+ activate_selected_actions!(existing_actions, selected_ids, timestamp)
279
+ deactivate_unselected_actions!(existing_actions, selected_ids, timestamp)
280
+ true
281
+ end
282
+
283
+ def enable_action!(role, action_id, timestamp)
284
+ actions = role.actions.with_deleted
285
+ action = actions.find_by(action_id: action_id)
286
+ return false if action && action.deleted_at.nil?
287
+
288
+ if action
289
+ actions.where(id: action.id).update_all(
290
+ deleted_at: nil,
291
+ updated_at: timestamp
292
+ )
293
+ else
294
+ Role::Action.create!(
295
+ role: role,
296
+ action_id: action_id,
297
+ created_at: timestamp,
298
+ updated_at: timestamp
299
+ )
300
+ end
301
+
302
+ true
303
+ end
304
+
305
+ def disable_action!(role, action_id, timestamp)
306
+ action = role.actions.find_by(action_id: action_id)
307
+ return false unless action
308
+
309
+ action.update_columns(
310
+ deleted_at: timestamp,
311
+ updated_at: timestamp
312
+ )
313
+ true
314
+ end
315
+
316
+ def insert_actions!(role, action_ids, timestamp)
317
+ records = action_ids.map do |action_id|
318
+ {
319
+ role_id: role.id,
320
+ action_id: action_id,
321
+ created_at: timestamp,
322
+ updated_at: timestamp
323
+ }
324
+ end
325
+
326
+ Role::Action.insert_all!(records) if records.any?
327
+ end
328
+
329
+ def activate_selected_actions!(actions, selected_ids, timestamp)
330
+ return if selected_ids.empty?
331
+
332
+ actions.where(action_id: selected_ids).update_all(
333
+ deleted_at: nil,
334
+ updated_at: timestamp
335
+ )
336
+ end
337
+
338
+ def deactivate_unselected_actions!(actions, selected_ids, timestamp)
339
+ unselected = actions.where(deleted_at: nil)
340
+ unselected = unselected.where.not(action_id: selected_ids) if selected_ids.any?
341
+ unselected.update_all(
342
+ deleted_at: timestamp,
343
+ updated_at: timestamp
344
+ )
345
+ end
346
+ end
347
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LesliShield
4
+ # Compiles a role's selected actions into its effective privilege cache.
5
+ # The compilation and its audit event are one atomic operation.
6
+ class RolePrivilegeDeploymentService
7
+ def initialize(actor)
8
+ @actor = actor
9
+ @role_service = RoleService.new(actor)
10
+ end
11
+
12
+ def deploy!(role_or_id)
13
+ role = manageable_role!(role_or_id)
14
+
15
+ role.with_lock do
16
+ # Revalidate after waiting for the lock because the actor's
17
+ # account or permission boundary may have changed.
18
+ manageable_role!(role.id)
19
+ timestamp = Time.current
20
+ previous_permissions = role.privileges
21
+ .where(active: true)
22
+ .distinct
23
+ .order(:controller, :action)
24
+ .pluck(:controller, :action)
25
+
26
+ deployed_permissions = RolePrivilegeService.new.rebuild!(
27
+ role,
28
+ timestamp: timestamp
29
+ )
30
+ role.update_columns(
31
+ deployed_at: timestamp,
32
+ updated_at: timestamp
33
+ )
34
+ RoleAudit.record!(
35
+ :role_privileges_deployed,
36
+ role: role,
37
+ actor: actor,
38
+ source: self.class,
39
+ details: {
40
+ permissions_added: permission_details(deployed_permissions - previous_permissions),
41
+ permissions_removed: permission_details(previous_permissions - deployed_permissions),
42
+ affected_users_count: affected_users_count(role)
43
+ }
44
+ )
45
+ end
46
+
47
+ role
48
+ end
49
+
50
+ private
51
+
52
+ attr_reader :actor, :role_service
53
+
54
+ # Store controller/action identities, not cache row IDs: a rebuild
55
+ # replaces those rows, and catalog resources may later be deleted.
56
+ def permission_details(pairs)
57
+ pairs.map do |controller, action|
58
+ { controller: controller, action: action }
59
+ end
60
+ end
61
+
62
+ # Count potential impact without storing user lists. Inactive roles
63
+ # and inactive/deleted users do not contribute to authorization.
64
+ def affected_users_count(role)
65
+ return 0 unless role.active?
66
+
67
+ User::Role.joins(:user)
68
+ .where(role_id: role.id)
69
+ .where(lesli_users: { account_id: role.account_id, active: true })
70
+ .distinct
71
+ .count(:user_id)
72
+ end
73
+
74
+ def manageable_role!(role_or_id)
75
+ role_id = role_or_id.respond_to?(:id) ? role_or_id.id : role_or_id
76
+ role_service.find!(role_id, manageable: true)
77
+ end
78
+ end
79
+ end
@@ -1,112 +1,76 @@
1
- =begin
2
-
3
- Lesli
4
-
5
- Copyright (c) 2026, Lesli Technologies, S. A.
6
-
7
- This program is free software: you can redistribute it and/or modify
8
- it under the terms of the GNU General Public License as published by
9
- the Free Software Foundation, either version 3 of the License, or
10
- (at your option) any later version.
11
-
12
- This program is distributed in the hope that it will be useful,
13
- but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- GNU General Public License for more details.
16
-
17
- You should have received a copy of the GNU General Public License
18
- along with this program. If not, see http://www.gnu.org/licenses/.
19
-
20
- Lesli · Ruby on Rails SaaS Development Framework.
21
-
22
- Made with ♥ by LesliTech
23
- Building a better future, one line of code at a time.
24
-
25
- @contact hello@lesli.tech
26
- @website https://www.lesli.tech
27
- @license GPLv3 http://www.gnu.org/licenses/gpl-3.0.en.html
28
-
29
- // · ~·~ ~·~ ~·~ ~·~ ~·~ ~·~ ~·~ ~·~ ~·~
30
- // ·
31
- =end
1
+ # frozen_string_literal: true
32
2
 
33
3
  module LesliShield
34
- class RolePrivilegeService < Lesli::ApplicationLesliService
35
-
36
- # Syncronize the descriptor privileges with the role privilege cache table
37
- def synchronize role
38
-
39
- # bulk all the descriptor privileges
40
- # this script was built manually for performance, maintenance
41
- # and to make it easy to read for future changes, basically what it does
42
- # is get the controllers and actions assigned to a descriptor through the
43
- # system_descriptor_privileges table and create an array of hashes with
44
- # all the raw privileges (this includes duplicated privileges)
45
- # IMPORTANT: A descriptor privilege is evaluated as active if:
46
- # - the role has assigned the descriptor through the power association
47
- # - the descriptor has assigned the privilege through the controller actions table
48
- # - the power has active that group of actions, this means that, if the power has
49
- # not marked as active the pshow, pindex, etc column the power is not active
50
- # even if it is assigned and active to a descriptor
51
-
52
- records = Lesli::Role.joins(%(
53
- INNER JOIN "lesli_shield_role_actions"
54
- ON "lesli_shield_role_actions"."role_id" = "lesli_roles"."id"
55
- )).joins(%(
56
- INNER JOIN lesli_resources as resource_actions
57
- ON resource_actions.id = lesli_shield_role_actions.action_id
58
- )).joins(%(
59
- INNER JOIN lesli_resources as resource_controllers
60
- ON resource_controllers.id = resource_actions.parent_id
61
- )).select(%(
62
- lesli_shield_role_actions.role_id as role_id,
63
- resource_controllers.route as controller,
64
- resource_actions.action as action,
65
- case when lesli_shield_role_actions.deleted_at is null then TRUE else FALSE end active
66
- )).with_deleted
67
-
68
- # get privileges only for the given role, this is needed to sync only modified roles
69
- records = records.where("lesli_shield_role_actions.role_id" => role.id)
70
-
71
- # get privileges only for the given role action, this is needed to sync only modified actions
72
- records = records.where("lesli_shield_role_actions.id" => @action.id) if @action
73
-
74
-
75
- # we use the deleted_at column to know if a privilege is enable or disable, NULL values
76
- # at the deleted_at column means privilege is active, so if we sort by deleted_at column
77
- # all the active privileges will be at the top, then the uniq method is going to take
78
- # always the active values, to completely disable a privilege for a specific controller/action
79
- # we have to disable in all the roles
80
- records = records.order("lesli_shield_role_actions.deleted_at DESC")
81
-
82
-
83
- # convert the results to json so it is easy to insert/update
84
- records = records.as_json(only: [:controller, :action, :role_id, :active])
85
-
86
-
87
- # IMPORTANT: We must save only uniq privileges in the role_privilege table
88
- # this means that it does not matters how many times we defined a privilege dependency
89
- # we insert the privilege only once.
90
- # Example: If we defined that we need access to UsersController#index in 20 descriptors,
91
- # in the role_privileges will be only one record for that specific controller and action
92
- records = records.uniq do |privilege|
93
-
94
- # NOTE: If can disable a privilege that belongs to a descriptor,
95
- # however, if the same privilege is define in another active descriptor,
96
- # the role that has both descriptor will be able to access the resources
97
- # of that privilege, that is a normal and desire behavior.
98
- [privilege["controller"], privilege["action"], privilege["role_id"]]
4
+ # Builds the effective authorization cache for one role.
5
+ #
6
+ # `Role::Action` is the source of truth: it stores the permissions selected
7
+ # by an administrator. `Role::Privilege` is only a cache used to authorize
8
+ # requests quickly. Rebuilding therefore replaces every cached row instead
9
+ # of trying to update the previous cache incrementally.
10
+ #
11
+ # This service is deliberately unaware of users and authorization policy.
12
+ # RolePrivilegeDeploymentService is responsible for validating the actor,
13
+ # locking the role, updating `deployed_at`, and recording the audit event.
14
+ class RolePrivilegeService
15
+ # Replaces the role's complete privilege cache.
16
+ #
17
+ # Deleted role actions and deleted catalog resources are automatically
18
+ # excluded by the models' default scopes. If the role has no selected
19
+ # actions, the resulting cache is empty.
20
+ #
21
+ # @param role [Lesli::Role] role whose cache will be rebuilt
22
+ # @param timestamp [Time] timestamp shared by every inserted cache row
23
+ # @return [Array<Array<String>>] unique `[controller, action]` pairs
24
+ def rebuild!(role, timestamp: Time.current)
25
+ permission_pairs = selected_permission_pairs(role)
26
+
27
+ Role::Privilege.transaction do
28
+ delete_previous_cache!(role)
29
+ insert_cache!(role, permission_pairs, timestamp)
99
30
  end
100
31
 
32
+ permission_pairs
33
+ end
34
+
35
+ private
36
+
37
+ # Different catalog entries may resolve to the same controller/action.
38
+ # The cache stores each effective permission only once.
39
+ def selected_permission_pairs(role)
40
+ role.actions
41
+ .joins(action: :parent)
42
+ .pluck(
43
+ "parents_lesli_resources.route",
44
+ "lesli_resources.action"
45
+ )
46
+ .uniq
47
+ .sort
48
+ end
49
+
50
+ # Privileges use soft deletion elsewhere. A rebuild needs a physical
51
+ # deletion so stale cache rows cannot survive the deployment.
52
+ def delete_previous_cache!(role)
53
+ Role::Privilege.with_deleted
54
+ .where(role_id: role.id)
55
+ .delete_all!
56
+ end
57
+
58
+ # The cache contains granted permissions only. `active: true` is kept
59
+ # because it is part of the authorization query's persisted contract.
60
+ def insert_cache!(role, permission_pairs, timestamp)
61
+ cache_rows = permission_pairs.map do |controller, action|
62
+ {
63
+ role_id: role.id,
64
+ controller: controller,
65
+ action: action,
66
+ active: true,
67
+ created_at: timestamp,
68
+ updated_at: timestamp
69
+ }
70
+ end
71
+ return if cache_rows.empty?
101
72
 
102
- # small check to ensure I have records to update/insert
103
- return if records.blank?
104
-
105
- # bulk update/insert into role privilege cache table
106
- # IMPORTANT: Due to the importance and how delicate this process is, it is better
107
- # to copy the controller name and actions from the system, instead of
108
- # just have a reference to the system_controller_actions table
109
- Role::Privilege.with_deleted.upsert_all(records, unique_by: [:controller, :action, :role_id])
110
- end
73
+ Role::Privilege.insert_all!(cache_rows)
74
+ end
111
75
  end
112
76
  end