rails_admin_next 2.2.0 → 3.0.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 373f306f26c44449a2adeabf854452a3592fdef08eb87ffb31c818f7ce662ddb
4
- data.tar.gz: 435fbec5b7817f3f1d7b53eacf233f04208c27de4a87e5eb15fdd6585f395328
3
+ metadata.gz: ab5a6bc8f57c396848dea3a851d668da3604777f07674304de1b2eaab84074df
4
+ data.tar.gz: 4b695b8d7a86cebf28db86e4f2730bfc081bfccb480c2279fb9fd8329407643f
5
5
  SHA512:
6
- metadata.gz: ea6a58ab5f4276088b29bde851ef2802316f370a208d50c0619dc3c6a2218e981f690b959f1776d8b6d74687a703595887f798b1ef11866b398fd4ec5e4d90e0
7
- data.tar.gz: 5e43c1a785d4bbc4bcfa06aea22a24989d2e5832ad7de1cef45e388f7a2f002823da4f50421dd1fbe9d4121b0324f05409194ea6f7f75f0751881c713253ca7e
6
+ metadata.gz: 4b665f2830ea9086fcae2e1ba66c83b5dcd2000f4ebf1652fb161dccdfcf04d6353d17453ba26f3590a2e73d4cca54106fbb2fbe86a80c2e1d4da9fa0a4386fd
7
+ data.tar.gz: bf1a98c7a6f8e14106f9460c1467099ef8c4a99755ffcc847b9d3f60364a9a9f03ad4f3e89781b60e5718df41654a7b7bb6c772b5b5350a9d29b0e1e2a0a7771
@@ -26,6 +26,16 @@ module RailsAdminNext
26
26
 
27
27
  attr_reader :object, :model_config, :abstract_model, :authorization_adapter
28
28
 
29
+ # nil without an authorization adapter. With one, a scope that is not a relation (nil, a
30
+ # Hash, a Proc, an Array) comes from a broken policy and lists nothing: merged in, most of
31
+ # them would widen a list to every record.
32
+ def authorization_scope(action, abstract_model)
33
+ return unless @authorization_adapter
34
+
35
+ scope = @authorization_adapter.query(action, abstract_model)
36
+ scope.is_a?(ActiveRecord::Relation) ? scope : abstract_model.model.none
37
+ end
38
+
29
39
  def get_model
30
40
  @model_name = to_model_name(params[:model_name])
31
41
  raise RailsAdminNext::ModelNotFound unless (@abstract_model = visible_abstract_model(@model_name))
@@ -6,6 +6,8 @@ module RailsAdminNext
6
6
  include RailsAdminNext::MainHelper
7
7
  include RailsAdminNext::ApplicationHelper
8
8
 
9
+ MAX_PICKER_SOURCE_PARENTS = 10
10
+
9
11
  before_action :check_for_cancel
10
12
 
11
13
  helper_method :list_scopes
@@ -17,7 +19,7 @@ module RailsAdminNext
17
19
 
18
20
  def list_entries(model_config = @model_config, auth_scope_key = :index, additional_scope = nil, pagination = !(params[:all] || params[:bulk_ids]))
19
21
  scope = model_config.scope
20
- auth_scope = @authorization_adapter&.query(auth_scope_key, model_config.abstract_model)
22
+ auth_scope = authorization_scope(auth_scope_key, model_config.abstract_model)
21
23
  scope = scope.merge(auth_scope) if auth_scope
22
24
  tab = list_scope if model_config == @model_config
23
25
  if tab
@@ -31,7 +33,7 @@ module RailsAdminNext
31
33
  # The association scope chains after get_collection, which only works on an unpaginated relation.
32
34
  def association_entries(model_config, collection_scope)
33
35
  scope = model_config.scope
34
- auth_scope = @authorization_adapter&.query(:index, model_config.abstract_model)
36
+ auth_scope = authorization_scope(:index, model_config.abstract_model)
35
37
  scope = scope.merge(auth_scope) if auth_scope
36
38
  scope = get_collection(model_config, scope, false)
37
39
  collection_scope ? scope.instance_eval(&collection_scope) : scope
@@ -45,7 +47,7 @@ module RailsAdminNext
45
47
 
46
48
  get_model unless action.root?
47
49
  get_object if action.member?
48
- @authorization_adapter.try(:authorize, action.authorization_key, @abstract_model, @object)
50
+ @authorization_adapter&.authorize(action.authorization_key, @abstract_model, @object)
49
51
  @action = action.with({controller: self, abstract_model: @abstract_model, object: @object})
50
52
  raise(ActionNotAllowed) unless @action.enabled?
51
53
 
@@ -214,6 +216,33 @@ module RailsAdminNext
214
216
  @_list_scopes ||= @model_config.list.with(controller: self, view: view_context, object: @abstract_model.model.new).scopes
215
217
  end
216
218
 
