mtfosbot/libs/middleware/index.js

36 lines
1.0 KiB
JavaScript
Raw Normal View History

2018-06-25 10:07:10 +00:00
const config = require('../../config')
const rawBody = require('raw-body')
2018-06-25 10:07:10 +00:00
const crypto = require('crypto')
const verifyLine = async (c, n) => {
if (!('request' in c) || !('raw' in c.request)) return c.throw(400, 'body not found')
let xSignature = c.get('x-line-signature') || ''
if (typeof xSignature !== 'string' || xSignature.length === 0) return c.throw(400, 'signature not found')
let signature = crypto.createHmac('SHA256', config.line.secret).update(c.request.raw).digest('base64')
if (signature !== xSignature) return c.throw(403, 'signature not match')
return n()
}
const getRaw = async (c, n) => {
let raw = await rawBody(c.req, {
length: c.request.length,
limit: '5mb',
encoding: c.request.charset
})
c.request.raw = raw
let txt = raw instanceof Buffer ? raw.toString() : raw
if (c.request.type === 'application/json') {
try {
c.request.body = JSON.parse(txt)
} catch (err) {
c.request.body = txt
}
}
return n()
}
2018-06-25 10:07:10 +00:00
module.exports = {
verifyLine,
getRaw
2018-06-25 10:07:10 +00:00
}