FIX: Redirect to provided origin after auth (#12558)

FIX: Redirect to provided origin after auth (#12558)

It used to redirect to the destination_url cookie which sometimes is set incorrectly.

diff --git a/app/controllers/users/omniauth_callbacks_controller.rb b/app/controllers/users/omniauth_callbacks_controller.rb
index b12852b..32b9bc3 100644
--- a/app/controllers/users/omniauth_callbacks_controller.rb
+++ b/app/controllers/users/omniauth_callbacks_controller.rb
@@ -40,7 +40,10 @@ class Users::OmniauthCallbacksController < ApplicationController
 
     preferred_origin = request.env['omniauth.origin']
 
-    if SiteSetting.enable_discourse_connect_provider && payload = cookies.delete(:sso_payload)
+    if session[:destination_url].present?
+      preferred_origin = session[:destination_url]
+      session.delete(:destination_url)
+    elsif SiteSetting.enable_discourse_connect_provider && payload = cookies.delete(:sso_payload)
       preferred_origin = session_sso_provider_url + "?" + payload
     elsif cookies[:destination_url].present?
       preferred_origin = cookies[:destination_url]
diff --git a/lib/middleware/omniauth_bypass_middleware.rb b/lib/middleware/omniauth_bypass_middleware.rb
index 4a32730..c794b11 100644
--- a/lib/middleware/omniauth_bypass_middleware.rb
+++ b/lib/middleware/omniauth_bypass_middleware.rb
@@ -34,6 +34,9 @@ class Middleware::OmniauthBypassMiddleware
 
       # If the user is trying to reconnect to an existing account, store in session
       request.session[:auth_reconnect] = !!request.params["reconnect"]
+
+      # If the client provided an origin, store in session to redirect back
+      request.session[:destination_url] = request.params["origin"]
     end
   end
 
diff --git a/spec/requests/omniauth_callbacks_controller_spec.rb b/spec/requests/omniauth_callbacks_controller_spec.rb
index 6024530..33359a2 100644
--- a/spec/requests/omniauth_callbacks_controller_spec.rb
+++ b/spec/requests/omniauth_callbacks_controller_spec.rb
@@ -766,6 +766,16 @@ RSpec.describe Users::OmniauthCallbacksController do
         expect(UserAssociatedAccount.count).to eq(1) # Reconnect has not yet happened
       end
 
+      it 'stores and redirects to \'origin\' parameter' do
+        # Log in normally
+        post "/auth/google_oauth2?origin=http://test.localhost/atesturl"
+        expect(response.status).to eq(302)
+        expect(session[:destination_url]).to eq("http://test.localhost/atesturl")
+
+        get "/auth/google_oauth2/callback.json"
+        expect(response.status).to eq(302)
+        expect(response.redirect_url).to eq("http://test.localhost/atesturl")
+      end
     end
 
     context 'after changing email' do

GitHub sha: dce48d8a

This commit appears in #12558 which was approved by eviltrout and davidtaylorhq. It was merged by davidtaylorhq.