219
+ # Export's included associations hold only the rows the user may list on the associated model.
220
+ # Loaded rows are filtered rather than the preload scoped: a through association with a where
221
+ # scope ignores a preload scope, and a through preload reuses its through association's rows,
222
+ # so every association loads in full before any is narrowed.
223
+ def authorize_included(records)
224
+ names = @schema&.dig(:include)&.keys
225
+ return records if @authorization_adapter.nil? || names.blank?
226
+
227
+ records = records.to_a
228
+ ActiveRecord::Associations::Preloader.new(records:, associations: names).call
229
+ names.each do |name|
230
+ klass = @abstract_model.model.reflect_on_association(name).klass
231
+ associations = records.map { it.association(name) }
232
+ loaded = klass.where(klass.primary_key => associations.flat_map { Array.wrap(it.target) }.map(&:id))
233
+ allowed = within_authorized(loaded, authorization_scope(:index, RailsAdminNext::AbstractModel.new(klass))).pluck(*Array(klass.primary_key)).to_set
234
+ associations.each do |association|
235
+ association.target =
236
+ if association.collection?
237
+ association.target.select { allowed.include?(it.id) }
238
+ elsif allowed.include?(association.target&.id)
239
+ association.target
240
+ end
241
+ end
242
+ end
243
+ records
244
+ end
245
+
217
246
  # A row-value IN: `where(primary_key => relation)` renders an empty condition for composite keys.
218
247
  def within_authorized(scope, auth_scope)
219
248
  key = Array(scope.primary_key).map { scope.arel_table[it] }
@@ -231,6 +260,7 @@ module RailsAdminNext
231
260
  end
232
261
 
233
262
  def get_association_scope_from_params
263
+ return nil unless params[:associated_collection].is_a?(String) && params[:source_abstract_model].is_a?(String)
234
264
  return nil unless params[:associated_collection].present? && params[:source_abstract_model].present?
235
265
  return nil unless (source_abstract_model = visible_abstract_model(to_model_name(params[:source_abstract_model])))
236
266
 
@@ -241,9 +271,70 @@ module RailsAdminNext
241
271
  # Polymorphic pickers never send associated_collection, and their collection ignores the listed records.
242
272
  return nil unless field&.association? && !field.polymorphic? && field.associated_model_config == @model_config
243
273
 
244
- source_object = source_abstract_model.get(params[:source_object_id])
274
+ # A new record's picker names no source. A named source that is missing, outside the model's
275
+ # scope or not editable lists the same way, so the response does not reveal which ids exist.
276
+ source_object = nil
277
+ if (source_id = params[:source_object_id]).present?
278
+ return nil unless source_id.is_a?(String) && (source_object = source_abstract_model.get(source_id, source_model_config.scope))
279
+ return nil unless source_editable?(source_abstract_model, source_object, picker_source_parents)
280
+ end
281
+
245
282
  @association = field.with(controller: self, object: source_object)
246
283
  @association.associated_collection_scope
247
284
  end
285
+
286
+ # The persisted records a nested subform's source sits under, innermost first. Capped because
287
+ # each level costs queries and the chain is client-supplied.
288
+ def picker_source_parents
289
+ Array.wrap(params[:source_parents]).first(MAX_PICKER_SOURCE_PARENTS).map do |parent|
290
+ return [] unless parent.is_a?(ActionController::Parameters) && parent[:model].is_a?(String) && parent[:id].is_a?(String)
291
+
292
+ parent
293
+ end
294
+ end
295
+
296
+ # Asks the adapter directly: going through the edit action's authorized? would also apply its
297
+ # enabled?/visible settings, changing pickers for hosts that only hide the edit link.
298
+ def source_editable?(abstract_model, object, parents)
299
+ return true unless @authorization_adapter
300
+
301
+ edit = RailsAdminNext::Config::Actions.find(:edit)
302
+ return false unless edit
303
+
304
+ editable?(edit, abstract_model, object) || edited_through_parent?(edit, abstract_model, object, parents)
305
+ end
306
+
307
+ def editable?(edit, abstract_model, object)
308
+ key = edit.with(controller: self, abstract_model:, object:).authorization_key
309
+ @authorization_adapter.authorized?(key, abstract_model, object)
310
+ end
311
+
312
+ # A subform's record is edited through the form it is nested in. A parent the user may edit
313
+ # renders its update section; any other parent is itself a subform, rendered from its nested
314
+ # section and reached through the next parent up. The form stops rendering an association's
315
+ # subforms after MAX_NESTED_FORM_RECURSION repeats, so a longer chain reaches no form.
316
+ def edited_through_parent?(edit, abstract_model, object, parents, nested_via = [])
317
+ parent_ref, *outer_parents = parents
318
+ return false unless parent_ref && (parent_model = visible_abstract_model(to_model_name(parent_ref[:model])))
319
+ return false unless (parent = parent_model.get(parent_ref[:id], parent_model.config.scope))
320
+
321
+ parent_editable = editable?(edit, parent_model, parent)
322
+ section = parent_editable ? parent_model.config.update : parent_model.config.nested
323
+ return false unless (field = nesting_field(section, parent, abstract_model, object))
324
+
325
+ nested_via += [field.name]
326
+ return false if nested_via.count(field.name) > RailsAdminNext::FormBuilder::MAX_NESTED_FORM_RECURSION
327
+
328
+ parent_editable || edited_through_parent?(edit, parent_model, parent, outer_parents, nested_via)
329
+ end
330
+
331
+ # The parent's form shows only the fields of its visible groups.
332
+ def nesting_field(section, parent, abstract_model, object)
333
+ section.with(controller: self, view: view_context, object: parent).visible_groups.flat_map(&:visible_fields).detect do |field|
334
+ next false unless field.nested_form && !field.read_only? && field.associated_model_config == abstract_model.config
335
+
336
+ field.multiple? ? parent.public_send(field.name).include?(object) : parent.public_send(field.name) == object
337
+ end
338
+ end
248
339
  end
