feat: add migration to fix image signed keys (#7076)

This commit is contained in:
Shivam Mishra
2023-05-15 15:13:26 +05:30
committed by GitHub
parent 5a8eff35b5
commit c70367bbd7
2 changed files with 56 additions and 1 deletions

View File

@@ -0,0 +1,55 @@
class ArticleKeyConverter
def initialize(article)
@article = article
end
def process
new_content = replace(@article.content)
@article.update(content: new_content)
end
private
def convert_key(id)
verifier_name = 'ActiveStorage'
key_generator = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base, iterations: 1000,
hash_digest_class: OpenSSL::Digest::SHA1)
key_generator = ActiveSupport::CachingKeyGenerator.new(key_generator)
secret = key_generator.generate_key(verifier_name.to_s)
verifier = ActiveSupport::MessageVerifier.new(secret)
begin
ActiveStorage::Blob.find(verifier.verify(id, purpose: :blob_id))
.try(:signed_id)
rescue StandardError
nil
end
end
def replace(text)
keys = get_keys(text)
keys.each do |key|
new_key = convert_key(key)
text = text.gsub(key, new_key) if new_key
end
text
end
def get_keys(text)
uris = text.scan(URI::DEFAULT_PARSER.make_regexp).flatten.select do |x|
x.to_s.include?('rails/active_storage')
end
uris.map { |x| x.split('/')[-2] }
end
end
class UpdateArticleImageKeys < ActiveRecord::Migration[7.0]
def change
# Iterate through all articles
Article.find_each do |article|
# Run the ArticleKeyConverter for each one
ArticleKeyConverter.new(article).process
end
end
end

View File

@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2023_05_10_113208) do
ActiveRecord::Schema[7.0].define(version: 2023_05_15_051424) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"