From 0f96156c5315d73fc7693ccf7df93caeb2aced41 Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Wed, 26 May 2021 18:49:04 +0200
Subject: [PATCH] Add basic SASL authentication.

---
 plomlombot.py | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)

diff --git a/plomlombot.py b/plomlombot.py
index dc9a46d..1128eff 100755
--- a/plomlombot.py
+++ b/plomlombot.py
@@ -471,8 +471,9 @@ def handle_url(url, notice, show_url=False):
 
 class Session:
 
-    def __init__(self, io, username, nickname, channel, twtfile, dbdir, rmlogs,
+    def __init__(self, io, username, nickname, sasl, channel, twtfile, dbdir, rmlogs,
                  markov_input, no_show_page_titles):
+        import base64
         self.io = io
         self.nickname = nickname
         self.users_in_chan = []
@@ -483,8 +484,16 @@ class Session:
         self.markovfile = chandir + "markovfeed"
         self.quotesfile = chandir + "quotes"
         self.log = Log(chandir, self.nickname, username, channel, rmlogs)
+        if sasl:
+            self.io.send_line("CAP REQ :sasl")
         self.io.send_line("NICK " + self.nickname)
         self.io.send_line("USER " + username + " 0 * : ")
+        if sasl:
+            self.io.send_line("AUTHENTICATE PLAIN")
+            auth = username + '\0' + username + '\0' + password
+            auth_encoded = base64.b64encode(auth.encode()).decode().rstrip()
+            self.io.send_line("AUTHENTICATE " + auth_encoded)
+            self.io.send_line("CAP END")
         self.io.send_line("JOIN " + channel)
         self.io.log = self.log
         self.log.separator_line()
@@ -567,6 +576,8 @@ def parse_command_line_arguments():
     parser.add_argument("-n, --nickname", action="store", dest="nickname",
                         default=NICKNAME, help="nickname to use (default: "
                         + NICKNAME + ")")
+    parser.add_argument("-a, --authenticate", action="store", dest="sasl",
+                        default=None, help="SASL password (default: none)")
     parser.add_argument("-t, --twtxtfile", action="store", dest="twtfile",
                         default=TWTFILE, help="twtxt file to use (default: "
                         + TWTFILE + ")")
@@ -592,7 +603,7 @@ while True:
         io = IO(opts.server, opts.port, opts.timeout)
         hash_server = hashlib.md5(opts.server.encode("utf-8")).hexdigest()
         dbdir = opts.dbdir + "/" + hash_server
-        session = Session(io, opts.username, opts.nickname, opts.channel,
+        session = Session(io, opts.username, opts.nickname, opts.sasl, opts.channel,
                           opts.twtfile, dbdir, opts.rmlogs, opts.markov_store,
                           opts.no_show_page_titles)
         session.loop()
-- 
2.30.2