From 09dc32405fcda4ba0015f56e301d360e1f8ab47b Mon Sep 17 00:00:00 2001 From: Mia <49593536+mia-pi-git@users.noreply.github.com> Date: Wed, 17 May 2023 17:12:28 -0500 Subject: [PATCH] Session: Improve existing user check to fix crash in addUser --- src/database.ts | 3 +++ src/user.ts | 7 +++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/database.ts b/src/database.ts index 59021e3..0fd9dd5 100644 --- a/src/database.ts +++ b/src/database.ts @@ -260,6 +260,9 @@ export class DatabaseTable { insert(partialRow: PartialOrSQL, where?: SQLStatement) { return this.queryExec()`INSERT INTO \`${this.name}\` (${partialRow as SQLValue}) ${where}`; } + insertIgnore(partialRow: PartialOrSQL, where?: SQLStatement) { + return this.queryExec()`INSERT IGNORE INTO \`${this.name}\` (${partialRow as SQLValue}) ${where}`; + } async tryInsert(partialRow: PartialOrSQL, where?: SQLStatement) { try { return await this.insert(partialRow, where); diff --git a/src/user.ts b/src/user.ts index 0155d1b..d48262f 100644 --- a/src/user.ts +++ b/src/user.ts @@ -123,16 +123,15 @@ export class Session { async addUser(username: string, password: string) { const hash = await bcrypt.hash(password, Config.passwordSalt); const userid = toID(username); - const exists = await users.get(userid, ['userid']); - if (exists) return null; const ip = this.context.getIp(); - const result = await users.insert({ + const result = await users.insertIgnore({ userid, username, passwordhash: hash, email: null, registertime: time(), ip, }); if (!result.affectedRows) { - throw new Error(`User could not be created. (${userid}, ${ip})`); + // 0 affected rows almost always means user already exists + return null; } return this.login(username, password); }