iron_admin 0.7.0 → 0.8.0

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 (210) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +129 -1
  3. data/README.md +48 -1
  4. data/UPGRADING.md +495 -8
  5. data/app/assets/tailwind/iron_admin/engine.css +79 -4
  6. data/app/components/iron_admin/dashboards/activity_feed_component/item_component.html.haml +6 -9
  7. data/app/components/iron_admin/dashboards/activity_feed_component.html.haml +6 -5
  8. data/app/components/iron_admin/dashboards/activity_feed_component.rb +21 -24
  9. data/app/components/iron_admin/dashboards/chart_component.html.haml +3 -5
  10. data/app/components/iron_admin/dashboards/chart_component.rb +86 -24
  11. data/app/components/iron_admin/dashboards/concerns/themed_card.rb +39 -0
  12. data/app/components/iron_admin/dashboards/metric_card_component.html.haml +8 -7
  13. data/app/components/iron_admin/dashboards/metric_card_component.rb +2 -0
  14. data/app/components/iron_admin/dashboards/progress_component.html.haml +11 -7
  15. data/app/components/iron_admin/dashboards/progress_component.rb +11 -6
  16. data/app/components/iron_admin/dashboards/quick_links_component/link_component.html.haml +8 -9
  17. data/app/components/iron_admin/dashboards/quick_links_component.html.haml +6 -5
  18. data/app/components/iron_admin/dashboards/quick_links_component.rb +4 -12
  19. data/app/components/iron_admin/dashboards/recent_table_component.html.haml +15 -10
  20. data/app/components/iron_admin/dashboards/recent_table_component.rb +49 -0
  21. data/app/components/iron_admin/dashboards/stats_grid_component/stat_component.html.haml +13 -14
  22. data/app/components/iron_admin/dashboards/stats_grid_component.html.haml +1 -0
  23. data/app/components/iron_admin/dashboards/stats_grid_component.rb +9 -11
  24. data/app/components/iron_admin/filters/bar_component.html.haml +8 -6
  25. data/app/components/iron_admin/filters/bar_component.rb +56 -9
  26. data/app/components/iron_admin/filters/control_styles.rb +82 -0
  27. data/app/components/iron_admin/filters/date_range_component.html.haml +9 -4
  28. data/app/components/iron_admin/filters/date_range_component.rb +10 -6
  29. data/app/components/iron_admin/filters/search_component.html.haml +4 -4
  30. data/app/components/iron_admin/filters/search_component.rb +3 -5
  31. data/app/components/iron_admin/filters/select_filter_component.html.haml +1 -1
  32. data/app/components/iron_admin/filters/select_filter_component.rb +5 -16
  33. data/app/components/iron_admin/form/belongs_to_autocomplete_component.html.haml +9 -5
  34. data/app/components/iron_admin/form/belongs_to_autocomplete_component.rb +10 -8
  35. data/app/components/iron_admin/form/belongs_to_component.html.haml +2 -2
  36. data/app/components/iron_admin/form/belongs_to_component.rb +4 -18
  37. data/app/components/iron_admin/form/checkbox_component.rb +2 -3
  38. data/app/components/iron_admin/form/concerns/form_input_behavior.rb +1 -1
  39. data/app/components/iron_admin/form/control_classes.rb +108 -0
  40. data/app/components/iron_admin/form/date_picker_component.rb +3 -7
  41. data/app/components/iron_admin/form/field_wrapper_component.html.haml +3 -3
  42. data/app/components/iron_admin/form/field_wrapper_component.rb +3 -3
  43. data/app/components/iron_admin/form/nested_form_component.html.haml +4 -5
  44. data/app/components/iron_admin/form/nested_form_component.rb +12 -2
  45. data/app/components/iron_admin/form/select_component.html.haml +1 -1
  46. data/app/components/iron_admin/form/select_component.rb +2 -16
  47. data/app/components/iron_admin/form/text_input_component.rb +1 -5
  48. data/app/components/iron_admin/form/textarea_component.rb +1 -5
  49. data/app/components/iron_admin/layout/flash_component.html.haml +1 -1
  50. data/app/components/iron_admin/layout/flash_component.rb +4 -3
  51. data/app/components/iron_admin/layout/navbar_component.html.haml +15 -9
  52. data/app/components/iron_admin/layout/navbar_component.rb +29 -1
  53. data/app/components/iron_admin/layout/shell_component.html.haml +4 -4
  54. data/app/components/iron_admin/layout/shell_component.rb +16 -3
  55. data/app/components/iron_admin/layout/sidebar_component.html.haml +21 -25
  56. data/app/components/iron_admin/layout/sidebar_component.rb +76 -1
  57. data/app/components/iron_admin/layout/theme_switcher_component.html.haml +15 -0
  58. data/app/components/iron_admin/layout/theme_switcher_component.rb +74 -0
  59. data/app/components/iron_admin/resources/actions_component.html.haml +15 -8
  60. data/app/components/iron_admin/resources/actions_component.rb +34 -2
  61. data/app/components/iron_admin/resources/breadcrumb_component.html.haml +3 -3
  62. data/app/components/iron_admin/resources/breadcrumb_component.rb +8 -7
  63. data/app/components/iron_admin/resources/bulk_actions_component.html.haml +9 -8
  64. data/app/components/iron_admin/resources/bulk_actions_component.rb +47 -4
  65. data/app/components/iron_admin/resources/data_table_component.html.haml +15 -15
  66. data/app/components/iron_admin/resources/data_table_component.rb +34 -3
  67. data/app/components/iron_admin/resources/related_list_component.html.haml +7 -7
  68. data/app/components/iron_admin/resources/related_list_component.rb +26 -2
  69. data/app/components/iron_admin/resources/show_field_component.html.haml +3 -3
  70. data/app/components/iron_admin/resources/show_field_component.rb +10 -4
  71. data/app/components/iron_admin/resources/styles.rb +136 -0
  72. data/app/components/iron_admin/ui/alert_component.html.haml +2 -2
  73. data/app/components/iron_admin/ui/alert_component.rb +27 -31
  74. data/app/components/iron_admin/ui/badge_component.rb +40 -20
  75. data/app/components/iron_admin/ui/button_component.rb +37 -11
  76. data/app/components/iron_admin/ui/card_component.rb +3 -3
  77. data/app/components/iron_admin/ui/dropdown_component.html.haml +1 -1
  78. data/app/components/iron_admin/ui/dropdown_component.rb +34 -13
  79. data/app/components/iron_admin/ui/empty_state_component.html.haml +4 -5
  80. data/app/components/iron_admin/ui/empty_state_component.rb +2 -2
  81. data/app/components/iron_admin/ui/modal_component.html.haml +5 -5
  82. data/app/components/iron_admin/ui/modal_component.rb +6 -4
  83. data/app/components/iron_admin/ui/pagination_component.html.haml +14 -14
  84. data/app/components/iron_admin/ui/pagination_component.rb +26 -9
  85. data/app/components/iron_admin/ui/scopes_component.html.haml +2 -2
  86. data/app/components/iron_admin/ui/scopes_component.rb +44 -11
  87. data/app/components/iron_admin/ui/tooltip_component.rb +11 -4
  88. data/app/controllers/iron_admin/application_controller.rb +58 -4
  89. data/app/controllers/iron_admin/audit_controller.rb +30 -6
  90. data/app/controllers/iron_admin/concerns/action_executable.rb +37 -0
  91. data/app/controllers/iron_admin/concerns/assignable_references.rb +149 -0
  92. data/app/controllers/iron_admin/concerns/authorizable.rb +11 -0
  93. data/app/controllers/iron_admin/concerns/blank_password_filterable.rb +21 -0
  94. data/app/controllers/iron_admin/concerns/event_emittable.rb +47 -7
  95. data/app/controllers/iron_admin/concerns/filterable.rb +34 -9
  96. data/app/controllers/iron_admin/concerns/nested_permittable.rb +5 -3
  97. data/app/controllers/iron_admin/concerns/nested_tenant_check.rb +159 -0
  98. data/app/controllers/iron_admin/concerns/polymorphic_references.rb +131 -0
  99. data/app/controllers/iron_admin/concerns/scopeable.rb +54 -7
  100. data/app/controllers/iron_admin/concerns/searchable.rb +3 -3
  101. data/app/controllers/iron_admin/concerns/tenant_assignable.rb +118 -0
  102. data/app/controllers/iron_admin/concerns/tenant_containment.rb +146 -0
  103. data/app/controllers/iron_admin/exports_controller.rb +2 -2
  104. data/app/controllers/iron_admin/imports_controller.rb +1 -1
  105. data/app/controllers/iron_admin/resources_controller.rb +48 -41
  106. data/app/controllers/iron_admin/search_controller.rb +1 -2
  107. data/app/controllers/iron_admin/themes_controller.rb +50 -0
  108. data/app/controllers/iron_admin/tools_controller.rb +58 -5
  109. data/app/helpers/iron_admin/action_form_helper.rb +19 -0
  110. data/app/helpers/iron_admin/application_helper.rb +93 -16
  111. data/app/helpers/iron_admin/assignable_records_helper.rb +32 -0
  112. data/app/helpers/iron_admin/component_overrides_helper.rb +9 -4
  113. data/app/helpers/iron_admin/field_display_helper.rb +88 -43
  114. data/app/helpers/iron_admin/related_records_helper.rb +51 -0
  115. data/app/helpers/iron_admin/theme_helper.rb +56 -46
  116. data/app/javascript/iron_admin/controllers/cp_bulk_select_controller.js +12 -0
  117. data/app/javascript/iron_admin/controllers/cp_chart_controller.js +4 -0
  118. data/app/javascript/iron_admin/controllers/cp_disclosure_controller.js +19 -0
  119. data/app/javascript/iron_admin/controllers/cp_search_shortcut_controller.js +39 -0
  120. data/app/javascript/iron_admin/index.js +4 -0
  121. data/app/views/iron_admin/audit/index.html.haml +78 -81
  122. data/app/views/iron_admin/dashboard/index.html.haml +10 -9
  123. data/app/views/iron_admin/form/_action_field.html.haml +50 -0
  124. data/app/views/iron_admin/form/_nested_row.html.haml +18 -13
  125. data/app/views/iron_admin/imports/new.html.haml +14 -13
  126. data/app/views/iron_admin/imports/preview.html.haml +24 -21
  127. data/app/views/iron_admin/resources/_form.html.haml +70 -68
  128. data/app/views/iron_admin/resources/action_form.html.haml +16 -59
  129. data/app/views/iron_admin/resources/bulk_action_form.html.haml +20 -58
  130. data/app/views/iron_admin/resources/edit.html.haml +3 -3
  131. data/app/views/iron_admin/resources/index.html.haml +87 -74
  132. data/app/views/iron_admin/resources/new.html.haml +2 -2
  133. data/app/views/iron_admin/resources/show.html.haml +53 -41
  134. data/app/views/iron_admin/search/index.html.haml +17 -9
  135. data/app/views/iron_admin/shared/_pagination.html.haml +13 -10
  136. data/app/views/iron_admin/shared/error.html.haml +16 -12
  137. data/app/views/iron_admin/tools/action_form.html.haml +9 -55
  138. data/app/views/iron_admin/tools/show.html.haml +4 -5
  139. data/app/views/layouts/iron_admin/_document_head.html.haml +24 -0
  140. data/app/views/layouts/iron_admin/application.html.haml +4 -17
  141. data/app/views/layouts/iron_admin/minimal.html.haml +7 -0
  142. data/config/importmap.rb +2 -0
  143. data/config/locales/en.yml +23 -0
  144. data/config/routes.rb +1 -0
  145. data/docs/FAQ.md +87 -37
  146. data/docs/README.md +8 -2
  147. data/docs/components/README.md +6 -2
  148. data/docs/components/dashboard-components.md +24 -35
  149. data/docs/components/filter-components.md +44 -92
  150. data/docs/components/form-components.md +16 -32
  151. data/docs/components/resource-components.md +46 -27
  152. data/docs/components/ui-components.md +44 -26
  153. data/docs/getting-started/installation.md +5 -1
  154. data/docs/getting-started/quick-start.md +36 -23
  155. data/docs/guides/authentication.md +182 -42
  156. data/docs/guides/components.md +97 -15
  157. data/docs/guides/custom-adapters.md +24 -4
  158. data/docs/guides/dashboard.md +68 -44
  159. data/docs/guides/export.md +24 -8
  160. data/docs/guides/extending.md +206 -51
  161. data/docs/guides/fields.md +229 -70
  162. data/docs/guides/imports.md +33 -18
  163. data/docs/guides/resources.md +333 -111
  164. data/docs/guides/theming.md +930 -58
  165. data/docs/guides/troubleshooting.md +7 -3
  166. data/docs/plugin-system-design.md +8 -7
  167. data/docs/reference/configuration.md +51 -16
  168. data/docs/reference/routes.md +1 -0
  169. data/docs/reference/theme-properties.md +101 -38
  170. data/lib/generators/iron_admin/install/templates/initializer.rb.tt +7 -2
  171. data/lib/generators/iron_admin/install_audit/templates/create_iron_admin_audit_entries.rb.tt +2 -0
  172. data/lib/iron_admin/action_field.rb +11 -0
  173. data/lib/iron_admin/adapters/active_record.rb +95 -0
  174. data/lib/iron_admin/adapters/base.rb +107 -0
  175. data/lib/iron_admin/adapters/http/query.rb +21 -0
  176. data/lib/iron_admin/adapters/http.rb +84 -4
  177. data/lib/iron_admin/adapters/mongoid.rb +96 -2
  178. data/lib/iron_admin/audit_log.rb +64 -6
  179. data/lib/iron_admin/authentication_warning.rb +31 -0
  180. data/lib/iron_admin/concerns/filter_definable.rb +15 -1
  181. data/lib/iron_admin/concerns/nestable.rb +25 -0
  182. data/lib/iron_admin/concerns/scope_countable.rb +56 -0
  183. data/lib/iron_admin/concerns/soft_deletable.rb +28 -9
  184. data/lib/iron_admin/configuration/components.rb +14 -3
  185. data/lib/iron_admin/configuration/theme/neutral_defaults.rb +179 -0
  186. data/lib/iron_admin/configuration/theme.rb +292 -87
  187. data/lib/iron_admin/configuration.rb +340 -45
  188. data/lib/iron_admin/dashboard.rb +22 -38
  189. data/lib/iron_admin/engine.rb +16 -2
  190. data/lib/iron_admin/errors.rb +3 -0
  191. data/lib/iron_admin/field.rb +78 -17
  192. data/lib/iron_admin/field_inferrer.rb +61 -3
  193. data/lib/iron_admin/field_override_warning.rb +67 -0
  194. data/lib/iron_admin/import/import_preview.rb +56 -7
  195. data/lib/iron_admin/import/importer.rb +91 -14
  196. data/lib/iron_admin/import/tenant_precheck.rb +67 -0
  197. data/lib/iron_admin/plugin/registration.rb +64 -0
  198. data/lib/iron_admin/plugin_registry.rb +3 -2
  199. data/lib/iron_admin/policy.rb +22 -12
  200. data/lib/iron_admin/policy_coverage_warning.rb +46 -0
  201. data/lib/iron_admin/request_context.rb +18 -0
  202. data/lib/iron_admin/resource.rb +218 -77
  203. data/lib/iron_admin/resource_registry.rb +86 -13
  204. data/lib/iron_admin/scope_counts.rb +73 -0
  205. data/lib/iron_admin/tenant_scope.rb +30 -0
  206. data/lib/iron_admin/tool.rb +61 -12
  207. data/lib/iron_admin/tool_context.rb +10 -6
  208. data/lib/iron_admin/version.rb +1 -1
  209. data/lib/iron_admin.rb +29 -2
  210. metadata +37 -7
