From 8d991c45e189e78bbac4f586f6a45f4a0b817511 Mon Sep 17 00:00:00 2001 From: nick evans Date: Sat, 14 Oct 2023 14:03:27 -0400 Subject: [PATCH] Delegate checking auth args to the authenticator Each authenticator has different parameters, so argument validation must be delegated to the authenticator classes. --- lib/net/smtp.rb | 26 +++++++------------------- lib/net/smtp/authenticator.rb | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/lib/net/smtp.rb b/lib/net/smtp.rb index 145f897..e359566 100644 --- a/lib/net/smtp.rb +++ b/lib/net/smtp.rb @@ -633,10 +633,7 @@ def tcp_socket(address, port) def do_start(helo_domain, user, secret, authtype) raise IOError, 'SMTP session already started' if @started - if user or secret - check_auth_method(authtype || DEFAULT_AUTH_TYPE) - check_auth_args user, secret - end + check_auth_args authtype, user, secret s = Timeout.timeout(@open_timeout, Net::OpenTimeout) do tcp_socket(@address, @port) end @@ -832,27 +829,18 @@ def open_message_stream(from_addr, *to_addrs, &block) # :yield: stream DEFAULT_AUTH_TYPE = :plain def authenticate(user, secret, authtype = DEFAULT_AUTH_TYPE) - check_auth_method authtype - check_auth_args user, secret + check_auth_args authtype, user, secret authenticator = Authenticator.auth_class(authtype).new(self) authenticator.auth(user, secret) end private - def check_auth_method(type) - unless Authenticator.auth_class(type) - raise ArgumentError, "wrong authentication type #{type}" - end - end - - def check_auth_args(user, secret, authtype = DEFAULT_AUTH_TYPE) - unless user - raise ArgumentError, 'SMTP-AUTH requested but missing user name' - end - unless secret - raise ArgumentError, 'SMTP-AUTH requested but missing secret phrase' - end + def check_auth_args(type, *args, **kwargs) + return unless type || args.any? || kwargs.any? + Authenticator.check_auth_type_args( + type || DEFAULT_AUTH_TYPE, *args, **kwargs + ) end # diff --git a/lib/net/smtp/authenticator.rb b/lib/net/smtp/authenticator.rb index 75350f0..98aaf75 100644 --- a/lib/net/smtp/authenticator.rb +++ b/lib/net/smtp/authenticator.rb @@ -13,6 +13,23 @@ def self.auth_class(type) Authenticator.auth_classes[type.intern] end + def self.check_auth_type_args(authtype, user, secret, type: nil, **auth) + return unless user || secret || auth.any? || authtype || type + klass = auth_class(type || authtype || DEFAULT_AUTH_TYPE) or + raise ArgumentError, "wrong authentication type #{type}" + klass.check_args(user, secret, **auth) + end + + def self.check_args(user_arg = nil, secret_arg = nil, + *, **) + unless user_arg + raise ArgumentError, 'SMTP-AUTH requested but missing user name' + end + unless secret_arg + raise ArgumentError, 'SMTP-AUTH requested but missing secret phrase' + end + end + attr_reader :smtp def initialize(smtp)