Skip to content

Commit 2edf32e

Browse files
committed
Discard outdated encrypted_github_access_token on after_find
Otherwise dirty attribute tracking will try to decrypt it and fail.
1 parent 053c5ba commit 2edf32e

File tree

2 files changed

+25
-13
lines changed

2 files changed

+25
-13
lines changed

app/models/shipit/user.rb

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ class User < Record
1414
validates :name, presence: true
1515

1616
encrypts :encrypted_github_access_token
17+
alias_attribute :github_access_token, :encrypted_github_access_token
18+
19+
after_find :discard_outdated_credentials!
1720

1821
def self.find_or_create_by_login!(login)
1922
find_or_create_by!(login: login) do |user|
@@ -58,14 +61,6 @@ def self.refresh_shard(shard_index, shards_count)
5861
end
5962
end
6063

61-
alias_attribute :github_access_token, :encrypted_github_access_token
62-
def github_access_token
63-
encrypted_github_access_token
64-
rescue ActiveRecord::Encryption::Errors::Decryption
65-
update_columns(encrypted_github_access_token: nil)
66-
nil
67-
end
68-
6964
def github_api
7065
return Shipit.github.api unless github_access_token
7166

@@ -134,6 +129,16 @@ def requires_fresh_login?
134129

135130
private
136131

132+
def discard_outdated_credentials!
133+
if encrypted_github_access_token_before_type_cast.present?
134+
begin
135+
encrypted_github_access_token
136+
rescue ActiveRecord::Encryption::Errors::Decryption
137+
update_column(:encrypted_github_access_token, nil)
138+
end
139+
end
140+
end
141+
137142
def identify_renamed_user!
138143
last_commit = commits.last
139144
return unless last_commit

test/models/users_test.rb

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -217,18 +217,25 @@ class UsersTest < ActiveSupport::TestCase
217217

218218
test "users with legacy encrypted access token get their token reset automatically" do
219219
legacy = shipit_users(:legacy)
220-
221-
assert_not_nil legacy.encrypted_github_access_token_before_type_cast
222-
223220
assert_nil legacy.github_access_token
224-
legacy.reload
225-
assert_nil legacy.encrypted_github_access_token_before_type_cast
226221

222+
legacy.update!(github_access_token: 'ghu_t0k3n')
223+
assert_equal 'ghu_t0k3n', legacy.github_access_token
224+
end
225+
226+
test "users with legacy encrypted access token can be updated" do
227+
legacy = shipit_users(:legacy)
227228
legacy.update!(github_access_token: 'ghu_t0k3n')
228229
legacy.reload
229230
assert_equal 'ghu_t0k3n', legacy.github_access_token
230231
end
231232

233+
test "users with legacy encrypted access token can have unrelated attributes updated" do
234+
legacy = shipit_users(:legacy)
235+
legacy.update!(name: 'Test')
236+
assert_equal 'Test', legacy.name
237+
end
238+
232239
test "users are always logged_in?" do
233240
assert_predicate @user, :logged_in?
234241
end

0 commit comments

Comments
 (0)