diff options
author | Julien Dessaux | 2022-10-30 23:16:47 +0100 |
---|---|---|
committer | Julien Dessaux | 2022-10-30 23:16:47 +0100 |
commit | dc5a002144ff7165e73fb38f4be186d827df98c6 (patch) | |
tree | c121abb7e34ae56adb33ca612d5ced962b411b63 /database/users.js | |
parent | Added a basic database schema and migration function (diff) | |
download | jeux-de-mots-dc5a002144ff7165e73fb38f4be186d827df98c6.tar.gz jeux-de-mots-dc5a002144ff7165e73fb38f4be186d827df98c6.tar.bz2 jeux-de-mots-dc5a002144ff7165e73fb38f4be186d827df98c6.zip |
Added register and login database functions, and use the last one in the login route
Diffstat (limited to '')
-rw-r--r-- | database/users.js | 34 |
1 files changed, 34 insertions, 0 deletions
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; +} |