diff --git a/app/models/user.rb b/app/models/user.rb index 280431476..4062a83a7 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -634,7 +634,10 @@ returns =end def update_last_login - self.last_login = Time.zone.now + # reduce DB/ES load by updating last_login every 10 minutes only + if !last_login || last_login < 10.minutes.ago + self.last_login = Time.zone.now + end # reset login failed self.login_failed = 0 diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 3da030b27..454a61526 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -40,6 +40,33 @@ RSpec.describe User, type: :model do .to be(nil) end end + + it "updates user's updates last_login and updated_at attributes" do + expect { described_class.authenticate(user.login, password) } + .to change { user.reload.last_login } + .and change { user.reload.updated_at } + end + + context 'when authenticated multiple after another' do + + before { described_class.authenticate(user.login, password) } + + it "doesn't update last_login and updated_at when last login was less than 10 minutes ago" do + travel 9.minutes + + expect { described_class.authenticate(user.login, password) } + .to not_change { user.reload.last_login } + .and not_change { user.reload.updated_at } + end + + it 'updates last_login and updated_at when last login was more than 10 minutes ago' do + travel 11.minutes + + expect { described_class.authenticate(user.login, password) } + .to change { user.reload.last_login } + .and change { user.reload.updated_at } + end + end end context 'with valid user and invalid password' do