discourse-md5_authentication/plugin.rb

61 lines
2.2 KiB
Ruby
Raw Normal View History

2024-06-11 05:28:46 +00:00
# plugins/discourse-md5_authentication/plugin.rb
2024-06-11 04:26:59 +00:00
# frozen_string_literal: true
2024-06-11 05:28:46 +00:00
# name: discourse-md5_authentication
2024-06-11 04:26:59 +00:00
# about: A plugin to authenticate users with MD5 passwords from legacy systems
# version: 0.5
2024-06-11 04:26:59 +00:00
# authors: saint
# url: https://gitea.federated.computer/saint/discourse-md5_authentication.git
# This block will run after Discourse has initialized
2024-06-11 04:26:59 +00:00
after_initialize do
# Define a module to contain the MD5 authentication logic
module LegacyMd5Authentication
# Override the current_user method to include MD5 authentication
def current_user
# Attempt to find the current user using the standard Discourse method
user = super
return user if user
# Check for MD5 authentication if no user is found by the standard method
email_or_username = @request.params[:login]
password = @request.params[:password]
if email_or_username && password
# Log the start of the MD5 authentication attempt
Rails.logger.info("MD5 Auth: Attempting to authenticate #{email_or_username}")
# Find the user by username or email, ignoring case
user = User.find_by_username_or_email(email_or_username.downcase.strip)
# Log if a user with an MD5 password is found
if user && user.custom_fields['md5_password']
Rails.logger.info("MD5 Auth: User found with MD5 password - #{user.username}")
2024-06-11 04:26:59 +00:00
# Check if the provided password matches the stored MD5 password
if user.custom_fields['md5_password'] == Digest::MD5.hexdigest(password)
# Log the successful MD5 password match
Rails.logger.info("MD5 Auth: MD5 password match for user #{user.username}")
# Update the user to use the new password and clear the MD5 password
user.update!(password: password)
user.custom_fields['md5_password'] = nil
user.save_custom_fields
# Set the current user in the environment
@env[CURRENT_USER_KEY] = user
return user
end
end
2024-06-11 04:26:59 +00:00
end
# Fallback to the original current_user method
nil
end
2024-06-11 04:26:59 +00:00
end
# Prepend our module to the DefaultCurrentUserProvider class
Auth::DefaultCurrentUserProvider.prepend LegacyMd5Authentication
2024-06-11 04:26:59 +00:00
end