docbrown/app/models/identity.rb
Jeremy Friesen ee0a521a83
Favoring delete_all on user relationships (#15443)
* Favoring delete_all on user relationships

Prior to this commit, several of the user's "has_many" were marked as
`depenedent: :destroy`.

In the case of :destroy, ActiveRecord instantiates each object and then
runs destroy. Whereas in the case of :delete, ActiveRecord issues a SQL
command to delete the related files.

It is often "safer" to use :destroy, as it guarantees that you'll
instantiate the record and run it's callbacks. But sometimes you have
to go with the speed of SQL.

And while not directly related to #15424 it is representative of our
callback ecosystem creating some unexpected computational loads.

Related to #15442 and #15424

* Noting models that user no longer cascade destroys
2021-11-23 11:50:12 -05:00

50 lines
1.8 KiB
Ruby

# @note When we destroy the related user, it's using dependent:
# :delete for the relationship. That means no before/after
# destroy callbacks will be called on this object.
class Identity < ApplicationRecord
NO_EMAIL_MSG = "No email found. Please relink your %<provider>s " \
"account to avoid errors.".freeze
belongs_to :user
scope :enabled, -> { where(provider: Authentication::Providers.enabled) }
Authentication::Providers.available.each do |provider_name|
scope provider_name, -> { where(provider: provider_name) }
end
validates :provider, inclusion: { in: Authentication::Providers.available.map(&:to_s) }
validates :uid, :provider, presence: true
validates :uid, uniqueness: { scope: :provider }, if: proc { |identity|
identity.uid_changed? || identity.provider_changed?
}
validates :user_id, presence: true
validates :user_id, uniqueness: { scope: :provider }, if: proc { |identity|
identity.user_id_changed? || identity.provider_changed?
}
# TODO: [@forem/oss] should this be transitioned to JSON?
serialize :auth_data_dump
# Builds an identity from OmniAuth's authentication payload
def self.build_from_omniauth(provider)
payload = provider.payload
identity = find_or_initialize_by(
provider: payload.provider,
uid: payload.uid,
)
identity.assign_attributes(
token: payload.credentials.token,
secret: payload.credentials.secret,
auth_data_dump: payload,
)
identity
end
def email
auth_data_dump&.info&.email || format(NO_EMAIL_MSG, provider: provider)
end
end