studio-engine 0.137.0 → 0.139.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -0
  3. data/README.md +86 -1
  4. data/app/assets/tailwind/studio_engine/engine.css +235 -0
  5. data/app/controllers/concerns/studio/connection_flow.rb +1 -1
  6. data/app/controllers/sessions_controller.rb +12 -3
  7. data/app/controllers/studio/integrations_controller.rb +43 -0
  8. data/app/controllers/studio/local_reviews_controller.rb +12 -0
  9. data/app/javascript/studio/carousel.js +109 -0
  10. data/app/javascript/studio/controllers/carousel_captions_controller.js +42 -0
  11. data/app/javascript/studio/controllers/carousel_controller.js +243 -1
  12. data/app/javascript/studio/stimulus.js +3 -1
  13. data/app/models/concerns/studio/account.rb +143 -0
  14. data/app/models/concerns/studio/omniauth_user.rb +9 -17
  15. data/app/models/error_log.rb +14 -5
  16. data/app/views/studio/_carousel.html.erb +74 -14
  17. data/app/views/studio/integrations/_card.html.erb +50 -0
  18. data/app/views/studio/integrations/index.html.erb +22 -0
  19. data/app/views/studio/integrations/show.html.erb +24 -0
  20. data/app/views/style/_tricks.html.erb +38 -0
  21. data/config/studio_tricks.yml +7 -0
  22. data/db/migrate/20261006120001_ensure_error_logs_table.rb +3 -1
  23. data/db/migrate/20261006120002_ensure_theme_settings_table.rb +3 -2
  24. data/db/migrate/20261108160000_require_slugs_on_engine_tables.rb +119 -0
  25. data/db/migrate/20261108160001_add_engine_state_checks.rb +94 -0
  26. data/db/migrate/20261108170000_add_users_role_known_check.rb +69 -0
  27. data/lib/generators/studio/connections/connections_generator.rb +10 -0
  28. data/lib/studio/connections.rb +53 -12
  29. data/lib/studio/integrations/egnyte.rb +69 -0
  30. data/lib/studio/integrations/microsoft_365.rb +63 -0
  31. data/lib/studio/integrations/quickbooks.rb +86 -0
  32. data/lib/studio/integrations.rb +265 -0
  33. data/lib/studio/node_tooling/README.md +9 -1
  34. data/lib/studio/node_tooling/e2e_helpers.js +93 -1
  35. data/lib/studio/node_tooling/playwright_base.js +51 -4
  36. data/lib/studio/roles.rb +17 -0
  37. data/lib/studio/version.rb +1 -1
  38. data/lib/studio.rb +59 -1
  39. metadata +16 -2
@@ -0,0 +1,42 @@
1
+ // carousel-captions: one caption under a carousel that follows its open slide (the
2
+ // image-only pattern, README "The carousel"). A caption inside each slide would ride
3
+ // a cascade's 3D move, so the captions live outside the row: one per item, in item
4
+ // order, laid in one grid cell, and this marks the open slide's caption data-current
5
+ // and hides the rest from assistive tech (aria-hidden). The page styles the cross-fade.
6
+ //
7
+ // <div data-studio-controller="carousel-captions">
8
+ // <%= render layout: "studio/carousel", ... %>
9
+ // <div data-carousel-captions-target="caption" data-current>first</div>
10
+ // <div data-carousel-captions-target="caption" aria-hidden="true">second</div>
11
+ // </div>
12
+ //
13
+ // It listens for the carousel's change event (studio/carousel CHANGE_EVENT), which
14
+ // bubbles from the region inside it, so it needs no observer and no timer. The server
15
+ // marks the caption of the slide the row opens on. A lazy controller (studio/stimulus):
16
+ // a page with no caption stage fetches nothing; one whose controller failed keeps the
17
+ // server's caption.
18
+ import { Controller } from "@hotwired/stimulus"
19
+ import { CHANGE_EVENT } from "studio/carousel"
20
+
21
+ export default class extends Controller {
22
+ static targets = ["caption"]
23
+
24
+ connect() {
25
+ this.follow = (event) => this.show(event.detail?.index)
26
+ this.element.addEventListener(CHANGE_EVENT, this.follow)
27
+ }
28
+
29
+ disconnect() {
30
+ this.element.removeEventListener(CHANGE_EVENT, this.follow)
31
+ }
32
+
33
+ show(index) {
34
+ if (!Number.isInteger(index) || index < 0 || index >= this.captionTargets.length) return
35
+ this.captionTargets.forEach((caption, at) => {
36
+ const open = at === index
37
+ caption.toggleAttribute("data-current", open)
38
+ if (open) caption.removeAttribute("aria-hidden")
39
+ else caption.setAttribute("aria-hidden", "true")
40
+ })
41
+ }
42
+ }
@@ -49,9 +49,33 @@
49
49
  // The pause button (WCAG 2.2.2) stops it until pressed again; under reduced motion
