A platform for community discussion. Free, open, simple.
FEATURE: Add Reddit OAuth support for onebox (#38040)
Rafael dos Santos Silva508b75ebf4ce
diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 15bf5e6c880..d7af6233664 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1814,6 +1814,8 @@ en:max_oneboxes_per_post: "Set the maximum number of oneboxes that can be included in a single post. Oneboxes provide a preview of linked content within the post."facebook_app_access_token: "A token generated from your Facebook app ID and secret. Used to generate Instagram oneboxes."github_onebox_access_tokens: "A mapping of a GitHub organisation or user to a GitHub access token which is used to generate GitHub oneboxes for private repos, commits, pull requests, issues, and file contents. Without this, only public GitHub URLs will be oneboxed."+ reddit_onebox_client_id: "Reddit API OAuth client ID used for authenticated Reddit oneboxes. Create a 'script' type app at reddit.com/prefs/apps to obtain credentials."+ reddit_onebox_client_secret: "Reddit API OAuth client secret used for authenticated Reddit oneboxes. Found under the 'script' type app created at reddit.com/prefs/apps."logo: "The logo image at the top left of your site. Use a wide rectangular image with a height of 120 and an aspect ratio greater than 3:1. If left blank, the site title text will be shown."logo_small: "The small logo image at the top left of your site, seen when scrolling down. Use a square 120 × 120 image. If left blank, a home glyph will be shown."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex bd073f46f7f..c85bd4877d8 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -2850,6 +2850,12 @@ onebox:type: listsecret: truelist_type: secret+ reddit_onebox_client_id:+ default: ""+ secret: true+ reddit_onebox_client_secret:+ default: ""+ secret: truespam:add_rel_nofollow_to_user_content: truehide_post_sensitivity:diff --git a/lib/onebox/engine/reddit_media_onebox.rb b/lib/onebox/engine/reddit_media_onebox.rbindex 81ab71317a2..7f46858d0dd 100644--- a/lib/onebox/engine/reddit_media_onebox.rb+++ b/lib/onebox/engine/reddit_media_onebox.rb@@ -1,9 +1,12 @@# frozen_string_literal: true+require_relative "../mixins/reddit_auth_header"+module Oneboxmodule Engineclass RedditMediaOneboxinclude Engine+ include Onebox::Mixins::RedditAuthHeaderalways_httpsmatches_domain(@@ -112,7 +115,11 @@ module Oneboxreturn @reddit_post if defined?(@reddit_post)json_url = @url.sub(%r{/?(\?.*)?$}, ".json")- response = Onebox::Helpers.fetch_response(json_url)+ headers = reddit_auth_header+ if headers.any?+ json_url = json_url.sub(%r{://(www|old|np|new)\.reddit\.com}, "://oauth.reddit.com")+ end+ response = Onebox::Helpers.fetch_response(json_url, headers:)parsed = ::MultiJson.load(response)@reddit_post = parsed[0]["data"]["children"][0]["data"]rescue StandardErrordiff --git a/lib/onebox/mixins/reddit_auth_header.rb b/lib/onebox/mixins/reddit_auth_header.rbnew file mode 100644index 00000000000..0814f178620--- /dev/null+++ b/lib/onebox/mixins/reddit_auth_header.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++module Onebox+ module Mixins+ module RedditAuthHeader+ def reddit_auth_header+ if SiteSetting.reddit_onebox_client_id.blank? ||+ SiteSetting.reddit_onebox_client_secret.blank?+ return {}+ end++ token = fetch_reddit_access_token+ return {} if token.blank?++ { "Authorization" => "Bearer #{token}" }+ end++ def reddit_authenticated?+ SiteSetting.reddit_onebox_client_id.present? &&+ SiteSetting.reddit_onebox_client_secret.present?+ end++ private++ def fetch_reddit_access_token+ Discourse+ .cache+ .fetch("reddit_onebox_access_token", expires_in: 50.minutes) do+ user = SiteSetting.reddit_onebox_client_id+ password = SiteSetting.reddit_onebox_client_secret++ response =+ Excon.post(+ "https://www.reddit.com/api/v1/access_token",+ body: URI.encode_www_form(grant_type: "client_credentials"),+ headers: {+ "Content-Type" => "application/x-www-form-urlencoded",+ "User-Agent" => Onebox::Helpers.user_agent,+ },+ user:,+ password:,+ )++ ::MultiJson.load(response.body)["access_token"] if response.status == 200+ end+ end+ end+ end+enddiff --git a/spec/lib/onebox/engine/reddit_media_onebox_spec.rb b/spec/lib/onebox/engine/reddit_media_onebox_spec.rbindex 970f3a1073d..dbecef7d566 100644--- a/spec/lib/onebox/engine/reddit_media_onebox_spec.rb+++ b/spec/lib/onebox/engine/reddit_media_onebox_spec.rb@@ -87,6 +87,62 @@ RSpec.describe Onebox::Engine::RedditMediaOnebox doendend+ describe "authenticated requests" do+ let(:image_link) do+ "https://www.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition"+ end+ let(:oauth_json_url) do+ "https://oauth.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition.json"+ end+ let(:token_url) { "https://www.reddit.com/api/v1/access_token" }++ context "when Reddit OAuth credentials are configured" do+ before do+ SiteSetting.reddit_onebox_client_id = "test_client_id"+ SiteSetting.reddit_onebox_client_secret = "test_client_secret"++ stub_request(:post, token_url).to_return(+ status: 200,+ body: { access_token: "test_token", token_type: "bearer", expires_in: 3600 }.to_json,+ )++ stub_request(:get, oauth_json_url).with(+ headers: {+ "Authorization" => "Bearer test_token",+ },+ ).to_return(status: 200, body: onebox_response("reddit_image"))+ end++ it "uses oauth.reddit.com with auth header" do+ described_class.new(image_link).to_html+ expect(WebMock).to have_requested(:get, oauth_json_url).with(+ headers: {+ "Authorization" => "Bearer test_token",+ },+ )+ end+ end++ context "when Reddit OAuth credentials are blank" do+ before do+ SiteSetting.reddit_onebox_client_id = ""+ SiteSetting.reddit_onebox_client_secret = ""++ stub_request(:get, "#{image_link}.json").to_return(+ status: 200,+ body: onebox_response("reddit_image"),+ )+ end++ it "uses www.reddit.com without auth header" do+ described_class.new(image_link).to_html+ expect(WebMock).to have_requested(:get, "#{image_link}.json").with { |req|+ req.headers.exclude?("Authorization")+ }+ end+ end+ end+describe ".===" doit "matches valid Reddit URL" dovalid_url = URI(image_link)