Skip to content

Commit ccf9d5d

Browse files
DEV: Introduce syntax_tree for ruby formatting (discourse#75)
1 parent 4a5259d commit ccf9d5d

File tree

9 files changed

+236
-191
lines changed

9 files changed

+236
-191
lines changed

.github/workflows/plugin-linting.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,12 @@ jobs:
5555
- name: Rubocop
5656
if: ${{ !cancelled() }}
5757
run: bundle exec rubocop .
58+
59+
- name: Syntax Tree
60+
if: ${{ !cancelled() }}
61+
run: |
62+
if test -f .streerc; then
63+
bundle exec stree check Gemfile $(git ls-files '*.rb') $(git ls-files '*.rake')
64+
else
65+
echo "Stree config not detected for this repository. Skipping."
66+
fi

.github/workflows/plugin-tests.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ jobs:
8080

8181
- name: Get yarn cache directory
8282
id: yarn-cache-dir
83-
run: echo "::set-output name=dir::$(yarn cache dir)"
83+
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
8484

8585
- name: Yarn cache
8686
uses: actions/cache@v3
@@ -130,7 +130,7 @@ jobs:
130130
shell: bash
131131
run: |
132132
if [ 0 -lt $(find plugins/${{ github.event.repository.name }}/spec -type f -name "*.rb" 2> /dev/null | wc -l) ]; then
133-
echo "::set-output name=files_exist::true"
133+
echo "files_exist=true" >> $GITHUB_OUTPUT
134134
fi
135135
136136
- name: Plugin RSpec
@@ -142,7 +142,7 @@ jobs:
142142
shell: bash
143143
run: |
144144
if [ 0 -lt $(find plugins/${{ github.event.repository.name }}/test/javascripts -type f \( -name "*.js" -or -name "*.es6" \) 2> /dev/null | wc -l) ]; then
145-
echo "::set-output name=files_exist::true"
145+
echo "files_exist=true" >> $GITHUB_OUTPUT
146146
fi
147147
148148
- name: Plugin QUnit

.rubocop.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
inherit_gem:
2-
rubocop-discourse: default.yml
2+
rubocop-discourse: stree-compat.yml

.streerc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
--print-width=100
2+
--plugins=plugin/trailing_comma

Gemfile

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# frozen_string_literal: true
22

3-
source 'https://rubygems.org'
3+
source "https://rubygems.org"
44

55
group :development do
6-
gem 'rubocop-discourse'
6+
gem "rubocop-discourse"
7+
gem "syntax_tree"
78
end

Gemfile.lock

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ GEM
66
parallel (1.22.1)
77
parser (3.1.2.1)
88
ast (~> 2.4.1)
9+
prettier_print (1.2.0)
910
rainbow (3.1.1)
1011
regexp_parser (2.6.0)
1112
rexml (3.2.5)
@@ -27,6 +28,8 @@ GEM
2728
rubocop-rspec (2.13.2)
2829
rubocop (~> 1.33)
2930
ruby-progressbar (1.11.0)
31+
syntax_tree (5.1.0)
32+
prettier_print (>= 1.2.0)
3033
unicode-display_width (2.3.0)
3134

3235
PLATFORMS
@@ -39,6 +42,7 @@ PLATFORMS
3942

4043
DEPENDENCIES
4144
rubocop-discourse
45+
syntax_tree
4246

4347
BUNDLED WITH
4448
2.3.10

plugin.rb

Lines changed: 96 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,19 @@ class ::OmniAuth::Strategies::Oauth2Basic < ::OmniAuth::Strategies::OAuth2
1313
option :name, "oauth2_basic"
1414

1515
uid do
16-
if path = SiteSetting.oauth2_callback_user_id_path.split('.')
16+
if path = SiteSetting.oauth2_callback_user_id_path.split(".")
1717
recurse(access_token, [*path]) if path.present?
1818
end
1919
end
2020

2121
info do
22-
if paths = SiteSetting.oauth2_callback_user_info_paths.split('|')
22+
if paths = SiteSetting.oauth2_callback_user_info_paths.split("|")
2323
result = Hash.new
2424
paths.each do |p|
25-
segments = p.split(':')
25+
segments = p.split(":")
2626
if segments.length == 2
2727
key = segments.first
28-
path = [*segments.last.split('.')]
28+
path = [*segments.last.split(".")]
2929
result[key] = recurse(access_token, path)
3030
end
3131
end
@@ -45,7 +45,7 @@ def recurse(obj, keys)
4545
end
4646
end
4747

48-
require 'faraday/logging/formatter'
48+
require "faraday/logging/formatter"
4949
class OAuth2FaradayFormatter < Faraday::Logging::Formatter
5050
def request(env)
5151
warn <<~LOG
@@ -76,7 +76,7 @@ def response(env)
7676

7777
class ::OAuth2BasicAuthenticator < Auth::ManagedAuthenticator
7878
def name
79-
'oauth2_basic'
79+
"oauth2_basic"
8080
end
8181

8282
def can_revoke?
@@ -90,52 +90,66 @@ def can_connect_existing_user?
9090
def register_middleware(omniauth)
9191
omniauth.provider :oauth2_basic,
9292
name: name,
93-
setup: lambda { |env|
94-
opts = env['omniauth.strategy'].options
95-
opts[:client_id] = SiteSetting.oauth2_client_id
96-
opts[:client_secret] = SiteSetting.oauth2_client_secret
97-
opts[:provider_ignores_state] = SiteSetting.oauth2_disable_csrf
98-
opts[:client_options] = {
99-
authorize_url: SiteSetting.oauth2_authorize_url,
100-
token_url: SiteSetting.oauth2_token_url,
101-
token_method: SiteSetting.oauth2_token_url_method.downcase.to_sym
102-
}
103-
opts[:authorize_options] = SiteSetting.oauth2_authorize_options.split("|").map(&:to_sym)
104-
105-
if SiteSetting.oauth2_authorize_signup_url.present? &&
106-
ActionDispatch::Request.new(env).params["signup"].present?
107-
opts[:client_options][:authorize_url] = SiteSetting.oauth2_authorize_signup_url
108-
end
109-
110-
if SiteSetting.oauth2_send_auth_header? && SiteSetting.oauth2_send_auth_body?
111-
# For maximum compatibility we include both header and body auth by default
112-
# This is a little unusual, and utilising multiple authentication methods
113-
# is technically disallowed by the spec (RFC2749 Section 5.2)
114-
opts[:client_options][:auth_scheme] = :request_body
115-
opts[:token_params] = { headers: { 'Authorization' => basic_auth_header } }
116-
elsif SiteSetting.oauth2_send_auth_header?
117-
opts[:client_options][:auth_scheme] = :basic_auth
118-
else
119-
opts[:client_options][:auth_scheme] = :request_body
120-
end
121-
122-
unless SiteSetting.oauth2_scope.blank?
123-
opts[:scope] = SiteSetting.oauth2_scope
124-
end
125-
126-
opts[:client_options][:connection_build] = lambda { |builder|
127-
if SiteSetting.oauth2_debug_auth && defined? OAuth2FaradayFormatter
128-
builder.response :logger, Rails.logger, { bodies: true, formatter: OAuth2FaradayFormatter }
93+
setup:
94+
lambda { |env|
95+
opts = env["omniauth.strategy"].options
96+
opts[:client_id] = SiteSetting.oauth2_client_id
97+
opts[:client_secret] = SiteSetting.oauth2_client_secret
98+
opts[:provider_ignores_state] = SiteSetting.oauth2_disable_csrf
99+
opts[:client_options] = {
100+
authorize_url: SiteSetting.oauth2_authorize_url,
101+
token_url: SiteSetting.oauth2_token_url,
102+
token_method: SiteSetting.oauth2_token_url_method.downcase.to_sym,
103+
}
104+
opts[:authorize_options] = SiteSetting
105+
.oauth2_authorize_options
106+
.split("|")
107+
.map(&:to_sym)
108+
109+
if SiteSetting.oauth2_authorize_signup_url.present? &&
110+
ActionDispatch::Request.new(env).params["signup"].present?
111+
opts[:client_options][
112+
:authorize_url
113+
] = SiteSetting.oauth2_authorize_signup_url
114+
end
115+
116+
if SiteSetting.oauth2_send_auth_header? &&
117+
SiteSetting.oauth2_send_auth_body?
118+
# For maximum compatibility we include both header and body auth by default
119+
# This is a little unusual, and utilising multiple authentication methods
120+
# is technically disallowed by the spec (RFC2749 Section 5.2)
121+
opts[:client_options][:auth_scheme] = :request_body
122+
opts[:token_params] = {
123+
headers: {
124+
"Authorization" => basic_auth_header,
125+
},
126+
}
127+
elsif SiteSetting.oauth2_send_auth_header?
128+
opts[:client_options][:auth_scheme] = :basic_auth
129+
else
130+
opts[:client_options][:auth_scheme] = :request_body
131+
end
132+
133+
unless SiteSetting.oauth2_scope.blank?
134+
opts[:scope] = SiteSetting.oauth2_scope
129135
end
130136

131-
builder.request :url_encoded # form-encode POST params
132-
builder.adapter FinalDestination::FaradayAdapter # make requests with FinalDestination::HTTP
137+
opts[:client_options][:connection_build] = lambda do |builder|
138+
if SiteSetting.oauth2_debug_auth && defined?(OAuth2FaradayFormatter)
139+
builder.response :logger,
140+
Rails.logger,
141+
{ bodies: true, formatter: OAuth2FaradayFormatter }
142+
end
143+
144+
builder.request :url_encoded # form-encode POST params
145+
builder.adapter FinalDestination::FaradayAdapter # make requests with FinalDestination::HTTP
146+
end
133147
}
134-
}
135148
end
136149

137150
def basic_auth_header
138-
"Basic " + Base64.strict_encode64("#{SiteSetting.oauth2_client_id}:#{SiteSetting.oauth2_client_secret}")
151+
"Basic " +
152+
Base64.strict_encode64("#{SiteSetting.oauth2_client_id}:#{SiteSetting.oauth2_client_secret}")
139153
end
140154

141155
def walk_path(fragment, segments, seg_index = 0)
@@ -182,19 +196,21 @@ def parse_segments(path)
182196
quoted = false
183197
escaped = false
184198

185-
path.split("").each do |char|
186-
next_char_escaped = false
187-
if !escaped && (char == '"')
188-
quoted = !quoted
189-
elsif !escaped && !quoted && (char == '.')
190-
segments.append +""
191-
elsif !escaped && (char == '\\')
192-
next_char_escaped = true
193-
else
194-
segments.last << char
199+
path
200+
.split("")
201+
.each do |char|
202+
next_char_escaped = false
203+
if !escaped && (char == '"')
204+
quoted = !quoted
205+
elsif !escaped && !quoted && (char == ".")
206+
segments.append +""
207+
elsif !escaped && (char == '\\')
208+
next_char_escaped = true
209+
else
210+
segments.last << char
211+
end
212+
escaped = next_char_escaped
195213
end
196-
escaped = next_char_escaped
197-
end
198214

199215
segments
200216
end
@@ -204,14 +220,14 @@ def log(info)
204220
end
205221

206222
def fetch_user_details(token, id)
207-
user_json_url = SiteSetting.oauth2_user_json_url.sub(':token', token.to_s).sub(':id', id.to_s)
223+
user_json_url = SiteSetting.oauth2_user_json_url.sub(":token", token.to_s).sub(":id", id.to_s)
208224
user_json_method = SiteSetting.oauth2_user_json_url_method.downcase.to_sym
209225

210226
log("user_json_url: #{user_json_method} #{user_json_url}")
211227

212228
bearer_token = "Bearer #{token}"
213229
connection = Faraday.new { |f| f.adapter FinalDestination::FaradayAdapter }
214-
headers = { 'Authorization' => bearer_token, 'Accept' => 'application/json' }
230+
headers = { "Authorization" => bearer_token, "Accept" => "application/json" }
215231
user_json_response = connection.run_request(user_json_method, user_json_url, nil, headers)
216232

217233
log("user_json_response: #{user_json_response.inspect}")
@@ -243,7 +259,7 @@ def fetch_user_details(token, id)
243259

244260
def primary_email_verified?(auth)
245261
return true if SiteSetting.oauth2_email_verified
246-
verified = auth['info']['email_verified']
262+
verified = auth["info"]["email_verified"]
247263
verified = true if verified == "true"
248264
verified = false if verified == "false"
249265
verified
@@ -254,19 +270,25 @@ def always_update_user_email?
254270
end
255271

256272
def after_authenticate(auth, existing_account: nil)
257-
log("after_authenticate response: \n\ncreds: #{auth['credentials'].to_hash}\nuid: #{auth['uid']}\ninfo: #{auth['info'].to_hash}\nextra: #{auth['extra'].to_hash}")
273+
log(
274+
"after_authenticate response: \n\ncreds: #{auth["credentials"].to_hash}\nuid: #{auth["uid"]}\ninfo: #{auth["info"].to_hash}\nextra: #{auth["extra"].to_hash}",
275+
)
258276

259277
if SiteSetting.oauth2_fetch_user_details?
260-
if fetched_user_details = fetch_user_details(auth['credentials']['token'], auth['uid'])
261-
auth['uid'] = fetched_user_details[:user_id] if fetched_user_details[:user_id]
262-
auth['info']['nickname'] = fetched_user_details[:username] if fetched_user_details[:username]
263-
auth['info']['image'] = fetched_user_details[:avatar] if fetched_user_details[:avatar]
264-
['name', 'email', 'email_verified'].each do |property|
265-
auth['info'][property] = fetched_user_details[property.to_sym] if fetched_user_details[property.to_sym]
278+
if fetched_user_details = fetch_user_details(auth["credentials"]["token"], auth["uid"])
279+
auth["uid"] = fetched_user_details[:user_id] if fetched_user_details[:user_id]
280+
auth["info"]["nickname"] = fetched_user_details[:username] if fetched_user_details[
281+
:username
282+
]
283+
auth["info"]["image"] = fetched_user_details[:avatar] if fetched_user_details[:avatar]
284+
%w[name email email_verified].each do |property|
285+
auth["info"][property] = fetched_user_details[property.to_sym] if fetched_user_details[
286+
property.to_sym
287+
]
266288
end
267289

268290
DiscoursePluginRegistry.oauth2_basic_additional_json_paths.each do |detail|
269-
auth['extra'][detail] = fetched_user_details["extra:#{detail}"]
291+
auth["extra"][detail] = fetched_user_details["extra:#{detail}"]
270292
end
271293
else
272294
result = Auth::Result.new
@@ -284,7 +306,9 @@ def enabled?
284306
end
285307
end
286308

287-
auth_provider title_setting: "oauth2_button_title",
288-
authenticator: OAuth2BasicAuthenticator.new
309+
auth_provider title_setting: "oauth2_button_title", authenticator: OAuth2BasicAuthenticator.new
289310

290-
load File.expand_path("../lib/validators/oauth2_basic/oauth2_fetch_user_details_validator.rb", __FILE__)
311+
load File.expand_path(
312+
"../lib/validators/oauth2_basic/oauth2_fetch_user_details_validator.rb",
313+
__FILE__,
314+
)

spec/integration/overrides_email_spec.rb

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
fab!(:initial_email) { "initial@example.com" }
77
fab!(:new_email) { "new@example.com" }
88
fab!(:user) { Fabricate(:user, email: initial_email) }
9-
fab!(:uac) { UserAssociatedAccount.create!(user: user, provider_name: "oauth2_basic", provider_uid: "12345") }
9+
fab!(:uac) do
10+
UserAssociatedAccount.create!(user: user, provider_name: "oauth2_basic", provider_uid: "12345")
11+
end
1012

1113
before do
1214
SiteSetting.oauth2_enabled = true
@@ -16,17 +18,13 @@
1618

1719
OmniAuth.config.test_mode = true
1820
OmniAuth.config.mock_auth[:oauth2_basic] = OmniAuth::AuthHash.new(
19-
provider: 'oauth2_basic',
20-
uid: '12345',
21-
info: OmniAuth::AuthHash::InfoHash.new(
22-
email: new_email
23-
),
21+
provider: "oauth2_basic",
22+
uid: "12345",
23+
info: OmniAuth::AuthHash::InfoHash.new(email: new_email),
2424
extra: {
25-
raw_info: OmniAuth::AuthHash.new(
26-
email_verified: true
27-
)
25+
raw_info: OmniAuth::AuthHash.new(email_verified: true),
2826
},
29-
credentials: OmniAuth::AuthHash.new
27+
credentials: OmniAuth::AuthHash.new,
3028
)
3129
end
3230

@@ -40,7 +38,7 @@
4038
expect(user.reload.email).to eq(initial_email)
4139
end
4240

43-
it 'updates user email if enabled' do
41+
it "updates user email if enabled" do
4442
SiteSetting.oauth2_overrides_email = true
4543

4644
get "/auth/oauth2_basic/callback"

0 commit comments

Comments
 (0)