-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth-middleware.js
63 lines (54 loc) · 1.71 KB
/
auth-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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'use strict'
/**
* NPM modules.
*/
var openpgp = require('openpgp')
/**
* Local modules.
*/
var logger = require('./logger')
module.exports = function AuthenticationMiddleware() {
return function handle(req, res, next) {
// read publicKey from body
var publicKey = req.body.publicKey
if (typeof publicKey === typeof void 0) {
logger.debug('Request body does not have a publicKey')
var e = new Error('Please provide a public key.')
e.status = 400
next(e)
} else {
var publicKey = openpgp.key.readArmored(publicKey).keys[0]
if (typeof publicKey === typeof void 0) {
logger.debug('Request body contains a public key that could not be ' +
'parsed correctly.')
var e = new Error('Invalid publicKey.')
e.status = 401
next(e)
} else {
// let the store validate
var store = require('./store')
try {
var longKeyId = publicKey.primaryKey.getKeyId().toHex().toUpperCase()
logger.info('Request body contains a public key with id "' +
longKeyId + '".')
store.validateKey(longKeyId, function validated(isAuthenticated) {
if (!isAuthenticated) {
logger.warn('Unauthorized access attempt: no key id matching "' +
longKeyId + '" was found in "' + store.keyFile + '".')
var e = new Error('Invalid publicKey.')
e.status = 401
next(e)
} else {
// continue
next()
}
})
} catch (e) {
// error raised in the store
if (!e.status) e.status = 500
next(e)
}
}
}
}
}