50
50
  // the row starts stopped. A move by autoplay writes nothing to the status line
51
51
  // (APG: a rotating carousel does not announce). Without loop it stops at the end.
52
+ //
53
+ // A CASCADE row (class carousel-cascade) does not scroll. Its slides share one grid
54
+ // cell and each wears data-cascade-step, its place from the open slide (cascadeStep,
55
+ // cascadeSlot); engine.css lays the 3D stack out from it and transitions it. The
56
+ // open slide carries data-current. Every slide is a stop, so the arrows, dots, keys
57
+ // and autoplay move it as they move a spotlight, through the same move() and
58
+ // scrollToStop(). A swipe or a drag (pointer events, past DRAG_THRESHOLD) moves it
59
+ // too; a click on a side slide brings that slide to the front and follows no link,
60
+ // and keyboard focus landing in a side slide in view does the same. TAB: a slide past
61
+ // the window is hidden, so Tab skips it. Tab from the track lands on the first slide
62
+ // in view and brings it to the front, and each Tab after moves one slide on. A cascade
63
+ // that does not loop and opens mid-row (the default :middle) has slides before the
64
+ // window that forward Tab never reaches: Shift+Tab from the first slide in view (its
65
+ // focus has moved the stack, so the slide before it is in view), Home, the arrow keys,
66
+ // the Previous arrow and the dots reach them. A looping cascade takes no clones: the
67
+ // steps wrap round the set, and a slide that crosses the stack round the seam
68
+ // (cascadeJumps) takes no glide but fades in, every time. A focused slide that leaves
69
+ // the window hands focus to the track, so the keys keep working.
70
+ //
71
+ // THE CHANGE EVENT (studio/carousel CHANGE_EVENT, "studio:carousel:change"): every
72
+ // style dispatches it from the region, bubbling, once per change of the open slide,
73
+ // after data-current has moved (announceChange). detail: { index, previous, slide,
74
+ // total }. A host follows the open slide with it instead of observing data-current.
52
75
  import { Controller } from "@hotwired/stimulus"
53
76
  import {
54
- CLONE_STRIP, TOLERANCE, autoplayRunning, autoplaySeconds, autoplayStop, centerStops, cloneCount, cloneLayout,
77
+ CHANGE_EVENT, CLONE_STRIP, TOLERANCE, autoplayRunning, changeDetail, clickedSlide, autoplaySeconds, autoplayStop, cascadeJumps, cascadeReach, cascadeSlot,
78
+ cascadeStep, cascadeSteps, cascadeTarget, centerStops, cloneCount, cloneLayout, dragSteps,
55
79
  currentStop, hiddenEnds, idleDelay, initialReasons, keyAction, loopPositionText, loopStop, nearestVirtual, ownsKey,
56
80
  perPage, positionText, seamJump, startStop, stops, targetStop, toggleLabel, withReason, wrapIndex
57
81
  } from "studio/carousel"
