-
Notifications
You must be signed in to change notification settings - Fork 6
/
sns_notifications_controller.rb
61 lines (52 loc) · 1.52 KB
/
sns_notifications_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true
class SnsNotificationsController < ApplicationController
skip_forgery_protection
before_action :verify_request_authenticity
def self.sns_client
@sns_client ||= Aws::SNS::Client.new(region: ReceiveSnsEmailDeliveryService.aws_region)
end
def create
case message_body["Type"]
when "SubscriptionConfirmation"
confirm_subscription ? (head :ok) : (head :bad_request)
when "Notification"
message = JSON.parse(message_body["Message"])
handle_message(message)
head :ok
end
end
private
def handle_message(message)
case message["notificationType"]
when "Received"
ReceiveSnsEmailDeliveryJob.perform_later(message)
else
warning_message = "Unhandled SNS notificationType: #{message["notificationType"]}"
Rails.logger.warn(warning_message)
Rollbar.warn(warning_message, message: message)
end
end
def verify_request_authenticity
head :unauthorized if raw_post.blank? || !message_verifier.authentic?(raw_post)
end
def raw_post
@raw_post ||= request.raw_post
end
def message_body
@message_body ||= JSON.parse(raw_post)
end
def message_verifier
@message_verifier ||= Aws::SNS::MessageVerifier.new
end
def confirm_subscription
SnsNotificationsController.sns_client.confirm_subscription(
topic_arn: message_body["TopicArn"],
token: message_body["Token"]
)
true
rescue Aws::SNS::Errors::ServiceError => e
Rails.logger.error(e.message)
Rollbar.error(e)
false
end
end