@@ -7,15 +7,16 @@ module IronAdmin
7
7
  # then customized via the {Resource.field} DSL. Each Field instance holds
8
8
  # the configuration for how a column/attribute should be displayed and edited.
9
9
  #
10
- # @example Field from database schema
11
- # # Automatically inferred for a string column
12
- # Field.new(:name, type: :string)
10
+ # @example Field from a string column
11
+ # # Inferred type for a string column. :string is not a field type.
12
+ # Field.new(:name, type: :text)
13
13
  #
14
14
  # @example Field with visibility control
15
- # Field.new(:salary, type: :integer, visible: ->(user) { user.hr? })
15
+ # Field.new(:salary, type: :number, visible: ->(user) { user.hr? })
16
16
  #
17
- # @example Field with multiple options
18
- # Field.new(:status, type: :select, options: %w[pending active completed])
17
+ # @example Select field
18
+ # # choices:, not options:. options: is the filter key.
19
+ # Field.new(:status, type: :select, choices: %w[pending active completed])
19
20
  #
20
21
  # @see IronAdmin::Resource.field For the DSL to configure fields
21
22
  # @see IronAdmin::FieldInferrer For automatic field inference
@@ -28,8 +29,9 @@ module IronAdmin
28
29
  # @return [Symbol] The field/column name