@@ -66,8 +90,13 @@ export default class extends Controller {
66
90
  this.settle = this.settle.bind(this)
67
91
  this.clickClone = this.clickClone.bind(this)
68
92
  this.loop = this.element.hasAttribute("data-carousel-loop")
93
+ this.cascade = this.element.classList.contains("carousel-cascade")
69
94
  this.cloned = 0
70
95
  this.removeClones()
96
+ if (this.cascade) {
97
+ this.connectCascade()
98
+ return
99
+ }
71
100
  this.scrollEnd = "onscrollend" in window
72
101
  this.trackTarget.addEventListener("scroll", this.schedule, { passive: true })
73
102
  if (this.scrollEnd) this.trackTarget.addEventListener("scrollend", this.settle, { passive: true })
@@ -77,12 +106,211 @@ export default class extends Controller {
77
106
  this.observer.observe(this.trackTarget)
78
107
  }
79
108
  this.element.setAttribute("data-carousel-ready", "")
109
+ // The first paint's slide: the change event fires only when the open slide leaves it.
110
+ this.opened = Math.max(0, Number(this.element.dataset.carouselStart) || 0)
80
111
  this.openAtStart()
81
112
  this.addClones()
82
113
  this.sync()
83
114
  this.startAutoplay()
84
115
  }
85
116
 
