-
Notifications
You must be signed in to change notification settings - Fork 0
/
express.js
66 lines (63 loc) · 1.59 KB
/
express.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
64
65
66
const isString = require('lodash.isstring')
const omit = require('lodash.omit')
const { verifyData } = require('./index')
module.exports = function (getUser, pickPublicKey) {
return async function (req, res, next) {
let body
if (req.body._sig && req.body.timestamp && req.body.userID) {
body = req.body
req.body = omit(body, [
'_sig',
'timestamp',
'userID'
])
} else if (req.query._sig && req.query.timestamp && req.query.userID) {
body = req.query
if (isString(body.timestamp)) {
body.timestamp = Number(body.timestamp)
}
req.query = omit(body, [
'_sig',
'timestamp',
'userID'
])
}
if (body) {
const user = await getUser(body.userID)
if (!user) {
// res.status(401).header('WWW-Authenticate', 'SignedMessage').send()
res.status(401).send({
error: true,
errorCode: 'NO_USER_ID'
})
return
}
const pubKey = pickPublicKey(user)
let validated = false
try {
validated = verifyData(body, pubKey)
} catch (e) {
console.warn('libbetterauth: Caught error at verifyData', e)
}
if (!validated) {
res.status(401).send({
error: true,
errorCode: 'VERIFICATION_FAILED'
})
return
}
req.user = user
}
next()
}
}
module.exports.authenticationMandatory = function (req, res, next) {
if (!req.user) {
res.status(403).send({
error: true,
errorCode: 'AUTHENTICATION_MANDATORY'
})
} else {
next()
}
}