This repository has been archived by the owner on Mar 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 118
/
index.js
252 lines (208 loc) · 8.28 KB
/
index.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import Debug from 'debug';
import errors from 'feathers-errors';
const debug = Debug('feathers-authentication:middleware');
const TEN_HOURS = 36000000;
// Usually this is a big no no but passport requires the
// request object to inspect req.body and req.query so we
// need to miss behave a bit. Don't do this in your own code!
export let exposeConnectMiddleware = function(req, res, next) {
req.feathers.req = req;
req.feathers.res = res;
next();
};
// Make the authenticated passport user also available for REST services.
// We might need this for when we have session supported auth.
// export let exposeAuthenticatedUser = function(options = {}) {
// return function(req, res, next) {
// req.feathers.user = req.user;
// next();
// };
// };
// Make sure than an auth token passed in is available for hooks
// and services. This gracefully falls back from
// header -> cookie -> body -> query string
export let normalizeAuthToken = function(options = {}) {
debug('Setting up normalizeAuthToken middleware with options:', options);
if (!options.header) {
throw new Error(`'header' must be provided to normalizeAuthToken() middleware`);
}
if (!options.cookie) {
throw new Error(`'cookie' must be provided to normalizeAuthToken() middleware`);
}
return function(req, res, next) {
let token = req.headers[options.header];
// Check the header for the token (preferred method)
if (token) {
// if the value contains "bearer" or "Bearer" then cut that part out
if ( /bearer/i.test(token) ) {
token = token.split(' ')[1];
}
}
// If we don't already have token in the header check for a cookie
if (!token && req.cookies && req.cookies[options.cookie]) {
token = req.cookies[options.cookie];
}
// Check the body next if we still don't have a token
else if (req.body.token) {
token = req.body.token;
delete req.body.token;
}
// Finally, check the query string. (worst method)
else if (req.query.token) {
token = req.query.token;
delete req.query.token;
}
// Tack it on to our feathers object so that it is passed to services
req.feathers.token = token;
next();
};
};
export let successfulLogin = function(options = {}) {
debug('Setting up successfulLogin middleware with options:', options);
if (!options.cookie) {
throw new Error(`'cookie' must be provided to successfulLogin() middleware`);
}
return function(req, res, next) {
// NOTE (EK): If we are not dealing with a browser or it was an
// XHR request then just skip this. This is primarily for
// handling the oauth redirects and for us to securely send the
// JWT to the client.
if (!options.successRedirect || req.xhr || req.is('json') || !req.accepts('html')) {
return next();
}
// clear any previous JWT cookie
res.clearCookie(options.cookie);
// Set a our JWT in a cookie.
// TODO (EK): Look into hardening this cookie a bit.
let expiration = new Date();
expiration.setTime(expiration.getTime() + TEN_HOURS);
res.cookie(options.cookie, res.data.token, { expires: expiration});
// Redirect to our success route
res.redirect(options.successRedirect);
};
};
export let failedLogin = function(options = {}) {
debug('Setting up failedLogin middleware with options:', options);
if (!options.cookie) {
throw new Error(`'cookie' must be provided to failedLogin() middleware`);
}
return function(error, req, res, next) {
// NOTE (EK): If we are not dealing with a browser or it was an
// XHR request then just skip this. This is primarily for
// handling redirecting on an oauth failure.
// console.log('Auth Error', error, options);
if (!options.failureRedirect || req.xhr || req.is('json') || !req.accepts('html')) {
return next(error);
}
// clear any previous JWT cookie
res.clearCookie(options.cookie);
debug('An authentication error occurred.', error);
// Redirect to our failure route
res.redirect(options.failureRedirect);
};
};
export let setupSocketIOAuthentication = function(app, options = {}) {
options = Object.assign({}, options);
debug('Setting up Socket.io authentication middleware with options:', options);
return function(socket) {
let errorHandler = function(error) {
socket.emit('unauthorized', error, function(){
// TODO (EK): Maybe we support disconnecting the socket
// if a certain number of authorization attempts have failed
// for brute force protection
// socket.disconnect('unauthorized');
});
throw error;
};
// Expose the request object to services and hooks
// for Passport. This is normally a big no no.
socket.feathers.req = socket.request;
socket.on('authenticate', function(data) {
// Authenticate the user using token strategy
if (data.token) {
if (typeof data.token !== 'string') {
return errorHandler(new errors.BadRequest('Invalid token data type.'));
}
const params = Object.assign({ provider: 'socketio' }, data);
// The token gets normalized in hook.params for REST so we'll stay with
// convention and pass it as params using sockets.
app.service(options.tokenEndpoint).create({}, params).then(response => {
socket.feathers.token = response.token;
socket.feathers.user = response.data;
socket.emit('authenticated', response);
}).catch(errorHandler);
}
// Authenticate the user using local auth strategy
else {
// Put our data in a fake req.body object to get local auth
// with Passport to work because it checks res.body for the
// username and password.
let params = {
provider: 'socketio',
req: socket.request
};
params.req.body = data;
app.service(options.localEndpoint).create(data, params).then(response => {
socket.feathers.token = response.token;
socket.feathers.user = response.data;
socket.emit('authenticated', response);
}).catch(errorHandler);
}
});
};
};
// TODO (EK): DRY this up along with the code in setupSocketIOAuthentication
export let setupPrimusAuthentication = function(app, options = {}) {
options = Object.assign({}, options);
debug('Setting up Primus authentication middleware with options:', options);
return function(socket) {
let errorHandler = function(error) {
socket.send('unauthorized', error);
// TODO (EK): Maybe we support disconnecting the socket
// if a certain number of authorization attempts have failed
// for brute force protection
// socket.end('unauthorized', error);
throw error;
};
socket.request.feathers.req = socket.request;
socket.on('authenticate', function(data) {
// Authenticate the user using token strategy
if (data.token) {
if (typeof data.token !== 'string') {
return errorHandler(new errors.BadRequest('Invalid token data type.'));
}
const params = Object.assign({ provider: 'primus' }, data);
// The token gets normalized in hook.params for REST so we'll stay with
// convention and pass it as params using sockets.
app.service(options.tokenEndpoint).create({}, params).then(response => {
socket.request.feathers.token = response.token;
socket.request.feathers.user = response.data;
socket.send('authenticated', response);
}).catch(errorHandler);
}
// Authenticate the user using local auth strategy
else {
// Put our data in a fake req.body object to get local auth
// with Passport to work because it checks res.body for the
// username and password.
let params = {
provider: 'primus',
req: socket.request
};
params.req.body = data;
app.service(options.localEndpoint).create(data, params).then(response => {
socket.request.feathers.token = response.token;
socket.request.feathers.user = response.data;
socket.send('authenticated', response);
}).catch(errorHandler);
}
});
};
};
export default {
exposeConnectMiddleware,
normalizeAuthToken,
successfulLogin,
setupSocketIOAuthentication,
setupPrimusAuthentication
};