이 플러그인은 사용자가 의심스러운 IP 주소에서 로그인할 때마다 모든 관리자에게 이메일 경보를 보내도록 설계되었습니다. 이를 위해 최신 인증 토큰(client_ip 필드 사용)에서 IP를 추출하고, 사이트 설정(ip_alert_suspicious_ips)에서 정의된 차단 목록과 해당 IP를 대조한 후, IP가 차단된 패턴과 일치하면 모든 관리자 사용자에게 경고 이메일을 전송합니다.
관찰된 오류:
플러그인 코드가 정상이며 표준 Discourse 플러그인 패턴을 따르고 있음에도 불구하고, 로그인 시 여전히 일반적 오류 메시지인 "Oops – The software powering this discussion forum encountered an unexpected problem"이 발생합니다. 오류 로그에는 우리의 [DiscourseIpAlert] 로그 메시지에 대한 명확한 표시가 없으며, 스택 트레이스에서도 플러그인 코드 내부의 문제를 직접적으로 가리키지 않습니다.
현재 상태:
사이트 설정을 확인하고 훅(on(:user_logged_in))이 올바르게 등록되었는지 확인하는 등 플러그인을 여러 번 검토하고 수정했습니다. IP 추출 및 이메일 전송 로직도 적절히 구현된 것으로 보이지만, 플러그인을 가리키는 명확한 스택 트레이스 없이 500 Internal Server Error가 계속 발생합니다.
도움을 부탁드립니다.
plugin.rb:
# frozen_string_literal: true
# name: discourse-ip-alert
# about: Sends an email alert when a user logs in from a suspicious IP address.
# version: 0.7
# authors: OrkoGrayskull (revised)
# required_version: 3.5.0
enabled_site_setting :ip_alert_enabled
enabled_site_setting :ip_alert_suspicious_ips
module ::DiscourseIpAlert
PLUGIN_NAME = "discourse-ip-alert"
require 'ipaddr'
require 'mail'
# Extracts the IP address from the latest authentication token
def self.extract_ip(user)
token = UserAuthToken.where(user_id: user.id).order(created_at: :desc).first
ip = token&.attributes["client_ip"]
Rails.logger.info("[DiscourseIpAlert] extract_ip: Extracted IP from UserAuthToken: #{ip.inspect}")
ip
rescue => e
Rails.logger.error("[DiscourseIpAlert] extract_ip error: #{e.message}")
nil
end
# Checks if the given IP address is present in the blocklist
def self.ip_blocked?(ip_address)
return false if ip_address.blank?
blocked_ips = SiteSetting.ip_alert_suspicious_ips.split(",").map(&:strip)
Rails.logger.info("[DiscourseIpAlert] ip_blocked?: Blocked IPs: #{blocked_ips.inspect}")
blocked_ips.any? do |blocked|
if blocked.include?('*')
regex = Regexp.new("^" + Regexp.escape(blocked).gsub('\\*', '\\d{1,3}') + "$")
Rails.logger.info("[DiscourseIpAlert] ip_blocked?: Comparing #{ip_address} with wildcard regex #{regex.inspect}")
ip_address.match?(regex)
else
begin
result = IPAddr.new(blocked).include?(ip_address)
Rails.logger.info("[DiscourseIpAlert] ip_blocked?: Comparing #{ip_address} with #{blocked}: #{result}")
result
rescue IPAddr::InvalidAddressError => e
Rails.logger.error("[DiscourseIpAlert] ip_blocked?: Invalid IP in blocklist: #{blocked} (#{e.message})")
false
end
end
end
rescue => e
Rails.logger.error("[DiscourseIpAlert] ip_blocked? error: #{e.message}")
false
end
# Sends a warning email to all admins
def self.send_warning_email(user, ip_address)
admin_emails = User.where(admin: true).pluck(:email)
return if admin_emails.empty?
subject = "⚠️ Warning: Login from a Suspicious IP!"
body = <<~BODY
Attention!
The user #{user.username} (#{user.email}) has logged in from the IP address #{ip_address},
which has been flagged as suspicious.
Please review this account.
BODY
admin_emails.each do |email|
begin
mail = Mail.new do
from ENV['DISCOURSE_NOTIFICATION_EMAIL'] || 'no-reply@example.org'
to email
subject subject
body body
end
Rails.logger.info("[DiscourseIpAlert] Sending warning email to #{email}")
mail.deliver!
rescue => e
Rails.logger.error("[DiscourseIpAlert] Error sending email to #{email}: #{e.message}")
end
end
rescue => e
Rails.logger.error("[DiscourseIpAlert] send_warning_email error: #{e.message}")
end
# Processes the user login: extracts the IP, checks the blocklist, and sends a warning email if necessary
def self.process_user_login(user)
Rails.logger.info("[DiscourseIpAlert] process_user_login for user: #{user.username}")
ip_address = extract_ip(user)
unless ip_address
Rails.logger.warn("[DiscourseIpAlert] No IP address extracted – skipping further processing.")
return
end
if ip_blocked?(ip_address)
Rails.logger.warn("[DiscourseIpAlert] Suspicious IP detected: #{ip_address}")
send_warning_email(user, ip_address)
else
Rails.logger.info("[DiscourseIpAlert] IP #{ip_address} is considered safe.")
end
rescue => e
Rails.logger.error("[DiscourseIpAlert] process_user_login error: #{e.message}")
end
end
after_initialize do
Rails.logger.info("[DiscourseIpAlert] after_initialize: Plugin is being integrated into the login process.")
# Register the hook that is called on every user login
on(:user_logged_in) do |user|
begin
Rails.logger.info("[DiscourseIpAlert] on(:user_logged_in) hook called for user: #{user.username}")
::DiscourseIpAlert.process_user_login(user)
rescue => e
Rails.logger.error("[DiscourseIpAlert] Error in on(:user_logged_in) hook: #{e.message}")
end
end
end
config/settings.yml:
ip_alert_enabled:
default: false
client: true
type: bool
description: "Enable the IP alert"
ip_alert_suspicious_ips:
default: "192.168.1.1,203.0.113.0/24"
client: true
type: string
description: "List of suspicious IP addresses (comma-separated)"