Class: Mailgun::OptInHandler

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

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.



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

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

  innerPayloadEncoded = Base64.encode64(JSON.generate(innerPayload))

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

  outerPayload = {'h' => digest,
                  'p' => innerPayloadEncoded}

  outerPayloadEncoded = Base64.encode64(JSON.generate(outerPayload))

  URI.escape(outerPayloadEncoded)
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.



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

def self.validate_hash(secret_app_id, unique_hash)
  outerPayload = JSON.parse(Base64.decode64(URI.unescape(unique_hash)))

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

  innerPayload = JSON.parse(Base64.decode64(URI.unescape(outerPayload['p'])))

  hash_provided = outerPayload['h']

  if(generated_hash == hash_provided)
    return {'recipient_address' => innerPayload['r'], 'mailing_list' => innerPayload['l']}
  else
    return false
  end
end