diff --git a/app/controllers/oauth/authorized_applications_controller.rb b/app/controllers/oauth/authorized_applications_controller.rb index 267409a9ce..9e541e5e3c 100644 --- a/app/controllers/oauth/authorized_applications_controller.rb +++ b/app/controllers/oauth/authorized_applications_controller.rb @@ -35,12 +35,6 @@ class Oauth::AuthorizedApplicationsController < Doorkeeper::AuthorizedApplicatio end def set_last_used_at_by_app - @last_used_at_by_app = Doorkeeper::AccessToken - .select('DISTINCT ON (application_id) application_id, last_used_at') - .where(resource_owner_id: current_resource_owner.id) - .where.not(last_used_at: nil) - .order(application_id: :desc, last_used_at: :desc) - .pluck(:application_id, :last_used_at) - .to_h + @last_used_at_by_app = current_resource_owner.applications_last_used end end diff --git a/app/models/user.rb b/app/models/user.rb index f717dcd860..be9ebac699 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -280,6 +280,15 @@ class User < ApplicationRecord save! end + def applications_last_used + Doorkeeper::AccessToken + .where(resource_owner_id: id) + .where.not(last_used_at: nil) + .group(:application_id) + .maximum(:last_used_at) + .to_h + end + def token_for_app(app) return nil if app.nil? || app.owner != self diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 4393be5a4e..9a5a070d25 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -598,4 +598,27 @@ RSpec.describe User do end end end + + describe '#applications_last_used' do + let!(:user) { Fabricate(:user) } + + let!(:never_used_application) { Fabricate :application, owner: user } + let!(:application_one) { Fabricate :application, owner: user } + let!(:application_two) { Fabricate :application, owner: user } + + before do + _other_user_token = Fabricate :access_token, last_used_at: 3.days.ago + _never_used_token = Fabricate :access_token, application: never_used_application, resource_owner_id: user.id, last_used_at: nil + _app_one_old_token = Fabricate :access_token, application: application_one, resource_owner_id: user.id, last_used_at: 5.days.ago + _app_one_new_token = Fabricate :access_token, application: application_one, resource_owner_id: user.id, last_used_at: 1.day.ago + _never_used_token = Fabricate :access_token, application: application_two, resource_owner_id: user.id, last_used_at: 5.days.ago + end + + it 'returns a hash of unique applications with last used values' do + expect(user.applications_last_used) + .to include(application_one.id => be_within(1.0).of(1.day.ago)) + .and include(application_two.id => be_within(1.0).of(5.days.ago)) + .and not_include(never_used_application.id) + end + end end