Skip to content

DEV: Introduce syntax_tree for ruby formatting #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/plugin-linting.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,12 @@ jobs:
- name: Rubocop
if: ${{ !cancelled() }}
run: bundle exec rubocop .

- name: Syntax Tree
if: ${{ !cancelled() }}
run: |
if test -f .streerc; then
bundle exec stree check Gemfile $(git ls-files '*.rb') $(git ls-files '*.rake')
else
echo "Stree config not detected for this repository. Skipping."
fi
6 changes: 3 additions & 3 deletions .github/workflows/plugin-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:

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

- name: Yarn cache
uses: actions/cache@v3
Expand Down Expand Up @@ -130,7 +130,7 @@ jobs:
shell: bash
run: |
if [ 0 -lt $(find plugins/${{ github.event.repository.name }}/spec -type f -name "*.rb" 2> /dev/null | wc -l) ]; then
echo "::set-output name=files_exist::true"
echo "files_exist=true" >> $GITHUB_OUTPUT
fi

- name: Plugin RSpec
Expand All @@ -142,7 +142,7 @@ jobs:
shell: bash
run: |
if [ 0 -lt $(find plugins/${{ github.event.repository.name }}/test/javascripts -type f \( -name "*.js" -or -name "*.es6" \) 2> /dev/null | wc -l) ]; then
echo "::set-output name=files_exist::true"
echo "files_exist=true" >> $GITHUB_OUTPUT
fi

- name: Plugin QUnit
Expand Down
2 changes: 1 addition & 1 deletion .rubocop.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
inherit_gem:
rubocop-discourse: default.yml
rubocop-discourse: stree-compat.yml
2 changes: 2 additions & 0 deletions .streerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
--print-width=100
--plugins=plugin/trailing_comma
5 changes: 3 additions & 2 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# frozen_string_literal: true

source 'https://rubygems.org'
source "https://rubygems.org"

group :development do
gem 'rubocop-discourse'
gem "rubocop-discourse"
gem "syntax_tree"
end
4 changes: 4 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ GEM
parallel (1.22.1)
parser (3.1.2.1)
ast (~> 2.4.1)
prettier_print (1.2.0)
rainbow (3.1.1)
regexp_parser (2.6.0)
rexml (3.2.5)
Expand All @@ -27,6 +28,8 @@ GEM
rubocop-rspec (2.13.2)
rubocop (~> 1.33)
ruby-progressbar (1.11.0)
syntax_tree (5.1.0)
prettier_print (>= 1.2.0)
unicode-display_width (2.3.0)

PLATFORMS
Expand All @@ -39,6 +42,7 @@ PLATFORMS

DEPENDENCIES
rubocop-discourse
syntax_tree

BUNDLED WITH
2.3.10
168 changes: 96 additions & 72 deletions plugin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ class ::OmniAuth::Strategies::Oauth2Basic < ::OmniAuth::Strategies::OAuth2
option :name, "oauth2_basic"

uid do
if path = SiteSetting.oauth2_callback_user_id_path.split('.')
if path = SiteSetting.oauth2_callback_user_id_path.split(".")
recurse(access_token, [*path]) if path.present?
end
end

info do
if paths = SiteSetting.oauth2_callback_user_info_paths.split('|')
if paths = SiteSetting.oauth2_callback_user_info_paths.split("|")
result = Hash.new
paths.each do |p|
segments = p.split(':')
segments = p.split(":")
if segments.length == 2
key = segments.first
path = [*segments.last.split('.')]
path = [*segments.last.split(".")]
result[key] = recurse(access_token, path)
end
end
Expand All @@ -45,7 +45,7 @@ def recurse(obj, keys)
end
end

require 'faraday/logging/formatter'
require "faraday/logging/formatter"
class OAuth2FaradayFormatter < Faraday::Logging::Formatter
def request(env)
warn <<~LOG
Expand Down Expand Up @@ -76,7 +76,7 @@ def response(env)

class ::OAuth2BasicAuthenticator < Auth::ManagedAuthenticator
def name
'oauth2_basic'
"oauth2_basic"
end

