-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
47 lines (42 loc) · 1.19 KB
/
middleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const axios = require('axios')
const auth_jwt = require('./auth-jwt.js')
const loginUrl = '/login?next=<url>'
exports.reject = function (req, res, next) {
const originUrlEncoded = encodeURIComponent(req.url || '/')
const redirectUrl = loginUrl.replace('<url>', originUrlEncoded)
const reqContentType = req.accepts('html', 'json')
if (reqContentType == 'json') {
/* handle POST request rejection */
res.json({
'pass': false,
'redirect': redirectUrl
})
} else {
/* GET/HEAD request, send 302 code */
res.redirect(redirectUrl)
}
}
exports.jwt_verifier = async function(jwt_secret_url) {
const url = jwt_secret_url
let secret = ''
try {
const response = await axios.get(url)
secret = response.data
} catch (err) {
console.error('failed to obtain secret from', url)
console.error(err.toString())
}
return function (req, res, next) {
const key = auth_jwt.JWT_token_key
const token = req.cookies[key] || ''
auth_jwt.verify(token, secret).then(ret => {
const [pass, msg] = ret
console.log(pass ? 'passed' : 'failed', msg)
if (pass) {
next()
} else {
exports.reject(req, res, next)
}
})
}
}