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 try_to_autologin into CurrentUser concern

Oliver Güntherff4f68356190
diff --git a/app/controllers/concerns/accounts/current_user.rb b/app/controllers/concerns/accounts/current_user.rb
index 9659bea1e6f..bc089498e8c 100644
--- a/app/controllers/concerns/accounts/current_user.rb
+++ b/app/controllers/concerns/accounts/current_user.rb
@@ -82,14 +82,11 @@ module Accounts::CurrentUser
return unless Setting::Autologin.enabled?
autologin_cookie_name = OpenProject::Configuration["autologin_cookie_name"]
- autologin_token = cookies[autologin_cookie_name]
- return unless autologin_token
-
- user = User.try_to_autologin(autologin_token)
-
- if user
- login_user(user)
- user
+ token = Token::AutoLogin.find_valid_token cookies[autologin_cookie_name]
+ if token.present?
+ session[:autologin_token_id] = token.id
+ login_user(token.user)
+ token.user
else
cookies.delete(autologin_cookie_name)
nil
diff --git a/app/models/token/auto_login.rb b/app/models/token/auto_login.rb
index 18016ecea05..ad01bc84d56 100644
--- a/app/models/token/auto_login.rb
+++ b/app/models/token/auto_login.rb
@@ -30,6 +30,35 @@
module Token
class AutoLogin < HashedToken
+ include ExpirableToken
+
+ has_many :autologin_session_links, class_name: "Sessions::AutologinSessionLink", foreign_key: "token_id",
+ dependent: :delete_all
+
+ ##
+ # Set validity time for autologin tokens
+ def self.validity_time
+ Setting.autologin.days
+ end
+
+ ##
+ # Find a valid autologin token from the given value.
+ # Validates the token by checking its expiration date and the user status.
+ #
+ # @param key [String] The plaintext token value
+ # @return [Token::AutoLogin, nil] The valid token or nil if not
+ def self.find_valid_token(key)
+ return if key.blank?
+
+ token = find_by_plaintext_value(key)
+
+ return if token.nil?
+ return if token.expired?
+ return unless token.user&.active?
+
+ token
+ end
+
protected
##
diff --git a/app/models/user.rb b/app/models/user.rb
index 9133f3750af..08c23826bcf 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -275,15 +275,6 @@ class User < Principal
user
end
- # Returns the user who matches the given autologin +key+ or nil
- def self.try_to_autologin(key)
- token = Token::AutoLogin.find_by_plaintext_value(key) # rubocop:disable Rails/DynamicFindBy
- # Make sure there's only 1 token that matches the key
- if token && (token.created_at > Setting.autologin.to_i.day.ago) && token.user&.active?
- token.user
- end
- end
-
# Columns required for formatting the user's name.
def self.columns_for_name(formatter = nil)
case formatter || Setting.user_format