Compare commits

...
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.

10 commits

12 changed files with 339 additions and 131 deletions

11
inc/console.coffee Normal file
View file

@ -0,0 +1,11 @@
FFTCGLOG = (unit) ->
@unit = unit
return
FFTCGLOG::log = (msg) ->
console.log "[#{@unit}] #{msg}"
FFTCGLOG::error = (msg) ->
console.error "[#{@unit}] #{msg}"
module.exports = FFTCGLOG

222
inc/db.coffee Normal file
View file

@ -0,0 +1,222 @@
# libraries
bcrypt = (require 'bcrypt')
sqlite3 = (require 'sqlite3').verbose()
FFTCGLOG = new (require './console')('FFTCGDB')
# bruteforce countermeasure
saltRounds = 13
FFTCGDB = (filename, truncate) ->
that = @
@filename = filename
@db = new sqlite3.Database @filename, (err) ->
if err
FFTCGLOG.error err.message
else
FFTCGLOG.log "Connected to '#{that.filename}'"
that.db.run 'PRAGMA foreign_keys = ON;', (err) ->
FFTCGLOG.error err.message if err
if truncate == true
that.db.run 'DROP TABLE IF EXISTS users;', (err) ->
FFTCGLOG.error err.message if err
that.db.run '''
CREATE TABLE users (
user integer PRIMARY KEY,
login text NOT NULL COLLATE NOCASE,
pwdhash text NOT NULL,
UNIQUE(login)
);
''', (err) ->
FFTCGLOG.error err.message if err
that.db.run 'DROP TABLE IF EXISTS decks;', (err) ->
FFTCGLOG.error err.message if err
that.db.run '''
CREATE TABLE decks (
deck integer PRIMARY KEY,
user integer NOT NULL,
json text,
FOREIGN KEY (user) REFERENCES users (user)
ON DELETE CASCADE
);
''', (err) ->
FFTCGLOG.error err.message if err
FFTCGLOG.log 'recreated DB'
return
FFTCGDB::close = ->
new Promise (resolve, reject) ->
@db.close (err) ->
if err
FFTCGLOG.log "Error closing: '#{err.message}'"
resolve 'ok'
else
FFTCGLOG.error "Closed '#{@filename}'"
reject 'db'
FFTCGDB::register = (login, password) ->
that = @
new Promise (resolve, reject) ->
# validate user input
if login == '' or password == ''
# no user name or password given
FFTCGLOG.log "reg: user name '#{login}' or password empty"
reject 'invalid'
# hash password
bcrypt.hash password, saltRounds, (err, hash) ->
if err
FFTCGLOG.log "reg: hash fail for name '#{login}'"
reject 'hash'
# try creating row in users table
stmt = that.db.prepare 'INSERT INTO users (login, pwdhash) VALUES (?, ?)'
stmt.run [login, hash], (err) ->
if err
FFTCGLOG.log "reg: DB fail '#{err.code}' for name '#{login}'"
stmt.finalize()
# reduce attack surface, don't disclose user names
reject 'db' # user already exists
else
FFTCGLOG.log "reg: OK '#{login}'"
stmt.finalize()
# registration successful
resolve
user: @lastID
login: login
FFTCGDB::login = (login, password) ->
that = @
new Promise (resolve, reject) ->
# get users table row
stmt = that.db.prepare 'SELECT user, login, pwdhash FROM users WHERE login = ?'
stmt.get [login], (err, row) ->
if err
FFTCGLOG.log "login: DB fail '#{err.code}' for name '#{login}'"
stmt.finalize()
reject 'db'
else if not row
# hash the password for timing attack reasons
bcrypt.hash password, saltRounds, (err, hash) ->
FFTCGLOG.log "login: nonexistent '#{login}'"
stmt.finalize()
# reduce attack surface, don't disclose user names
reject 'login' # user doesnt exist
else
bcrypt.compare password, row.pwdhash, (err, res) ->
if err
FFTCGLOG.log "login: hash fail for name '#{login}'"
reject 'hash'
if res == true
FFTCGLOG.log "login: OK '#{row.login}'"
stmt.finalize()
# login successful
resolve
user: row.user
login: row.login
else
FFTCGLOG.log "login: wrong password for '#{login}'"
stmt.finalize()
# login failed
reject 'login'
FFTCGDB::addDeck = (user, deckCards) ->
that = @
new Promise (resolve, reject) ->
# try creating row in decks table
stmt = that.db.prepare 'INSERT INTO decks (user, json) VALUES (?, ?)'
stmt.run [user, JSON.stringify deckCards], (err) ->
if err
FFTCGLOG.log "addDeck: DB fail '#{err.code}' for id '#{user}'"
stmt.finalize()
reject 'db'
else
stmt.finalize()
# deck added successfully, now add cards
that.modDeck(@lastID, deckCards)
.then (deckID) ->
resolve deckID
.catch (error) ->
reject error
FFTCGDB::modDeck = (deckID, deckCards) ->
that = @
new Promise (resolve, reject) ->
# delete old deck cards
stmt = that.db.prepare 'DELETE FROM decks_cards WHERE deck = ?'
stmt.run [deckID], (err) ->
stmt.finalize()
if err
FFTCGLOG.log "modDeck: DB fail '#{err.code}' for deck '#{deckID}'"
reject 'db'
else
stmt = that.db.prepare 'INSERT INTO decks_cards (deck, card, quant) VALUES (?, ?, ?)'
# add new cards
that.db.parallelize ->
# needs to be done in several queries
promiseCount = deckCards.length
deckCards.forEach (card) ->
stmt.run [deckID, card.id, card.quant], (err) ->
if err
FFTCGLOG.log "modDeck: DB fail '#{err.code}' for card '#{deckID}', '#{card.id}', '#{card.quant}'"
stmt.finalize()
reject 'db'
else
# check if all queries are done
promiseCount -= 1
if promiseCount == 0
FFTCGLOG.log "modDeck: OK '#{deckID}'"
stmt.finalize()
resolve deckID
FFTCGDB::getDecks = (user) ->
that = @
new Promise (resolve, reject) ->
# try deleting correct row in decks table
decks = {}
stmt = that.db.prepare 'SELECT decks.deck, decks.json FROM decks INNER JOIN users ON decks.user = users.user WHERE users.user = ?'
stmt.all [user], (err, rows) ->
stmt.finalize()
if err
FFTCGLOG.log "getDeck: DB fail '#{err.code}' for deck '#{deckID}'"
reject 'db'
else
FFTCGLOG.log "getDeck: OK '#{deckID}'"
for row in rows
decks[row.deck] = JSON.parse row.json
resolve decks
FFTCGDB::delDeck = (deckID) ->
that = @
new Promise (resolve, reject) ->
# try deleting correct row in decks table
stmt = that.db.prepare 'DELETE FROM decks WHERE deck = ?'
stmt.run [deckID], (err) ->
stmt.finalize()
if err
FFTCGLOG.log "delDeck: DB fail '#{err.code}' for deck '#{deckID}'"
reject 'db'
else
FFTCGLOG.log "delDeck: OK '#{deckID}'"
resolve deckID
module.exports = FFTCGDB

