DisposableGuard

Ruby on Rails

class DisposableEmailFilter
  def initialize(app)
    @app = app
  end

  def call(env)
    req = Rack::Request.new(env)
    email = req.params["email"]

    if email
      begin
        uri = URI("https://api.disposableguard.com/v1/check")
        uri.query = URI.encode_www_form({ email: email })

        response = Net::HTTP.get_response(uri, {
          "Authorization" => "Bearer #{ENV['DG_KEY']}"
        })

        if response.is_a?(Net::HTTPSuccess)
          data = JSON.parse(response.body)
          if data["is_disposable"]
            return [400, { "Content-Type" => "application/json" },
              [{ error: "Please use a real email address." }.to_json]]
          end
        end
      rescue => e
        # fail-open
      end
    end

    @app.call(env)
  end
end

Notes

Add to `config/application.rb`: `config.middleware.use DisposableEmailFilter`. Requires `net/http` and `json` (both stdlib).