Skip to content

Commit

Permalink
Merge pull request #462 from taoeffect/updated-deps
Browse files Browse the repository at this point in the history
Updated dependencies + removed dependencies
  • Loading branch information
taoeffect committed Aug 6, 2018
2 parents 0c421a8 + 4b72dfb commit da3881f
Show file tree
Hide file tree
Showing 13 changed files with 1,316 additions and 822 deletions.
28 changes: 18 additions & 10 deletions .Gruntfile.babel.js
Expand Up @@ -7,12 +7,19 @@ http://www.sitepoint.com/setting-up-es6-project-using-babel-browserify/
https://babeljs.io/docs/setup/#browserify
*/
import * as _ from './frontend/simple/utils/giLodash.js'
import {setupPrimus} from './shared/functions'
import {setupPrimus} from './shared/functions.js'
import {
dasherize,
capitalize,
camelize,
startsWith,
endsWith,
chompLeft
} from './shared/string.js'

const fs = require('fs')
const path = require('path')
const url = require('url')
const S = require('string')
const vueify = require('vueify')
const pathmodify = require('pathmodify')

Expand Down Expand Up @@ -127,15 +134,15 @@ module.exports = (grunt) => {
middleware: (connect, opts, middlewares) => {
middlewares.unshift((req, res, next) => {
var f = url.parse(req.url).pathname
f = path.join('dist', S(f).endsWith('/') ? f + 'index.html' : f)
f = path.join('dist', endsWith(f, '/') ? f + 'index.html' : f)
if (/^dist\/(frontend|node_modules)\/.*\.(sass|scss|js|vue)$/.test(f)) {
// handle serving source-maps
res.end(fs.readFileSync(S(f).chompLeft('dist/').s))
} else if (S(f).endsWith('.html') && fs.existsSync(f)) {
res.end(fs.readFileSync(chompLeft(f, 'dist/')))
} else if (endsWith(f, '.html') && fs.existsSync(f)) {
// parse all HTML files for SSI
// TODO: delete this section?
res.end(fs.readFileSync(f))
} else if (S(f).startsWith('dist/simple/') && !/\.[a-z][a-z0-9]+(\?[^/]*)?$/.test(f)) {
} else if (startsWith(f, 'dist/simple/') && !/\.[a-z][a-z0-9]+(\?[^/]*)?$/.test(f)) {
// if we are a vue-router route, send main index file
console.log(`Req: ${req.url}, sending index.html for: ${f}`)
res.end(fs.readFileSync('dist/simple/index.html'))
Expand Down Expand Up @@ -231,6 +238,7 @@ module.exports = (grunt) => {
// This is used by grunt-sass and vueify
function sassCfg () {
return {
implementation: require('node-sass'),
sourceMap: development,
// https://github.com/vuejs/vueify/issues/34#issuecomment-161722961
// indentedSyntax: true,
Expand All @@ -246,10 +254,10 @@ function sassCfg () {

function browserifyCfg ({straight, lazy}, cfg = {}) {
var globalize = x => // views/UserGroupView.vue -> UserGroupView
S(path.parse(x).name).dasherize().capitalize().camelize().s
camelize(capitalize(dasherize(path.parse(x).name)))
var keyify = x => // views/UserGroupView.vue -> userGroupView
S(path.parse(x).name).dasherize().chompLeft('-').camelize().s
var p = (s, ...v) => _.flatten(_.zip(s, v)).join('').replace('/', path.sep)
camelize(chompLeft(dasherize(path.parse(x).name), '-'))
// var p = (s, ...v) => _.flatten(_.zip(s, v)).join('').replace('/', path.sep)

function gencfg (out, paths, isLazy) {
var c = {
Expand All @@ -261,7 +269,7 @@ function browserifyCfg ({straight, lazy}, cfg = {}) {
// pathmodify.mod.re(/^jquery$/i, 'sprint-js'),
// pathmodify.mod.dir('vendor', p`${__dirname}/frontend/simple/assets/vendor`),
// https://vuejs.org/v2/guide/installation.html#Standalone-vs-Runtime-only-Build
pathmodify.mod.id('vue', p`${__dirname}/node_modules/vue/dist/vue.common.js`)
pathmodify.mod.id('vue', `${__dirname}/node_modules/vue/dist/vue.common.js`)
]
}]],
browserifyOptions: {
Expand Down
2 changes: 1 addition & 1 deletion .babelrc
Expand Up @@ -6,5 +6,5 @@
]
}
}]],
"plugins": ["lodash", "transform-flow-strip-types", "transform-inline-environment-variables", "transform-runtime", "transform-class-properties", "transform-object-rest-spread"]
"plugins": ["transform-flow-strip-types", "transform-inline-environment-variables", "transform-runtime", "transform-class-properties", "transform-object-rest-spread"]
}
70 changes: 27 additions & 43 deletions backend/auth.js
Expand Up @@ -2,53 +2,37 @@
// https://hapijs.com/tutorials/auth
// https://hapijs.com/tutorials/plugins

import {verify} from '../shared/functions'
import {verify, b64ToStr} from '../shared/functions.js'

const Boom = require('boom')

exports.register = function (
server: Object,
opts: Object,
next: (?Error) => void
) {
server.auth.scheme('gi-auth', function (server, options) {
return {
authenticate: function (request, reply) {
const {authorization} = request.headers
if (!authorization) return reply(Boom.unauthorized('Missing authorization'))

var [scheme, json] = authorization.split(/\s+/)
if (scheme !== 'gi') return reply(Boom.badRequest('Bad authentication'))

try {
json = JSON.parse(b64ToStr(json))
} catch (e) {
return reply(Boom.badRequest('Invalid token format'))
exports.plugin = {
name: 'gi-auth',
register: function (server: Object, opts: Object) {
server.auth.scheme('gi-auth', function (server, options) {
return {
authenticate: function (request, h) {
const {authorization} = request.headers
if (!authorization) h.unauthenticated(Boom.unauthorized('Missing authorization'))

var [scheme, json] = authorization.split(/\s+/)
if (scheme !== 'gi') h.unauthenticated(Boom.badRequest('Bad authentication'))

try {
json = JSON.parse(b64ToStr(json))
} catch (e) {
return h.unauthenticated(Boom.badRequest('Invalid token format'))
}
// http://hapijs.com/api/#serverauthschemename-scheme
var isValid = verify(json.msg, json.key, json.sig)
json.userId = json.key
var credentials = { credentials: json }
if (!isValid) return h.unauthenticated(Boom.unauthorized('Bad credentials'), credentials)
return h.authenticated(credentials)
}
// http://hapijs.com/api/#serverauthschemename-scheme
options.verify(request, json, (err, isValid, credentials) => {
credentials = { credentials: credentials || json }
if (err) return reply(err, null, credentials)
if (!isValid) return reply(Boom.unauthorized('Bad credentials'), null, credentials)
return reply.continue(credentials)
})
}
}
})

var b64ToBuf = b64 => Buffer.from(b64, 'base64')
var b64ToStr = b64 => b64ToBuf(b64).toString('utf8')
server.auth.strategy('gi-auth', 'gi-auth', {
verify: function (req, json, cb) {
var result = verify(json.msg, json.key, json.sig)
json.userId = json.key
cb(null, result, json)
}
})

next()
}
})

exports.register.attributes = {
name: 'gi-auth'
server.auth.strategy('gi-auth', 'gi-auth')
}
}
10 changes: 10 additions & 0 deletions backend/index.js
Expand Up @@ -33,3 +33,13 @@ process.on('message', function () {
})
primus.destroy({timeout: 1000}) // TODO: close: false ?
})

process.on('uncaughtException', (err) => {
console.error('[server] Unhandled exception:', err, err.stack)
process.exit(1)
})

process.on('unhandledRejection', (reason, p) => {
console.error('[server] Unhandled promise rejection:', p, 'reason:', reason)
process.exit(1)
})
41 changes: 22 additions & 19 deletions backend/routes.js
Expand Up @@ -12,25 +12,26 @@ module.exports = function (server: Object) {
server.route({
path: '/event',
method: ['PUT', 'POST'],
config: {
options: {
auth: 'gi-auth', // TODO: implement real group-based auth
validate: { payload: Joi.string().required() }
},
handler: function (request, reply) {
handler: function (request, h) {
try {
console.log('/event handler')
const entry = GIMessage.deserialize(request.payload)
server.handleEntry(entry)
reply(entry.hash())
return entry.hash()
} catch (err) {
logger(err)
reply(err)
return err
}
}
})
server.route({
path: '/events/{contractID}/{since}',
method: ['GET'],
handler: async function (request, reply) {
handler: async function (request, h) {
try {
const {contractID, since} = request.params
var stream = db.streamEntriesSince(contractID, since)
Expand All @@ -43,58 +44,60 @@ module.exports = function (server: Object) {
// we're currently returning a Readable stream, which doesn't have
// '.end'. If there are any issues we can try switching to returning a
// Writable stream. Both types however do have .destroy.
request.on('disconnect', stream.destroy.bind(stream))
reply(stream)
request.events.once('disconnect', () => {
stream.destroy.bind(stream)
})
return stream
} catch (err) {
logger(err)
reply(err)
return err
}
}
})
server.route({
path: '/name',
method: ['POST'],
config: { validate: { payload: {
options: { validate: { payload: {
name: Joi.string().required(),
value: Joi.string().required()
} } },
handler: function (request, reply) {
handler: function (request, h) {
try {
const {name, value} = request.payload
if (db.lookupName(name)) {
reply(Boom.conflict('exists'))
return Boom.conflict('exists')
} else {
db.registerName(name, value)
reply({name, value})
return {name, value}
}
} catch (err) {
logger(err)
reply(err)
return err
}
}
})
server.route({
path: '/name/{name}',
method: ['GET'],
handler: function (request, reply) {
handler: function (request, h) {
try {
reply(db.lookupName(request.params.name) || Boom.notFound())
return db.lookupName(request.params.name) || Boom.notFound()
} catch (err) {
logger(err)
reply(err)
return err
}
}
})
server.route({
path: '/latestHash/{contractID}',
method: ['GET'],
handler: function (request, reply) {
handler: function (request, h) {
try {
var entry = db.lastEntry(request.params.contractID)
reply(entry ? entry.hash() : Boom.notFound())
return entry ? entry.hash() : Boom.notFound()
} catch (err) {
logger(err)
reply(err)
return err
}
}
})
Expand Down
14 changes: 9 additions & 5 deletions backend/server.js
Expand Up @@ -8,13 +8,17 @@ import {makeResponse} from '../shared/functions.js'
import {RESPONSE_TYPE} from '../shared/constants.js'
import {bold} from 'chalk'

export var hapi = new Hapi.Server({
// NOTE: migration guides for Hapi v16 -> v17:
// https://github.com/hapijs/hapi/issues/3658
// https://medium.com/yld-engineering-blog/so-youre-thinking-about-updating-your-hapi-js-server-to-v17-b5732ab5bdb8
// https://futurestud.io/tutorials/hapi-v17-upgrade-guide-your-move-to-async-await

export var hapi = Hapi.server({
// TODO: improve logging and base it on process.env.NODE_ENV
// https://github.com/okTurtles/group-income-simple/issues/32
debug: false
})

hapi.connection({
// debug: false, // <- Hapi v16 was outputing too many unnecessary debug statements
// // v17 doesn't seem to do this anymore so I've re-enabled the logging
debug: { log: ['error'], request: ['error'] },
port: process.env.API_PORT,
// See: https://github.com/hapijs/discuss/issues/262#issuecomment-204616831
routes: { cors: { origin: [process.env.FRONTEND_URL] } }
Expand Down
2 changes: 1 addition & 1 deletion frontend/simple/assets/vendor/primus.js
Expand Up @@ -3336,7 +3336,7 @@ module.exports = Primus;

},{"demolish":1,"emits":2,"eventemitter3":3,"inherits":4,"querystringify":7,"recovery":8,"tick-tock":11,"url-parse":12,"yeast":13}]},{},[14])(14)
;
Primus.prototype.ark["responder"] = function (){};
Primus.prototype.ark["responder"] = function(){};
return Primus;
},
[
Expand Down
5 changes: 1 addition & 4 deletions frontend/simple/utils/giLodash.test.js
Expand Up @@ -32,10 +32,7 @@ describe('Test giLodash', function () {
it('Test flatten', function () {
let a = [1, [2, [3, 4]], 5]
let b = _.flatten(a)
should(a).not.equal(b)
should(Array.isArray(b[1])).equal(false)
should(Array.isArray(b[2])).equal(true)
should(b.length).equal(4)
should(b).deepEqual([1, 2, [3, 4], 5]) // important: use deepEqual not equal
})
it('Test zip', function () {
let a = _.zip([1, 2], ['a', 'b'], [true, false, null])
Expand Down

0 comments on commit da3881f

Please sign in to comment.