249
340
  end
@@ -8,6 +8,10 @@ module RailsAdminNext
8
8
  # one association, rather than depth, leaves chains of distinct models uncapped.
9
9
  MAX_NESTED_FORM_RECURSION = 3
10
10
 
11
+ # The config this form renders its object with: a subform's is its association's, which can
12
+ # differ from the record's own class under STI.
13
+ attr_reader :model_config
14
+
11
15
  def generate(options = {})
12
16
  without_field_error_proc_added_div do
13
17
  options.reverse_merge!(
@@ -15,6 +19,7 @@ module RailsAdminNext
15
19
  model_config: @template.instance_variable_get(:@model_config),
16
20
  nested_in: false
17
21
  )
22
+ @model_config = options[:model_config]
18
23
 
19
24
  object_infos +
20
25
  visible_groups(options[:model_config], generator_action(options[:action], options[:nested_in])).collect do |fieldset|
@@ -53,7 +53,7 @@
53
53
  </div>
54
54
  </div>
55
55
  </div>
56
- <% visible_fields.select{ |f| f.association? && !f.association.polymorphic? }.each do |field| %>
56
+ <% visible_fields.select{ |f| f.association? && !f.association.polymorphic? && f.associated_model_listable? }.each do |field| %>
57
57
  <% fields = field.associated_model_config.export.with(controller: self.controller, view: self, object: (associated_model = field.associated_model_config.abstract_model.model).new).visible_fields.select{ |f| !f.association? } %>
58
58
  <div class="control-group row">
59
59
  <div class="col-sm-12">
