docbrown/app/models/identity.rb
Jeremy Friesen b115b2d17e
Appeasing Rubocop as it sneaks some changes in (#16085)
I was working on another branch and as part of my commit, Rubocop
removed a validation (but not the spec that asserted the validation).

Below is the "non-updating" rubocop offense on the other branch.

```shell
❯ rubocop ./app/models/notification_subscription.rb
Inspecting 1 file
C

Offenses:

app/models/notification_subscription.rb:13:29: C: [Correctable]
Rails/RedundantPresenceValidationOnBelongsTo: Remove explicit presence
validation for notifiable_id.
  validates :notifiable_id, presence: true
                            ^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense auto-correctable
```

To remediate, I ran:

```shell
> rubocop --only "Rails/RedundantPresenceValidationOnBelongsTo" \
  --auto-correct
```

This resolved the `app/models`.  Then did some regex magic and removed
the assertions from `spec/models`.

For Forem folks, I wrote a [forem.team post][1] discuss if this is how
we want to proceed.

[1]:https://forem.team/jeremy/rubocop-auto-updating-mayhem-33a6
2022-01-13 07:48:01 -05:00

49 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, 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