Files
nairobi/config/initializers/ahoy.rb
Javi Martín 96ae69fe93 Use a GDPR-compliant configuration for Ahoy
As mentioned in Ahoy's README [1]:

> Ahoy provides a number of options to help with GDPR compliance.
> Update config/initializers/ahoy.rb with:
>
> class Ahoy::Store < Ahoy::DatabaseStore
>   def authenticate(data)
>     # disables automatic linking of visits and users
>   end
> end
>
> Ahoy.mask_ips = true
> Ahoy.cookies = :none

As also mentioned in the README:

> If Ahoy was installed before v5, add an index before making this
> change.
> (...)
> For Active Record, create a migration with:
> add_index :ahoy_visits, [:visitor_token, :started_at]

However, the `visitor_token` doesn't exist in our table, since we
generated the `visits` table when Ahoy used the `visitor_id` column. So
we're using this column for the index.

Note we also need to change the `visit` method, since otherwise we get
an exception [2]. As mentioned on the issue reporting the exception:

> you'll need to copy the latest version of that method and adapt it to
> your model. I believe you'll want to replace:
>
> where(visit_token: ahoy.visit_token) with
> where(id: ensure_uuid(ahoy.visit_token))
>
> where(visitor_token: ahoy.visitor_token) with
> where(visitor_id: ensure_uuid(ahoy.visitor_token))

So we're copying the latest version of that method and changing it
accordingly.

[1] https://github.com/ankane/ahoy/blob/v5.0.2/README.md
[2] Issue 549 in https://github.com/ankane/ahoy
2024-05-09 14:56:25 +02:00

55 lines
1.3 KiB
Ruby

Ahoy.api = true
Ahoy.server_side_visits = :when_needed
Ahoy.mask_ips = true
Ahoy.cookies = :none
# Most code comes from:
# https://github.com/ankane/ahoy/blob/3661b7f9a/docs/Ahoy-2-Upgrade.md
class Ahoy::Store < Ahoy::DatabaseStore
def authenticate(...)
end
def track_visit(data)
data[:id] = ensure_uuid(data.delete(:visit_token))
data[:visitor_id] = ensure_uuid(data.delete(:visitor_token))
super(data)
end
def track_event(data)
data[:id] = ensure_uuid(data.delete(:event_id))
data[:ip] = request.ip
super(data)
end
def visit
unless defined?(@visit)
if ahoy.send(:existing_visit_token) || ahoy.instance_variable_get(:@visit_token)
@visit = visit_model.where(id: ensure_uuid(ahoy.visit_token)).take if ahoy.visit_token
elsif !Ahoy.cookies? && ahoy.visitor_token
@visit = visit_model.where(visitor_id: ensure_uuid(ahoy.visitor_token))
.where(started_at: Ahoy.visit_duration.ago..)
.order(started_at: :desc)
.first
else
@visit = nil
end
end
@visit
end
def visit_model
Visit
end
def ensure_uuid(id)
UUIDTools::UUID.parse(id).to_s
rescue
UUIDTools::UUID.sha1_create(UUIDTools::UUID.parse(Ahoy::Tracker::UUID_NAMESPACE), id).to_s
end
def exclude?
false
end
end