data/docs/UPGRADING.md CHANGED
@@ -75,7 +75,9 @@ end
75
75
  ```
76
76
 
77
77
  The module defines an `AuthorizationAdapter` class. `authorize_with` builds it with
78
- `new(controller, *args, **options, &block)` and it answers:
78
+ `new(controller, *args, **options, &block)`. It must publicly define the first four methods
79
+ below; `authorize_with` raises `ArgumentError` while the initializer loads, naming any that are
80
+ missing or private:
79
81
 
80
82
  - `authorize(action, abstract_model, object)`: raises when the action is denied.
81
83
  - `authorized?(action, abstract_model, object)`: returns a boolean, for links and buttons.
@@ -87,6 +89,10 @@ The module defines an `AuthorizationAdapter` class. `authorize_with` builds it w
87
89
  subclass of a built-in adapter inherits its `validate_options!`, so one that takes options of
88
90
  its own overrides it.
89
91
 
92
+ An adapter that a `config.authorize_with { ... }` block assigns to `@authorization_adapter` is not
93
+ checked at boot; if it lacks `authorize`, the first admin action raises `NoMethodError` instead of
94
+ running unauthorized.
95
+
90
96
  `lib/rails_admin_next/extensions/pundit/authorization_adapter.rb` in the gem is the template.
91
97
  The removed CanCanCan adapter is a starting point you can copy:
92
98
  [v1.3.0 `extensions/cancancan/authorization_adapter.rb`](https://github.com/6temes/rails_admin_next/blob/v1.3.0/lib/rails_admin_next/extensions/cancancan/authorization_adapter.rb),
@@ -725,6 +731,29 @@ page, is not destroyed, and counts in the "failed to be deleted" message. Before
725
731
  delete honoured only the scope, so a `destroy?` rule that reads the record, such as
726
732
  `!record.locked?`, stopped the single delete but not the bulk one.
727
733
 
734
+ ## Export includes an association only if its model may be listed
735
+
736
+ With Pundit or ActionPolicy configured, export leaves out an association unless the policy grants
737
+ `index?` on the associated model (or the rule named by the index action's `authorization_key`) and
738
+ the index action is enabled for it.
739
+ The export form stops offering its fields, and a submitted `schema[include]` naming it is dropped,
740
+ for CSV, JSON and XML alike. Before, the user needed only `export?` on the exported model, so a
741
+ user who could export players but not list teams still got each player's team columns. With no
742
+ authorization adapter nothing changes.
743
+
744
+ An included association also exports only the records the associated model's policy scope (Pundit
745
+ `Scope`, ActionPolicy `relation_scope`) lets the user list. A linked record outside that scope
746
+ exports as an empty cell in CSV and is left out of JSON and XML, as if the row had no such record.
747
+ An associated model whose policy defines no scope exports none of its records, as its list shows
748
+ none. Each batch of exported rows narrows an included association with one more query, whatever its
749
+ shape, through associations included. The list and show pages still show associated records by
750
+ their label without this scope.
751
+
752
+ A method on the exported model that reads an included association sees the narrowed records, so
753
+ one that dereferences a hidden `belongs_to` gets `nil`. A virtual field of the exported model is its
754
+ own field: one that reads an association in full exports what it reads, whatever the associated
755
+ model's scope.
756
+
728
757
  ## `associated_collection_scope` runs after the list sort
729
758
 
730
759
  Association pickers apply `associated_collection_scope` after the picked model's list sort,
@@ -765,6 +794,50 @@ keep the old access.
765
794
  The walk follows Ruby class inheritance, not the `type` column: a concrete subclass of a model
766
795
  takes that model's policy even when it is not STI.
767
796
 
797
+ The Pundit adapter builds the parent's policy as `PolicyClass.new(pundit_user, record)` and its
798
+ scope as `PolicyClass::Scope.new(pundit_user, scope)`, Pundit's standard constructors. If your
799
+ policy classes take different arguments, a subclass that falls back to its parent's policy raises
800
+ instead. The navigation checks every visible model, so every admin page then shows an error:
801
+ access is denied, never granted. Define that subclass's own policy to avoid the fallback.
802
+
803
+ ## A scope that is not a relation lists nothing
804
+
805
+ A policy scope that returned `nil` (a Pundit `Scope#resolve` or an ActionPolicy `relation_scope`
806
+ with a branch that falls through, such as `scope.all if user.admin?`) used to remove the
807
+ restriction, so the list, export, bulk actions, association pickers and dashboard counts showed
808
+ every record. A `Hash` or a `Proc` did the same, and an `Array` (`scope.to_a`) raised. With an
809
+ authorization adapter configured, a scope that is not an `ActiveRecord::Relation` now lists
810
+ nothing, whichever adapter returned it, custom adapters included. That includes the model class
811
+ itself: return `scope.all` or `Model.all`, not `Model`. Return a relation from every branch of the
812
+ scope. Without an authorization adapter nothing changes.
813
+
814
+ ## Association pickers check the source record
815
+
816
+ An association picker's list can be shaped by the record whose form it sits on: an
817
+ `associated_collection_scope` block reads it as `bindings[:object]`. The picker now binds that
818
+ record only when it can be loaded through the source model's `scope`, and, with an authorization
819
+ adapter configured, only when the adapter allows the edit action on it (`edit?` unless the
820
+ action's `authorization_key` is changed; ActionPolicy aliases `edit?` to `update?`, Pundit does
821
+ not). A host with an adapter but no `edit` action binds no record.
822
+
823
+ Otherwise the picker skips the field's `associated_collection_scope` and lists the picked model's
824
+ index, as it does for any picker request it rejects. A source id that does not exist gets the same
825
+ list, so the response does not reveal which ids exist. A new record's form names no source and
826
+ still runs `associated_collection_scope` with a `nil` record.
827
+
828
+ Hosts without an adapter see two changes: a source record outside the model's `scope` is no longer
829
+ bound, and a source id that does not exist now lists the index instead of running
830
+ `associated_collection_scope` with a `nil` record.
831
+
832
+ Inside a nested form the record is the nested one. Its pickers now also send the persisted records
833
+ it is nested under. The record counts as editable when the adapter allows editing a parent and the
834
+ record belongs to a nested-form association that parent's form shows and lets the user edit: the
835
+ `update` section of the parent the user edits, and the `nested` section of any parent in between,
836
+ counting only fields in visible groups and no deeper than the form renders. A model edited only
837
+ through its parent's form no longer needs an `edit?` policy of its own. That check runs the
838
+ parent's `visible` blocks with `bindings[:controller]`, `bindings[:view]` and `bindings[:object]`
839
+ set, but no `bindings[:form]`.
840
+
768
841
  ## Removed: options deprecated before RailsAdmin 3.0
769
842
 
770
843
  These six were deprecated upstream between 2019-07 and 2022-01 and had no effect for
@@ -812,3 +885,31 @@ no gem migration to run — your existing `rails_admin_histories` table (if any)
812
885
  A record's history page now honours its column sort, and with no sort it lists newest
813
886
  first, like the model history page. It used to list a record's versions oldest first
814
887
  whatever the sort.
