Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Move destruction into the autologin token and session link

Oliver Güntherec298dc14346
diff --git a/app/controllers/my/auto_login_tokens_controller.rb b/app/controllers/my/auto_login_tokens_controller.rb
index 176b4e6bf6a..c75274c2753 100644
--- a/app/controllers/my/auto_login_tokens_controller.rb
+++ b/app/controllers/my/auto_login_tokens_controller.rb
@@ -41,11 +41,6 @@ module My
def destroy
@token.destroy
- # Destroy all linked sessions to it
- linked_sessions = Sessions::AutologinSessionLink.where(token_id: @token.id)
- Sessions::UserSession.where(id: linked_sessions.select(:session_id)).delete_all
- linked_sessions.delete_all
-
flash[:notice] = I18n.t(:notice_successful_delete)
redirect_to my_sessions_path
end
diff --git a/app/models/sessions/autologin_session_link.rb b/app/models/sessions/autologin_session_link.rb
index 9250cf2f2ac..3341f2f9d2e 100644
--- a/app/models/sessions/autologin_session_link.rb
+++ b/app/models/sessions/autologin_session_link.rb
@@ -32,5 +32,17 @@ module Sessions
class AutologinSessionLink < ApplicationRecord
belongs_to :token, class_name: "Token::AutoLogin"
belongs_to :session, class_name: "Sessions::UserSession"
+
+ before_destroy :delete_sessions
+
+ private
+
+ ##
+ # When the session link is destroyed (because the autologin token got destroyed),
+ # linked sessions should be destroyed. As the sessions table is unlogged for performance reasons,
+ # we cannot use a foreign key on_delete constraint but have to do it manually here.
+ def delete_sessions
+ Sessions::UserSession.where(id: session_id).delete_all
+ end
end
end
diff --git a/app/models/token/auto_login.rb b/app/models/token/auto_login.rb
index ad01bc84d56..8e8e83ca1d4 100644
--- a/app/models/token/auto_login.rb
+++ b/app/models/token/auto_login.rb
@@ -32,8 +32,11 @@ module Token
class AutoLogin < HashedToken
include ExpirableToken
- has_many :autologin_session_links, class_name: "Sessions::AutologinSessionLink", foreign_key: "token_id",
- dependent: :delete_all
+ has_many :autologin_session_links,
+ class_name: "Sessions::AutologinSessionLink",
+ foreign_key: "token_id",
+ dependent: :destroy,
+ inverse_of: :token
##
# Set validity time for autologin tokens