-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmiddleware.js
115 lines (97 loc) · 2.89 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
'use strict'
const jwt = require('jsonwebtoken')
const async = require('async')
const passport = require.main.require('passport')
const nconf = require.main.require('nconf')
const user = require.main.require('./src/user')
// const plugins = require.main.require('./src/plugins')
const errorHandler = require('./lib/errorHandler')
// const utils = require('./utils');
const Middleware = {
regexes: {
tokenRoute: new RegExp(
'^' +
nconf.get('relative_path') +
'\\/api\\/v\\d+\\/users\\/(\\d+)\\/tokens$'
)
}
}
Middleware.requireUser = async function (req, res, next) {
var routeMatch
// If plugins handle the response, stop default actions
if (res.headersSent) {
return
}
if (req.headers.hasOwnProperty('authorization')) {
passport.authenticate('bearer', { session: false }, function (err, user) {
if (err) {
return next(err)
}
if (!user) {
return errorHandler.respond(401, res)
}
// If the token received was a master token, a _uid must also be present for all calls
if (user.hasOwnProperty('uid')) {
req.login(user, function (err) {
if (err) {
return errorHandler.respond(500, res)
}
req.uid = user.uid
req.loggedIn = req.uid > 0
next()
})
} else if (user.hasOwnProperty('master') && user.master === true) {
user.uid = req.body.request._uid || req.query._uid || 1
delete user.master
req.login(user, function (err) {
if (err) {
return errorHandler.respond(500, res)
}
req.uid = user.uid
req.loggedIn = req.uid > 0
next()
})
} else {
return errorHandler.respond(500, res)
}
})(req, res, next)
} else if (
(routeMatch = req.originalUrl.match(Middleware.regexes.tokenRoute))
) {
// If token generation route is hit, check password instead
if (!utils.checkRequired(['password'], req, res)) {
return false
}
var uid = routeMatch[1]
user.isPasswordCorrect(uid, req.body.password, req.ip, function (err, ok) {
if (!err && ok) {
req.login({ uid: parseInt(uid, 10) }, function (err) {
if (err) {
return errorHandler.respond(500, res)
}
req.uid = user.uid
req.loggedIn = req.uid > 0
next()
})
} else {
errorHandler.respond(401, res)
}
})
} else {
// No bearer token, jwt, or special handling instructions, transparently pass-through
// next()
return errorHandler.respond(401, res)
}
}
Middleware.requireAdmin = function (req, res, next) {
if (!req.user) {
return errorHandler.respond(401, res)
}
user.isAdministrator(req.user.uid, function (err, isAdmin) {
if (err || !isAdmin) {
return errorHandler.respond(403, res)
}
next()
})
}
module.exports = Middleware