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/server.coffee

80 lines
2 KiB
CoffeeScript
Raw Normal View History

2018-12-07 09:38:46 +00:00
# node libraries
bodyParser = (require 'body-parser')
2018-12-07 09:38:46 +00:00
express = (require 'express')
2018-12-15 20:09:01 +00:00
sharedSession = (require 'express-socket.io-session')
2018-12-07 09:38:46 +00:00
helmet = (require 'helmet')
http = (require 'http')
path = (require 'path')
# my libraries
2018-12-14 22:41:43 +00:00
FFTCGSOCKET = (require './inc/fftcgsocket')
FFTCGDB = (require './inc/fftcgdb')
FFTCGSESSION = (require './inc/fftcgsession')
2018-12-14 06:03:03 +00:00
2018-12-15 20:09:01 +00:00
# express framework
app = express()
app.use helmet()
app.use bodyParser.urlencoded
extended: true
2018-12-15 20:09:01 +00:00
# sessions
sessionMiddleware = FFTCGSESSION(app)
2018-12-15 20:09:01 +00:00
app.use sessionMiddleware
# open fftcg db
fftcgdb = new FFTCGDB path.resolve(__dirname, './fftcg.db')
app.post '/register', (req, res) ->
fftcgdb.register req.body.login, req.body.password
.then (userid) ->
console.log "registered '#{req.body.login}'"
res.json
status: 'ok'
uid: userid
text: req.body.login
.catch (err) ->
console.log "failed to register '#{req.body.login}'"
res.json
status: 'fail'
text: err
app.post '/login', (req, res) ->
fftcgdb.login req.body.login, req.body.password
.then (userid) ->
req.session.userID = userid
req.session.save()
console.log "logged in '#{req.body.login}'"
res.json
status: 'ok'
uid: userid
text: req.body.login
.catch (err) ->
console.log "failed to login '#{req.body.login}'"
res.json
status: 'fail'
text: err
2018-12-15 20:09:01 +00:00
# Static content
app.use express.static path.resolve(__dirname, 'public_html')
2018-12-15 20:09:01 +00:00
2018-11-29 13:47:18 +00:00
# Templates
app.set 'view engine', 'pug'
app.get '/:template.html', (req, res) ->
if req.session
console.log "logged in as '#{req.session.userID}'"
2018-11-29 13:47:18 +00:00
res.render (req.params.template + '.pug')
2018-12-07 09:38:46 +00:00
# Create server
2018-12-14 22:41:43 +00:00
web = http.Server app
2018-12-07 09:38:46 +00:00
web.listen 3000, ->
console.log '[FFTCG] Listening on port 3000 ...'
2018-12-15 20:09:01 +00:00
# socket.io
socket = new FFTCGSOCKET web, sharedSession sessionMiddleware
2018-12-14 22:41:43 +00:00
2018-12-07 09:38:46 +00:00
# Handle termination
process.on 'SIGINT', ->
socket.close()
2018-12-07 09:38:46 +00:00
console.log '[FFTCG] shutting down after SIGINT'
process.exit()