117
+ // -- the cascade --------------------------------------------------------------
118
+
119
+ connectCascade() {
120
+ const slides = this.slideTargets
121
+ const marked = slides.findIndex((slide) => slide.hasAttribute("data-current"))
122
+ this.active = marked >= 0 ? marked : 0
123
+ this.opened = this.active
124
+ // A #fragment inside a slide opens on that slide.
125
+ const hash = window.location?.hash
126
+ if (hash && hash.length > 1) {
127
+ let target = null
128
+ try { target = document.getElementById(decodeURIComponent(hash.slice(1))) } catch { target = null }
129
+ const index = target ? slides.findIndex((slide) => slide.contains(target)) : -1
130
+ if (index >= 0) this.active = index
131
+ }
132
+ this.cascadeListeners = [
133
+ ["pointerdown", (event) => this.dragStart(event)],
134
+ ["pointermove", (event) => this.dragMove(event)],
135
+ ["pointerup", (event) => this.dragEnd(event)],
136
+ ["pointercancel", () => { this.pressed = null; this.dragCancel() }],
137
+ ["click", (event) => this.clickSide(event), true],
138
+ ["focusin", (event) => this.focusSide(event)],
139
+ ["dragstart", (event) => event.preventDefault()]
140
+ ]
141
+ this.cascadeListeners.forEach(([type, handler, capture]) => this.trackTarget.addEventListener(type, handler, { capture: !!capture }))
142
+ if (typeof ResizeObserver === "function") {
143
+ this.observer = new ResizeObserver(this.schedule)
144
+ this.observer.observe(this.trackTarget)
145
+ }
146
+ this.element.setAttribute("data-carousel-ready", "")
147
+ this.sync()
148
+ this.startAutoplay()
149
+ }
150
+
151
+ disconnectCascade() {
152
+ this.cascadeListeners?.forEach(([type, handler, capture]) => this.trackTarget.removeEventListener(type, handler, { capture: !!capture }))
153
+ this.cascadeListeners = null
154
+ this.dragCancel()
155
+ }
156
+
157
+ // The reach CSS lays out: 1 on a three-slide cascade or a narrow region, else 2.
158
+ reach() {
159
+ const css = parseFloat(getComputedStyle(this.trackTarget).getPropertyValue("--carousel-cascade-reach"))
160
+ return css > 0 ? css : cascadeReach(this.element.dataset.carouselVisible)
161
+ }
162
+
163
+ syncCascade() {
164
+ const total = this.slideTargets.length
165
+ this.page = 1
166
+ this.positions = Array.from({ length: Math.max(1, total) }, (_, index) => index)
167
+ this.full = null
168
+ this.active = Math.min(Math.max(0, this.active || 0), Math.max(0, total - 1))
169
+ this.current = this.virtual = this.active
170
+ this.element.toggleAttribute("data-carousel-static", total < 2)
171
+ const wraps = this.loop && total > 1
172
+ if (this.hasPrevTarget) this.prevTarget.setAttribute("aria-disabled", String(!wraps && this.active === 0))
173
+ if (this.hasNextTarget) this.nextTarget.setAttribute("aria-disabled", String(!wraps && this.active >= total - 1))
174
+ const steps = cascadeSteps(total, this.active, this.loop)
175
+ const jumps = this.laid ? cascadeJumps(this.laid, steps, this.active) : steps.map(() => false)
176
+ // A jumping slide's fade replays only if the style saw it without the mark first.
177
+ // It may still wear the mark from its last jump (Next then Previous round the
178
+ // seam), or have lost it earlier in this same task (move() syncs before it moves),
179
+ // which the style never saw: drop the mark, settle the style, then set it.
180
+ if (jumps.some(Boolean)) {
181
+ this.slideTargets.forEach((slide, index) => { if (jumps[index]) slide.removeAttribute("data-cascade-jump") })
182
+ void this.trackTarget.offsetWidth
183
+ }
184
+ this.slideTargets.forEach((slide, index) => {
185
+ slide.setAttribute("data-cascade-step", cascadeSlot(steps[index]))
186
+ slide.toggleAttribute("data-cascade-jump", jumps[index])
187
+ slide.toggleAttribute("data-current", index === this.active)
188
+ })
189
+ this.laid = steps
190
+ this.dotTargets.forEach((dot, index) => {
191
+ dot.hidden = index >= total
192
+ if (index === this.active) dot.setAttribute("aria-current", "true")
193
+ else dot.removeAttribute("aria-current")
194
+ })
195
+ this.announceChange(this.active)
196
+ }
197
+
198
+ // THE CHANGE EVENT (studio/carousel CHANGE_EVENT): once per change of the open
199
+ // slide, after data-current has moved, bubbling from the region.
200
+ announceChange(index) {
201
+ const detail = changeDetail(this.opened, index, this.slideTargets)
202
+ if (!detail) return
203
+ this.opened = index
204
+ this.element.dispatchEvent(new CustomEvent(CHANGE_EVENT, { bubbles: true, detail }))
205
+ }
206
+
207
+ // Brings slide `index` to the front. A focused slide that leaves the window hands
208
+ // focus to the track (a hidden slide cannot hold it), so the keys keep working.
209
+ activate(index) {
210
+ const total = this.slideTargets.length
211
+ if (!(total > 0)) return
212
+ this.active = Math.min(total - 1, Math.max(0, index))
213
+ this.sync()
214
+ const focused = this.slideTargets.findIndex((slide) => slide.contains(document.activeElement))
215
+ if (focused >= 0 && Math.abs(cascadeStep(focused, this.active, total, this.loop)) > this.reach()) {
216
+ this.trackTarget.focus({ preventScroll: true })
217
+ }
218
+ }
219
+
220
+ slideAt(target) {
221
+ const slide = target?.closest?.(".carousel-slide")
222
+ return slide && this.trackTarget.contains(slide) ? this.slideTargets.indexOf(slide) : -1
223
+ }
224
+
225
+ // A press on a side slide: the click that follows brings it to the front and opens
226
+ // nothing. The slide is read at the press, so a link whose focus already moved the
227
+ // stack still counts as a side slide's. A click with no press (event.detail 0:
228
+ // Enter or Space on a focused link) is read where it lands (clickedSlide), so a
229
+ // press released off the track leaves nothing behind for Enter on the open card.
230
+ clickSide(event) {
231
+ if (this.dragged) {
232
+ this.dragged = false
233
+ event.preventDefault()
234
+ event.stopPropagation()
235
+ return
236
+ }
237
+ const index = clickedSlide(this.pressed, event.detail, this.slideAt(event.target))
238
+ this.pressed = null
239
+ if (index < 0 || index === this.active) return
240
+ event.preventDefault()
241
+ event.stopPropagation()
242
+ this.interacted()
243
+ this.scrollToStop(index)
244
+ }
245
+
246
+ // Keyboard focus in a side slide brings it to the front, so Tab moves one slide on
247
+ // from the first slide in view (see TAB above for the slides before the window). A
248
+ // mouse press focuses without :focus-visible and leaves the move to its click.
249
+ focusSide(event) {
250
+ const index = this.slideAt(event.target)
251
+ if (index < 0 || index === this.active) return
252
+ let keyboard = true
253
+ try { keyboard = event.target.matches(":focus-visible") } catch { keyboard = true }
254
+ if (!keyboard) return
255
+ this.interacted()
256
+ this.scrollToStop(index, { announce: false })
257
+ }
258
+
259
+ // A press released off the track sends no pointerup here, so its record is stale:
260
+ // the next press of the same pointer replaces it. A second finger is ignored.
261
+ dragStart(event) {
262
+ if (event.button > 0 || (this.drag && this.drag.id !== event.pointerId)) return
263
+ const index = this.slideAt(event.target)
264
+ this.pressed = index >= 0 && index !== this.active ? index : null
265
+ this.dragged = false
266
+ this.drag = { id: event.pointerId, x: event.clientX, y: event.clientY, live: false }
267
+ }
268
+
269
+ dragMove(event) {
270
+ const drag = this.drag
271
+ if (!drag || event.pointerId !== drag.id) return
272
+ const dx = event.clientX - drag.x
273
+ if (!drag.live) {
274
+ if (Math.abs(dx) < 8 || Math.abs(dx) < Math.abs(event.clientY - drag.y)) return
275
+ drag.live = true
276
+ // Captured only once it is a drag, so a plain click still lands on its link.
277
+ try { this.trackTarget.setPointerCapture(drag.id) } catch { /* the pointer is gone */ }
278
+ this.element.setAttribute("data-carousel-dragging", "")
279
+ }
280
+ this.trackTarget.style.setProperty("--carousel-cascade-drag", `${Math.round(dx * 0.35)}px`)
281
+ }
282
+
283
+ dragEnd(event) {
284
+ const drag = this.drag
285
+ if (!drag || event.pointerId !== drag.id) return
286
+ const live = drag.live
287
+ this.dragCancel()
288
+ if (!live) return
289
+ const by = dragSteps(event.clientX - drag.x, this.stepWidth())
290
+ this.pressed = null
291
+ this.dragged = true
292
+ // The click a drag ends in is swallowed by clickSide; a touch drag fires none.
293
+ setTimeout(() => { this.dragged = false }, 0)
294
+ if (by === 0) return
295
+ this.interacted()
296
+ const total = this.slideTargets.length
297
+ const to = cascadeTarget(this.active, by, total, this.loop)
298
+ if (to !== this.active) this.scrollToStop(to)
299
+ }
300
+
301
+ dragCancel() {
302
+ this.drag = null
303
+ this.element?.removeAttribute("data-carousel-dragging")
304
+ this.trackTarget?.style.removeProperty("--carousel-cascade-drag")
305
+ }
306
+
307
+ // The width a drag crosses per step: the open slide's, or a fifth of the row.
308
+ stepWidth() {
309
+ const open = this.slideTargets[this.active]
310
+ const width = open ? open.getBoundingClientRect().width : 0
311
+ return width > 0 ? width * 0.6 : this.trackTarget.clientWidth / 5
312
+ }
313
+
86
314
  openAtStart() {
87
315
  const start = Number(this.element.dataset.carouselStart)
88
316
  if (!(start > 0)) return
@@ -101,6 +329,7 @@ export default class extends Controller {
101
329
  }
102
330
 
103
331
  disconnect() {
332
+ if (this.cascade) this.disconnectCascade()
104
333
  this.trackTarget.removeEventListener("scroll", this.schedule)
105
334
  this.trackTarget.removeEventListener("scrollend", this.settle)
106
335
  this.trackTarget.removeEventListener("click", this.clickClone)
@@ -332,6 +561,10 @@ export default class extends Controller {
332
561
  }
333
562
 
334
563
  sync() {
564
+ if (this.cascade) {
565
+ this.syncCascade()
566
+ return
567
+ }
335
568
  const track = this.trackTarget
336
569
  const { positions, page } = this.measure()
337
570
  const ends = hiddenEnds(track)
@@ -368,6 +601,9 @@ export default class extends Controller {
368
601
  if (index === this.current) dot.setAttribute("aria-current", "true")
369
602
  else dot.removeAttribute("aria-current")
370
603
  })
604
+ // A looping row resting on a copy is on its way home (settle): it announces the
605
+ // real slide once it lands there, so the slide the event names carries the mark.
606
+ if (!this.cloned || this.virtual === this.current) this.announceChange(this.current)
371
607
  }
372
608
 
373
609
  prev() { this.move("prev") }
@@ -412,6 +648,12 @@ export default class extends Controller {
412
648
  // row the index is virtual: a clone's place glides there and settle() jumps home,
413
649
  // but under reduced motion the row goes straight to the real slide.
414
650
  scrollToStop(index, { announce = true } = {}) {
651
+ if (this.cascade) {
652
+ if (!(index >= 0 && index < this.slideTargets.length)) return
653
+ this.activate(index)
654
+ if (announce && this.hasStatusTarget) this.statusTarget.textContent = positionText(index, 1, this.slideTargets.length)
655
+ return
656
+ }
415
657
  const reduce = window.matchMedia?.(REDUCE).matches
416
658
  if (this.cloned) {
417
659
  const total = this.positions.length
@@ -71,7 +71,8 @@ export const schema = {
71
71
  // So is the page header: its tabs are links, and a row whose controller failed
72
72
  // keeps its bar at all times (data-studio-controller-failed="page-header").
73
73
  // So is the carousel: its track is a native scroll row, and one whose controller
74
- // failed keeps a scrollbar and hides the arrows and dots it cannot drive.
74
+ // failed keeps a scrollbar and hides the arrows and dots it cannot drive. So are
75
+ // the carousel's captions: a stage whose controller failed keeps the server's caption.
75
76
  // So is infinite scroll: a list whose controller failed keeps its "Load more"
76
77
  // link, which loads the next page by itself. So is pull to refresh: nothing
77
78
  // depends on it, and the browser's own reload still works.
@@ -93,6 +94,7 @@ export const LAZY = {
93
94
  "copy-text": () => import("studio/controllers/copy_text_controller"),
94
95
  "page-header": () => import("studio/controllers/page_header_controller"),
95
96
  "carousel": () => import("studio/controllers/carousel_controller"),
97
+ "carousel-captions": () => import("studio/controllers/carousel_captions_controller"),
96
98
  "infinite-scroll": () => import("studio/controllers/infinite_scroll_controller"),
97
99
  "pull-to-refresh": () => import("studio/controllers/pull_to_refresh_controller")
98
100
  }
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Studio
4
+ # The engine-owned account contract (database audit 2026-11-07, section 3,
5
+ # "Recommended primitive: Studio::Account"). One copy of the rules nine apps
6
+ # typed by hand:
7
+ #
8
+ # class User < ApplicationRecord
9
+ # include Studio::Account
10
+ # studio_roles %w[viewer admin] # optional: narrow, never widen
11
+ #
12
+ # def name_slug = name.to_s.parameterize # Sluggable's, the host's own
13
+ # end
14
+ #
15
+ # It gives the host:
16
+ #
17
+ # * `admin?` (role "admin") and a default `display_name`;
18
+ # * `normalizes :email`: stripped, downcased, and a blank address stored as
19
+ # NULL, so "" and " " never collide on the unique index or match a lookup;
20
+ # * `validates :role, inclusion:` against Studio::Roles, or the host's
21
+ # narrower list, with the default role filled on create;
22
+ # * Sluggable and Studio::OmniauthUser (the engine's Google find-or-create,
23
+ # with its race rescue);
24
+ # * one safe email lookup, `User.account_for_email(address)` and, for code
25
+ # that holds a model class rather than including this,
26
+ # `Studio::Account.find_by_email(User, address)`.
27
+ #
28
+ # THE NAME. The audit named the concern Studio::User. It cannot be: inside
29
+ # `module Studio`, a bare `User` resolves to Studio::User before ::User, and
30
+ # the engine reads the host's User bare in Studio::ErrorHandling#current_user,
31
+ # Studio::LinkConsumption and Studio::LocalReviewsController. A Studio::User
32
+ # constant would hand those the concern instead of the model.
33
+ # test/integration/studio_account_test.rb holds that line.
34
+ #
35
+ # THE LOOKUP RULE (the account-takeover class the hub and Turf fixed on
36
+ # 2026-11-08). `find_by(email: nil)` matches ANY account without an email:
37
+ # every wallet and guest sign-up. So a blank address finds nobody, the match
38
+ # is case-insensitive (`LOWER(email)`), and a lookup that LINKS a Google
39
+ # identity to the account it finds takes Google's verification first.
40
+ module Account
41
+ extend ActiveSupport::Concern
42
+
43
+ included do
44
+ include Sluggable
45
+ include Studio::OmniauthUser
46
+
47
+ class_attribute :studio_role_list, instance_writer: false, default: Studio::Roles
48
+
49
+ normalizes :email, with: ->(address) { Studio::Account.normalize_email(address) }
50
+
51
+ before_validation :studio_fill_default_role, on: :create
52
+ validates :role, inclusion: { in: ->(record) { record.class.studio_role_list } },
53
+ if: -> { has_attribute?(:role) }
54
+ end
55
+
56
+ class_methods do
57
+ # Narrows the roles this app accepts. Every one must be in Studio::Roles:
58
+ # a host cannot invent a role the engine does not know.
59
+ def studio_roles(list)
60
+ roles = Array(list).map(&:to_s).uniq
61
+ raise ArgumentError, "studio_roles needs at least one role" if roles.empty?
62
+
63
+ unknown = roles - Studio::Roles
64
+ if unknown.any?
65
+ raise ArgumentError, "studio_roles may only narrow Studio::Roles (#{Studio::Roles.join(', ')}); " \
66
+ "unknown: #{unknown.join(', ')}. Add a role to the engine, for every app."
67
+ end
68
+
69
+ self.studio_role_list = roles.freeze
70
+ end
71
+
72
+ # The role a new account takes: viewer, or the first of a list without it.
73
+ def studio_default_role
74
+ studio_role_list.include?(Studio::DEFAULT_ROLE) ? Studio::DEFAULT_ROLE : studio_role_list.first
75
+ end
76
+
77
+ # The account holding this address, or nil. A blank address finds nobody.
78
+ def account_for_email(address)
79
+ Studio::Account.find_by_email(self, address)
80
+ end
81
+ end
82
+
83
+ class << self
84
+ # " Mia@Example.COM " -> "mia@example.com"; blank -> nil.
85
+ def normalize_email(value)
86
+ email = value.to_s.strip.downcase
87
+ email.empty? ? nil : email
88
+ end
89
+
90
+ # The one safe lookup by address, for any model with an `email` column.
91
+ # Blank finds nobody; the compare is LOWER(email), so a row stored before
92
+ # `normalizes` still matches.
93
+ def find_by_email(model, address)
94
+ email = normalize_email(address)
95
+ return nil if email.nil?
96
+ return nil unless model.respond_to?(:attribute_names) && model.attribute_names.include?("email")
97
+
98
+ model.where(model.arel_table[:email].lower.eq(email)).first
99
+ end
100
+
101
+ # The account a lost race left behind: a concurrent sign-in made the row
102
+ # this one collided with. The Google id always identifies it; the address
103
+ # only when Google verified it, because an unverified address proves
104
+ # nothing about who holds the mailbox. Nobody found: the collision is
105
+ # logged with ErrorLog.capture! and the answer is nil, never a stranger.
106
+ def race_winner(model, provider:, uid:, email: nil, email_verified: false, error: nil)
107
+ found = model.find_by(provider: provider, uid: uid) if provider.present? && uid.present?
108
+ found ||= find_by_email(model, email) if email_verified
109
+ return found if found
110
+
111
+ log_unmatched_race(error)
112
+ nil
113
+ end
114
+
115
+ private
116
+
117
+ def log_unmatched_race(error)
118
+ return unless error
119
+
120
+ Rails.logger.warn("[studio account] sign-in collided with nobody to find: #{error.class}: #{error.message.to_s[0, 300]}")
121
+ ErrorLog.capture!(error) if defined?(::ErrorLog) && ::ErrorLog.respond_to?(:capture!)
122
+ rescue StandardError => e
123
+ Rails.logger.warn("[studio account] could not log the collision: #{e.class}")
124
+ end
125
+ end
126
+
127
+ def admin?
128
+ role.to_s == "admin"
129
+ end
130
+
131
+ def display_name
132
+ try(:name).presence || try(:email).to_s.split("@").first.presence || "User"
133
+ end
134
+
135
+ private
136
+
137
+ def studio_fill_default_role
138
+ return unless has_attribute?(:role) && role.blank?
139
+
140
+ self.role = self.class.studio_default_role
141
+ end
142
+ end
143
+ end
@@ -69,15 +69,14 @@ module Studio
69
69
  create_with_free_slug(model, attributes, email_verified: email_verified)
70
70
  end
71
71
 
72
+ # Kept under these names for callers that predate Studio::Account, which
73
+ # now owns the one safe lookup: a blank address finds nobody.
72
74
  def normalize_email(value)
73
- email = value.to_s.strip.downcase
74
- email.empty? ? nil : email
75
+ Studio::Account.normalize_email(value)
75
76
  end
76
77
 
77
78
  def find_by_email(model, email)
78
- return nil unless column?(model, "email")
79
-
80
- model.where(model.arel_table[:email].lower.eq(email)).first
79
+ Studio::Account.find_by_email(model, email)
81
80
  end
82
81
 
83
82
  private
@@ -99,13 +98,15 @@ module Studio
99
98
  # verified it, the same rule as step 2 above. An unverified address
100
99
  # that collides with someone else's row hands that row to nobody.
101
100
  found = model.find_by(provider: assignable[:provider], uid: assignable[:uid])
102
- found ||= find_by_email(model, assignable[:email]) if email_verified && assignable[:email]
101
+ found ||= find_by_email(model, assignable[:email]) if email_verified
103
102
  return found if found
104
103
  end
105
104
  end
106
105
 
107
- log_unmatched_collision(last_error)
108
- nil
106
+ # Nobody to find on either attempt: Studio::Account.race_winner logs it.
107
+ Studio::Account.race_winner(model, provider: attributes[:provider], uid: attributes[:uid],
108
+ email: attributes[:email], email_verified: email_verified,
109
+ error: last_error)
109
110
  end
110
111
 
111
112
  def slug_needs_fallback?(model, record)
@@ -126,15 +127,6 @@ module Studio
126
127
  record.define_singleton_method(:name_slug) { id ? "user-#{id}" : "user-#{token}" }
127
128
  end
128
129
 
129
- def log_unmatched_collision(error)
130
- return unless error
131
-
132
- Rails.logger.warn("[omniauth] Google sign-in collided with nobody to find: #{error.class}: #{error.message.to_s[0, 300]}")
133
- ErrorLog.capture!(error) if defined?(::ErrorLog) && ::ErrorLog.respond_to?(:capture!)
134
- rescue StandardError => e
135
- Rails.logger.warn("[omniauth] could not log the collision: #{e.class}")
136
- end
137
-
138
130
  def column?(model, name)
139
131
  model.respond_to?(:attribute_names) && model.attribute_names.include?(name)
140
132
  end
@@ -1,11 +1,13 @@
1
1
  class ErrorLog < ApplicationRecord
2
+ # `slug` is NOT NULL and unique (RequireSlugsOnEngineTables), so every insert
3
+ # carries one, including a host's bare `ErrorLog.create!`. Sluggable writes a
4
+ # unique placeholder before the insert and settles it to `error-log-<id>` right
5
+ # after, inside the create, once the id exists.
6
+ include Sluggable
7
+
2
8
  belongs_to :target, polymorphic: true, optional: true
3
9
  belongs_to :parent, polymorphic: true, optional: true
4
10
 
5
- def to_param
6
- slug
7
- end
8
-
9
11
  def inspect_field
10
12
  read_attribute(:inspect)
11
13
  end
@@ -25,7 +27,6 @@ class ErrorLog < ApplicationRecord
25
27
  inspect: safe_inspect,
26
28
  backtrace: cleaned.to_json
27
29
  )
28
- log.update_column(:slug, "error-log-#{log.id}")
29
30
 
30
31
  # Fan out to Sentry if the host app loaded sentry-ruby. Guard with
31
32
  # respond_to? so we don't blow up on old SDK versions. The DB ErrorLog
@@ -42,4 +43,12 @@ class ErrorLog < ApplicationRecord
42
43
 
43
44
  log
44
45
  end
46
+
47
+ private
48
+
49
+ # The id does not exist before the insert, so the first call returns a unique
50
+ # placeholder; Sluggable calls it again after the insert.
51
+ def name_slug
52
+ id ? "error-log-#{id}" : "error-log-new-#{SecureRandom.hex(8)}"
53
+ end
45
54
  end