Implement version check middleware

Signed-off-by: Yukai Huang <yukaihuangtw@gmail.com>
This commit is contained in:
Yukai Huang 2019-12-26 16:56:31 +08:00
parent eefcf28fcf
commit 11265238db
3 changed files with 60 additions and 1 deletions

6
app.js
View File

@ -25,6 +25,8 @@ var response = require('./lib/response')
var models = require('./lib/models')
var csp = require('./lib/csp')
const { versionCheckMiddleware } = require('./lib/web/middleware/checkVersion')
function createHttpServer () {
if (config.useSSL) {
const ca = (function () {
@ -167,6 +169,10 @@ app.use(require('./lib/middleware/checkURIValid'))
app.use(require('./lib/middleware/redirectWithoutTrailingSlashes'))
app.use(require('./lib/middleware/codiMDVersion'))
if (config.autoVersionCheck) {
app.use(versionCheckMiddleware)
}
// routes need sessions
// template files
app.set('views', config.viewPath)

View File

@ -178,5 +178,6 @@ module.exports = {
// Generated id: "31-good-morning-my-friend---do-you-have-5"
// 2nd appearance: "31-good-morning-my-friend---do-you-have-5-1"
// 3rd appearance: "31-good-morning-my-friend---do-you-have-5-2"
linkifyHeaderStyle: 'keep-case'
linkifyHeaderStyle: 'keep-case',
autoVersionCheck: true
}

View File

@ -0,0 +1,52 @@
'use strict'
const { promisify } = require('util')
const request = require('request')
const logger = require('../../logger')
const config = require('../../config')
let lastCheckAt
let latest = true
let versionItem = null
const VERSION_CHECK_ENDPOINT = 'https://evangelion.codimd.dev/'
const CHECK_TIMEOUT = 1000 * 60 * 60 * 24 // 1 day
const rp = promisify(request)
exports.versionCheckMiddleware = async function (req, res, next) {
if (lastCheckAt && (lastCheckAt + CHECK_TIMEOUT > Date.now())) {
return next()
}
// update lastCheckAt whether the check would fail or not
lastCheckAt = Date.now()
try {
const { statusCode, body: data } = await rp({
url: `${VERSION_CHECK_ENDPOINT}?v=${config.version}`,
method: 'GET',
json: true
})
if (statusCode !== 200 || data.status === 'error') {
logger.error('Version check failed.')
return next()
}
latest = data.latest
versionItem = latest ? null : data.versionItem
return next()
} catch (err) {
// ignore and skip version check
logger.error('Version check failed.')
logger.error(err)
return next()
}
}
exports.versionItem = versionItem
exports.outdated = outdated