-
Notifications
You must be signed in to change notification settings - Fork 71
/
fastboot-request.js
62 lines (48 loc) · 1.54 KB
/
fastboot-request.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
'use strict';
const cookie = require('cookie');
const FastBootHeaders = require('./fastboot-headers');
class FastBootRequest {
constructor(request, hostWhitelist) {
this.hostWhitelist = hostWhitelist;
this.protocol = `${request.protocol}:`;
this.headers = new FastBootHeaders(request.headers);
this.queryParams = request.query;
this.path = request.url;
this.method = request.method;
this.body = request.body;
this.cookies = this.extractCookies(request);
}
host() {
if (!this.hostWhitelist) {
throw new Error('You must provide a hostWhitelist to retrieve the host');
}
var host = this.headers.get('host');
var matchFound = this.hostWhitelist.some(function(entry) {
if (entry[0] === '/' && entry.slice(-1) === '/') {
var regexp = new RegExp(entry.slice(1, -1));
return regexp.test(host);
} else {
return entry === host;
}
});
if (!matchFound) {
throw new Error(`The host header did not match a hostWhitelist entry. Host header: ${host}`);
}
return host;
}
extractCookies(request) {
// If cookie-parser middleware has already parsed the cookies,
// just use that.
if (request.cookies) {
return request.cookies;
}
// Otherwise, try to parse the cookies ourselves, if they exist.
var cookies = request.headers.cookie;
if (cookies) {
return cookie.parse(cookies);
}
// Return an empty object instead of undefined if no cookies are present.
return {};
}
}
module.exports = FastBootRequest;