29
30
  attr_reader :name
30
31
 
31
- # @return [Symbol] The field type (:string, :text, :integer, :boolean,
32
- # :date, :datetime, :select, :belongs_to, etc.)
32
+ # @return [Symbol] The field type (:text, :textarea, :number, :boolean,
33
+ # :date, :datetime, :select, :belongs_to, and the other types
34
+ # {Resource.field} documents). :string and :integer are not types.
33
35
  attr_reader :type
34
36
 
35
37
  # @return [Boolean, Proc] Whether the field is visible
@@ -38,31 +40,36 @@ module IronAdmin
38
40
  # @return [Boolean, Proc] Whether the field is read-only
39
41
  attr_reader :readonly
40
42
 
41
- # @return [Hash] Additional field options (e.g., :options, :format, :autocomplete)
43
+ # @return [Hash] Additional field options (e.g., :choices, :format, :autocomplete)
42
44
  attr_reader :options
43
45
 
44
46
  # Creates a new Field instance.
45
47
  #
46
48
  # @param name [Symbol] The field/column name
47
49
  # @param options [Hash] Configuration options
48
- # @option options [Symbol] :type The field type
50
+ # @option options [Symbol] :type The field type. See {Resource.field} for the
51
+ # types the inferrer and the form actually use. :string and :integer render
52
+ # a text input.
49
53
  # @option options [Boolean, Proc] :visible Whether the field is visible
