Class: AhoyEmail::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/ahoy_email/utils.rb

Constant Summary collapse

OPTION_KEYS =
{
  message: %i(message mailer user extra),
  utm_params: %i(utm_source utm_medium utm_term utm_content utm_campaign),
  click: %i(campaign url_options unsubscribe_links)
}

Class Method Summary collapse

Class Method Details

.publish(name, event) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ahoy_email/utils.rb', line 32

def publish(name, event)
  method_name = "track_#{name}"
  AhoyEmail.subscribers.each do |subscriber|
    subscriber = subscriber.new if subscriber.is_a?(Class)
    if subscriber.respond_to?(method_name)
      subscriber.send(method_name, event.dup)
    elsif name == :click && subscriber.respond_to?(:click)
      # legacy
      subscriber.send(:click, event.dup)
    end
  end
end

.secret_tokensObject



45
46
47
# File 'lib/ahoy_email/utils.rb', line 45

def secret_tokens
  Array(AhoyEmail.secret_token || (raise "Secret token is empty"))
end

.signature(token:, campaign:, url:, secret_token: nil) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/ahoy_email/utils.rb', line 10

def signature(token:, campaign:, url:, secret_token: nil)
  secret_token ||= secret_tokens.first

  # encode and join with a character outside encoding
  data = [token, campaign, url].map { |v| Base64.strict_encode64(v.to_s) }.join("|")

  Base64.urlsafe_encode64(OpenSSL::HMAC.digest("SHA256", secret_token, data), padding: false)
end

.signature_verified?(legacy:, token:, campaign:, url:, signature:) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ahoy_email/utils.rb', line 19

def signature_verified?(legacy:, token:, campaign:, url:, signature:)
  secret_tokens.any? do |secret_token|
    expected_signature =
      if legacy
        OpenSSL::HMAC.hexdigest("SHA1", secret_token, url)
      else
        signature(token: token, campaign: campaign, url: url, secret_token: secret_token)
      end

    ActiveSupport::SecurityUtils.secure_compare(signature, expected_signature)
  end
end