def can_revoke?
Expand All @@ -90,52 +90,66 @@ def can_connect_existing_user?
def register_middleware(omniauth)
omniauth.provider :oauth2_basic,
name: name,
setup: lambda { |env|
opts = env['omniauth.strategy'].options
opts[:client_id] = SiteSetting.oauth2_client_id
opts[:client_secret] = SiteSetting.oauth2_client_secret
opts[:provider_ignores_state] = SiteSetting.oauth2_disable_csrf
opts[:client_options] = {
authorize_url: SiteSetting.oauth2_authorize_url,
token_url: SiteSetting.oauth2_token_url,
token_method: SiteSetting.oauth2_token_url_method.downcase.to_sym
}
opts[:authorize_options] = SiteSetting.oauth2_authorize_options.split("|").map(&:to_sym)

if SiteSetting.oauth2_authorize_signup_url.present? &&
ActionDispatch::Request.new(env).params["signup"].present?
opts[:client_options][:authorize_url] = SiteSetting.oauth2_authorize_signup_url
end

if SiteSetting.oauth2_send_auth_header? && SiteSetting.oauth2_send_auth_body?
# For maximum compatibility we include both header and body auth by default
# This is a little unusual, and utilising multiple authentication methods
# is technically disallowed by the spec (RFC2749 Section 5.2)
opts[:client_options][:auth_scheme] = :request_body
opts[:token_params] = { headers: { 'Authorization' => basic_auth_header } }
elsif SiteSetting.oauth2_send_auth_header?
opts[:client_options][:auth_scheme] = :basic_auth
else
opts[:client_options][:auth_scheme] = :request_body
end

unless SiteSetting.oauth2_scope.blank?
opts[:scope] = SiteSetting.oauth2_scope
end

opts[:client_options][:connection_build] = lambda { |builder|
if SiteSetting.oauth2_debug_auth && defined? OAuth2FaradayFormatter
builder.response :logger, Rails.logger, { bodies: true, formatter: OAuth2FaradayFormatter }
setup:
lambda { |env|
opts = env["omniauth.strategy"].options
opts[:client_id] = SiteSetting.oauth2_client_id
opts[:client_secret] = SiteSetting.oauth2_client_secret
opts[:provider_ignores_state] = SiteSetting.oauth2_disable_csrf
opts[:client_options] = {
authorize_url: SiteSetting.oauth2_authorize_url,
token_url: SiteSetting.oauth2_token_url,
token_method: SiteSetting.oauth2_token_url_method.downcase.to_sym,
}
opts[:authorize_options] = SiteSetting
.oauth2_authorize_options
.split("|")
.map(&:to_sym)

if SiteSetting.oauth2_authorize_signup_url.present? &&
ActionDispatch::Request.new(env).params["signup"].present?
opts[:client_options][
:authorize_url
] = SiteSetting.oauth2_authorize_signup_url
end

if SiteSetting.oauth2_send_auth_header? &&
SiteSetting.oauth2_send_auth_body?
# For maximum compatibility we include both header and body auth by default
# This is a little unusual, and utilising multiple authentication methods
# is technically disallowed by the spec (RFC2749 Section 5.2)
opts[:client_options][:auth_scheme] = :request_body
opts[:token_params] = {
headers: {
"Authorization" => basic_auth_header,
},
}
elsif SiteSetting.oauth2_send_auth_header?
opts[:client_options][:auth_scheme] = :basic_auth
else
opts[:client_options][:auth_scheme] = :request_body
end

unless SiteSetting.oauth2_scope.blank?
opts[:scope] = SiteSetting.oauth2_scope
end

builder.request :url_encoded # form-encode POST params
builder.adapter FinalDestination::FaradayAdapter # make requests with FinalDestination::HTTP
opts[:client_options][:connection_build] = lambda do |builder|
if SiteSetting.oauth2_debug_auth && defined?(OAuth2FaradayFormatter)
builder.response :logger,
Rails.logger,
{ bodies: true, formatter: OAuth2FaradayFormatter }
end

builder.request :url_encoded # form-encode POST params
builder.adapter FinalDestination::FaradayAdapter # make requests with FinalDestination::HTTP
end
}
}
end

def basic_auth_header
"Basic " + Base64.strict_encode64("#{SiteSetting.oauth2_client_id}:#{SiteSetting.oauth2_client_secret}")
"Basic " +
Base64.strict_encode64("#{SiteSetting.oauth2_client_id}:#{SiteSetting.oauth2_client_secret}")
end

def walk_path(fragment, segments, seg_index = 0)
Expand Down Expand Up @@ -182,19 +196,21 @@ def parse_segments(path)
quoted = false
escaped = false

path.split("").each do |char|
next_char_escaped = false
if !escaped && (char == '"')
quoted = !quoted
elsif !escaped && !quoted && (char == '.')
segments.append +""
elsif !escaped && (char == '\\')
next_char_escaped = true
else
segments.last << char
path
.split("")
.each do |char|
next_char_escaped = false
if !escaped && (char == '"')
quoted = !quoted
elsif !escaped && !quoted && (char == ".")
segments.append +""
elsif !escaped && (char == '\\')
next_char_escaped = true
else
segments.last << char
end
escaped = next_char_escaped
end
escaped = next_char_escaped
end

segments
end
Expand All @@ -204,14 +220,14 @@ def log(info)
end

def fetch_user_details(token, id)
user_json_url = SiteSetting.oauth2_user_json_url.sub(':token', token.to_s).sub(':id', id.to_s)
user_json_url = SiteSetting.oauth2_user_json_url.sub(":token", token.to_s).sub(":id", id.to_s)
user_json_method = SiteSetting.oauth2_user_json_url_method.downcase.to_sym

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

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

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

def primary_email_verified?(auth)
return true if SiteSetting.oauth2_email_verified
verified = auth['info']['email_verified']
verified = auth["info"]["email_verified"]
verified = true if verified == "true"
verified = false if verified == "false"
verified
Expand All @@ -254,19 +270,25 @@ def always_update_user_email?
end

def after_authenticate(auth, existing_account: nil)
log("after_authenticate response: \n\ncreds: #{auth['credentials'].to_hash}\nuid: #{auth['uid']}\ninfo: #{auth['info'].to_hash}\nextra: #{auth['extra'].to_hash}")
log(
"after_authenticate response: \n\ncreds: #{auth["credentials"].to_hash}\nuid: #{auth["uid"]}\ninfo: #{auth["info"].to_hash}\nextra: #{auth["extra"].to_hash}",
)

if SiteSetting.oauth2_fetch_user_details?
if fetched_user_details = fetch_user_details(auth['credentials']['token'], auth['uid'])
auth['uid'] = fetched_user_details[:user_id] if fetched_user_details[:user_id]
auth['info']['nickname'] = fetched_user_details[:username] if fetched_user_details[:username]
auth['info']['image'] = fetched_user_details[:avatar] if fetched_user_details[:avatar]
['name', 'email', 'email_verified'].each do |property|
auth['info'][property] = fetched_user_details[property.to_sym] if fetched_user_details[property.to_sym]
if fetched_user_details = fetch_user_details(auth["credentials"]["token"], auth["uid"])
auth["uid"] = fetched_user_details[:user_id] if fetched_user_details[:user_id]
auth["info"]["nickname"] = fetched_user_details[:username] if fetched_user_details[
:username
]
auth["info"]["image"] = fetched_user_details[:avatar] if fetched_user_details[:avatar]
%w[name email email_verified].each do |property|
auth["info"][property] = fetched_user_details[property.to_sym] if fetched_user_details[
property.to_sym
]
end

DiscoursePluginRegistry.oauth2_basic_additional_json_paths.each do |detail|
auth['extra'][detail] = fetched_user_details["extra:#{detail}"]
auth["extra"][detail] = fetched_user_details["extra:#{detail}"]
end
else
result = Auth::Result.new
Expand All @@ -284,7 +306,9 @@ def enabled?
end
end

auth_provider title_setting: "oauth2_button_title",
authenticator: OAuth2BasicAuthenticator.new
auth_provider title_setting: "oauth2_button_title", authenticator: OAuth2BasicAuthenticator.new

load File.expand_path("../lib/validators/oauth2_basic/oauth2_fetch_user_details_validator.rb", __FILE__)
load File.expand_path(
"../lib/validators/oauth2_basic/oauth2_fetch_user_details_validator.rb",
__FILE__,
)
20 changes: 9 additions & 11 deletions spec/integration/overrides_email_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
fab!(:initial_email) { "initial@example.com" }
fab!(:new_email) { "new@example.com" }
fab!(:user) { Fabricate(:user, email: initial_email) }
fab!(:uac) { UserAssociatedAccount.create!(user: user, provider_name: "oauth2_basic", provider_uid: "12345") }
fab!(:uac) do
UserAssociatedAccount.create!(user: user, provider_name: "oauth2_basic", provider_uid: "12345")
end

before do
SiteSetting.oauth2_enabled = true
Expand All @@ -16,17 +18,13 @@

OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:oauth2_basic] = OmniAuth::AuthHash.new(
provider: 'oauth2_basic',
uid: '12345',
info: OmniAuth::AuthHash::InfoHash.new(
email: new_email
),
provider: "oauth2_basic",
uid: "12345",
info: OmniAuth::AuthHash::InfoHash.new(email: new_email),
extra: {
raw_info: OmniAuth::AuthHash.new(
email_verified: true
)
raw_info: OmniAuth::AuthHash.new(email_verified: true),
},
credentials: OmniAuth::AuthHash.new
credentials: OmniAuth::AuthHash.new,
)
end

Expand All @@ -40,7 +38,7 @@
expect(user.reload.email).to eq(initial_email)
end

it 'updates user email if enabled' do
it "updates user email if enabled" do
SiteSetting.oauth2_overrides_email = true

get "/auth/oauth2_basic/callback"
Expand Down
Loading