Created
February 20, 2021 17:18
-
-
Save conroywhitney/07d8e14d5bfd821b7a43d1479aa8f730 to your computer and use it in GitHub Desktop.
Ruby on Rails implementation of purging AMP cache (https://developers.google.com/amp/cache/update-cache)
This file contains 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
# app/models/amp_purge.rb | |
# | |
# frozen_string_literal: true | |
# | |
# Ruby on Rails implementation of purging AMP cache | |
# https://developers.google.com/amp/cache/update-cache | |
# | |
# Replace "example" with your domain | |
# | |
# Run like: | |
# $ rails c | |
# > AmpPurge.new("/foo/bar.amp").purge | |
# | |
# Open the "Signed URL" in your browser | |
# You should see an OK response | |
require "base64" | |
require "openssl" | |
class AmpPurge | |
attr_accessor :article_path | |
def initialize(article_path) | |
@article_path = article_path | |
end | |
def purge | |
puts "Unsigned Path ----------------" | |
puts unsigned_path | |
puts "Valid Signature? -------------" | |
puts public_key.verify(digest, signature, unsigned_path) | |
puts "Signed URL -------------------" | |
puts signed_url | |
end | |
private | |
def base64_signature | |
Base64.urlsafe_encode64(signature) | |
end | |
def base_url | |
"https://www-example-com.cdn.ampproject.org" | |
end | |
def digest | |
OpenSSL::Digest::SHA256.new | |
end | |
def params | |
{ | |
amp_action: "flush", | |
amp_ts: Time.now.utc.to_i | |
} | |
end | |
def private_key | |
OpenSSL::PKey::RSA.new( | |
File.read(Rails.root.join("amp-private-key.pem")) | |
) | |
end | |
def public_key | |
OpenSSL::PKey::RSA.new( | |
File.read(Rails.root.join("amp-public-key.pem")) | |
) | |
end | |
def signature | |
private_key.sign(digest, unsigned_path) | |
end | |
def signed_url | |
"#{base_url}#{unsigned_path}&_url_signature=#{base64_signature}" | |
end | |
def unsigned_path | |
"/update-cache/c/s/www.example.com#{article_path}?#{params.to_param}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment