-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
205 lines (167 loc) · 5.52 KB
/
app.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const passport = require('passport')
const BasicStrategy = require('passport-http').BasicStrategy
const LocalStrategy = require('passport-local').Strategy
const BearerStrategy = require('passport-http-bearer').Strategy
const ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy
const errors = require('./errors')
const logger = require('./logger')
const routes = require('./routes/index')
const api = require('./api')
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(passport.initialize())
//generate API docs
app.get('/swagger.json', function(req, res) {
res.json(require('./swagger')())
})
app.post('/auth/oauth/access_token', require('./oauth2').token)
const credentialsLogin = function(username, password, done) {
api.models.User.findOne({ username: username })
.then((user) => {
if(!user) {
done(null, false)
return Promise.resolve()
}
return api.models.User.validPassword(password, user.password)
.then((valid) => {
if(!valid) {
done(null, false)
return Promise.resolve()
}
done(null, user)
return Promise.resolve()
})
})
.catch((e) => done(e))
}
// passport config
passport.use('client_password', new ClientPasswordStrategy(function(clientId, clientSecret, done) {
api.models.Client.findOne({ id: clientId, secret: clientSecret })
.then((client) => {
if (!client) {
return done(null, false)
}
if (!client.enabled) {
return done(null, false)
}
return done(null, client)
})
.catch((e) => done(e))
}))
passport.use('client_basic', new BasicStrategy(function(username, password, done) {
api.models.Client.findOne({ id: username, secret: password })
.then((client) => {
if(!client) {
done(null, false)
return Promise.resolve()
}
if(!client.enabled) {
done(null, false)
return Promise.resolve()
}
done(null, client)
})
}))
passport.use(new LocalStrategy(credentialsLogin))
passport.use(new BearerStrategy(function(t, done) {
return api.models.Token.findOne({ token: t })
.then((token) => {
if (!token) {
return done(null, false)
}
if (token.isExpired()) {
return api.models.Token.remove({ _id: token._id })
.then(() => {
return Promise.reject(new errors.Unauthorized('Token is expired'))
})
}
return api.models.User.findOne({ id: token.userId})
.then((user) => {
if(user === null) {
return done(null, false)
}
if(!user.enabled) {
return done(null, false)
}
done(null, user, { token })
})
})
.catch((e) => {
logger.warn('Exception on bearer auth: %s', e.message)
logger.debug(e.stack)
done(e, false)
})
}))
passport.serializeUser(function(user, done) {
done(null, user._id)
})
passport.deserializeUser(function(id, done) {
api.models.User.findById(id)
.then((user) => {
if(!user) {
return done(new Error('Cannot deserialize user'), null)
}
done(null, user)
})
.catch((err) => {
done(err, null)
})
})
for (const path in routes) {
const isRoot = path === ''
const subpath = isRoot ? '' : `/${path}`
const subrouter = require('express-promise-router')()
// check token only on subpath like user, role, token
if(!isRoot) {
subrouter.use(passport.authenticate('bearer', {
failWithError: true,
session: false
}))
// register custom callback
let authorize = null
if(routes[path].authorize) {
authorize = routes[path].authorize
}
subrouter.use(require('./authz').check({ type: path, authorize }))
}
routes[path].router(subrouter)
app.use(`/auth${subpath}`, subrouter)
}
// last call catch 404 and forward to error handler
app.use(function(req, res, next) {
next(new errors.NotFound())
})
// error handlers
app.use(function(err, req, res, next) {
if(err.message === 'Unauthorized') {
err = new errors.Unauthorized()
}
const AuthenticationError = require('passport/lib/errors/authenticationerror')
if(err instanceof AuthenticationError) {
err = new errors.Unauthorized()
}
if(err instanceof errors.HttpError) {
res.status(err.code)
res.json(err.toJSON())
return
}
if(err.code && (err.code >= 400 && err.code <= 510)) {
res.status(err.code)
res.json({
code: err.code,
message: err.message
})
return
}
logger.error('Error: %s', err.message)
logger.debug(err.stack)
const internalError = new errors.InternalServer()
res.status(internalError.code)
res.json(internalError.toJSON())
})
module.exports = app