50
54
  # (default: true). If a Proc, receives the current user.
51
55
  # @option options [Boolean, Proc] :readonly Whether the field is read-only
52
56
  # (default: false). If a Proc, receives the current user.
53
- # @option options [String] :label Custom display label
54
- # @option options [Array] :options For select fields, available choices
57
+ # @option options [String] :label No effect on page labels, which humanize the
58
+ # name. Import column matching uses it as an extra header candidate.
59
+ # @option options [Array] :choices Choices for a :select field. The form reads
60
+ # :choices. :options is the filter key.
55
61
  # @option options [Boolean] :autocomplete For belongs_to, force autocomplete mode
56
- # @option options [Proc] :format Custom formatting proc for display
62
+ # @option options [String] :format strftime pattern for a :date or :datetime.
63
+ # A Proc is not called. See {Resource.field}.
57
64
  #
58
65
  # @example Basic field
59
- # Field.new(:email, type: :string)
66
+ # Field.new(:email, type: :text)
60
67
  #
61
68
  # @example Conditional visibility
62
- # Field.new(:ssn, type: :string, visible: ->(user) { user.admin? })
69
+ # Field.new(:ssn, type: :text, visible: ->(user) { user.admin? })
63
70
  #
64
- # @example Select field with options
65
- # Field.new(:priority, type: :select, options: %w[low medium high])
71
+ # @example Select field
72
+ # Field.new(:priority, type: :select, choices: %w[low medium high])
66
73
  def initialize(name, **options)
67
74
  @name = name
68
75
  @type = options.delete(:type)
@@ -100,6 +107,60 @@ module IronAdmin
100
107
  SECRET_TYPES.include?(type)
101
108
  end
102
109
 
110
+ # Returns a new field with the same name, applying +overrides+.
111
+ #
112
+ # The override's :type, :visible and :readonly win when those keys are
113
+ # present; otherwise the current raw values are kept, procs included.
114
+ # Every other key is merged into {#options}. Does not modify +self+.
115
+ #
116
+ # @param overrides [Hash]
117
+ # @return [IronAdmin::Field]
118
+ def merge(**overrides)
119
+ Field.new(
120
+ name,
121
+ type: overrides.fetch(:type, type),
122
+ visible: overrides.fetch(:visible, visible),
123
+ readonly: overrides.fetch(:readonly, readonly),
124
+ **options.merge(overrides.except(:type, :visible, :readonly))
125
+ )
126
+ end
127
+
128
+ # Whether the user must not see or probe this field.
129
+ #
130
+ # @param user [Object, nil] Current user, passed through to a visibility proc
131
+ # @return [Boolean] true when {#secret?} or the field is not visible
132
+ def concealed_from?(user)
133
+ secret? || !visible?(user)
134
+ end
135
+
136
+ # Whether the field is concealed for every user.
137
+ #
138
+ # A visibility Proc is not always concealed. {SECRET_TYPES} are.
139
+ #
140
+ # @return [Boolean]
141
+ def always_concealed?
142
+ secret? || visible == false
143
+ end
144
+
145
+ # Columns that store this field's value.
146
+ #
147
+ # +:belongs_to+ includes {#name} and +options[:foreign_key]+.
148
+ # +:polymorphic_belongs_to+ includes {#name}, +options[:type_column]+ and
149
+ # +options[:id_column]+. Other types include only {#name}. Nil entries are
150
+ # removed and every name is returned as a Symbol.
151
+ #
152
+ # @return [Array<Symbol>]
153
+ def column_names
154
+ case type
155
+ when :belongs_to
156
+ [name, options[:foreign_key]].compact.map(&:to_sym)
157
+ when :polymorphic_belongs_to
158
+ [name, options[:type_column], options[:id_column]].compact.map(&:to_sym)
159
+ else
160
+ [name.to_sym]
161
+ end
162
+ end
163
+
103
164
  private
