forked from nodeSolidServer/node-solid-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebid-tls.js
More file actions
69 lines (60 loc) · 1.67 KB
/
webid-tls.js
File metadata and controls
69 lines (60 loc) · 1.67 KB
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
64
65
66
67
68
69
const webid = require('webid/tls')
const debug = require('../../debug').authentication
function initialize (app, argv) {
app.use('/', handler)
}
function handler (req, res, next) {
// User already logged in? skip
if (req.session.userId) {
debug('User: ' + req.session.userId)
res.set('User', req.session.userId)
return next()
}
// No certificate? skip
const certificate = getCertificateViaTLS(req)
if (!certificate) {
setEmptySession(req)
return next()
}
// Verify webid
webid.verify(certificate, function (err, result) {
if (err) {
debug('Error processing certificate: ' + err.message)
setEmptySession(req)
return next()
}
req.session.userId = result
debug('Identified user: ' + req.session.userId)
res.set('User', req.session.userId)
return next()
})
}
// Tries to obtain a client certificate retrieved through the TLS handshake
function getCertificateViaTLS (req) {
const certificate = req.connection.getPeerCertificate &&
req.connection.getPeerCertificate()
if (certificate && Object.keys(certificate).length > 0) {
return certificate
}
debug('No peer certificate received during TLS handshake.')
}
function setEmptySession (req) {
req.session.userId = ''
}
/**
* Sets the `WWW-Authenticate` response header for 401 error responses.
* Used by error-pages handler.
*
* @param req {IncomingRequest}
* @param res {ServerResponse}
*/
function setAuthenticateHeader (req, res) {
let locals = req.app.locals
res.set('WWW-Authenticate', `WebID-TLS realm="${locals.host.serverUri}"`)
}
module.exports = {
initialize,
handler,
setAuthenticateHeader,
setEmptySession
}