mirror of
https://github.com/discourse/discourse.git
synced 2024-11-30 12:43:54 -06:00
5c524ea8a4
Previously we used custom fields to denote a user was anonymous, this was risky in that custom fields are prone to race conditions and are not properly dedicated, missing constraints and so on. The new table `anonymous_users` is properly protected. There is only one possible shadow account per user, which is enforced using a constraint. Every anonymous user will have a unique row in the new table.
60 lines
1.6 KiB
Ruby
60 lines
1.6 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class AddUniqueConstraintToShadowAccounts < ActiveRecord::Migration[5.2]
|
|
|
|
def up
|
|
create_table :anonymous_users do |t|
|
|
t.integer :user_id, null: false
|
|
t.integer :master_user_id, null: false
|
|
t.boolean :active, null: false
|
|
t.timestamps
|
|
|
|
t.index [:user_id], unique: true
|
|
t.index [:master_user_id], unique: true, where: 'active'
|
|
end
|
|
|
|
rows = DB.exec <<~SQL
|
|
DELETE FROM user_custom_fields
|
|
WHERE name = 'shadow_id' AND value in (
|
|
SELECT value
|
|
FROM user_custom_fields
|
|
WHERE name = 'shadow_id'
|
|
GROUP BY value
|
|
HAVING COUNT(*) > 1
|
|
)
|
|
SQL
|
|
|
|
if rows > 0
|
|
STDERR.puts "Removed #{rows} duplicate shadow users"
|
|
end
|
|
|
|
rows = DB.exec <<~SQL
|
|
INSERT INTO anonymous_users(user_id, master_user_id, created_at, updated_at, active)
|
|
SELECT value::int, user_id, created_at, updated_at, 't'
|
|
FROM user_custom_fields
|
|
WHERE name = 'shadow_id'
|
|
SQL
|
|
|
|
rows += DB.exec <<~SQL
|
|
INSERT INTO anonymous_users(user_id, master_user_id, created_at, updated_at, active)
|
|
SELECT f.user_id, value::int, f.created_at, f.updated_at, 'f'
|
|
FROM user_custom_fields f
|
|
LEFT JOIN anonymous_users a on a.user_id = f.user_id
|
|
WHERE name = 'master_id' AND a.user_id IS NULL
|
|
SQL
|
|
|
|
if rows > 0
|
|
STDERR.puts "Migrated #{rows} anon users to new structure"
|
|
end
|
|
|
|
DB.exec <<~SQL
|
|
DELETE FROM user_custom_fields
|
|
WHERE name in ('shadow_id', 'master_id')
|
|
SQL
|
|
end
|
|
|
|
def down
|
|
raise ActiveRecord::IrreversibleMigration
|
|
end
|
|
end
|