discourse/lib/onebox/engine/github_commit_onebox.rb
Martin Brennan 97e2b353f6
FEATURE: Allow for multiple GitHub onebox tokens (#27887)
Followup 560e8aff75

GitHub auth tokens cannot be made with permissions to
access multiple organisations. This is quite limiting.
This commit changes the site setting to be a "secret list"
type, which allows for a key/value mapping where the value
is treated like a password in the UI.

Now when a GitHub URL is requested for oneboxing, the
org name from the URL is used to determine which token
to use for the request.

Just in case anyone used the old site setting already,
there is a migration to create a `default` entry
with that token in the new list setting, and for
a period of time we will consider that token valid to
use for all GitHub oneboxes as well.
2024-07-15 13:07:36 +10:00

58 lines
1.7 KiB
Ruby

# frozen_string_literal: true
require_relative "../mixins/github_body"
require_relative "../mixins/github_auth_header"
module Onebox
module Engine
class GithubCommitOnebox
include Engine
include LayoutSupport
include JSON
include Onebox::Mixins::GithubBody
include Onebox::Mixins::GithubAuthHeader
matches_regexp(%r{^https?://(?:www\.)?(?:(?:\w)+\.)?(github)\.com(?:/)?(?:.)*/commit/})
always_https
def url
"https://api.github.com/repos/#{match[:org]}/#{match[:repository]}/commits/#{match[:sha]}"
end
private
def match
return @match if defined?(@match)
@match = @url.match(%{github\.com/(?<org>[^/]+)/(?<repository>[^/]+)/commit/(?<sha>[^/]+)})
@match ||=
@url.match(
%{github\.com/(?<org>[^/]+)/(?<repository>[^/]+)/pull/(?<pr>[^/]+)/commit/(?<sha>[^/]+)},
)
@match
end
def data
result = raw(github_auth_header(match[:org])).clone
lines = result["commit"]["message"].split("\n")
result["title"] = lines.first
result["body"], result["excerpt"] = compute_body(lines[1..lines.length].join("\n"))
committed_at = Time.parse(result["commit"]["committer"]["date"])
result["committed_at"] = committed_at.strftime("%I:%M%p - %d %b %y %Z")
result["committed_at_date"] = committed_at.strftime("%F")
result["committed_at_time"] = committed_at.strftime("%T")
result["link"] = link
ulink = URI(link)
result["domain"] = "#{ulink.host}/#{ulink.path.split("/")[1]}/#{ulink.path.split("/")[2]}"
result["i18n"] = { committed: I18n.t("onebox.github.committed") }
result
end
end
end
end