104
165
 
105
166
  # @api private
@@ -12,6 +12,10 @@ module IronAdmin
12
12
  # - Enum column detection (generates select fields)
13
13
  # - belongs_to association detection (generates association fields)
14
14
  # - has_many/has_one shadowing (excludes columns named after associations)
15
+ # - Credential columns ({CREDENTIAL_COLUMNS}, {CREDENTIAL_PATTERN}) are
16
+ # inferred hidden and read-only, so hashes and tokens are not shown,
17
+ # searched, exported, or edited. A resource may pass visible: true to
18
+ # show one; it stays read-only unless readonly: false is passed too.
15
19
  #
16
20
  # @example Basic usage
17
21
  # fields = IronAdmin::FieldInferrer.call(User)
@@ -28,6 +32,33 @@ module IronAdmin
28
32
  # @return [Regexp]
29
33
  EMAIL_PATTERN = /\A(email|.*_email)\z/
30
34
 
35
+ # Column names that store credentials (Devise, +has_secure_password+, OTP).
36
+ # Inferred fields for these names are hidden and read-only.
37
+ #
38
+ # @return [Array<String>]
39
+ CREDENTIAL_COLUMNS = %w[
40
+ encrypted_password
41
+ password_digest
42
+ reset_password_token
43
+ confirmation_token
44
+ unlock_token
45
+ remember_token
46
+ invitation_token
47
+ authentication_token
48
+ otp_secret
49
+ encrypted_otp_secret
50
+ encrypted_otp_secret_iv
51
+ encrypted_otp_secret_salt
52
+ otp_backup_codes
53
+ ].freeze
54
+
55
+ # Custom +has_secure_password+ digest columns, for example
56
+ # +recovery_password_digest+. Does not match +password_digest+ (listed in
57
+ # {CREDENTIAL_COLUMNS}) or ordinary names such as +variation_digest+.
58
+ #
59
+ # @return [Regexp]
60
+ CREDENTIAL_PATTERN = /\A\w+_password_digest\z/
61
+
31
62
  # Maps database column types to field types.
32
63
  # @return [Hash{Symbol => Symbol}]
