-
-
Save tvdeyen/4706780 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/char_converter.rb | |
require 'uri' | |
module Support | |
class CharConverter | |
SANITIZE_ENV_KEYS = [ | |
#"HTTP_COOKIE", # including this will give -> WARNING: Can't verify CSRF token authenticity and kill you session cookies | |
"HTTP_REFERER", | |
"PATH_INFO", | |
"QUERY_STRING", | |
"REQUEST_PATH", | |
"REQUEST_URI", | |
] | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
@app.call(sanitize_env(env)) | |
end | |
def sanitize_env(env) | |
SANITIZE_ENV_KEYS.each do |key| | |
next unless value = env[key] | |
value = sanitize_string(URI.decode(value)) | |
env[key] = URI.encode(value) | |
end | |
env | |
end | |
def sanitize_string(string) | |
return string unless string.is_a? String | |
# Try it as UTF-8 directly | |
cleaned = string.dup.force_encoding('UTF-8') | |
if cleaned.valid_encoding? | |
cleaned | |
else | |
# Some of it might be old Windows code page | |
string.encode(Encoding::UTF_8, Encoding::Windows_1250) | |
end | |
rescue EncodingError | |
# Force it to UTF-8, throwing out invalid bits | |
string.encode!('UTF-8', invalid: :replace, undef: :replace) | |
end | |
end | |
end | |
Rails.application.config.middleware.insert_before(ActionDispatch::ParamsParser, Support::CharConverter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment