aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/action_mailbox/base_controller.rb
blob: 5af59f8140a176170d22f02799868de528253515 (plain) (blame)
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
# The base class for all Active Mailbox ingress controllers.
class ActionMailbox::BaseController < ActionController::Base
  skip_forgery_protection

  def self.prepare
    # Override in concrete controllers to run code on load.
  end

  before_action :ensure_configured

  private
    def ensure_configured
      unless ActionMailbox.ingress == ingress_name
        head :not_found
      end
    end

    def ingress_name
      self.class.name[/^ActionMailbox::Ingresses::(.*?)::/, 1].underscore.to_sym
    end


    def authenticate_by_password
      if password.present?
        http_basic_authenticate_or_request_with username: "actionmailbox", password: password, realm: "Action Mailbox"
      else
        raise ArgumentError, "Missing required ingress credentials"
      end
    end

    def password
      Rails.application.credentials.dig(:action_mailbox, :ingress_password) || ENV["RAILS_INBOUND_EMAIL_PASSWORD"]
    end


    # TODO: Extract to ActionController::HttpAuthentication
    def http_basic_authenticate_or_request_with(username:, password:, realm: nil)
      authenticate_or_request_with_http_basic(realm || "Application") do |given_username, given_password|
        ActiveSupport::SecurityUtils.secure_compare(given_username, username) &
          ActiveSupport::SecurityUtils.secure_compare(given_password, password)
      end
    end
end