diff --git a/app/models/user.rb b/app/models/user.rb index 56608f687..c6342695f 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -88,7 +88,6 @@ class User < ApplicationRecord before_validation :set_password_and_uid, on: :create - after_create_commit :create_access_token after_save :update_presence_in_redis, if: :saved_change_to_availability? scope :order_by_full_name, -> { order('lower(name) ASC') } diff --git a/db/migrate/20210714110714_remove_duplicate_access_tokens_for_existing_users.rb b/db/migrate/20210714110714_remove_duplicate_access_tokens_for_existing_users.rb new file mode 100644 index 000000000..23cacbf8a --- /dev/null +++ b/db/migrate/20210714110714_remove_duplicate_access_tokens_for_existing_users.rb @@ -0,0 +1,12 @@ +class RemoveDuplicateAccessTokensForExistingUsers < ActiveRecord::Migration[6.0] + def up + # find all models and group them on owner + grouped_tokens = AccessToken.all.group_by(&:owner) + grouped_tokens.each_value do |duplicates| + # we want to keep the latest token as it is being used in all requests + duplicates.pop + # Remaining ones are duplicates, delete them all + duplicates.each { |duplicate| AccessToken.find_by(id: duplicate).destroy } + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 399b27a3d..3eb64e8f8 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2021_07_08_140842) do +ActiveRecord::Schema.define(version: 2021_07_14_110714) do # These are extensions that must be enabled in order to support this database enable_extension "pg_stat_statements" diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index e9ec95754..8acff2aaa 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -72,4 +72,12 @@ RSpec.describe User do expect(user.valid_sso_auth_token?(sso_auth_token)).to eq false end end + + describe 'access token' do + it 'creates a single access token upon user creation' do + new_user = create(:user) + token_count = AccessToken.where(owner: new_user).count + expect(token_count).to eq(1) + end + end end