mastodon/app/models/canonical_email_block.rb
Claire 3c18311d86 Fix error when suspending user with an already-existing canonical email block (#17036)
* Fix error when suspending user with an already-existing canonical email block

Fixes #17033

While attempting to create a `CanonicalEmailBlock` with an existing hash would
raise an `ActiveRecord::RecordNotUnique` error, this being done within a
transaction would cancel the whole transaction. For this reason, checking for
uniqueness in Rails would query the database within the transaction and avoid
invalidating the whole transaction for this reason.

A race condition is still possible, where multiple accounts sharing a canonical
email would be blocked in concurrent transactions, in which only one would
succeed, but that is way less likely to happen that the current issue, and can
always be retried after the first failure, unlike the current situation.

* Add tests
2021-11-26 01:22:10 +01:00

28 lines
782 B
Ruby

# frozen_string_literal: true
# == Schema Information
#
# Table name: canonical_email_blocks
#
# id :bigint(8) not null, primary key
# canonical_email_hash :string default(""), not null
# reference_account_id :bigint(8) not null
# created_at :datetime not null
# updated_at :datetime not null
#
class CanonicalEmailBlock < ApplicationRecord
include EmailHelper
belongs_to :reference_account, class_name: 'Account'
validates :canonical_email_hash, presence: true, uniqueness: true
def email=(email)
self.canonical_email_hash = email_to_canonical_email_hash(email)
end
def self.block?(email)
where(canonical_email_hash: email_to_canonical_email_hash(email)).exists?
end
end