Skip to content

Instantly share code, notes, and snippets.

@wellington1993
Last active August 30, 2023 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wellington1993/b721c8446e2d75f9c9cbd8571c2b7644 to your computer and use it in GitHub Desktop.
Save wellington1993/b721c8446e2d75f9c9cbd8571c2b7644 to your computer and use it in GitHub Desktop.
Esse código é um exemplo de como usar um middleware personalizado e um patch para tratar requisições multipart de forma diferente em Ruby on Rails. Ele modifica o cabeçalho Content-Type e registra o erro quando ocorre um EOFError ao analisar o corpo da requisição. This code is an example of how to use a custom middleware and a patch to handle mu…
# encoding: utf-8
# rack_multipart_fix.rb
# patch que modifica o metodo fast_forward_to_first_boundary do rack
# patch that modifies the method fast_forward_to_first_boundary of rack
module Rack
module Multipart
class << self
# cria um apelido para o metodo original parse_multipart, chamando-o de original_parse_multipart
# creates an alias for the original method parse_multipart, calling it original_parse_multipart
alias_method :original_parse_multipart, :parse_multipart
# redefine o metodo parse_multipart, recebendo um objeto env como argumento
# redefines the method parse_multipart, receiving an object env as argument
def parse_multipart(env)
begin
# tenta executar o metodo original parse_multipart, passando o objeto env como argumento, e retorna o resultado
# tries to execute the original method parse_multipart, passing the object env as argument, and returns the result
original_parse_multipart(env)
rescue EOFError => e
# loga a mensagem e a pilha de chamadas do erro no arquivo de log da aplicacao
# logs the message and the stack trace of the error in the application log file
logger.error "Erro ao analisar requisicao multipart: #{e.message}"
logger.error "Error while parsing multipart request: #{e.message}"
logger.error e.backtrace.join("\n")
# retorna nil para evitar que o erro seja propagado para a aplicacao
# returns nil to avoid that the error is propagated to the application
nil
end
end
end
end
end
# middleware que trata as requisicoes multipart de forma diferente
# middleware that handles multipart requests differently
class BadMultipartFormDataSanitizer
def initialize(app)
# recebe uma aplicacao como argumento no construtor e armazena em uma variavel chamada @app
# receives an application as argument in the constructor and stores it in a variable called @app
@app = app
end
def call(env)
# define um metodo chamado call, que recebe um objeto env como argumento. Esse objeto env contem as informacoes da requisicao HTTP, como o metodo, a URI, os cabecalhos e o corpo.
# defines a method called call, that receives an object env as argument. This object env contains the information of the HTTP request, such as the method, the URI, the headers and the body.
if env['CONTENT_TYPE'] =~ /multipart\/form-data/
# verifica se o cabecalho Content-Type da requisicao tem o valor multipart/form-data, que indica que a requisicao e do tipo multipart.
# checks if the header Content-Type of the request has the value multipart/form-data, which indicates that the request is of type multipart.
begin
# tenta analisar o corpo da requisicao usando o metodo Rack::Multipart.parse_multipart, que retorna um hash com as partes da requisicao.
# tries to parse the body of the request using the method Rack::Multipart.parse_multipart, which returns a hash with the parts of the request.
Rack::Multipart.parse_multipart(env)
rescue EOFError => ex
# se ocorrer uma excecao EOFError ao analisar o corpo da requisicao, modifica o cabecalho Content-Type para multipart/form-data sem a parte do limite (boundary). Isso serve para lidar com o caso em que o corpo da requisicao esta vazio ou incompleto.
# if an exception EOFError occurs while parsing the body of the request, modifies the header Content-Type to multipart/form-data without the part of the limit (boundary). This serves to handle the case where the body of the request is empty or incomplete.
env['CONTENT_TYPE'] = 'multipart/form-data'
end
end
# chama o metodo call da aplicacao passando o objeto env modificado e retorna o resultado.
# calls the method call of the application passing the object env modified and returns the result.
@app.call(env)
end
end
# insere o middleware BadMultipartFormDataSanitizer antes do middleware Rack::MethodOverride na pilha do rack
# inserts the middleware BadMultipartFormDataSanitizer before the middleware Rack::MethodOverride in the rack stack
Rails.application.middleware.insert_before Rack::MethodOverride, "BadMultipartFormDataSanitizer"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment