Files
chatwoot/app/builders/account_builder.rb
Vishnu Narayanan df7401f71c fix: account email validation during signup (#11307)
- Refactor email validation logic to be a service
- Use the service for both email/pass signup and Google SSO
- fix account email validation during signup
- Use `blocked_domain` setting for both email/pass signup and Google
Sign In [`BLOCKED_DOMAIN` via GlobalConfig]
- add specs for `account_builder`
- add specs for the new service

---------

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2025-05-20 20:45:39 -07:00

78 lines
1.8 KiB
Ruby

# frozen_string_literal: true
class AccountBuilder
include CustomExceptions::Account
pattr_initialize [:account_name, :email!, :confirmed, :user, :user_full_name, :user_password, :super_admin, :locale]
def perform
if @user.nil?
validate_email
validate_user
end
ActiveRecord::Base.transaction do
@account = create_account
@user = create_and_link_user
end
[@user, @account]
rescue StandardError => e
Rails.logger.debug e.inspect
raise e
end
private
def user_full_name
# the empty string ensures that not-null constraint is not violated
@user_full_name || ''
end
def account_name
# the empty string ensures that not-null constraint is not violated
@account_name || ''
end
def validate_email
Account::SignUpEmailValidationService.new(@email).perform
end
def validate_user
if User.exists?(email: @email)
raise UserExists.new(email: @email)
else
true
end
end
def create_account
@account = Account.create!(name: account_name, locale: I18n.locale)
Current.account = @account
end
def create_and_link_user
if @user.present? || create_user
link_user_to_account(@user, @account)
@user
else
raise UserErrors.new(errors: @user.errors)
end
end
def link_user_to_account(user, account)
AccountUser.create!(
account_id: account.id,
user_id: user.id,
role: AccountUser.roles['administrator']
)
end
def create_user
@user = User.new(email: @email,
password: user_password,
password_confirmation: user_password,
name: user_full_name)
@user.type = 'SuperAdmin' if @super_admin
@user.confirm if @confirmed
@user.save!
end
end