OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Extract common functionality between account and omniauth controller
Oliver Günther3b50663c34b0
diff --git a/app/controllers/account_controller.rb b/app/controllers/account_controller.rbindex e1fa97a0492..3d7f75cceeb 100644--- a/app/controllers/account_controller.rb+++ b/app/controllers/account_controller.rb@@ -32,6 +32,7 @@ class AccountController < ApplicationControllerinclude Accounts::Registrationinclude Accounts::UserConsentinclude Accounts::UserLimits+ include Accounts::UserLogininclude Accounts::UserPasswordChange# prevents login action to be filtered by check_if_login_required application scope filterdiff --git a/app/controllers/concerns/accounts/registration.rb b/app/controllers/concerns/accounts/registration.rbindex 7c52a08c6e5..ca11d39edfc 100644--- a/app/controllers/concerns/accounts/registration.rb+++ b/app/controllers/concerns/accounts/registration.rb@@ -49,7 +49,7 @@ module Accounts::Registrationredirect_to signin_path(back_url: params[:back_url])end- def register_plain_user(user)+ def register_plain_user(user) # rubocop:disable Metrics/AbcSizeuser.attributes = permitted_params.user.transform_values do |val|if val.is_a? Stringval.strip!@@ -64,7 +64,7 @@ module Accounts::Registrationrespond_for_registered_user(user)end- def register_with_auth_source(user)+ def register_with_auth_source(user) # rubocop:disable Metrics/AbcSize# on-the-fly registration via omniauth or via auth sourceif pending_omniauth_registration?user.assign_attributes permitted_params.user_register_via_omniauth@@ -79,6 +79,28 @@ module Accounts::Registrationendend+ def register_via_omniauth(session, user_attributes)+ handle_omniauth_authentication(session[:auth_source_registration], user_params: user_attributes)+ end++ def handle_omniauth_authentication(auth_hash, user_params: nil) # rubocop:disable Metrics/AbcSize+ call = ::Authentication::OmniauthService+ .new(strategy: request.env["omniauth.strategy"], auth_hash:, controller: self)+ .call(user_params)++ if call.success?+ session[:omniauth_provider] = auth_hash[:provider]+ flash[:notice] = call.message if call.message.present?+ login_user_if_active(call.result, just_registered: call.result.just_created?)+ elsif call.includes_error?(:base, :failed_to_activate)+ redirect_omniauth_register_modal(call.result, auth_hash)+ else+ error = call.message+ Rails.logger.error "Authorization request failed: #{error}"+ show_error error+ end+ end+def respond_for_registered_user(user)call = ::Users::RegisterUserService.new(user).call@@ -116,6 +138,11 @@ module Accounts::RegistrationHash(session[:auth_source_registration])[:omniauth]end+ def show_error(error)+ flash[:error] = error+ redirect_to signin_path+ end+# Log an attempt to log in to an account in "registered" state and show a flash message.def account_not_activated(flash_now: true)flash_error_message(log_reason: "NOT ACTIVATED", flash_now:) dodiff --git a/app/controllers/concerns/accounts/user_login.rb b/app/controllers/concerns/accounts/user_login.rbindex 698f8280588..4ff237cc3f8 100644--- a/app/controllers/concerns/accounts/user_login.rb+++ b/app/controllers/concerns/accounts/user_login.rb@@ -10,4 +10,33 @@ module Accounts::UserLoginredirect_after_login(user)end++ ##+ # Log an attempt to log in to a locked account or with invalid credentials+ # and show a flash message.+ def flash_and_log_invalid_credentials(flash_now: true, is_logged_in: false)+ if is_logged_in+ flash[:error] = I18n.t(:notice_account_wrong_password)+ return+ end++ flash_error_message(log_reason: "invalid credentials", flash_now:) do+ if Setting.brute_force_block_after_failed_logins.to_i > 0+ :notice_account_invalid_credentials_or_blocked+ else+ :notice_account_invalid_credentials+ end+ end+ end++ def flash_error_message(log_reason: "", flash_now: true)+ flash_hash = flash_now ? flash.now : flash++ logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} " \+ "at #{Time.now.utc}: #{log_reason}"++ flash_message = yield++ flash_hash[:error] = I18n.t(flash_message)+ endenddiff --git a/app/controllers/concerns/accounts/user_password_change.rb b/app/controllers/concerns/accounts/user_password_change.rbindex b6ea6e6db3e..c4b602d7c95 100644--- a/app/controllers/concerns/accounts/user_password_change.rb+++ b/app/controllers/concerns/accounts/user_password_change.rb@@ -61,24 +61,6 @@ module Accounts::UserPasswordChangerender_password_change user, call.message, show_user_name:end- ##- # Log an attempt to log in to a locked account or with invalid credentials- # and show a flash message.- def flash_and_log_invalid_credentials(flash_now: true, is_logged_in: false)- if is_logged_in- flash[:error] = I18n.t(:notice_account_wrong_password)- return- end-- flash_error_message(log_reason: "invalid credentials", flash_now:) do- if Setting.brute_force_block_after_failed_logins.to_i > 0- :notice_account_invalid_credentials_or_blocked- else- :notice_account_invalid_credentials- end- end- end-def render_password_change(user, message, show_user_name: false)flash[:error] = message unless message.nil?@user = user@@ -98,15 +80,4 @@ module Accounts::UserPasswordChangeendfalseend-- def flash_error_message(log_reason: "", flash_now: true)- flash_hash = flash_now ? flash.now : flash-- logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} " \- "at #{Time.now.utc}: #{log_reason}"-- flash_message = yield-- flash_hash[:error] = I18n.t(flash_message)- endenddiff --git a/app/controllers/omni_auth_login_controller.rb b/app/controllers/omni_auth_login_controller.rbindex cb2eaf7e68e..74dad853055 100644--- a/app/controllers/omni_auth_login_controller.rb+++ b/app/controllers/omni_auth_login_controller.rb@@ -29,6 +29,7 @@class OmniAuthLoginController < ApplicationControllerinclude OmniauthHelperinclude Accounts::Registration+ include Accounts::UserLogin# disable CSRF protection since that should be covered by the omniauth strategy# the other filters are not applicable either since OmniAuth is doing authentication@@ -39,13 +40,13 @@ class OmniAuthLoginController < ApplicationControllerskip_before_action :check_if_login_requiredskip_before_action :check_session_lifetime- no_authorization_required! :login, :failure+ no_authorization_required! :callback, :failurehelper :omniauthlayout "no_menu"- def login+ def callbackparams[:back_url] = omniauth_back_url if remember_back_url?# Extract auth info and perform check / login or activate user@@ -82,30 +83,5 @@ class OmniAuthLoginController < ApplicationControllerrequest.env["omniauth.origin"].presence || params[:RelayState]end- def show_error(error)- flash[:error] = error- redirect_to action: :login- end-- def register_via_omniauth(session, user_attributes)- handle_omniauth_authentication(session[:auth_source_registration], user_params: user_attributes)- end-- def handle_omniauth_authentication(auth_hash, user_params: nil) # rubocop:disable Metrics/AbcSize- call = ::Authentication::OmniauthService- .new(strategy: request.env["omniauth.strategy"], auth_hash:, controller: self)- .call(user_params)-- if call.success?- session[:omniauth_provider] = auth_hash[:provider]- flash[:notice] = call.message if call.message.present?- login_user_if_active(call.result, just_registered: call.result.just_created?)- elsif call.includes_error?(:base, :failed_to_activate)- redirect_omniauth_register_modal(call.result, auth_hash)- else- error = call.message- Rails.logger.error "Authorization request failed: #{error}"- show_error error- end- end+ def default_breadcrumb; endenddiff --git a/config/routes.rb b/config/routes.rbindex 4818683c2c9..9caca4554e3 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -63,7 +63,7 @@ Rails.application.routes.draw do# Add catch method for Rack OmniAuth to allow route helpers# Note: This renders a 404 in rails but is caught by omniauth in Rack before- get "/auth/failure", to: "account#failure"+ get "/auth/failure", to: "omni_auth_login#failure", as: "omni_auth_failure"get "/auth/:provider", to: proc { [404, {}, [""]] }, as: "omni_auth_start"match "/auth/:provider/callback", to: "omni_auth_login#callback", as: "omni_auth_callback", via: %i[get post]diff --git a/modules/auth_saml/lib/open_project/auth_saml/engine.rb b/modules/auth_saml/lib/open_project/auth_saml/engine.rbindex 730510ea996..09f680d1cc3 100644--- a/modules/auth_saml/lib/open_project/auth_saml/engine.rb+++ b/modules/auth_saml/lib/open_project/auth_saml/engine.rb@@ -73,7 +73,7 @@ module OpenProject# Set the uid and index for the logout in this session againsession.merge! prev_session.slice(*h[:retain_from_session])- redirect_to omni_auth_start_path(h[:name]) + "/spslo"+ redirect_to "#{omni_auth_start_path(h[:name])}/spslo"endh.symbolize_keysdiff --git a/spec/controllers/account_controller_spec.rb b/spec/controllers/account_controller_spec.rbindex ad9ceb42dd2..4753200c817 100644--- a/spec/controllers/account_controller_spec.rb+++ b/spec/controllers/account_controller_spec.rb@@ -1040,4 +1040,78 @@ RSpec.describe AccountController, :skip_2fa_stage doendendend++ describe "registering through auth source" do+ context "when not providing all required fields" do+ let(:omniauth_strategy) { double("Google Strategy", name: "google") } # rubocop:disable RSpec/VerifiedDoubles+ let(:omniauth_hash) do+ OmniAuth::AuthHash.new(+ provider: "google",+ strategy: omniauth_strategy,+ uid: "123545",+ info: { name: "foo",+ email: "[email protected]",+ first_name: "foo",+ last_name: "bar" }+ )+ end++ before do+ request.env["omniauth.auth"] = omniauth_hash+ request.env["omniauth.strategy"] = omniauth_strategy+ end++ it "registers user via post" do+ allow(OpenProject::OmniAuth::Authorization).to receive(:after_login!)++ auth_source_registration = omniauth_hash.merge(+ omniauth: true,+ timestamp: Time.current+ )+ session[:auth_source_registration] = auth_source_registration+ post :register,+ params: {+ user: {+ login: "[email protected]",+ firstname: "Foo",+ lastname: "Smith",+ mail: "[email protected]"+ }+ }+ expect(response).to redirect_to home_url(first_time_user: true)++ user = User.find_by_login("[email protected]")+ expect(OpenProject::OmniAuth::Authorization)+ .to have_received(:after_login!).with(user, a_hash_including(omniauth_hash), any_args)+ expect(user).to be_an_instance_of(User)+ expect(user.ldap_auth_source_id).to be_nil+ expect(user.current_password).to be_nil+ expect(user.identity_url).to eql("google:123545")+ end++ context "when after a timeout expired" do+ before do+ session[:auth_source_registration] = omniauth_hash.merge(+ omniauth: true,+ timestamp: 42.days.ago+ )+ end++ it "does not register the user when providing all the missing fields" do+ post :register,+ params: {+ user: {+ firstname: "Foo",+ lastname: "Smith",+ mail: "[email protected]"+ }+ }++ expect(response).to redirect_to signin_path+ expect(flash[:error]).to eq(I18n.t(:error_omniauth_registration_timed_out))+ expect(User.find_by_login("[email protected]")).to be_nil+ end+ end+ end+ endenddiff --git a/spec/controllers/concerns/omniauth_login_spec.rb b/spec/controllers/concerns/omniauth_login_spec.rbindex b02e82b77b0..b7ff40174c3 100644--- a/spec/controllers/concerns/omniauth_login_spec.rb+++ b/spec/controllers/concerns/omniauth_login_spec.rb@@ -29,7 +29,7 @@require "spec_helper"# Concern is included into AccountController and depends on methods available there-RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/SpecFilePathFormat+RSpec.describe OmniAuthLoginController, :skip_2fa_stage do # rubocop:disable RSpec/SpecFilePathFormatlet(:omniauth_strategy) { double("Google Strategy", name: "google") } # rubocop:disable RSpec/VerifiedDoubleslet(:omniauth_hash) doOmniAuth::AuthHash.new(@@ -57,7 +57,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Specontext "when providing all required fields" dobefore dorequest.env["omniauth.origin"] = "https://example.net/some_back_url"- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "registers the user on-the-fly" do@@ -93,7 +93,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendit "takes the uid from the mapped attributes" do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }user = User.find_by_login("[email protected]")expect(user).to be_an_instance_of(User)@@ -129,7 +129,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe}end- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }user = User.find_by_login("[email protected]")expect(user).to be_an_instance_of(User)@@ -142,7 +142,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spedescribe "unavailable" doit "keeps the default mapping" do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }user = User.find_by_login("[email protected]")expect(user).to be_an_instance_of(User)@@ -163,62 +163,10 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendit "renders user form" do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to render_template :registerexpect(assigns(:user).mail).to eql("[email protected]")end-- it "registers user via post" do- allow(OpenProject::OmniAuth::Authorization).to receive(:after_login!)-- auth_source_registration = omniauth_hash.merge(- omniauth: true,- timestamp: Time.current- )- session[:auth_source_registration] = auth_source_registration- post :register,- params: {- user: {- login: "[email protected]",- firstname: "Foo",- lastname: "Smith",- mail: "[email protected]"- }- }- expect(response).to redirect_to home_url(first_time_user: true)-- user = User.find_by_login("[email protected]")- expect(OpenProject::OmniAuth::Authorization)- .to have_received(:after_login!).with(user, a_hash_including(omniauth_hash), any_args)- expect(user).to be_an_instance_of(User)- expect(user.ldap_auth_source_id).to be_nil- expect(user.current_password).to be_nil- expect(user.identity_url).to eql("google:123545")- end-- context "when after a timeout expired" do- before do- session[:auth_source_registration] = omniauth_hash.merge(- omniauth: true,- timestamp: 42.days.ago- )- end-- it "does not register the user when providing all the missing fields" do- post :register,- params: {- user: {- firstname: "Foo",- lastname: "Smith",- mail: "[email protected]"- }- }-- expect(response).to redirect_to signin_path- expect(flash[:error]).to eq(I18n.t(:error_omniauth_registration_timed_out))- expect(User.find_by_login("[email protected]")).to be_nil- end- endendcontext "with self-registration disabled",@@ -237,7 +185,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spebefore dorequest.env["omniauth.origin"] = "https://example.net/some_back_url"- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "shows a notice about the activated account", :aggregate_failures do@@ -274,14 +222,14 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendit "signs in the user after successful external authentication" do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to redirect_to my_page_pathendit "logs a successful login" dopost_at = Time.now.utc- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }user.reloadexpect(user.last_login_on.utc.to_i).to be >= post_at.utc.to_i@@ -290,7 +238,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Specontext "with a back_url present" dobefore dorequest.env["omniauth.origin"] = "http://test.host/projects"- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "redirects to that url", :aggregate_failures do@@ -301,7 +249,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Specontext "with a back_url from a login path" dobefore dorequest.env["omniauth.origin"] = "http://test.host/login"- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "redirects to that url", :aggregate_failures do@@ -322,7 +270,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendit "signs in the user after successful external authentication" do- expect { post :omniauth_login, params: { provider: :google } }+ expect { post :callback, params: { provider: :google } }.not_to change { user.reload.firstname }expect(response).to redirect_to my_page_path@@ -376,7 +324,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendit "logs in the user" do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to redirect_to my_page_pathexpect(OpenProject::OmniAuth::Authorization)@@ -389,7 +337,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendit "is rejected against google" do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to redirect_to signin_pathexpect(flash[:error]).to eq "I only want to see [email protected] here."@@ -399,7 +347,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speit "is rejected against any other provider too" doomniauth_hash.provider = "any other"- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to redirect_to signin_pathexpect(flash[:error]).to eq "I only want to see [email protected] here."@@ -416,7 +364,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendit "is rejected against google" do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to redirect_to signin_pathexpect(flash[:error]).to eq "Go away foo!"@@ -427,7 +375,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speit "is approved against any other provider" doomniauth_hash.provider = "some other"- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to redirect_to home_url(first_time_user: true)@@ -444,7 +392,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speomniauth_hash.provider = "yet another"config.global_email = "[email protected]"- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }expect(response).to redirect_to signin_pathexpect(flash[:error]).to eq "I only want to see [email protected] here."@@ -460,7 +408,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speuser.registeruser.save!- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "shows a notice about the activated account", :aggregate_failures do@@ -475,7 +423,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speuser.inviteuser.save!- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "shows a notice about the activated account", :aggregate_failures do@@ -490,7 +438,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speuser.lockuser.save!- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "shows an error indicating a failed login", :aggregate_failures do@@ -511,7 +459,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Speendbefore do- post :omniauth_login, params: { provider: :google }+ post :callback, params: { provider: :google }endit "responds with an error" do@@ -530,13 +478,13 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spedescribe "Error occurs during authentication" doit "redirects to login page" do- post :omniauth_failure+ post :failureexpect(response).to redirect_to signin_pathendit "logs a warn message" doallow(Rails.logger).to receive(:warn)- post :omniauth_failure, params: { message: "invalid_credentials" }+ post :failure, params: { message: "invalid_credentials" }expect(Rails.logger).to have_received(:warn).with("invalid_credentials")end