JSON schema working

This commit is contained in:
Jörn-Michael Miehe 2019-02-15 13:06:16 +01:00
parent 6306a4457d
commit d9eb9796b1
2 changed files with 48 additions and 17 deletions

View file

@ -12,6 +12,37 @@ fftcgdb = new FFTCGDB path.resolve(__dirname, 'fftcg.db'), true
# open session storage (volatile data)
session = new FFTCGSESSION
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'
@ -29,31 +60,34 @@ module.exports = [
# register user
url: '/user/register'
method: 'POST'
schema: JSONSCHEMA.user()
handler: (request, reply) ->
fftcgdb.register request.body.login, request.body.password
.then (user) ->
# registration successful
logger.info "OK registration '#{request.body.login}'"
reply.send
status: 'ok'
user: user.user
login: user.login
success: true
user: user
.catch (err) ->
# registration failed
logger.debug "FAIL registration '#{request.body.login}'"
reply.send
status: 'fail'
text: err
success: false
err: err
,
# log in user
url: '/user/login'
method: 'POST'
schema: JSONSCHEMA.user()
handler: (request, reply) ->
session_id = request.cookies.session ? ''
new Promise (resolve, reject) ->
new Promise (resolve) ->
session.check session_id
.then (user) ->
logger.debug "user '#{user.login}' resumed session '#{session_id}'"
logger.debug "OK '#{user.login}' resumed session '#{session_id}'"
resolve user
.catch ->
@ -62,21 +96,19 @@ module.exports = [
# login successful: start new session
session.start user
.then (session_id) ->
logger.debug "user '#{user.login}' logged into session '#{session_id}'"
logger.info "OK '#{user.login}' created session '#{session_id}'"
reply.setCookie 'session', session_id
resolve user
.catch (err) ->
logger.info "failed login for '#{request.body.login}'"
# login failed
logger.info "FAIL login for '#{request.body.login}'"
reply.send
status: 'fail'
success: false
msg: err
.then (user) ->
# user is logged in
reply.send
status: 'ok'
success: true
user: user
,
]

View file

@ -11,8 +11,7 @@ routes = (require './routes')
# fastify framework
fastify.register (require 'fastify-cookie')
fastify.register (require 'fastify-ws'), library: 'uws'
fastify.register (require 'fastify-static'), root: path.join __dirname, 'tmpfront'
fastify.register (require 'fastify-static'), root: (path.join __dirname, 'tmpfront')
fastify.ready()
.then ->