2018-06-25 10:07:10 +00:00
|
|
|
const config = require('../../config')
|
2018-06-26 16:59:53 +00:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
|
2018-06-26 16:59:53 +00:00
|
|
|
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 = {
|
2018-06-26 16:59:53 +00:00
|
|
|
verifyLine,
|
|
|
|
getRaw
|
2018-06-25 10:07:10 +00:00
|
|
|
}
|