skadi 0.4.0.beta.5 → 1.0.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.
@@ -1 +1 @@
1
- var e=[],t=[],n=-1,r,i,a=!1,o={},s=window,c=document,l={...c.currentScript.dataset},u=()=>{r??=setTimeout(d,500)},d=()=>{r&&=(clearTimeout(r),null),navigator.sendBeacon(l.endpoint,new Blob([JSON.stringify({view:l.view,demographics:e,events:t,consent:o,...a&&{exit_page:i}})],{type:`application/json`}))&&(e=[],t=[],o={})},f=(e,t)=>{if(e<=0)return null;if(e<t[0])return`< ${t[0]}ms`;for(let n=1;n<t.length;n++)if(e<=t[n])return`${t[n-1]}ms to ${t[n]}ms`;return`> ${t[3]}ms`},p=(t,n,r=!1)=>{if(n===null)return;let i={name:t,value:n.toString()};r&&(i.uri=l.uri),e.push(i)};new PerformanceObserver(e=>{let t=e.getEntries().at(-1);t&&(n=t.startTime)}).observe({type:`largest-contentful-paint`,buffered:!0}),new PerformanceObserver((e,t)=>{let n=e.getEntriesByName(`first-contentful-paint`)[0];n&&(p(`FCP`,f(n.startTime,[1e3,1800,3e3,4500]),!0),t.disconnect())}).observe({type:`paint`,buffered:!0}),s.addEventListener(`load`,()=>{l.visit===`1`&&(p(`Timezone`,Intl.DateTimeFormat().resolvedOptions().timeZone),p(`Locale`,Intl.NumberFormat().resolvedOptions().locale),p(`Screen size`,`${s.innerWidth}x${s.innerHeight}`),p(`Input device`,s.matchMedia(`(pointer: fine)`).matches?`mouse`:`touch`)),u()}),c.addEventListener(`click`,e=>{let t=e.target?.closest(`a`);t?.href&&(t.target===`_blank`||e.ctrlKey||e.metaKey||(i=t.href))}),s.addEventListener(`pagehide`,()=>{p(`LCP`,f(n,[1500,2500,4e3,6e3]),!0),a=!0,d()}),s.addEventListener(`visibilitychange`,()=>{r&&d()}),s.skadi={event:(e,n={})=>{t.push({name:e,properties:n}),u()},demographic:(e,t,n=!1)=>{p(e,t,n),u()},consent:e=>{o=e,d()}};
1
+ var e=[],t=[],n=-1,r,i,a,o,s,c=window,l=document,u=c.addEventListener,d=()=>{a=l.querySelector(`meta[name=skadi]`)?.dataset??{}};d();var f=()=>{r??=setTimeout(p,500)},p=(n=!1)=>{r&&=(clearTimeout(r),null),!(!a.view&&!s)&&navigator.sendBeacon(a.endpoint,new Blob([JSON.stringify({view:a.view,user:a.user,demographics:e,events:t,consent:s,...n&&{exit_page:i}})],{type:`application/json`}))&&(e=[],t=[],s=void 0)},m=e=>e>0?`${Math.ceil(e/100)*100}ms`:null,h=(t,n,r=!1)=>{if(!a.view||n===null)return;let i={name:t,value:n.toString()};r&&(i.uri=a.uri),e.push(i)},g=new PerformanceObserver(e=>{for(let t of e.getEntries())t.entryType===`paint`?t.name===`first-contentful-paint`&&h(`FCP`,m(t.startTime),!0):n=t.startTime}),_=e=>g.observe({type:e,buffered:!0});_(`paint`),_(`largest-contentful-paint`),u(`load`,f),u(`turbo:load`,()=>{if(!o){o=!0;return}p(!0),i=void 0,d(),f()}),l.addEventListener(`click`,e=>{let t=e.target?.closest(`a`);t?.href&&(t.target===`_blank`||e.ctrlKey||e.metaKey||(i=t.href))}),u(`pagehide`,()=>{o||h(`LCP`,m(n),!0),p(!0)}),u(`visibilitychange`,()=>{r&&p()}),c.skadi={event:(e,n={},r)=>{a.view&&(t.push({name:e,properties:n,sensitive:r}),f())},demographic:(e,t,n)=>{h(e,t,n),f()},consent:e=>{s=e,p()}};
@@ -0,0 +1 @@
1
+ window.addEventListener(`load`,()=>{let e=window.skadi;e?.demographic(`Timezone`,Intl.DateTimeFormat().resolvedOptions().timeZone),e?.demographic(`Locale`,Intl.NumberFormat().resolvedOptions().locale),e?.demographic(`Screen size`,`${window.innerWidth}x${window.innerHeight}`),e?.demographic(`Input device`,window.matchMedia(`(pointer: fine)`).matches?`mouse`:`touch`)});
@@ -8,6 +8,10 @@ module Skadi
8
8
  serve_built_asset("skadi.js")