888
+
889
+ ## History and "last created" stay inside the authorization scope
890
+
891
+ With an authorization adapter configured, the dashboard and the history pages now show only
892
+ what the user may list:
893
+
894
+ - The dashboard's history feed shows changes only to records of models the user may `index`,
895
+ and only to records inside that model's authorization scope (the scope `query(:index, ...)`
896
+ returns).
897
+ - A model's history page (`history_index`) shows changes only to records inside the scope
898
+ `query(:history, ...)` returns.
899
+ - A model's "Last created" time on the dashboard reads the newest record inside the scope.
900
+
901
+ Changes to a deleted record are no longer shown under an authorization adapter, since no live
902
+ record places them inside a scope. A record's own history page (`history_show`) is unchanged:
903
+ it is authorized against the record itself. Without an authorization adapter, nothing changes.
904
+
905
+ A custom auditing adapter must accept the new keyword arguments when an authorization adapter is
906
+ configured: `latest(count, scopes:)`, where `scopes` maps each `AbstractModel` the user may list
907
+ to its authorized relation, and `listing_for_model(..., scope:)`, the model's authorized relation.
908
+ Restrict versions to items inside those relations. An adapter that does not accept them raises
909
+ `ArgumentError` instead of listing unscoped history.
910
+
911
+ A `last_created_at` override in model config is not scoped for you. It runs with
912
+ `bindings[:controller]`, so it can read
913
+ `bindings[:controller].authorization_scope(:index, abstract_model)`: the authorized relation, an
914
+ empty one when the policy scope is broken, or `nil` without an authorization adapter. Calling the
915
+ adapter's `query` directly skips that check.
@@ -38,17 +38,19 @@ module RailsAdminNext
38
38
  unless @objects.blank?
39
39
  # Rescue per record: dependent: :restrict_with_exception raises, and an
40
40
  # escaping raise would abandon every record behind it in the batch.
41
+ # Audit inside the loop so any other raise still leaves a history row
42
+ # for each record already destroyed.
41
43
  destroyed, not_destroyed = Array.wrap(@objects).partition do |object|
42
44
  next false unless destroyable.call(object)
43
45
 
44
46
  object.destroy
45
- object.destroyed?
47
+ next false unless object.destroyed?
48
+
49
+ @auditing_adapter&.delete_object(object, @abstract_model, _current_user)
50
+ true
46
51
  rescue ActiveRecord::DeleteRestrictionError
47
52
  false
48
53
  end
49
- destroyed.each do |object|
50
- @auditing_adapter&.delete_object(object, @abstract_model, _current_user)
51
- end
52
54
  end
53
55
  end
54
56
 
@@ -20,17 +20,26 @@ module RailsAdminNext
20
20
 
21
21
  register_instance_option :controller do
22
22
  proc do
23
- @history = @auditing_adapter&.latest(@action.auditing_versions_limit) if @action.history?
24
- if @action.statistics?
23
+ history = @action.history? && @auditing_adapter
24
+ if history || @action.statistics?
25
25
  model_configs = RailsAdminNext::Config.visible_models(controller: self)
26
-
26
+ scopes = model_configs.to_h { [it.abstract_model, authorization_scope(:index, it.abstract_model)] }
27
+ end
28
+ if history
29
+ @history =
30
+ if @authorization_adapter
31
+ @auditing_adapter.latest(@action.auditing_versions_limit, scopes:)
32
+ else
33
+ @auditing_adapter.latest(@action.auditing_versions_limit)
34
+ end
35
+ end
36
+ if @action.statistics?
27
37
  @abstract_models = model_configs.map(&:abstract_model)
28
38
  @most_recent_created = {}
29
39
  @count = {}
30
40
  @max = 0
31
41
  model_configs.each do |config|
32
- scope = @authorization_adapter&.query(:index, config.abstract_model)
33
- current_count = config.abstract_model.count({}, scope)
42
+ current_count = config.abstract_model.count({}, scopes[config.abstract_model])
34
43
  @max = (current_count > @max) ? current_count : @max
35
44
  name = config.abstract_model.model.name
36
45
  @count[name] = current_count
@@ -21,7 +21,13 @@ module RailsAdminNext
21
21
  register_instance_option :controller do
22
22
  proc do
23
23
  @general = true
24
- @history = @auditing_adapter&.listing_for_model(@abstract_model, params[:query], params[:sort], params[:sort_reverse], params[:all], params[:page]) || []
24
+ listing = [@abstract_model, params[:query], params[:sort], params[:sort_reverse], params[:all], params[:page]]
25
+ @history =
26
+ if @authorization_adapter
27
+ @auditing_adapter&.listing_for_model(*listing, scope: authorization_scope(:history, @abstract_model))
28
+ else
29
+ @auditing_adapter&.listing_for_model(*listing)
30
+ end || []
25
31
 
26
32
  render @action.template_name
27
33
  end
@@ -50,7 +50,7 @@ module RailsAdminNext
50
50
  @objects.collect { |object| {id: object.id.to_s, label: object.send(@model_config.object_label_method).to_s} }
51
51
  end
52
52
  else
53
- @objects.to_json(@schema || serialization_schema.default)
53
+ authorize_included(@objects).to_json(@schema || serialization_schema.default)
54
54
  end
55
55
 
56
56
  if params[:send_data]
@@ -61,7 +61,7 @@ module RailsAdminNext
61
61
  end
62
62
 
63
63
  format.xml do
64
- output = @objects.map { |object| object.serializable_hash(@schema || serialization_schema.default) }.to_xml(root: @abstract_model.model.model_name.plural)
64
+ output = authorize_included(@objects).map { |object| object.serializable_hash(@schema || serialization_schema.default) }.to_xml(root: @abstract_model.model.model_name.plural)
65
65
  if params[:send_data]
66
66
  send_data output, filename: "#{params[:model_name]}_#{DateTime.now.strftime("%Y-%m-%d_%Hh%Mm%S")}.xml"
