This repository has been archived on 2024-04-29. You can view files and clone it, but cannot push or open issues or pull requests.
node-fftcg/inc/fftcgdb.coffee

81 lines
1.9 KiB
CoffeeScript
Raw Normal View History

2018-12-07 09:38:46 +00:00
# libraries
bcrypt = (require 'bcrypt')
sqlite3 = (require 'sqlite3').verbose()
2018-12-16 01:37:00 +00:00
# bruteforce countermeasure
saltRounds = 13
2018-12-14 06:03:03 +00:00
FFTCGDB = (filename) ->
@filename = filename
@db = new sqlite3.Database @filename, (err) ->
if err
console.error err.message
@db.run """
CREATE TABLE IF NOT EXISTS users (
login text NOT NULL COLLATE NOCASE,
pwdhash text NOT NULL,
session text,
2018-12-14 06:03:03 +00:00
UNIQUE(login)
);
"""
console.log "[FFTCGDB] Connected to '#{@filename}'"
2018-12-14 06:03:03 +00:00
return
FFTCGDB::close = ->
new Promise (resolve, reject) ->
@db.close (err) ->
if err
resolve "[FFTCGDB] Error closing: '#{err.message}'"
else
reject "[FFTCGDB] Closed '#{@filename}'"
2018-12-14 06:03:03 +00:00
FFTCGDB::register = (login, password) ->
that = @
new Promise (resolve, reject) ->
# validate username
2018-12-14 06:03:03 +00:00
# hash password
2018-12-07 09:38:46 +00:00
bcrypt.hash password, saltRounds, (err, hash) ->
reject 'hash' if err
2018-12-14 06:03:03 +00:00
# try creating row in users table
that.db.run "INSERT INTO users (login, pwdhash) VALUES ('#{login}', '#{hash}');", (err) ->
if err
if err.code == 'SQLITE_CONSTRAINT'
reject 'existence'
else
reject 'db'
else
# registration successful
2018-12-16 01:37:00 +00:00
resolve @lastID
2018-12-14 06:03:03 +00:00
FFTCGDB::login = (login, password) ->
that = @
new Promise (resolve, reject) ->
# validate username
2018-12-14 06:03:03 +00:00
# get users table row
that.db.all "SELECT rowid, pwdhash FROM users WHERE login = '#{login}';", (err, rows) ->
if err
reject 'db'
2018-12-07 09:38:46 +00:00
else if rows.length == 0
2018-12-16 01:37:00 +00:00
# hashing the password for timing attack reasons
bcrypt.hash password, saltRounds, (err, hash) ->
reject 'existence'
2018-12-07 09:38:46 +00:00
else
row = rows[0]
bcrypt.compare password, row.pwdhash, (err, res) ->
reject 'hash' if err
if res == true
resolve row.rowid
else
reject 'login'
module.exports = FFTCGDB