From 6a6c5eb804cc11f9f40532d5565b34fadd7878e9 Mon Sep 17 00:00:00 2001 From: David Hoppenbrouwers Date: Sat, 8 Oct 2022 15:59:58 +0200 Subject: [PATCH] Fix exception when trying to register existing user --- db/sqlite.py | 34 ++++++++++++++++++++-------------- main.py | 2 +- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/db/sqlite.py b/db/sqlite.py index 4b9ab32..8394006 100644 --- a/db/sqlite.py +++ b/db/sqlite.py @@ -51,8 +51,10 @@ class DB: ).fetchone() comments = db.execute(''' select comment_id, parent_id, author_id, name, text, create_time, modify_time - from comments, users - where thread_id = ? and author_id = user_id + from comments + left join users + on author_id = user_id + where thread_id = ? ''', (thread,) ) @@ -293,18 +295,22 @@ class DB: return False def add_user(self, username, password, time): - db = self._db() - c = db.cursor() - c.execute(''' - insert into users(name, password, join_time) - values (lower(?), ?, ?) - ''', - (username, password, time) - ) - if c.rowcount > 0: - db.commit() - return True - return False + try: + db = self._db() + c = db.cursor() + c.execute(''' + insert into users(name, password, join_time) + values (lower(?), ?, ?) + ''', + (username, password, time) + ) + if c.rowcount > 0: + db.commit() + return True + return False + except sqlite3.IntegrityError: + # User already exists, probably + return False def _db(self): return sqlite3.connect(self.conn) diff --git a/main.py b/main.py index efceab0..371733d 100644 --- a/main.py +++ b/main.py @@ -274,7 +274,7 @@ def register(): ): flash('CAPTCHA answer is incorrect', 'error') elif not db.add_user(username, hash_password(password), time.time_ns()): - flash('Failed to create user (username may already be taken)') + flash('Failed to create account (username may already be taken)', 'error') else: flash('Account has been created. You can login now.', 'success') return redirect(url_for('index'))