67
67
  else
@@ -70,7 +70,7 @@ module RailsAdminNext
70
70
  end
71
71
 
72
72
  format.csv do
73
- header, encoding, output = CSVConverter.new(@objects, @schema).to_csv(params[:csv_options].permit!.to_h)
73
+ header, encoding, output = CSVConverter.new(@objects, @schema, prepare_batch: method(:authorize_included)).to_csv(params[:csv_options].permit!.to_h)
74
74
  if params[:send_data]
75
75
  send_data output,
76
76
  type: "text/csv; charset=#{encoding}; #{"header=present" if header}",
@@ -16,6 +16,13 @@ module RailsAdminNext
16
16
  nested_form ? :"#{name}_attributes" : association.key_accessor
17
17
  end
18
18
 
19
+ # Exporting an association's columns reads its records, so it takes the right to list them.
20
+ def associated_model_listable?
21
+ return true unless bindings[:controller].authorization_adapter
22
+
23
+ RailsAdminNext::Config::Actions.find(:index)&.with(controller: bindings[:controller], abstract_model: associated_model_config.abstract_model)&.authorized?
24
+ end
25
+
19
26
  register_instance_option :pretty_value do
20
27
  v = bindings[:view]
21
28
  [value].flatten.select(&:present?).collect do |associated|
@@ -154,8 +161,29 @@ module RailsAdminNext
154
161
  RailsAdminNext.config.default_associated_collection_limit
155
162
  end
156
163
 
164
+ # The picker authorizes its source record through these, so a subform's record the user
165
+ # edits only through its parent's form still scopes its choices.
166
+ def picker_source_params
167
+ {
168
+ source_object_id: (abstract_model.format_id(bindings[:object].id) if bindings[:object].persisted?),
169
+ source_abstract_model: abstract_model.to_param,
170
+ source_parents: picker_source_parents.presence,
171
+ associated_collection: name
172
+ }.compact
173
+ end
174
+
157
175
  private
158
176
 
177
+ def picker_source_parents
178
+ builder = bindings[:form]
179
+ parents = []
180
+ while (builder = builder&.options&.[](:parent_builder)) && builder.object.persisted?
181
+ parent_model = builder.model_config.abstract_model
182
+ parents << {model: parent_model.to_param, id: parent_model.format_id(builder.object.id)}
183
+ end
184
+ parents
185
+ end
186
+
159
187
  def format_key(key)
160
188
  if key.is_a?(Array)
161
189
  RailsAdminNext.config.composite_keys_serializer.serialize(key)