33
64
  TYPE_MAP = {
@@ -63,6 +94,24 @@ module IronAdmin
63
94
  new(adapter).call
64
95
  end
65
96
 
97
+ # Whether +name+ is a credential column that must stay hidden and read-only.
98
+ #
99
+ # True when +name+ is in {CREDENTIAL_COLUMNS}, or when it matches
100
+ # {CREDENTIAL_PATTERN} (a custom +has_secure_password+ attribute such as
101
+ # +recovery_password_digest+). +variation_digest+, +token_count+, and
102
+ # +api_token_expires_at+ are not credentials.
103
+ #
104
+ # @param name [String, Symbol]
105
+ # @return [Boolean]
106
+ #
107
+ # @example
108
+ # IronAdmin::FieldInferrer.credential_column?("encrypted_password") #=> true
109
+ # IronAdmin::FieldInferrer.credential_column?("variation_digest") #=> false
110
+ def self.credential_column?(name)
111
+ column_name = name.to_s
112
+ CREDENTIAL_COLUMNS.include?(column_name) || column_name.match?(CREDENTIAL_PATTERN)
113
+ end
114
+
66
115
  # Creates a new FieldInferrer for the given adapter.
67
116
  #
68
117
  # @param adapter [IronAdmin::Adapters::Base] An adapter instance
@@ -115,17 +164,26 @@ module IronAdmin
115
164
 
116
165
  # @api private
117
166
  # Builds a field from a database column.
167
+ # Credential columns stay hidden and read-only; the inferred type is kept.
118
168
  def build_field(column)
119
169
  name = column.name.to_sym
170
+ options = credential_field_options(name)
120
171
 
121
172
  if enum_column?(name)
122
- Field.new(name, type: :select, choices: @adapter.enums[name.to_s].keys)
173
+ Field.new(name, type: :select, choices: @adapter.enums[name.to_s].keys, **options)
123
174
  else
124
- type = infer_type(column)
125
- Field.new(name, type: type)
175
+ Field.new(name, type: infer_type(column), **options)
126
176
  end
127
177
  end
128
178
 
179
+ # @api private
180
+ # Options that hide a credential column. Empty for every other column.
181
+ def credential_field_options(name)
182
+ return {} unless self.class.credential_column?(name)
183
+
184
+ { visible: false, readonly: true }
185
+ end
186
+
129
187
  # @api private
130
188
  # Infers a more specific type for string columns based on naming conventions.
131
189
  def infer_type(column)
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IronAdmin
4
+ # Logs when a resource's {IronAdmin::Resource.field} overrides match no inferred field.
5
+ module FieldOverrideWarning
6
+ # Warns in development and test, once per distinct set of unresolved overrides.
7
+ #
8
+ # Each resource with unresolved names produces one warning line. The warning
9
+ # repeats only when the set of resource names and unresolved field names
10
+ # changes. A resource whose fields cannot be resolved is skipped.
11
+ #
12
+ # @param resources [Enumerable] registry entries, default {ResourceRegistry.all}
13
+ # @param env [#development?, #test?]
14
+ # @param logger [#warn]
15
+ # @return [Boolean] whether any warning was logged
16
+ def self.call(resources: ResourceRegistry.all, env: Rails.env, logger: Rails.logger)
17
+ return false unless env.development? || env.test?
18
+
19
+ signature = unresolved_signature(resources)
20
+ return false if signature == @reported_signature
21
+
22
+ @reported_signature = signature
23
+ log_warnings(signature, logger)
24
+ signature.any?
25
+ end
26
+
27
+ # Forgets the set of overrides reported by the previous {.call}.
28
+ #
29
+ # @return [void]
30
+ def self.reset!
31
+ @reported_signature = nil
32
+ end
33
+
34
+ def self.unresolved_signature(resources)
35
+ entries = resources.filter_map { |resource| unresolved_entry(resource) }
36
+ entries.sort
37
+ end
38
+
39
+ def self.unresolved_entry(resource)
40
+ names = resource.unresolved_field_overrides
41
+ return if names.empty?
42
+
43
+ [resource.name.to_s, names]
44
+ rescue StandardError
45
+ nil
46
+ end
47
+
48
+ def self.log_warnings(signature, logger)
49
+ signature.each do |resource_name, names|
50
+ logger.warn(warning_message(resource_name, names))
51
+ end
52
+ end
53
+
54
+ def self.warning_message(resource_name, names)
55
+ details = names.map { |name| warning_clause(name) }.join(" ")
56
+ "[IronAdmin] #{resource_name}: #{details}"
57
+ end
58
+
59
+ def self.warning_clause(name)
60
+ clause = "field :#{name} matches no field, so its options are ignored."
61
+ return clause unless name.to_s.end_with?("_id")
62
+
63
+ "#{clause} Foreign keys of belongs_to associations are configured under the association name."
64
+ end
65
+ private_class_method :unresolved_signature, :unresolved_entry, :log_warnings, :warning_message, :warning_clause
66
+ end
67
+ end
@@ -5,25 +5,74 @@ module IronAdmin
5
5
  Row = Struct.new(:number, :attributes, :errors, keyword_init: true) unless const_defined?(:Row)
6
6
  Error = Struct.new(:row_number, :message, keyword_init: true) unless const_defined?(:Error)
7
7
 
8
- ImportPreview = Struct.new(:total_rows, :headers, :mapping, :rows, :errors, keyword_init: true) do
9
- # Plain text for a type-cast cell value, so the preview shows what will be
10
- # imported rather than Ruby inspect output (quoted strings, "nil").
8
+ # `fields` maps each mapped field name to its {IronAdmin::Field}, so each
9
+ # cell can be formatted as the show page displays that field.
10
+ ImportPreview = Struct.new(:total_rows, :headers, :mapping, :rows, :errors, :fields, keyword_init: true) do
11
+ # Plain text for a type-cast cell value, formatted as the show page
12
+ # displays the column's field (Yes/No, date formats, currency) instead of
13
+ # Ruby output. Only the text changes: the attributes the import saves stay as cast.
11
14
  def cell_text(row, field_name)
12
15
  value = row.attributes[field_name]
16
+ return "" if value.nil?
13
17
 
18
+ field_text(value, fields.to_h[field_name]) || plain_text(value)
19
+ end
20
+
21
+ private
22
+
23
+ # @return [String, nil] nil when the field's type has no formatting for the value
24
+ def field_text(value, field)
25
+ case field&.type
26
+ when :boolean then boolean_text(value)
27
+ when :date, :datetime then field_time_text(value, field)
28
+ when :currency then currency_text(value, field)
29
+ when :badge, :radio then value.to_s.humanize
30
+ when *Field::SECRET_TYPES then "\u2022" * 8 # The show page's password mask
31
+ end
32
+ end
33
+
34
+ def plain_text(value)
14
35
  case value
15
- when nil then ""
16
36
  when Hash, Array then value.to_json
17
37
  else value.respond_to?(:strftime) ? preview_time_text(value) : value.to_s
18
38
  end
19
39
  end
20
40
 
21
- private
41
+ # The show page's labels (FieldDisplayHelper#display_boolean), with
42
+ # defaults for a locale that has none.
43
+ def boolean_text(value)
44
+ case value
45
+ when true then I18n.t("iron_admin.fields.boolean_true", default: "Yes")
46
+ when false then I18n.t("iron_admin.fields.boolean_false", default: "No")
47
+ end
48
+ end
49
+
50
+ # FieldDisplayHelper#display_date and #display_datetime: the field's
51
+ # format, or the default one.
52
+ def field_time_text(value, field)
53
+ return unless value.respond_to?(:strftime)
54
+
55
+ pattern = field.options[:format]
56
+ return preview_time_text(value, date_only: field.type == :date) unless pattern.is_a?(String)
57
+
58
+ text = value.strftime(pattern)
59
+ field.type == :datetime ? text.squish : text
60
+ end
61
+
62
+ # FieldDisplayHelper#display_currency, for a value that is a number.
63
+ def currency_text(value, field)
64
+ number = value.is_a?(Numeric) ? value : Float(value.to_s, exception: false)
65
+ return unless number
66
+
67
+ precision = field.options[:precision] || 2
68
+ amount = ActiveSupport::NumberHelper.number_to_delimited(format("%.#{precision}f", number.to_f))
69
+ "#{field.options[:symbol] || "$"}#{amount}"
70
+ end
22
71
 
23
72
  # The default formats of the show and index pages
24
73
  # (FieldDisplayHelper#display_date and #display_datetime), with no locale lookup.
25
- def preview_time_text(value)
26
- return value.strftime("%b %d, %Y") unless value.respond_to?(:hour)
74
+ def preview_time_text(value, date_only: !value.respond_to?(:hour))
75
+ return value.strftime("%b %d, %Y") if date_only
27
76
 
28
77
  value.strftime("%b %d, %Y at %l:%M %p").squish
29
78
  end
@@ -3,6 +3,8 @@
3
3
  module IronAdmin
4
4
  module Import
5
5
  class Importer
6
+ include TenantPrecheck
7
+
6
8
  PARSERS = {
7
9
  csv: Parser::Csv,
8
10
  json: Parser::Json,
@@ -31,7 +33,8 @@ module IronAdmin
31
33
  headers: headers,
32
34
  mapping: mapping,
33
35
  rows: rows,
34
- errors: rows.flat_map(&:errors)
36
+ errors: rows.flat_map(&:errors),
37
+ fields: @resource_class.importable_fields(current_user).index_by(&:name).slice(*mapping.values)
35
38
  )
36
39
  end
37
40
 
@@ -101,11 +104,11 @@ module IronAdmin
101
104
  return collect_existing_errors(row, result_state) if row.errors.any?
102
105
 
103
106
  record = find_existing_record(row.attributes)
104
- validation_errors = validate_record(record, row.attributes)
107
+ action = record ? :update : :create
108
+ validation_errors = permission_errors(action).presence || validate_record(record, row.attributes)
105
109
  return add_error_messages(row, validation_errors, result_state) if validation_errors.any?
106
110
 
107
- action = record ? :update : :create
108
- saved_record, persist_errors = persist_row(record, row.attributes)
111
+ saved_record, persist_errors = persist_inside_savepoint(record, row.attributes)
109
112
  return add_error_messages(row, persist_errors, result_state) if persist_errors.any?
110
113
 
111
114
  increment_success_count(action, result_state)
@@ -130,9 +133,7 @@ module IronAdmin
130
133
  attributes = build_attributes(raw_row, mapping)
131
134
  attributes = apply_transform(attributes)
132
135
  validation_errors = custom_validation_errors(attributes)
133
- # Validate against the record an upsert would update, as execute! does,
134
- # so a matching row is not reported as a uniqueness failure.
135
- validation_errors += validate_record(find_existing_record(attributes), attributes) if validate_model
136
+ validation_errors += row_operation_errors(attributes) if validate_model
136
137
  row_errors = validation_errors.map { |message| Error.new(row_number: row_number, message: message) }
137
138
 
138
139
  Row.new(number: row_number, attributes: attributes, errors: row_errors)
@@ -163,13 +164,33 @@ module IronAdmin
163
164
  end
164
165
 
165
166
  def validate_record(record, attributes)
166
- model_record = record || adapter.build(attributes)
167
- assign_attributes(model_record, attributes) if record
167
+ writable = record ? attributes_without_tenant(attributes) : attributes
168
+ model_record = record || adapter.build_in(IronAdmin::TenantScope.apply(adapter.all), writable)
169
+ assign_attributes(model_record, writable) if record
168
170
  return [] unless model_record.respond_to?(:valid?) && !model_record.valid?
169
171
 
170
172
  model_record.errors.full_messages
171
173
  end
172
174
 
175
+ # Validate against the record an upsert would update, as execute! does,
176
+ # so a matching row is not reported as a uniqueness failure, and check
177
+ # the permission for what the row would do.
178
+ def row_operation_errors(attributes)
179
+ existing = find_existing_record(attributes)
180
+ permission_errors(existing ? :update : :create).presence || validate_record(existing, attributes)
181
+ end
182
+
183
+ # A row that matches an existing record updates it, so it needs the
184
+ # :update permission; any other row needs :create.
185
+ #
186
+ # @param action [Symbol] :create or :update
187
+ # @return [Array<String>]
188
+ def permission_errors(action)
189
+ return [] if @resource_class.crud_allowed?(action, current_user)
190
+
191
+ [I18n.t("iron_admin.imports.errors.not_permitted.#{action}")]
192
+ end
193
+
173
194
  def custom_validation_errors(attributes)
174
195
  block = @resource_class.import_validate_block
175
196
  return [] unless block
@@ -191,20 +212,68 @@ module IronAdmin
191
212
  return nil unless lookup.size == keys.size && lookup.values.all?(&:present?)
192
213
 
193
214
  # find_by_keys is an IronAdmin adapter hook, not an ActiveRecord dynamic finder.
194
- return adapter.find_by_keys(lookup) unless IronAdmin.configuration.tenant_scope_block # rubocop:disable Rails/DynamicFindBy
215
+ return adapter.find_by_keys(lookup) unless IronAdmin::TenantScope.configured? # rubocop:disable Rails/DynamicFindBy
195
216
 
196
217
  scoped_existing_record(lookup)
197
218
  end
198
219
 
199
220
  def scoped_existing_record(lookup)
200
- scope = adapter.all
201
- scope = IronAdmin.configuration.tenant_scope_block.call(scope) if IronAdmin.configuration.tenant_scope_block
221
+ scope = IronAdmin::TenantScope.apply(adapter.all)
202
222
 
203
223
  lookup.reduce(scope) do |current_scope, (key, value)|
204
224
  adapter.filter(current_scope, key, value)
205
225
  end.first
206
226
  end
207
227
 
228
+ # Persists one row and keeps it inside the tenant.
229
+ #
230
+ # Transactional adapters use a savepoint and roll that savepoint back
231
+ # when the saved record is outside the tenant. Adapters that cannot roll
232
+ # back are checked in memory first. Anything other than an exact +true+
233
+ # rejects the row and writes nothing. Other rows in the import stay.
234
+ #
235
+ # @param record [Object, nil] existing row to update, or +nil+ to create
236
+ # @param attributes [Hash] cast attributes for the row
237
+ # @return [Array(Object, Array<String>)] the saved record and its errors
238
+ def persist_inside_savepoint(record, attributes)
239
+ blocked = unverified_import_message(record, attributes)
240
+ return [nil, [blocked]] if blocked
241
+
242
+ saved_record = nil
243
+ messages = []
244
+ outside_tenant = false
245
+
246
+ adapter.savepoint do
247
+ adapter.wrap_rollback do
248
+ saved_record, messages = persist_row(record, attributes)
249
+ outside_tenant = messages.empty? && !imported_record_in_tenant?(saved_record)
250
+ raise IronAdmin::Rollback if outside_tenant
251
+ end
252
+ end
253
+
254
+ messages = [I18n.t("iron_admin.imports.errors.outside_tenant")] if outside_tenant
255
+ [saved_record, messages]
256
+ end
257
+
258
+ # @param record [Object, nil]
259
+ # @return [Boolean] +true+ when no tenant scope is configured or the record is inside it
260
+ def imported_record_in_tenant?(record)
261
+ return true unless IronAdmin::TenantScope.configured?
262
+ return false if record.nil?
263
+
264
+ scope = IronAdmin::TenantScope.apply(adapter.all)
265
+ !scoped_record(scope, record).nil?
266
+ end
267
+
268
+ # @param scope [Object]
269
+ # @param record [Object]
270
+ # @return [Object, nil]
271
+ def scoped_record(scope, record)
272
+ Array(adapter.primary_key).reduce(scope) do |current, column|
273
+ adapter.filter(current, column.to_sym, record.public_send(column))
274
+ end.first
275
+ end
276
+
208
277
  # A save can fail without errors, for example when a model callback
209
278
  # throws :abort or an HTTP adapter cannot reach the API, so the save
210
279
  # itself is checked too.
@@ -212,9 +281,10 @@ module IronAdmin
212
281
  # @return [Array(Object, Array<String>)] The saved record and its errors
213
282
  def persist_row(record, attributes)
214
283
  if record
215
- saved = adapter.update_record(record, attributes)
284
+ saved = adapter.update_record(record, attributes_without_tenant(attributes))
216
285
  else
217
- record = adapter.create_record(attributes)
286
+ record = adapter.build_in(IronAdmin::TenantScope.apply(adapter.all), attributes)
287
+ adapter.save(record)
218
288
  saved = !record.respond_to?(:persisted?) || record.persisted?
219
289
  end
220
290
  [record, saved ? [] : save_failure_messages(record)]
@@ -231,6 +301,13 @@ module IronAdmin
231
301
  record.errors.full_messages
232
302
  end
233
303
 
304
+ # Tenant columns are not writable on an existing row.
305
+ def attributes_without_tenant(attributes)
306
+ protected_keys = adapter.scope_attributes(IronAdmin::TenantScope.apply(adapter.all)).keys.map(&:to_s)
307
+ removable = attributes.keys.select { |name| protected_keys.include?(name.to_s) }
308
+ attributes.except(*removable)
309
+ end
310
+
234
311
  def assign_attributes(record, attributes)
235
312
  if record.respond_to?(:assign_attributes)
236
313
  record.assign_attributes(attributes)
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IronAdmin
4
+ module Import
5
+ # In-memory tenant check used when an import adapter cannot roll back.
6
+ module TenantPrecheck
7
+ private
8
+
9
+ # Error for a non-transactional adapter when the row is not proven in-tenant.
10
+ #
11
+ # Returns +nil+ when the row may be written: the adapter can roll back,
12
+ # no tenant scope is configured, or {#import_candidate_verdict} is +true+.
13
+ #
14
+ # @param record [Object, nil]
15
+ # @param attributes [Hash]
16
+ # @return [String, nil]
17
+ def unverified_import_message(record, attributes)
18
+ return nil if adapter.supports_transactions?
19
+ return nil unless IronAdmin::TenantScope.configured?
20
+
21
+ verdict = import_candidate_verdict(record, attributes)
22
+ return nil if verdict == true
23
+
24
+ I18n.t(import_tenant_error_key(verdict))
25
+ end
26
+
27
+ # Translates {IronAdmin::Adapters::Base#scope_match} for existing import callers.
28
+ #
29
+ # @param record [Object, nil]
30
+ # @param attributes [Hash]
31
+ # @return [Boolean, nil] +true+ for +:inside+, +false+ for +:outside+, +nil+ for +:unknown+
32
+ def import_candidate_verdict(record, attributes)
33
+ scope = IronAdmin::TenantScope.apply(adapter.all)
34
+ candidate = import_candidate(record, attributes, scope)
35
+ return nil if candidate.nil?
36
+
37
+ case adapter.scope_match(scope, candidate)
38
+ when :inside then true
39
+ when :outside then false
40
+ end
41
+ end
42
+
43
+ # Candidate from the attributes {#persist_row} will write.
44
+ #
45
+ # An update is previewed with tenant columns removed, the same hash
46
+ # validation and +update_record+ use. A create is built from the row
47
+ # attributes +build_in+ receives.
48
+ #
49
+ # @param record [Object, nil]
50
+ # @param attributes [Hash]
51
+ # @param scope [Object]
52
+ # @return [Object, nil]
53
+ def import_candidate(record, attributes, scope)
54
+ return adapter.preview(record, attributes_without_tenant(attributes)) if record
55
+
56
+ adapter.build_in(scope, attributes)
57
+ end
58
+
59
+ # @param verdict [Boolean, nil]
60
+ # @return [String]
61
+ def import_tenant_error_key(verdict)
62
+ name = verdict.nil? ? "tenant_unverifiable" : "outside_tenant"
63
+ "iron_admin.imports.errors.#{name}"
64
+ end
65
+ end
66
+ end
67
+ end