From bce6e9e878c4e3843f8ba8473778cc4b0595144f Mon Sep 17 00:00:00 2001 From: Blake Erickson Date: Wed, 16 May 2018 14:53:10 -0600 Subject: [PATCH] ADD: can now walk json that contains arrays I feel like this is kind of a hack to handle a change with Auth0 where the actual user id is inside of an array of identities. While I do think it would be good to build an actual plugin for Auth0 to better handle their use case I do feel that it is important that we can handle Auth0 with this plugin for now. --- plugin.rb | 8 ++++++-- spec/plugin_spec.rb | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/plugin.rb b/plugin.rb index 09c7f6f..38dcd5d 100644 --- a/plugin.rb +++ b/plugin.rb @@ -50,8 +50,12 @@ class OAuth2BasicAuthenticator < ::Auth::OAuth2Authenticator def walk_path(fragment, segments) first_seg = segments[0] return if first_seg.blank? || fragment.blank? - return nil unless fragment.is_a?(Hash) - deref = fragment[first_seg] || fragment[first_seg.to_sym] + return nil unless fragment.is_a?(Hash) || fragment.is_a?(Array) + if fragment.is_a?(Hash) + deref = fragment[first_seg] || fragment[first_seg.to_sym] + else + deref = fragment[0] # Take just the first array for now, maybe later we can teach it to walk the array if we need to + end return (deref.blank? || segments.size == 1) ? deref : walk_path(deref, segments[1..-1]) end diff --git a/spec/plugin_spec.rb b/spec/plugin_spec.rb index dfe7607..4ecf4f7 100644 --- a/spec/plugin_spec.rb +++ b/spec/plugin_spec.rb @@ -1,4 +1,5 @@ require 'rails_helper' +require 'json' # This is ugly... but it works! # Need to load plugin.rb to avoid: @@ -40,4 +41,32 @@ describe OAuth2BasicAuthenticator do expect(result.user).to eq(user) end end + + it 'can walk json' do + authenticator = OAuth2BasicAuthenticator.new('oauth2_basic') + json_string = '{"user":{"id":1234,"email":{"address":"test@example.com"}}}' + SiteSetting.oauth2_json_email_path = 'user.email.address' + result = authenticator.json_walk({}, JSON.parse(json_string), :email) + + expect(result).to eq "test@example.com" + end + + it 'can walk json that contains an array' do + authenticator = OAuth2BasicAuthenticator.new('oauth2_basic') + json_string = '{"email":"test@example.com","identities":[{"user_id":"123456789","provider":"auth0","isSocial":false}]}' + SiteSetting.oauth2_json_user_id_path = 'identities.[].user_id' + result = authenticator.json_walk({}, JSON.parse(json_string), :user_id) + + expect(result).to eq "123456789" + end + + it 'can walk json and handle an empty array' do + authenticator = OAuth2BasicAuthenticator.new('oauth2_basic') + json_string = '{"email":"test@example.com","identities":[]}' + SiteSetting.oauth2_json_user_id_path = 'identities.[].user_id' + result = authenticator.json_walk({}, JSON.parse(json_string), :user_id) + + expect(result).to eq nil + end + end