Class: Mailgun::OptInHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/mailgun/lists/opt_in_handler.rb

Overview

Public: Provides methods for creating and handling opt-in URLs,

particularlly for mailing lists.

See: github.com/mailgun/mailgun-ruby/blob/master/OptInHandler.md

Class Method Summary collapse

Class Method Details

.generate_hash(mailing_list, secret_app_id, recipient_address) ⇒ String

Generates a hash that can be used to validate opt-in recipients. Encodes all the necessary data in the URL.

Parameters:

  • mailing_list (String)

    The mailing list the user should be subscribed to.

  • secret_app_id (String)

    A secret passphrase used as a constant for the hash.

  • recipient_address (Hash)

    The address of the user that should be subscribed.

Returns:

  • (String)

    A url encoded URL suffix hash.


20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mailgun/lists/opt_in_handler.rb', line 20

def self.generate_hash(mailing_list, secret_app_id, recipient_address)
  inner_payload = { 'l' => mailing_list, 'r' => recipient_address }

  inner_payload_encoded = Base64.encode64(JSON.generate(inner_payload))

  sha1_digest = OpenSSL::Digest.new('sha1')
  digest = OpenSSL::HMAC.hexdigest(sha1_digest, secret_app_id, inner_payload_encoded)

  outer_payload = { 'h' => digest, 'p' => inner_payload_encoded }

  outer_payload_encoded = Base64.encode64(JSON.generate(outer_payload))

  CGI.escape(outer_payload_encoded)
end

.validate_hash(secret_app_id, unique_hash) ⇒ Hash or Boolean

Validates the hash provided from the generate_hash method.

Parameters:

  • secret_app_id (String)

    A secret passphrase used as a constant for the hash.

  • unique_hash (Hash)

    The hash from the user. Likely via link click.

Returns:

  • (Hash or Boolean)

    A hash with 'recipient_address' and 'mailing_list', if validates. Otherwise, boolean false.


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/mailgun/lists/opt_in_handler.rb', line 40

def self.validate_hash(secret_app_id, unique_hash)
  outer_payload = JSON.parse(Base64.decode64(CGI.unescape(unique_hash)))

  sha1_digest = OpenSSL::Digest.new('sha1')
  generated_hash = OpenSSL::HMAC.hexdigest(sha1_digest, secret_app_id, outer_payload['p'])

  inner_payload = JSON.parse(Base64.decode64(CGI.unescape(outer_payload['p'])))

  hash_provided = outer_payload['h']

  if generated_hash == hash_provided
    return { 'recipient_address' => inner_payload['r'], 'mailing_list' => inner_payload['l'] }
  end
  false
end