diff --git a/app/models/user.rb b/app/models/user.rb index cc0b712..5bd7282 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -5,7 +5,7 @@ class User < ApplicationRecord encrypts :slack_access_token, :github_access_token validates :slack_uid, uniqueness: true, allow_nil: true - validates :github_uid, uniqueness: true, allow_nil: true + validates :github_uid, uniqueness: { conditions: -> { where.not(github_access_token: nil) } }, allow_nil: true validates :timezone, inclusion: { in: TZInfo::Timezone.all_identifiers }, allow_nil: false validates :country_code, inclusion: { in: ISO3166::Country.codes }, allow_nil: true @@ -365,8 +365,17 @@ class User < ApplicationRecord Rails.logger.info "GitHub user data: #{user_data.inspect}" Rails.logger.info "GitHub user ID type: #{user_data['id'].class}" + # Clear GitHub access tokens from any other users with this GitHub UID + github_uid = user_data["id"] + other_users = User.where(github_uid: github_uid).where.not(id: current_user.id).where.not(github_access_token: nil) + + other_users.find_each do |user| + Rails.logger.info "Clearing GitHub token for User ##{user.id} (GitHub UID: #{github_uid}) - linking to new account" + user.update!(github_access_token: nil) + end + # Update GitHub-specific fields - current_user.github_uid = user_data["id"] + current_user.github_uid = github_uid current_user.username ||= user_data["login"] current_user.github_username = user_data["login"] current_user.github_avatar_url = user_data["avatar_url"] diff --git a/db/migrate/20250623135342_add_github_index_to_users.rb b/db/migrate/20250623135342_add_github_index_to_users.rb new file mode 100644 index 0000000..6445097 --- /dev/null +++ b/db/migrate/20250623135342_add_github_index_to_users.rb @@ -0,0 +1,6 @@ +class AddGithubIndexToUsers < ActiveRecord::Migration[8.0] + def change + add_index :users, [ :github_uid, :github_access_token ], + name: "index_users_on_github_uid_and_access_token" + end +end diff --git a/db/schema.rb b/db/schema.rb index e9504e1..87c9594 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[8.0].define(version: 2025_06_18_170000) do +ActiveRecord::Schema[8.0].define(version: 2025_06_23_135342) do create_schema "pganalyze" # These are extensions that must be enabled in order to support this database @@ -494,6 +494,7 @@ ActiveRecord::Schema[8.0].define(version: 2025_06_18_170000) do t.string "mailing_address_otc" t.boolean "allow_public_stats_lookup", default: true, null: false t.boolean "default_timezone_leaderboard", default: true, null: false + t.index ["github_uid", "github_access_token"], name: "index_users_on_github_uid_and_access_token" t.index ["slack_uid"], name: "index_users_on_slack_uid", unique: true t.index ["timezone"], name: "index_users_on_timezone" end