From 399fef668d0d2db7655da2536200e17f71a1b791 Mon Sep 17 00:00:00 2001 From: Billy Zhou Date: Tue, 26 Feb 2019 14:28:11 +0100 Subject: [PATCH] Refactoring: Simplyfied if statement and removed reference to issue #2431 because it's more of a byproduct than an actual fix. --- app/models/user.rb | 5 ++++- spec/models/user_spec.rb | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) 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