View file

@ -1,108 +0,0 @@
# libraries
bcrypt = (require 'bcrypt')
sqlite3 = (require 'sqlite3').verbose()
# bruteforce countermeasure
saltRounds = 13
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,
UNIQUE(login)
);
"""
console.log "[FFTCGDB] Connected to '#{@filename}'"
return
FFTCGDB::close = ->
new Promise (resolve, reject) ->
@db.close (err) ->
if err
resolve "[FFTCGDB] Error closing: '#{err.message}'"
else
reject "[FFTCGDB] Closed '#{@filename}'"
FFTCGDB::register = (login, password) ->
that = @
new Promise (resolve, reject) ->
# validate user input
if login == '' or password == ''
# no user name or password given
console.log "[FFTCGDB] reg: user name '#{login}' or password empty"
reject 'invalid'
# hash password
bcrypt.hash password, saltRounds, (err, hash) ->
if err
console.log "[FFTCGDB] reg: hash fail for name '#{login}'"
reject 'hash'
# try creating row in users table
stmt = that.db.prepare 'INSERT INTO users (login, pwdhash) VALUES (?, ?)'
stmt.run [login, hash], (err) ->
if err
console.log "[FFTCGDB] reg: DB fail '#{err.code}' for name '#{login}'"
stmt.finalize()
# reduce attack surface, don't disclose user names
reject 'db' # user already exists
else
console.log "[FFTCGDB] reg: OK '#{login}'"
stmt.finalize()
# registration successful
resolve
uid: @lastID
login: login
FFTCGDB::login = (login, password) ->
that = @
new Promise (resolve, reject) ->
# get users table row
stmt = that.db.prepare 'SELECT rowid, login, pwdhash FROM users WHERE login = ?'
stmt.get [login], (err, row) ->
if err
console.log "[FFTCGDB] login: DB fail '#{err.code}' for name '#{login}'"
stmt.finalize()
reject 'db'
else if not row
# hash the password for timing attack reasons
bcrypt.hash password, saltRounds, (err, hash) ->
console.log "[FFTCGDB] login: nonexistent '#{login}'"
stmt.finalize()
# reduce attack surface, don't disclose user names
reject 'login' # user doesnt exist
else
bcrypt.compare password, row.pwdhash, (err, res) ->
if err
console.log "[FFTCGDB] login: hash fail for name '#{login}'"
reject 'hash'
if res == true
console.log "[FFTCGDB] login: OK '#{row.login}'"
stmt.finalize()
# login successful
resolve
uid: row.rowid
login: row.login
else
console.log "[FFTCGDB] login: wrong password for '#{login}'"
stmt.finalize()
# login failed
reject 'login'
module.exports = FFTCGDB

View file

@ -3,13 +3,25 @@ express = (require 'express')
path = (require 'path') path = (require 'path')
# my libraries # my libraries
FFTCGDB = (require './fftcgdb') FFTCGDB = (require './db')
FFTCGLOG = new (require './console')('FFTCGROUTER')
# open fftcg db # open fftcg db
fftcgdb = new FFTCGDB path.resolve(__dirname, '../fftcg.db') fftcgdb = new FFTCGDB path.resolve(__dirname, '../fftcg.db')
# create router # create router
FFTCGROUTER = express.Router() FFTCGROUTER = express.Router()
# request logging
FFTCGROUTER.use (req, res, next) ->
if req.session.user
FFTCGLOG.log "user '#{req.session.user.login}' requested '#{req.url}'"
else
FFTCGLOG.log "requested '#{req.url}'"
next()
# static content
FFTCGROUTER.use express.static path.resolve(__dirname, '../public_html') FFTCGROUTER.use express.static path.resolve(__dirname, '../public_html')
# register user # register user
@ -19,7 +31,7 @@ FFTCGROUTER.post '/register', (req, res) ->
# registration successful, return JSON status # registration successful, return JSON status
res.json res.json
status: 'ok' status: 'ok'
uid: user.id user: user.user
login: user.login login: user.login
.catch (err) -> .catch (err) ->
@ -39,7 +51,7 @@ FFTCGROUTER.post '/login', (req, res) ->
# return JSON status # return JSON status
res.json res.json
status: 'ok' status: 'ok'
uid: user.uid user: user.user
login: user.login login: user.login
.catch (err) -> .catch (err) ->
@ -48,4 +60,23 @@ FFTCGROUTER.post '/login', (req, res) ->
status: 'fail' status: 'fail'
text: err text: err
# Templates
FFTCGROUTER.get '/:template.html', (req, res) ->
# redirect logged-in users to user cp
if req.session.user and req.params.template == 'index'
return res.redirect '/usercp.html'
# render requested template
res.render (req.params.template + '.pug'), (err, html) ->
# redirect invalid requests to index
if err
return res.redirect '/index.html'
# actual response
res.send html
# default route
FFTCGROUTER.use (req, res) ->
return res.redirect '/index.html'
module.exports = FFTCGROUTER module.exports = FFTCGROUTER

View file

@ -1,6 +1,7 @@
# node libraries # node libraries
socketio = (require 'socket.io') socketio = (require 'socket.io')
path = (require 'path') path = (require 'path')
FFTCGLOG = new (require './console')('FFTCGSOCKET')
# my libraries # my libraries
@ -14,17 +15,17 @@ FFTCGSOCKET = (http, session) ->
# on new connection # on new connection
@io.on 'connection', (socket) -> @io.on 'connection', (socket) ->
@session = socket.handshake.session @session = socket.handshake.session
console.log "session '#{@session.id}' connected" FFTCGLOG.log "session '#{@session.id}' connected"
console.log "is user '#{@session.userID}'" if @session.userID FFTCGLOG.log "is user '#{@session.userID}'" if @session.userID
socket.on 'disconnect', -> socket.on 'disconnect', ->
console.log "session '#{that.session.id}' disconnected" FFTCGLOG.log "session '#{that.session.id}' disconnected"
console.log "is user '#{that.session.userID}'" if that.session.userID FFTCGLOG.log "is user '#{that.session.userID}'" if that.session.userID
return return
FFTCGSOCKET::close = -> FFTCGSOCKET::close = ->
console.log '[FFTCGSOCKET] shutting down' FFTCGLOG.log 'shutting down'
if @db if @db
@db.close() @db.close()
.then (msg) -> .then (msg) ->

View file

@ -7,9 +7,10 @@ http = (require 'http')
path = (require 'path') path = (require 'path')
# my libraries # my libraries
FFTCGSOCKET = (require './inc/fftcgsocket') FFTCGSOCKET = (require './inc/socket')
FFTCGSESSION = (require './inc/fftcgsession') FFTCGSESSION = (require './inc/session')
FFTCGROUTER = (require './inc/fftcgrouter') FFTCGROUTER = (require './inc/router')
FFTCGLOG = new (require './inc/console')('FFTCG')
# express framework # express framework
app = express() app = express()
@ -24,23 +25,16 @@ app.use sessionMiddleware
# routes # routes
app.use FFTCGROUTER app.use FFTCGROUTER
# Templates
app.set 'view engine', 'pug'
app.get '/:template.html', (req, res) ->
if req.session.user
console.log "[FFTCG] user is '#{req.session.user.login}'"
res.render (req.params.template + '.pug')
# socket.io # socket.io
web = http.Server app web = http.Server app
socket = new FFTCGSOCKET web, sharedSession sessionMiddleware socket = new FFTCGSOCKET web, sharedSession sessionMiddleware
# Create server # Create server
web.listen 3000, -> web.listen 3000, ->
console.log '[FFTCG] Listening on port 3000 ...' FFTCGLOG.log 'Listening on port 3000 ...'
# Handle termination # Handle termination
process.on 'SIGINT', -> process.on 'SIGINT', ->
socket.close() socket.close()
console.log '[FFTCG] shutting down after SIGINT' FFTCGLOG.log 'shutting down after SIGINT'
process.exit() process.exit()

View file

@ -49,6 +49,7 @@ $ ->
if data.status == 'ok' if data.status == 'ok'
that.fullReset() that.fullReset()
showAlert 'success', "successfully logged in '#{data.login}'" showAlert 'success', "successfully logged in '#{data.login}'"
location.reload()
else else
switch data.text switch data.text

View file

@ -6,7 +6,6 @@
html, body { html, body {
height: 100%; height: 100%;
overflow: hidden;
} }

11
src/usercp.coffee Normal file
View file

@ -0,0 +1,11 @@
# libs
window.$ = require('jquery')
# import bootstrap
require './style/custom.scss'
require 'bootstrap/js/dist/alert'
require 'bootstrap/js/dist/collapse'
# on load
$ ->
return

45
views/usercp.pug Normal file
View file

@ -0,0 +1,45 @@
doctype html
html
head
title Crafty Things
script(src='/usercp.bundle.js')
body
header.jumbotron.jumbotron-fluid.py-4.bg-primary.text-light.text-center
div.container
h1 Hello World!
h2 App under development, please don't submit any valuable data!
div.container.bg-light
h3 Yavook!FFTCG
div#alert-area
div.row
div.col-md-8
h4 My Decks
ul.list-group#my-decks
li.list-group-item
div.row
div.col-3.btn-group(role="group")
button.btn.btn-secondary(data-toggle="collapse" data-target="#modDeck0") Edit
button.btn.btn-secondary#delDeck0 Delete
div.col-9.align-self-center item1
form.collapse.pt-2#modDeck0(name="modDeck0")
div.form-group
label(for="deck") Decklist:
textarea.form-control.form-control-sm.text-monospace(name="deck" rows="20" required)
div.form-group
button.btn.btn-primary.w-100(type="submit") Confirm
p Hello
div.col-md-4
h4 New Deck
form(name="addDeck")
div.form-group
label(for="deck") Paste decklist:
textarea.form-control.form-control-sm.text-monospace(name="deck" rows="20" required)
div.form-group
button.btn.btn-primary.w-100(type="submit") Add

View file

@ -5,7 +5,8 @@ module.exports = {
entry: { entry: {
index: './src/index.coffee', index: './src/index.coffee',
game: './src/game.coffee' game: './src/game.coffee',
usercp: './src/usercp.coffee'
}, },
devtool: 'inline-source-map', devtool: 'inline-source-map',