Session: Improve existing user check to fix crash in addUser

This commit is contained in:
Mia
2023-05-17 17:12:28 -05:00
parent a5a18b5e23
commit 09dc32405f
2 changed files with 6 additions and 4 deletions

View File

@@ -260,6 +260,9 @@ export class DatabaseTable<Row> {
insert(partialRow: PartialOrSQL<Row>, where?: SQLStatement) {
return this.queryExec()`INSERT INTO \`${this.name}\` (${partialRow as SQLValue}) ${where}`;
}
insertIgnore(partialRow: PartialOrSQL<Row>, where?: SQLStatement) {
return this.queryExec()`INSERT IGNORE INTO \`${this.name}\` (${partialRow as SQLValue}) ${where}`;
}
async tryInsert(partialRow: PartialOrSQL<Row>, where?: SQLStatement) {
try {
return await this.insert(partialRow, where);

View File

@@ -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);
}