From 97d04dcc9855c9184f774031b060ea47801a6fb9 Mon Sep 17 00:00:00 2001 From: moustachu Date: Wed, 15 Jan 2025 16:26:39 +0100 Subject: [PATCH] fix!(omniauth): keep verified email in session between registration form when needed --- config/application.rb | 1 + ...niauth_registrations_controller_extends.rb | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 lib/extends/controllers/decidim/devise/omniauth_registrations_controller_extends.rb diff --git a/config/application.rb b/config/application.rb index 759eb48b0d..b18de87ff4 100644 --- a/config/application.rb +++ b/config/application.rb @@ -48,6 +48,7 @@ class Application < Rails::Application config.after_initialize do # Controllers require "extends/controllers/decidim/devise/sessions_controller_extends" + require "extends/controllers/decidim/devise/omniauth_registrations_controller_extends" require "extends/controllers/decidim/editor_images_controller_extends" require "extends/controllers/decidim/proposals/proposals_controller_extends" require "extends/controllers/decidim/newsletters_controller_extends" diff --git a/lib/extends/controllers/decidim/devise/omniauth_registrations_controller_extends.rb b/lib/extends/controllers/decidim/devise/omniauth_registrations_controller_extends.rb new file mode 100644 index 0000000000..1922fe4657 --- /dev/null +++ b/lib/extends/controllers/decidim/devise/omniauth_registrations_controller_extends.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +module OmniauthRegistrationsControllerExtends + extend ActiveSupport::Concern + + included do + def create + form_params = user_params_from_oauth_hash || params[:user] + + @form = form(Decidim::OmniauthRegistrationForm).from_params(form_params) + @form.email ||= verified_email + + Decidim::CreateOmniauthRegistration.call(@form, verified_email) do + on(:ok) do |user| + if user.active_for_authentication? + sign_in_and_redirect user, event: :authentication + set_flash_message :notice, :success, kind: @form.provider.capitalize + else + expire_data_after_sign_in! + user.resend_confirmation_instructions unless user.confirmed? + redirect_to decidim.root_path + flash[:notice] = t("devise.registrations.signed_up_but_unconfirmed") + end + end + + on(:invalid) do + set_flash_message :notice, :success, kind: @form.provider.capitalize + session["devise.omniauth.verified_email"] = verified_email + render :new + end + + on(:error) do |user| + set_flash_message :alert, :failure, kind: @form.provider.capitalize, reason: t("decidim.devise.omniauth_registrations.create.email_already_exists") if user.errors[:email] + session["devise.omniauth.verified_email"] = verified_email + render :new + end + end + end + + private + + def verified_email + @verified_email ||= oauth_data.dig(:info, :email) || session.delete("devise.omniauth.verified_email") + end + end +end + +Decidim::Devise::OmniauthRegistrationsController.class_eval do + include(OmniauthRegistrationsControllerExtends) +end