58 lines
1.3 KiB
CoffeeScript
58 lines
1.3 KiB
CoffeeScript
# libraries
|
|
bcrypt = (require 'bcrypt')
|
|
sqlite3 = (require 'sqlite3').verbose()
|
|
|
|
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,
|
|
nickname text,
|
|
pwd text NOT NULL,
|
|
socket text,
|
|
UNIQUE(login)
|
|
);
|
|
"""
|
|
console.log 'Connected to', @filename
|
|
return
|
|
|
|
FFTCGDB::close = ->
|
|
@db.close (err) ->
|
|
if err
|
|
console.error err.message
|
|
console.log 'Closed', @filename
|
|
|
|
FFTCGDB::register = (login, password) ->
|
|
that = @
|
|
# bruteforce countermeasure
|
|
saltRounds = 13
|
|
|
|
new Promise (resolve, reject) ->
|
|
# validate username
|
|
login = login.toLowerCase()
|
|
# hash password
|
|
bcrypt.hash password, saltRounds, (err, hash) ->
|
|
reject 'bcrypt fail' if err
|
|
# try creating row in users table
|
|
that.db.run "INSERT INTO users (login, pwd) VALUES ('#{login}', '#{hash}');", (err, result) ->
|
|
reject 'sqlite fail' if err
|
|
# registration successful
|
|
resolve login
|
|
|
|
FFTCGDB::login = (login, password) ->
|
|
that = @
|
|
|
|
new Promise (resolve, reject) ->
|
|
|
|
|
|
module.exports = FFTCGDB
|
|
|
|
# Handle termination
|
|
process.on 'SIGINT', ->
|
|
console.log '[FFTCG-DB] shutting down'
|
|
FFTCGDB.close()
|