From 4e028e9ccaea8b84799143ef5fe3d48441273805 Mon Sep 17 00:00:00 2001 From: Sarah Sunday <3252602+ssunday@users.noreply.github.com> Date: Thu, 22 Sep 2022 10:51:39 -0500 Subject: [PATCH] Add XOAuth2 authenticator --- lib/net/imap/authenticators.rb | 1 + lib/net/imap/authenticators/xoauth2.rb | 20 ++++++++++++++++++++ test/net/imap/test_imap_authenticators.rb | 12 +++++++++++- 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 lib/net/imap/authenticators/xoauth2.rb diff --git a/lib/net/imap/authenticators.rb b/lib/net/imap/authenticators.rb index 0aa864fc..d6f5ff69 100644 --- a/lib/net/imap/authenticators.rb +++ b/lib/net/imap/authenticators.rb @@ -45,3 +45,4 @@ def authenticators require_relative "authenticators/login" require_relative "authenticators/cram_md5" require_relative "authenticators/digest_md5" +require_relative "authenticators/xoauth2" diff --git a/lib/net/imap/authenticators/xoauth2.rb b/lib/net/imap/authenticators/xoauth2.rb new file mode 100644 index 00000000..0310eaaa --- /dev/null +++ b/lib/net/imap/authenticators/xoauth2.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +class Net::IMAP::XOauth2Authenticator + def process(_data) + build_oauth2_string(@user, @oauth2_token) + end + + private + + def initialize(user, oauth2_token) + @user = user + @oauth2_token = oauth2_token + end + + def build_oauth2_string(user, oauth2_token) + format("user=%s\1auth=Bearer %s\1\1".encode('us-ascii'), user, oauth2_token) + end + + Net::IMAP.add_authenticator 'XOAUTH2', self +end diff --git a/test/net/imap/test_imap_authenticators.rb b/test/net/imap/test_imap_authenticators.rb index 97519615..e6a98f9a 100644 --- a/test/net/imap/test_imap_authenticators.rb +++ b/test/net/imap/test_imap_authenticators.rb @@ -29,6 +29,17 @@ def test_plain_no_null_chars assert_raise(ArgumentError) { plain("u", "p", authzid: "bad\0authz") } end + # ---------------------- + # XOAUTH2 + # ---------------------- + + def test_xoauth2 + assert_equal( + "user=username\1auth=Bearer token\1\1".encode('us-ascii'), + Net::IMAP::XOauth2Authenticator.new("username", "token").process(nil) + ) + end + # ---------------------- # LOGIN (obsolete) # ---------------------- @@ -128,5 +139,4 @@ def test_digest_md5_authenticator ) ) end - end