Skip to content

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

Extract common functionality between account and omniauth controller

Oliver Günther3b50663c34b0
diff --git a/app/controllers/account_controller.rb b/app/controllers/account_controller.rb
index e1fa97a0492..3d7f75cceeb 100644
--- a/app/controllers/account_controller.rb
+++ b/app/controllers/account_controller.rb
@@ -32,6 +32,7 @@ class AccountController < ApplicationController
include Accounts::Registration
include Accounts::UserConsent
include Accounts::UserLimits
+ include Accounts::UserLogin
include Accounts::UserPasswordChange
# prevents login action to be filtered by check_if_login_required application scope filter
diff --git a/app/controllers/concerns/accounts/registration.rb b/app/controllers/concerns/accounts/registration.rb
index 7c52a08c6e5..ca11d39edfc 100644
--- a/app/controllers/concerns/accounts/registration.rb
+++ b/app/controllers/concerns/accounts/registration.rb
@@ -49,7 +49,7 @@ module Accounts::Registration
redirect_to signin_path(back_url: params[:back_url])
end
- def register_plain_user(user)
+ def register_plain_user(user) # rubocop:disable Metrics/AbcSize
user.attributes = permitted_params.user.transform_values do |val|
if val.is_a? String
val.strip!
@@ -64,7 +64,7 @@ module Accounts::Registration
respond_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 source
if pending_omniauth_registration?
user.assign_attributes permitted_params.user_register_via_omniauth
@@ -79,6 +79,28 @@ module Accounts::Registration
end
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 respond_for_registered_user(user)
call = ::Users::RegisterUserService.new(user).call
@@ -116,6 +138,11 @@ module Accounts::Registration
Hash(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:) do
diff --git a/app/controllers/concerns/accounts/user_login.rb b/app/controllers/concerns/accounts/user_login.rb
index 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::UserLogin
redirect_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)
+ end
end
diff --git a/app/controllers/concerns/accounts/user_password_change.rb b/app/controllers/concerns/accounts/user_password_change.rb
index 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::UserPasswordChange
render_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::UserPasswordChange
end
false
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)
- end
end
diff --git a/app/controllers/omni_auth_login_controller.rb b/app/controllers/omni_auth_login_controller.rb
index 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 < ApplicationController
include OmniauthHelper
include 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 < ApplicationController
skip_before_action :check_if_login_required
skip_before_action :check_session_lifetime
- no_authorization_required! :login, :failure
+ no_authorization_required! :callback, :failure
helper :omniauth
layout "no_menu"
- def login
+ def callback
params[: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 < ApplicationController
request.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; end
end
diff --git a/config/routes.rb b/config/routes.rb
index 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.rb
index 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 again
session.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"
end
h.symbolize_keys
diff --git a/spec/controllers/account_controller_spec.rb b/spec/controllers/account_controller_spec.rb
index 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 do
end
end
end
+
+ 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",
+ }
+ }
+ 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",
+ }
+ }
+
+ 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
+ end
end
diff --git a/spec/controllers/concerns/omniauth_login_spec.rb b/spec/controllers/concerns/omniauth_login_spec.rb
index 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/SpecFilePathFormat
let(:omniauth_strategy) { double("Google Strategy", name: "google") } # rubocop:disable RSpec/VerifiedDoubles
let(:omniauth_hash) do
OmniAuth::AuthHash.new(
@@ -57,7 +57,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
context "when providing all required fields" do
before do
request.env["omniauth.origin"] = "https://example.net/some_back_url"
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "registers the user on-the-fly" do
@@ -93,7 +93,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
end
it "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/Spe
describe "unavailable" do
it "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/Spe
end
it "renders user form" do
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
expect(response).to render_template :register
expect(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",
- }
- }
- 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",
- }
- }
-
- 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
context "with self-registration disabled",
@@ -237,7 +185,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
before do
request.env["omniauth.origin"] = "https://example.net/some_back_url"
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "shows a notice about the activated account", :aggregate_failures do
@@ -274,14 +222,14 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
end
it "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_path
end
it "logs a successful login" do
post_at = Time.now.utc
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
user.reload
expect(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/Spe
context "with a back_url present" do
before do
request.env["omniauth.origin"] = "http://test.host/projects"
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "redirects to that url", :aggregate_failures do
@@ -301,7 +249,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
context "with a back_url from a login path" do
before do
request.env["omniauth.origin"] = "http://test.host/login"
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "redirects to that url", :aggregate_failures do
@@ -322,7 +270,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
end
it "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/Spe
end
it "logs in the user" do
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
expect(response).to redirect_to my_page_path
expect(OpenProject::OmniAuth::Authorization)
@@ -389,7 +337,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
end
it "is rejected against google" do
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
expect(response).to redirect_to signin_path
expect(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/Spe
it "is rejected against any other provider too" do
omniauth_hash.provider = "any other"
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
expect(response).to redirect_to signin_path
expect(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/Spe
end
it "is rejected against google" do
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
expect(response).to redirect_to signin_path
expect(flash[:error]).to eq "Go away foo!"
@@ -427,7 +375,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
it "is approved against any other provider" do
omniauth_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/Spe
omniauth_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_path
expect(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/Spe
user.register
user.save!
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "shows a notice about the activated account", :aggregate_failures do
@@ -475,7 +423,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
user.invite
user.save!
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "shows a notice about the activated account", :aggregate_failures do
@@ -490,7 +438,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
user.lock
user.save!
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "shows an error indicating a failed login", :aggregate_failures do
@@ -511,7 +459,7 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
end
before do
- post :omniauth_login, params: { provider: :google }
+ post :callback, params: { provider: :google }
end
it "responds with an error" do
@@ -530,13 +478,13 @@ RSpec.describe AccountController, :skip_2fa_stage do # rubocop:disable RSpec/Spe
describe "Error occurs during authentication" do
it "redirects to login page" do
- post :omniauth_failure
+ post :failure
expect(response).to redirect_to signin_path
end
it "logs a warn message" do
allow(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