diff options
Diffstat (limited to 'database')
-rw-r--r-- | database/db.js | 2 | ||||
-rw-r--r-- | database/users.js | 34 |
2 files changed, 35 insertions, 1 deletions
diff --git a/database/db.js b/database/db.js index d849429..259ab58 100644 --- a/database/db.js +++ b/database/db.js @@ -11,7 +11,7 @@ db.pragma("foreign_keys = ON"); db.transaction(function migrate() { let version; try { - version = db.prepare("SELECT version FROM schema_version").all()[0].version; + version = db.prepare("SELECT version FROM schema_version").get().version; } catch { version = 0; } diff --git a/database/users.js b/database/users.js new file mode 100644 index 0000000..4b534b8 --- /dev/null +++ b/database/users.js @@ -0,0 +1,34 @@ +import bcrypt from "bcrypt"; + +import db from "./db.js"; + +const saltRounds = 10; + +const createUserStatement = db.prepare("INSERT INTO users (username, hash, email) VALUES (?, ?, ?);"); +const loginStatement = db.prepare("SELECT id, hash, email FROM users WHERE username = ?;"); + +export async function createUser(username, password, email) { + const hash = await bcrypt.hash(password, saltRounds); + try { + return createUserStatement.run(username, hash, email).lastInsertRowid; + } catch { + return null; + } +} + +export async function login(username, password) { + try { + var user = loginStatement.get(username); + } catch { + return null; + } + const result = await bcrypt.compare(password, user.hash); + if (result === true) { + return { + id: user.id, + username: username, + email: user.email, + }; + } + return null; +} |