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

83 lines
1.9 KiB
CoffeeScript
Raw Permalink Normal View History

2018-12-16 02:02:57 +00:00
# node libraries
express = (require 'express')
2018-12-16 02:02:57 +00:00
path = (require 'path')
# my libraries
2018-12-27 11:19:19 +00:00
FFTCGDB = (require './db')
2018-12-27 12:03:58 +00:00
FFTCGLOG = new (require './console')('FFTCGROUTER')
2018-12-16 02:02:57 +00:00
# open fftcg db
fftcgdb = new FFTCGDB path.resolve(__dirname, '../fftcg.db')
# create router
FFTCGROUTER = express.Router()
# request logging
FFTCGROUTER.use (req, res, next) ->
if req.session.user
2018-12-27 12:03:58 +00:00
FFTCGLOG.log "user '#{req.session.user.login}' requested '#{req.url}'"
else
2018-12-27 12:03:58 +00:00
FFTCGLOG.log "requested '#{req.url}'"
next()
# static content
FFTCGROUTER.use express.static path.resolve(__dirname, '../public_html')
2018-12-16 02:02:57 +00:00
# register user
FFTCGROUTER.post '/register', (req, res) ->
fftcgdb.register req.body.login, req.body.password
.then (user) ->
# registration successful, return JSON status
2018-12-16 02:02:57 +00:00
res.json
status: 'ok'
2018-12-27 02:03:22 +00:00
user: user.user
login: user.login
2018-12-16 02:02:57 +00:00
.catch (err) ->
# registration failed, return JSON status
2018-12-16 02:02:57 +00:00
res.json
status: 'fail'
text: err
# log in user
FFTCGROUTER.post '/login', (req, res) ->
fftcgdb.login req.body.login, req.body.password
.then (user) ->
# login successful, save stuff in session
req.session.user = user
2018-12-16 02:02:57 +00:00
req.session.save()
# return JSON status
2018-12-16 02:02:57 +00:00
res.json
status: 'ok'
2018-12-27 02:03:22 +00:00
user: user.user
login: user.login
2018-12-16 02:02:57 +00:00
.catch (err) ->
# login failed, return JSON status
2018-12-16 02:02:57 +00:00
res.json
status: 'fail'
text: err
# Templates
FFTCGROUTER.get '/:template.html', (req, res) ->
2018-12-27 00:24:14 +00:00
# redirect logged-in users to user cp
if req.session.user and req.params.template == 'index'
2018-12-27 00:24:14 +00:00
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'
2018-12-16 02:02:57 +00:00
module.exports = FFTCGROUTER