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/backend/routes.coffee

119 lines
2.8 KiB
CoffeeScript
Raw Normal View History

# node libraries
2019-02-16 18:03:21 +00:00
(require 'debug').enable 'routes'
2019-02-15 02:50:11 +00:00
logger = (require 'logging').default 'routes'
path = (require 'path')
# my libraries
FFTCGDB = (require './db')
FFTCGSESSION = (require './session')
# open fftcg.db (persistent data)
fftcgdb = new FFTCGDB path.resolve(__dirname, 'fftcg.db'), true
# open session storage (volatile data)
session = new FFTCGSESSION
2019-02-15 12:06:16 +00:00
JSONSCHEMA =
user: ->
body:
login: type: 'string'
password: type: 'string'
response:
200:
type: 'object'
required: ['success']
properties:
success: type: 'boolean'
err: type: 'string'
user:
type: 'object'
required: ['user', 'login']
properties:
user: type: 'number'
login: type: 'string'
# user is required iff success
# err is required otherwise
if:
properties:
success:
const: true
then:
required: ['user']
else:
required: ['err']
module.exports = [
# test
url: '/test'
method: 'POST'
handler: (request, reply) ->
logger.info 'Cookies', request.cookies
logger.info 'Body', request.body
logger.info 'Query', request.query
logger.info 'Params', request.params
reply.setCookie 'foo', 'foo'
reply.send
hello: 'world'
,
# register user
url: '/user/register'
method: 'POST'
2019-02-15 12:06:16 +00:00
schema: JSONSCHEMA.user()
handler: (request, reply) ->
2019-02-16 18:03:21 +00:00
fftcgdb.register(request.body.login, request.body.password)
.then (user) ->
logger.info "OK registration '#{request.body.login}'"
reply.send
success: true
user: user
return
2019-02-16 18:03:21 +00:00
.catch (err) ->
logger.debug "FAIL registration '#{request.body.login}'"
reply.send
success: false
err: err
,
# log in user
url: '/user/login'
method: 'POST'
2019-02-15 12:06:16 +00:00
schema: JSONSCHEMA.user()
handler: (request, reply) ->
2019-02-15 02:50:11 +00:00
session_id = request.cookies.session ? ''
2019-02-15 12:06:16 +00:00
new Promise (resolve) ->
2019-02-15 02:50:11 +00:00
session.check session_id
2019-02-16 18:03:21 +00:00
.then (user) ->
# active session found
logger.debug "OK '#{user.login}' resumed session '#{session_id}'"
resolve user
2019-02-16 18:03:21 +00:00
.catch ->
fftcgdb.login request.body.login, request.body.password
.then (user) ->
# login successful: start new session
session.start user
.then (session_id) ->
logger.info "OK '#{user.login}' created session '#{session_id}'"
reply.setCookie 'session', session_id
resolve user
2019-02-16 18:03:21 +00:00
.catch (err) ->
# login failed
logger.info "FAIL login for '#{request.body.login}'"
reply.send
success: false
err: err
2019-02-15 02:50:11 +00:00
.then (user) ->
2019-02-16 18:03:21 +00:00
# tell about the user who logged in
2019-02-15 02:50:11 +00:00
reply.send
2019-02-15 12:06:16 +00:00
success: true
2019-02-15 02:50:11 +00:00
user: user
,
]