@@ -68,7 +68,7 @@ module RailsAdminNext
68
68
  {
69
69
  xhr: !associated_collection_cache_all,
70
70
  "edit-url": ((inline_edit && bindings[:view].authorized?(:edit, associated_model_config.abstract_model)) ? bindings[:view].edit_path(model_name: associated_model_config.abstract_model.to_param, id: "__ID__") : ""),
71
- remote_source: bindings[:view].index_path(associated_model_config.abstract_model, source_object_id: abstract_model.format_id(bindings[:object].id), source_abstract_model: abstract_model.to_param, associated_collection: name, current_action: bindings[:view].current_action, compact: true),
71
+ remote_source: bindings[:view].index_path(associated_model_config.abstract_model, **picker_source_params, current_action: bindings[:view].current_action, compact: true),
72
72
  scopeBy: dynamic_scope_relationships,
73
73
  sortable: !!orderable,
74
74
  removable: !!removable,
@@ -52,7 +52,7 @@ module RailsAdminNext
52
52
  def widget_options
53
53
  {
54
54
  xhr: !associated_collection_cache_all,
55
- remote_source: bindings[:view].index_path(associated_model_config.abstract_model, source_object_id: abstract_model.format_id(bindings[:object].id), source_abstract_model: abstract_model.to_param, associated_collection: name, current_action: bindings[:view].current_action, compact: true),
55
+ remote_source: bindings[:view].index_path(associated_model_config.abstract_model, **picker_source_params, current_action: bindings[:view].current_action, compact: true),
56
56
  scopeBy: dynamic_scope_relationships
57
57
  }
58
58
  end
@@ -108,8 +108,12 @@ module RailsAdminNext
108
108
  abstract_model.scoped
109
109
  end
110
110
 
111
+ # Bound to a controller with an authorization adapter, only the records the user may list count.
111
112
  register_instance_option :last_created_at do
112
- abstract_model.model.last.try(:created_at) if abstract_model.properties.detect { |c| c.name == :created_at }
113
+ next unless abstract_model.properties.detect { |c| c.name == :created_at }
114
+
115
+ authorized_scope = bindings&.dig(:controller)&.authorization_scope(:index, abstract_model)
116
+ (authorized_scope&.unscope(:order) || abstract_model.model).last.try(:created_at)
113
117
  end
114
118
 
115
119
  # Act as a proxy for the base section configuration that actually
@@ -16,6 +16,8 @@ module RailsAdminNext
16
16
 
17
17
  DEFAULT_AUTHORIZE = proc {}
18
18
 
19
+ AUTHORIZATION_ADAPTER_METHODS = %i[authorize authorized? query attributes_for].freeze
20
+
19
21
  DEFAULT_AUDIT = proc {}
20
22
 
21
23
  DEFAULT_CURRENT_USER = proc {}
@@ -199,7 +201,8 @@ module RailsAdminNext
199
201
  # while this config block runs, so a misconfigured option fails at boot.
200
202
  #
201
203
  # A custom adapter is registered with
202
- # RailsAdminNext.add_extension(key, mod, authorization: true) before it is named here.
204
+ # RailsAdminNext.add_extension(key, mod, authorization: true) before it is named here, and
205
+ # must publicly define authorize, authorized?, query and attributes_for, or this raises.
203
206
  # See docs/UPGRADING.md for the adapter contract.
204
207
  #
205
208
  # @see RailsAdminNext::Config::DEFAULT_AUTHORIZE
@@ -218,6 +221,11 @@ module RailsAdminNext
218
221
  "(no per-record checks or list scoping). See docs/UPGRADING.md."
219
222
  end
220
223
  klass.setup if klass.respond_to? :setup
224
+ missing = AUTHORIZATION_ADAPTER_METHODS.reject { klass.public_method_defined?(it) }
225
+ if missing.any?
226
+ raise ArgumentError, "Authorization adapter #{extension.inspect} (#{klass.name || klass.inspect}) " \
227
+ "does not publicly define #{missing.join(", ")}. See docs/UPGRADING.md for the adapter contract."
228
+ end
221
229
  klass.validate_options!(*args, **options) if klass.respond_to? :validate_options!
222
230
  @authorize = proc do
223
231
  @authorization_adapter = klass.new(*([self] + args).compact, **options, &block)
@@ -104,8 +104,12 @@ module RailsAdminNext
104
104
  {id: :desc}
105
105
  end
106
106
 
107
- def latest(count = 100)
108
- version_class
107
+ # +scopes+ maps each AbstractModel the user may list to the relation that user may see; nil
108
+ # means unrestricted. Under scopes, a version shows only while its item is in its model's
109
+ # relation, so a deleted record's versions drop out.
110
+ def latest(count = 100, scopes: nil)
111
+ versions = scopes ? versions_within(scopes) : version_class.all
112
+ versions
109
113
  .order(sort_by).includes(:item).limit(count)
110
114
  .collect { |version| VersionProxy.new(version, user_class) }
111
115
  end
@@ -122,8 +126,9 @@ module RailsAdminNext
122
126
  # do nothing
123
127
  end
124
128
 
125
- def listing_for_model(model, query, sort, sort_reverse, all, page, per_page = RailsAdminNext::Config.default_items_per_page || 20)
126
- listing_for_model_or_object(model, nil, query, sort, sort_reverse, all, page, per_page)
129
+ # +scope+ is the relation of the model's records the user may see; nil means unrestricted.
130
+ def listing_for_model(model, query, sort, sort_reverse, all, page, per_page = RailsAdminNext::Config.default_items_per_page || 20, scope: nil)
131
+ listing_for_model_or_object(model, nil, query, sort, sort_reverse, all, page, per_page, scope:)
127
132
  end
128
133
 
129
134
  def listing_for_object(model, object, query, sort, sort_reverse, all, page, per_page = RailsAdminNext::Config.default_items_per_page || 20)
@@ -133,7 +138,7 @@ module RailsAdminNext
133
138
  protected
134
139
 
135
140
  # - model - a RailsAdminNext::AbstractModel
136
- def listing_for_model_or_object(model, object, query, sort, sort_reverse, all, page, per_page)
141
+ def listing_for_model_or_object(model, object, query, sort, sort_reverse, all, page, per_page, scope: nil)
137
142
  sort =
138
143
  if sort.present?
139
144
  {COLUMN_MAPPING[sort.to_sym] => sort_reverse ? :desc : :asc}
@@ -141,7 +146,7 @@ module RailsAdminNext
141
146
  sort_by
142
147
  end
143
148
 
144
- versions = object.nil? ? versions_for_model(model) : object.public_send(model.model.versions_association_name)
149
+ versions = object.nil? ? versions_for_model(model, scope) : object.public_send(model.model.versions_association_name)
145
150
  versions = versions.where("event LIKE ?", "%#{query}%") if query.present?
146
151
  versions = versions.reorder(sort)
147
152
 
@@ -163,18 +168,29 @@ module RailsAdminNext
163
168
  RailsAdminNext::PaginatedCollection.new(proxies, current_page: page.number, per_page:, total_count: recordset.records_count)
164
169
  end
165
170
 
166
- def versions_for_model(model)
167
- model_name = model.model.name
168
- base_class_name = model.model.base_class.name
171
+ def versions_for_model(model, scope = nil)
172
+ version_class_for(model.model).where(versions_condition(model.model, scope))
173
+ end
169
174
 
170
- options =
171
- if base_class_name == model_name
172
- {item_type: model_name}
173
- else
174
- {item_type: base_class_name, item_id: model.model.all}
175
- end
175
+ def versions_condition(model, scope)
176
+ if scope
177
+ {item_type: model.base_class.name, item_id: scope.reselect(model.primary_key)}
178
+ elsif model.base_class == model
179
+ {item_type: model.name}
180
+ else
181
+ {item_type: model.base_class.name, item_id: model.all}
182
+ end
183
+ end
184
+
185
+ def versions_within(scopes)
186
+ scopes.filter_map { |abstract_model, scope|
187
+ model = abstract_model.model
188
+ version_class.where(versions_condition(model, scope)) if versioned?(model)
189
+ }.reduce(:or) || version_class.none
190
+ end
176
191
 
177
- version_class_for(model.model).where(options)
192
+ def versioned?(model)
193
+ model.respond_to?(:paper_trail_options)
178
194
  end
179
195
 
180
196
  # PT can be configured to use [custom version
@@ -6,7 +6,9 @@ module RailsAdminNext
6
6
  class CSVConverter
7
7
  BATCH_SIZE = 1000
8
8
 
9
- def initialize(objects = [], schema = nil)
9
+ # prepare_batch receives each batch of records before its rows are written.
10
+ def initialize(objects = [], schema = nil, prepare_batch: ->(batch) { batch })
11
+ @prepare_batch = prepare_batch
10
12
  @fields = []
11
13
  @associations = []
12
14
  schema ||= {}
@@ -20,7 +22,7 @@ module RailsAdminNext
20
22
  @methods = [(schema[:only] || []) + (schema[:methods] || [])].flatten.compact
21
23
  @fields = @methods.collect { |m| export_field_for(m) }.compact
22
24
  @empty = ::I18n.t("admin.export.empty_value_for_associated_objects")
23
- schema_include = schema.delete(:include) || {}
25
+ schema_include = schema[:include] || {}
24
26
 
25
27
  @associations = schema_include.each_with_object({}) do |(key, values), hash|
26
28
  association = export_field_for(key)
@@ -76,12 +78,16 @@ module RailsAdminNext
76
78
  end
77
79
 
78
80
  def each_object(&)
79
- return @objects.each(&) unless @objects.is_a?(ActiveRecord::Relation)
81
+ each_batch { @prepare_batch.call(it).each(&) }
82
+ end
83
+
84
+ def each_batch(&)
85
+ return yield(@objects.to_a) unless @objects.is_a?(ActiveRecord::Relation)
80
86
  # Batching sets its own limit and offset, which would drop the relation's.
81
- return @objects.each(&) if @objects.limit_value || @objects.offset_value
87
+ return yield(@objects.to_a) if @objects.limit_value || @objects.offset_value
82
88
 
83
89
  if (direction = primary_key_direction)
84
- @objects.unscope(:order).find_each(order: direction, batch_size: BATCH_SIZE, &)
90
+ @objects.unscope(:order).find_in_batches(order: direction, batch_size: BATCH_SIZE, &)
85
91
  else
86
92
  each_in_offset_batches(&)
87
93
  end
@@ -104,13 +110,13 @@ module RailsAdminNext
104
110
  # The primary-key tie-break makes the order total, so rows that tie on the sort
105
111
  # column cannot shift between batches. A short batch is not the last one: sorting
106
112
  # on an eager-loaded has-many column returns fewer records than the limit.
107
- def each_in_offset_batches(&)
113
+ def each_in_offset_batches
108
114
  ordered = @objects.order(Array(@model.primary_key).index_with(:asc))
109
115
  0.step(by: BATCH_SIZE) do |offset|
110
116
  batch = ordered.limit(BATCH_SIZE).offset(offset).to_a
111
117
  break if batch.empty?
112
118
 
113
- batch.each(&)
119
+ yield batch
114
120
  end
115
121
  end
116
122
 
@@ -39,7 +39,7 @@ module RailsAdminNext
39
39
  fields = @section.visible_fields
40
40
  names = field_names(fields.select { |f| !f.association? || f.association.polymorphic? })
41
41
  if @include_associations
42
- names[:include] = fields.select { |f| f.association? && !f.association.polymorphic? }.to_h do |field|
42
+ names[:include] = fields.select { |f| f.association? && !f.association.polymorphic? && f.associated_model_listable? }.to_h do |field|
43
43
  associated = field.associated_model_config.export.with(@section.bindings.merge(object: field.associated_model_config.abstract_model.model.new))
44
44
  [field.name, field_names(associated.visible_fields.reject(&:association?))]
45
45
  end
@@ -5,9 +5,9 @@ module RailsAdminNext
5
5
  # Releases are cut by publishing a Release-Drafter draft: the gem-push workflow stamps
6
6
  # the tag's version over these constants at build time, so the in-repo values are only
7
7
  # the floor a local `gem build` produces.
8
- MAJOR = 2
9
- MINOR = 2
10
- PATCH = 0
8
+ MAJOR = 3
9
+ MINOR = 0
10
+ PATCH = 1
11
11
  PRE = nil
12
12
 
13
13
  class << self
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rails_admin_next
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.0
4
+ version: 3.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daniel López Prat