9
9
  end
10
10
 
11
+ def visit_tracking_script
12
+ serve_built_asset("skadiVisit.js")
13
+ end
14
+
11
15
  def dashboard_js
12
16
  serve_built_asset("dashboard.js")
13
17
  end
@@ -4,13 +4,21 @@ module Skadi
4
4
 
5
5
  do_not_track! if defined?(do_not_track!)
6
6
 
7
- before_action :set_dashboard
8
- before_action :set_dashboard_permissions
7
+ before_action :forbidden!, only: %i[index show], unless: :can_view
8
+ before_action -> { head :forbidden }, except: %i[index show], unless: :can_view
9
9
 
10
- def show
11
- return head :forbidden unless can_view
10
+ before_action :set_dashboard, only: %i[show data update destroy]
11
+ before_action :set_dashboard_permissions, only: %i[show data update destroy]
12
+
13
+ def index
14
+ dashboards = Skadi::Dashboard.order(:name).to_a
15
+
16
+ render :index, locals: { dashboards:, can_edit: }
17
+ end
12
18
 
19
+ def show
13
20
  render :show, locals: {
21
+ dashboard: @dashboard,
14
22
  dashboard_configuration: @dashboard.configuration,
15
23
  dataset_schema: Skadi::Schema.frontend_schema,
16
24
  can_edit: can_edit,
@@ -19,9 +27,8 @@ module Skadi
19
27
  end
20
28
 
21
29
  def data
22
- return head :forbidden unless can_view
23
-
24
- query_filters = params.permit(:date_from, :date_to, :page)
30
+ # slice before permit so host apps that raise on unpermitted parameters don't reject the other keys in the request
31
+ query_filters = params.slice(:date_from, :date_to, :page).permit(:date_from, :date_to, :page)
25
32
 
26
33
  if can_edit && params[:configuration].present?
27
34
  return custom_chart_data(query_filters)
@@ -35,23 +42,58 @@ module Skadi
35
42
  rescue ActiveRecord::StatementInvalid => e
36
43
  message = can_dangerously_use_sql ? e.message : "Something went wrong fetching the data. Please contact a site admin."
37
44
  render json: { error: message }, status: :unprocessable_content
45
+ rescue ActiveRecord::ReadOnlyError
46
+ render json: { error: "Dashboard queries are read only." }, status: :unprocessable_content
38
47
  rescue Skadi::Dashboard::Error => e
39
48
  render json: { error: e.message }, status: :unprocessable_content
40
49
  end
41
50
 
42
51
  def update
43
- return head :forbidden unless can_view && can_edit
52
+ return head :forbidden unless can_edit
44
53
 
45
- # The dashboard validator will strongly check the structure of :configuration
46
- @dashboard.configuration = params.to_unsafe_h[:configuration]
54
+ expected_updated_at = parse_timestamp(params[:updated_at])
55
+ if expected_updated_at.nil?
56
+ return render json: { error: "The updated_at parameter must be a valid timestamp" }, status: :unprocessable_content
57
+ end
47
58
 
48
- if @dashboard.save
49
- head :ok
50
- else
51
- render json: { error: "Dashboard validation failed. #{@dashboard.errors.full_messages.join("\n")}" }, status: :unprocessable_content
59
+ # Locking reloads the dashboard so the timestamp check and save can't interleave with another editor's save
60
+ @dashboard.with_lock do
61
+ if @dashboard.updated_at_timestamp != Skadi::Dashboard.timestamp(expected_updated_at)
62
+ render json: {
63
+ error: "This dashboard has been changed by someone else since it was loaded.",
64
+ updated_at: @dashboard.updated_at_timestamp,
65
+ }, status: :conflict
66
+ next
67
+ end
68
+
69
+ @dashboard.assign_attributes(params.slice(:name, :description).permit(:name, :description))
70
+ # The dashboard validator will strongly check the structure of :configuration
71
+ @dashboard.configuration = params.to_unsafe_h[:configuration]
72
+
73
+ if @dashboard.save
74
+ render json: { updated_at: @dashboard.updated_at_timestamp }
75
+ else
76
+ render json: { error: "Dashboard validation failed. #{@dashboard.errors.full_messages.join("\n")}" }, status: :unprocessable_content
77
+ end
52
78
  end
53
79
  end
54
80
 
81
+ def create
82
+ return head :forbidden unless can_edit
83
+
84
+ dashboard = Skadi::Dashboard.create!(name: "New dashboard", configuration: Skadi::Dashboard.blank_configuration)
85
+
86
+ redirect_to dashboard_path(dashboard)
87
+ end
88
+
89
+ def destroy
90
+ return head :forbidden unless can_edit
91
+
92
+ @dashboard.destroy!
93
+
94
+ head :ok
95
+ end
96
+
55
97
  private def custom_chart_data(query_filters)
56
98
  # The dashboard validator will strongly check the structure of :configuration
57
99
  chart_configuration = params[:configuration].to_unsafe_h
@@ -68,7 +110,27 @@ module Skadi
68
110
  end
69
111
 
70
112
  private def set_dashboard
71
- @dashboard = Skadi::Dashboard.first_or_create!(name: "Default dashboard", configuration: Skadi::Dashboard.default_configuration)
113
+ @dashboard = Skadi::Dashboard.find(params[:id])
114
+ end
115
+
116
+ private def parse_timestamp(value)
117
+ return nil unless value.is_a?(String)
118
+
119
+ return Time.iso8601(value)
120
+ rescue ArgumentError
121
+ return nil
122
+ end
123
+
124
+ # Responds to a user who cannot view the dashboard, using the configured method (e.g. a redirect to a login page) when there is one
125
+ private def forbidden!
126
+ forbidden_method = Skadi.configuration.dashboard_forbidden_method
127
+ if forbidden_method.present? && respond_to?(forbidden_method, true)
128
+ send(forbidden_method)
129
+
130
+ return if performed?
131
+ end
132
+
133
+ head :forbidden
72
134
  end
73
135
 
74
136
  private def set_dashboard_permissions
@@ -7,18 +7,26 @@ module Skadi
7
7
 
8
8
  prepend_before_action :limit_payload_size!
9
9
 
10
- rate_limit to: 60, within: 1.minute, with: -> { head :too_many_requests }
10
+ # The configuration is read once, when this class is loaded, so the rate limit must be set in an initializer
11
+ if (rate_limit_to = Skadi.configuration.tracking_rate_limit)
12
+ rate_limit to: rate_limit_to, within: Skadi.configuration.tracking_rate_limit_period, with: -> { head :too_many_requests }
13
+ end
11
14
 
12
15
  before_action :set_params
13
16
  before_action :set_view
14
17
 
15
18
  def track
19
+ if @params["user"].is_a?(String)
20
+ user_id = Rails.application.message_verifier(:skadi).verified(@params["user"], purpose: :consent)
21
+ end
22
+ handle_consent @params["consent"], user_id
23
+
24
+ return head :no_content unless skadi.view
25
+
16
26
  if @params["exit_page"].present? && @params["exit_page"].is_a?(String)
17
27
  @view.exit_page = Skadi::Url.redact_and_normalise_url(@params["exit_page"], request: request)
18
28
  end
19
29
 
20
- handle_consent @params["consent"]
21
-
22
30
  if @params["events"].present? && @params["events"].is_a?(Array)
23
31
  handle_events @params["events"]
24
32
  end
@@ -47,33 +55,28 @@ module Skadi
47
55
  private def set_view
48
56
  # Check that the view token is a valid UUID
49
57
  unless @params["view"].is_a?(String) && @params["view"].length == 36
50
- return head :bad_request
58
+ return
51
59
  end
52
60
 
53
61
  @view = Skadi::View.includes(:visit).find_by(view_token: @params["view"])
54
62
 
55
- return head :not_found unless @view
63
+ return unless @view
56
64
 
57
- return head :gone unless @view.created_at > Time.current - Skadi.configuration.visit_duration
65
+ return unless @view.created_at > Time.current - Skadi.configuration.visit_duration
58
66
 
59
67
  # We're not using _prepare to generate the view/visit, so we have to set them manually
60
68
  skadi._attach(view: @view, visit: @view.visit)
61
69
  end
62
70
 
63
- private def handle_consent(consent)
71
+ private def handle_consent(consent, user_id = nil)
64
72
  return unless consent.is_a?(Hash)
65
73
 
66
- if consent["cookie"] == true || consent["cookie"] == false
67
- skadi.cookie_consent!(consent["cookie"])
68
- end
69
-
70
- if consent["anonymity_set"] == true || consent["anonymity_set"] == false
71
- skadi.anonymity_set_consent!(consent["anonymity_set"])
72
- end
73
-
74
- if consent["user"] == true || consent["user"] == false
75
- skadi.user_consent!(consent["user"])
76
- end
74
+ skadi.consent(
75
+ anonymity_set: consent["anonymity_set"],
76
+ cookie: consent["cookie"],
77
+ user: consent["user"],
78
+ user_id:,
79
+ )
77
80
  end
78
81
 
79
82
  private def handle_events(events)
@@ -82,7 +85,7 @@ module Skadi
82
85
  next unless event["name"].is_a?(String) && event["name"].present?
83
86
  next unless event["properties"].is_a?(Hash)
84
87
 
85
- skadi.event(event["name"], event["properties"])
88
+ skadi.event(event["name"], event["properties"], sensitive: event["sensitive"] == true)
86
89
  end
87
90
  end
88
91
 
@@ -3,36 +3,65 @@ module Skadi
3
3
  class InvalidSkadiTagType < StandardError; end
4
4
 
5
5
  mattr_accessor :skadi_script_src
6
+ mattr_accessor :skadi_visit_script_src
6
7
 
7
8
  def skadi_tag(type = :inline)
8
- return if skadi.do_not_track? || skadi.view.nil?
9
-
10
- tag_attributes = {
11
- data: {
12
- uri: request.route_uri_pattern,
13
- endpoint: Skadi::Engine.routes.url_helpers.tracking_endpoint_path,
14
- view: skadi.view.token,
15
- },
16
- nonce: content_security_policy_nonce,
17
- }
18
- tag_attributes[:data][:visit] = "1" if skadi.new_visit?
19
-
20
- case type
9
+ script_tag = case type
21
10
  when :route
22
- content_tag("script", "", {
11
+ skadi_script = content_tag("script", "", {
23
12
  src: Skadi::Engine.routes.url_helpers.tracking_script_path(v: Skadi::VERSION),
24
- **tag_attributes,
13
+ nonce: content_security_policy_nonce,
25
14
  })
15
+
16
+ if skadi.new_visit?
17
+ skadi_visit_script = content_tag("script", "", {
18
+ src: Skadi::Engine.routes.url_helpers.visit_tracking_script_path(v: Skadi::VERSION),
19
+ nonce: content_security_policy_nonce,
20
+ })
21
+ end
22
+
23
+ skadi_script + skadi_visit_script
26
24
  when :inline
27
25
  self.skadi_script_src ||= Engine.root.join("app", "assets", "builds", "skadi.js").read.html_safe
28
- content_tag(
26
+
27
+ skadi_script = content_tag(
29
28
  "script",
30
29
  skadi_script_src,
31
- tag_attributes,
30
+ nonce: content_security_policy_nonce,
32
31
  )
32
+
33
+ if skadi.new_visit?
34
+ self.skadi_visit_script_src ||= Engine.root.join("app", "assets", "builds", "skadiVisit.js").read.html_safe
35
+ skadi_visit_script = content_tag(
36
+ "script",
37
+ skadi_visit_script_src,
38
+ nonce: content_security_policy_nonce,
39
+ )
40
+ end
41
+
42
+ skadi_script + skadi_visit_script
33
43
  else
34
44
  raise InvalidSkadiTagType.new("Invalid type given to skadi_tag. Expecting :route, :inline, but got :#{type}.")
35
45
  end
46
+
47
+ meta_data = {
48
+ uri: request.route_uri_pattern&.delete_suffix("(.:format)"),
49
+ endpoint: Skadi::Engine.routes.url_helpers.tracking_endpoint_path,
50
+ view: skadi.view&.token,
51
+ }
52
+
53
+ if skadi.view.nil? || skadi.visit&.user_id.nil?
54
+ # We need to include the user_id in do_not_track pages because the tracking controller can't derive it
55
+ user_id = skadi.visit&.user_id || skadi.logged_in_user&.id
56
+
57
+ if user_id
58
+ meta_data[:user] = Rails.application.message_verifier(:skadi).generate(user_id, purpose: :consent, expires_in: 1.day)
59
+ end
60
+ end
61
+
62
+ meta_tag = tag.meta(name: "skadi", data: meta_data)
63
+
64
+ return meta_tag + script_tag
36
65
  end
37
66
  end
38
67
  end
@@ -1,5 +1,7 @@
1
1
  module Skadi
2
2
  class ApplicationRecord < ::ActiveRecord::Base
3
3
  self.abstract_class = true
4
+
5
+ ActiveSupport.run_load_hooks(:skadi_application_record, self)
4
6
  end
5
7
  end
@@ -6,6 +6,7 @@ module Skadi
6
6
  class UnsupportedOperatorError < Error; end
7
7
  class DatasetConfigurationError < Error; end
8
8
 
9
+ validates :name, presence: true
9
10
  validates_with DashboardValidator
10
11
 
11
12
  # Used by the validator to prevent the unauthorised use of SQL, while allowing existing charts that use SQL to be duplicated.
@@ -42,6 +43,17 @@ module Skadi
42
43
 
43
44
  def self.default_configuration = DEFAULT_CONFIGURATION.deep_dup
44
45
 
46
+ # The configuration for a newly created dashboard: a single tab with no charts
47
+ def self.blank_configuration
48
+ [ { "id" => SecureRandom.uuid, "title" => "Tab 1", "children" => [] } ]
49
+ end
50
+
51
+ # Formats a time for comparing dashboard versions. Microseconds are kept so that saves within the same second are distinguishable.
52
+ def self.timestamp(time) = time.utc.iso8601(6)
53
+
54
+ # Sent to the frontend and back on each save, so a save based on an outdated version can be rejected
55
+ def updated_at_timestamp = self.class.timestamp(updated_at)
56
+
45
57
  def chart_data(chart_id, filters)
46
58
  chart_configuration = find_chart_by_id(chart_id) unless chart_id.nil?
47
59
 
@@ -26,7 +26,8 @@ module Skadi
26
26
  result = {
27
27
  data: [],
28
28
  }
29
- Skadi::ApplicationRecord.connection.transaction do
29
+ connection = Skadi::DashboardRecord.connection
30
+ connection.transaction do
30
31
  if chart["type"] == "table"
31
32
  # Note that the page starts with 1
32
33
  page = if untrusted_param_filters["page"].is_a?(Integer) && untrusted_param_filters["page"] > 0
@@ -38,7 +39,7 @@ module Skadi
38
39
  # We cannot union more than one query when selecting multiple fields for the table dataset so just take the first one as a precaution
39
40
  query = queries.first
40
41
 
41
- result[:resultCount] = Skadi::Visit.connection.select_one("
42
+ result[:resultCount] = connection.select_one("
42
43
  SELECT COUNT(*) as count FROM (#{query}) q
43
44
  ")["count"]
44
45
 
@@ -48,12 +49,12 @@ module Skadi
48
49
 
49
50
  result[:resultOffset] = offset
50
51
 
51
- result[:data] = Skadi::Visit.connection.select_all("
52
+ result[:data] = connection.select_all("
52
53
  SELECT * FROM (#{query}) q LIMIT #{limit} OFFSET #{offset}
53
54
  ")
54
55
  else
55
- result[:data] = Skadi::ApplicationRecord.connection.unprepared_statement do
56
- Skadi::Visit.connection.select_all("
56
+ result[:data] = connection.unprepared_statement do
57
+ connection.select_all("
57
58
  SELECT
58
59
  *
59
60
  FROM
@@ -71,6 +72,17 @@ module Skadi
71
72
  end
72
73
 
73
74
  private def build_sql_query(dataset, chart, untrusted_param_filters)
75
+ # The table chart can display arbitrary data so we allow any columns
76
+ if chart["type"] == "table"
77
+ # We still wrap in a subquery to prevent data modification
78
+ return "
79
+ SELECT
80
+ *
81
+ FROM
82
+ (#{dataset["sql"]}) AS t
83
+ "
84
+ end
85
+
74
86
  model = Skadi::Visit
75
87
 
76
88
  safe_group = [ "t.split" ]
@@ -0,0 +1,10 @@
1
+ module Skadi
2
+ # Holds the connection used to run dashboard queries. It has no tables of its own: the dashboard builds its SQL with the
3
+ # other models and only executes it here. It shares Skadi::ApplicationRecord's connection unless
4
+ # Skadi.configuration.dashboard_database is set, in which case the engine connects it to that database.
5
+ class DashboardRecord < ApplicationRecord
6
+ self.abstract_class = true
7
+
8
+ ActiveSupport.run_load_hooks(:skadi_dashboard_record, self)
9
+ end
10
+ end
@@ -137,10 +137,10 @@ module Skadi
137
137
  return @types
138
138
  end
139
139
 
140
- Context = Struct.new(:record, :allowed_sql_strings, :dataset_ids)
140
+ Context = Struct.new(:record, :allowed_sql_strings, :dataset_ids, :chart_type)
141
141
 
142
142
  def validate(record)
143
- context = Context.new(record, nil, [])
143
+ context = Context.new(record, nil, [], nil)
144
144
 
145
145
  validate_type(ArrayOf.new(:DashboardTabConfig, 1), record.configuration, "configuration", context:)
146
146
  end
@@ -262,7 +262,7 @@ module Skadi
262
262
  return add_error(path, "must be a string", context:)
263
263
  end
264
264
 
265
- unless [ "date", "split", "count" ].all? { |it| value.include?(it) }
265
+ unless context.chart_type == "table" || [ "date", "split", "count" ].all? { |it| value.include?(it) }
266
266
  add_error(path, "must include the fields date, split and count", context:)
267
267
  end
268
268
  end
@@ -283,7 +283,7 @@ module Skadi
283
283
  table, _ = field.split(".", 2)
284
284
 
285
285
  # Ensure that the relevant table is joined
286
- if !value["belongs_to"]&.key?(table)
286
+ if !value["belongs_to"].is_a?(Hash) || !value["belongs_to"].key?(table)
287
287
  add_error("#{path}.selects[#{index}]", "#{field.inspect} requires a join with the #{table} table", context:)
288
288
  end
289
289
  end
@@ -297,7 +297,7 @@ module Skadi
297
297
 
298
298
  # Early return if the count is defined or is a foreign key on the current dataset
299
299
  schema = Schema.database_schema[value["type"].to_sym]
300
- return if schema[:counts]&.key?(count_by) || schema[:belongs_to]&.key?(count_by)
300
+ return if schema.nil? || schema[:counts]&.key?(count_by) || schema[:belongs_to]&.key?(count_by)
301
301
 
302
302
  # Find the table that has the given count as one of its counts
303
303
  owner = schema[:belongs_to]&.keys&.find do |table|
@@ -314,6 +314,8 @@ module Skadi
314
314
  return add_error(path, "Unknown type #{type.inspect}", context:) unless self.class.types.key?(type)
315
315
 
316
316
  if type == :ChartConfig && value.is_a?(Hash)
317
+ context.chart_type = value["type"]
318
+
317
319
  context.dataset_ids = []
318
320
 
319
321
  if value["datasets"].is_a?(Array)
@@ -48,7 +48,7 @@ module Skadi
48
48
  tracked: {
49
49
  **SELECT_FILTER_AND_SPLIT,
50
50
  type: :boolean,
51
- sql: "(skadi_visits.tracking_token IS NOT NULL)",
51
+ sql: "(skadi_visits.tracking_token IS NOT NULL OR skadi_visits.user_id IS NOT NULL)",
52
52
  description: "Whether the visit is tracked across multiple views and events using a cookie or anonymity set.",
53
53
  },
54
54
  cookies_enabled: {
@@ -32,11 +32,7 @@ module Skadi
32
32
  # @param user [ActiveModel::Model, nil]
33
33
  # @param request [ActionDispatch::Request]
34
34
  # @return [Skadi::Visit]
35
- def self.build_from(tracking_token, user_id = nil, request = nil, cookies_enabled: nil)
36
- if cookies_enabled.nil?
37
- cookies_enabled = request&.cookie_jar&.key?("skadi_id") || false
38
- end
39
-
35
+ def self.build_from(tracking_token, user_id = nil, request = nil, cookies_enabled:)
40
36
  new(
41
37
  visit_token: SecureRandom.uuid_v7,
42
38
  tracking_token: tracking_token,
@@ -55,5 +51,7 @@ module Skadi
55
51
  cookies_enabled: cookies_enabled,
56
52
  )
57
53
  end
54
+
55
+ ActiveSupport.run_load_hooks(:skadi_visit, self)
58
56
  end
59
57
  end
@@ -0,0 +1,33 @@
1
+ <%# locals: (dashboards:, can_edit:) %>
2
+
3
+ <% content_for :head do %>
4
+ <%= stylesheet_link_tag "#{Skadi::Engine.routes.url_helpers.dashboard_css_path}?#{Skadi::VERSION}",
5
+ media: "all",
6
+ nonce: true
7
+ %>
8
+ <% end %>
9
+
10
+ <%= render "layout" do %>
11
+ <main class="w-full max-w-192 mx-auto flex flex-col gap-4 p-4">
12
+ <h1 class="text-night-950 text-xl font-semibold">Skadi Analytics Dashboards</h1>
13
+
14
+ <% if dashboards.empty? %>
15
+ <p class="text-gray-600">There are no dashboards yet.</p>
16
+ <% else %>
17
+ <ul class="flex flex-col gap-2">
18
+ <% dashboards.each do |dashboard| %>
19
+ <li class="bg-white border border-night-50 p-4">
20
+ <a href="<%= dashboard_path(dashboard) %>" class="text-night-700 font-semibold"><%= dashboard.name %></a>
21
+ <% if dashboard.description.present? %>
22
+ <p class="whitespace-pre-wrap text-gray-600"><%= dashboard.description %></p>
23
+ <% end %>
24
+ </li>
25
+ <% end %>
26
+ </ul>
27
+ <% end %>
28
+
29
+ <% if can_edit %>
30
+ <%= button_to "New dashboard", dashboards_path, class: "w-max" %>
31
+ <% end %>
32
+ </main>
33
+ <% end %>
@@ -1,16 +1,26 @@
1
- <%# locals: (dashboard_configuration:, dataset_schema:, can_edit:, can_dangerously_use_sql:) %>
1
+ <%# locals: (dashboard:, dashboard_configuration:, dataset_schema:, can_edit:, can_dangerously_use_sql:) %>
2
2
 
3
3
  <% content_for :head do %>
4
- <%= stylesheet_link_tag "#{Skadi::Engine.routes.url_helpers.dashboard_css_path}?#{Skadi::VERSION}", media: "all" %>
4
+ <%= stylesheet_link_tag "#{Skadi::Engine.routes.url_helpers.dashboard_css_path}?#{Skadi::VERSION}",
5
+ media: "all",
6
+ nonce: true
7
+ %>
5
8
  <%= javascript_include_tag "#{Skadi::Engine.routes.url_helpers.dashboard_js_path}?#{Skadi::VERSION}",
6
9
  data: {
7
10
  "dashboard-config": dashboard_configuration.to_json,
11
+ "dashboard-name": dashboard.name,
12
+ "dashboard-description": dashboard.description.to_s,
13
+ "dashboard-updated-at": dashboard.updated_at_timestamp,
8
14
  "dataset-schema": dataset_schema.to_json,
9
15
  "can-edit": can_edit ? "true" : "false",
10
16
  "can-dangerously-use-sql": can_dangerously_use_sql ? "true" : "false",
11
- "fetch-data-path": dashboard_data_path,
12
- "update-dashboard-path": dashboard_update_path,
13
- } %>
17
+ "fetch-data-path": dashboard_data_path(dashboard),
18
+ "update-dashboard-path": dashboard_update_path(dashboard),
19
+ "delete-dashboard-path": dashboard_path(dashboard),
20
+ "dashboards-index-path": root_path,
21
+ },
22
+ nonce: true
23
+ %>
14
24
  <% end %>
15
25
 
16
26
  <%= render "layout" do %>
data/config/routes.rb CHANGED
@@ -1,14 +1,17 @@
1
1
  Skadi::Engine.routes.draw do
2
- root to: "dashboard#show"
2
+ root to: "dashboard#index"
3
3
 
4
4
  post "/", to: "tracking#track", as: :tracking_endpoint
5
5
 
6
6
  get "/skadi.js", to: "asset#tracking_script", as: :tracking_script
7
+ get "/skadiVisit.js", to: "asset#visit_tracking_script", as: :visit_tracking_script
7
8
  get "/dashboard.css", to: "asset#dashboard_css", as: :dashboard_css
8
9
  get "/dashboard.js", to: "asset#dashboard_js", as: :dashboard_js
9
10
 
10
- get "/dashboard", to: "dashboard#show", as: :dashboard
11
- post "/dashboard/update", to: "dashboard#update", as: :dashboard_update
11
+ post "/dashboards", to: "dashboard#create", as: :dashboards
12
12
 
13
- post "/data", to: "dashboard#data", as: :dashboard_data
13
+ get "/:id", to: "dashboard#show", as: :dashboard
14
+ delete "/:id", to: "dashboard#destroy"
15
+ post "/:id/update", to: "dashboard#update", as: :dashboard_update
16
+ post "/:id/data", to: "dashboard#data", as: :dashboard_data
14
17
  end
@@ -32,6 +32,16 @@ Skadi.configure do |config|
32
32
  # config.dashboard_edit_controller_method = :skadi_dashboard_can_edit
33
33
  # config.dashboard_dangerously_use_sql_controller_method = :skadi_dashboard_can_dangerously_use_sql
34
34
 
35
+ # Method to call when the user is forbidden trying to view the dashboard. Can
36
+ # be used to redirect to an auth page. Falls back to `head :forbidden`.
37
+ # config.dashboard_forbidden_method = :redirect_to_auth
38
+
39
+ # Rate limit for the tracking endpoint, per IP address. Each page view sends
40
+ # at least two requests. Set the limit to nil to disable. Defaults to 200
41
+ # requests per minute.
42
+ #
43
+ # config.tracking_rate_limit = 200
44
+ # config.tracking_rate_limit_period = 1.minute
35
45
 
36
46
  # Add custom fields to the events table in the Skadi dashboard.
37
47
  # @see [Skadi::Schema]
@@ -64,7 +64,12 @@ class <%= migration_class_name %> < ActiveRecord::Migration[<%= "#{ActiveRecord:
64
64
 
65
65
  add_index :skadi_views, :view_token, unique: true
66
66
  add_index :skadi_views, :created_at
67
+ <%- if db_engine == :mysql -%>
68
+ # MySQL cannot index a text column without a prefix length
69
+ add_index :skadi_views, [:path, :created_at], length: { path: 191 }
70
+ <%- else -%>
67
71
  add_index :skadi_views, [:path, :created_at]
72
+ <%- end -%>
68
73
  add_index :skadi_views, [:visit_id, :created_at]
69
74
 
70
75
  create_table :skadi_events do |t|