arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/express/lib/request.js
node_modules/express/lib/request.jsRaw
  1/*!
  2 * express
  3 * Copyright(c) 2009-2013 TJ Holowaychuk
  4 * Copyright(c) 2013 Roman Shtylman
  5 * Copyright(c) 2014-2015 Douglas Christopher Wilson
  6 * MIT Licensed
  7 */
  8
  9'use strict';
 10
 11/**
 12 * Module dependencies.
 13 * @private
 14 */
 15
 16var accepts = require('accepts');
 17var deprecate = require('depd')('express');
 18var isIP = require('net').isIP;
 19var typeis = require('type-is');
 20var http = require('http');
 21var fresh = require('fresh');
 22var parseRange = require('range-parser');
 23var parse = require('parseurl');
 24var proxyaddr = require('proxy-addr');
 25
 26/**
 27 * Request prototype.
 28 */
 29
 30var req = exports = module.exports = {
 31  __proto__: http.IncomingMessage.prototype
 32};
 33
 34/**
 35 * Return request header.
 36 *
 37 * The `Referrer` header field is special-cased,
 38 * both `Referrer` and `Referer` are interchangeable.
 39 *
 40 * Examples:
 41 *
 42 *     req.get('Content-Type');
 43 *     // => "text/plain"
 44 *
 45 *     req.get('content-type');
 46 *     // => "text/plain"
 47 *
 48 *     req.get('Something');
 49 *     // => undefined
 50 *
 51 * Aliased as `req.header()`.
 52 *
 53 * @param {String} name
 54 * @return {String}
 55 * @public
 56 */
 57
 58req.get =
 59req.header = function header(name) {
 60  if (!name) {
 61    throw new TypeError('name argument is required to req.get');
 62  }
 63
 64  if (typeof name !== 'string') {
 65    throw new TypeError('name must be a string to req.get');
 66  }
 67
 68  var lc = name.toLowerCase();
 69
 70  switch (lc) {
 71    case 'referer':
 72    case 'referrer':
 73      return this.headers.referrer
 74        || this.headers.referer;
 75    default:
 76      return this.headers[lc];
 77  }
 78};
 79
 80/**
 81 * To do: update docs.
 82 *
 83 * Check if the given `type(s)` is acceptable, returning
 84 * the best match when true, otherwise `undefined`, in which
 85 * case you should respond with 406 "Not Acceptable".
 86 *
 87 * The `type` value may be a single MIME type string
 88 * such as "application/json", an extension name
 89 * such as "json", a comma-delimited list such as "json, html, text/plain",
 90 * an argument list such as `"json", "html", "text/plain"`,
 91 * or an array `["json", "html", "text/plain"]`. When a list
 92 * or array is given, the _best_ match, if any is returned.
 93 *
 94 * Examples:
 95 *
 96 *     // Accept: text/html
 97 *     req.accepts('html');
 98 *     // => "html"
 99 *
100 *     // Accept: text/*, application/json
101 *     req.accepts('html');
102 *     // => "html"
103 *     req.accepts('text/html');
104 *     // => "text/html"
105 *     req.accepts('json, text');
106 *     // => "json"
107 *     req.accepts('application/json');
108 *     // => "application/json"
109 *
110 *     // Accept: text/*, application/json
111 *     req.accepts('image/png');
112 *     req.accepts('png');
113 *     // => undefined
114 *
115 *     // Accept: text/*;q=.5, application/json
116 *     req.accepts(['html', 'json']);
117 *     req.accepts('html', 'json');
118 *     req.accepts('html, json');
119 *     // => "json"
120 *
121 * @param {String|Array} type(s)
122 * @return {String|Array|Boolean}
123 * @public
124 */
125
126req.accepts = function(){
127  var accept = accepts(this);
128  return accept.types.apply(accept, arguments);
129};
130
131/**
132 * Check if the given `encoding`s are accepted.
133 *
134 * @param {String} ...encoding
135 * @return {String|Array}
136 * @public
137 */
138
139req.acceptsEncodings = function(){
140  var accept = accepts(this);
141  return accept.encodings.apply(accept, arguments);
142};
143
144req.acceptsEncoding = deprecate.function(req.acceptsEncodings,
145  'req.acceptsEncoding: Use acceptsEncodings instead');
146
147/**
148 * Check if the given `charset`s are acceptable,
149 * otherwise you should respond with 406 "Not Acceptable".
150 *
151 * @param {String} ...charset
152 * @return {String|Array}
153 * @public
154 */
155
156req.acceptsCharsets = function(){
157  var accept = accepts(this);
158  return accept.charsets.apply(accept, arguments);
159};
160
161req.acceptsCharset = deprecate.function(req.acceptsCharsets,
162  'req.acceptsCharset: Use acceptsCharsets instead');
163
164/**
165 * Check if the given `lang`s are acceptable,
166 * otherwise you should respond with 406 "Not Acceptable".
167 *
168 * @param {String} ...lang
169 * @return {String|Array}
170 * @public
171 */
172
173req.acceptsLanguages = function(){
174  var accept = accepts(this);
175  return accept.languages.apply(accept, arguments);
176};
177
178req.acceptsLanguage = deprecate.function(req.acceptsLanguages,
179  'req.acceptsLanguage: Use acceptsLanguages instead');
180
181/**
182 * Parse Range header field, capping to the given `size`.
183 *
184 * Unspecified ranges such as "0-" require knowledge of your resource length. In
185 * the case of a byte range this is of course the total number of bytes. If the
186 * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
187 * and `-2` when syntactically invalid.
188 *
189 * When ranges are returned, the array has a "type" property which is the type of
190 * range that is required (most commonly, "bytes"). Each array element is an object
191 * with a "start" and "end" property for the portion of the range.
192 *
193 * The "combine" option can be set to `true` and overlapping & adjacent ranges
194 * will be combined into a single range.
195 *
196 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
197 * should respond with 4 users when available, not 3.
198 *
199 * @param {number} size
200 * @param {object} [options]
201 * @param {boolean} [options.combine=false]
202 * @return {number|array}
203 * @public
204 */
205
206req.range = function range(size, options) {
207  var range = this.get('Range');
208  if (!range) return;
209  return parseRange(size, range, options);
210};
211
212/**
213 * Return the value of param `name` when present or `defaultValue`.
214 *
215 *  - Checks route placeholders, ex: _/user/:id_
216 *  - Checks body params, ex: id=12, {"id":12}
217 *  - Checks query string params, ex: ?id=12
218 *
219 * To utilize request bodies, `req.body`
220 * should be an object. This can be done by using
221 * the `bodyParser()` middleware.
222 *
223 * @param {String} name
224 * @param {Mixed} [defaultValue]
225 * @return {String}
226 * @public
227 */
228
229req.param = function param(name, defaultValue) {
230  var params = this.params || {};
231  var body = this.body || {};
232  var query = this.query || {};
233
234  var args = arguments.length === 1
235    ? 'name'
236    : 'name, default';
237  deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');
238
239  if (null != params[name] && params.hasOwnProperty(name)) return params[name];
240  if (null != body[name]) return body[name];
241  if (null != query[name]) return query[name];
242
243  return defaultValue;
244};
245
246/**
247 * Check if the incoming request contains the "Content-Type"
248 * header field, and it contains the give mime `type`.
249 *
250 * Examples:
251 *
252 *      // With Content-Type: text/html; charset=utf-8
253 *      req.is('html');
254 *      req.is('text/html');
255 *      req.is('text/*');
256 *      // => true
257 *
258 *      // When Content-Type is application/json
259 *      req.is('json');
260 *      req.is('application/json');
261 *      req.is('application/*');
262 *      // => true
263 *
264 *      req.is('html');
265 *      // => false
266 *
267 * @param {String|Array} types...
268 * @return {String|false|null}
269 * @public
270 */
271
272req.is = function is(types) {
273  var arr = types;
274
275  // support flattened arguments
276  if (!Array.isArray(types)) {
277    arr = new Array(arguments.length);
278    for (var i = 0; i < arr.length; i++) {
279      arr[i] = arguments[i];
280    }
281  }
282
283  return typeis(this, arr);
284};
285
286/**
287 * Return the protocol string "http" or "https"
288 * when requested with TLS. When the "trust proxy"
289 * setting trusts the socket address, the
290 * "X-Forwarded-Proto" header field will be trusted
291 * and used if present.
292 *
293 * If you're running behind a reverse proxy that
294 * supplies https for you this may be enabled.
295 *
296 * @return {String}
297 * @public
298 */
299
300defineGetter(req, 'protocol', function protocol(){
301  var proto = this.connection.encrypted
302    ? 'https'
303    : 'http';
304  var trust = this.app.get('trust proxy fn');
305
306  if (!trust(this.connection.remoteAddress, 0)) {
307    return proto;
308  }
309
310  // Note: X-Forwarded-Proto is normally only ever a
311  //       single value, but this is to be safe.
312  proto = this.get('X-Forwarded-Proto') || proto;
313  return proto.split(/\s*,\s*/)[0];
314});
315
316/**
317 * Short-hand for:
318 *
319 *    req.protocol === 'https'
320 *
321 * @return {Boolean}
322 * @public
323 */
324
325defineGetter(req, 'secure', function secure(){
326  return this.protocol === 'https';
327});
328
329/**
330 * Return the remote address from the trusted proxy.
331 *
332 * The is the remote address on the socket unless
333 * "trust proxy" is set.
334 *
335 * @return {String}
336 * @public
337 */
338
339defineGetter(req, 'ip', function ip(){
340  var trust = this.app.get('trust proxy fn');
341  return proxyaddr(this, trust);
342});
343
344/**
345 * When "trust proxy" is set, trusted proxy addresses + client.
346 *
347 * For example if the value were "client, proxy1, proxy2"
348 * you would receive the array `["client", "proxy1", "proxy2"]`
349 * where "proxy2" is the furthest down-stream and "proxy1" and
350 * "proxy2" were trusted.
351 *
352 * @return {Array}
353 * @public
354 */
355
356defineGetter(req, 'ips', function ips() {
357  var trust = this.app.get('trust proxy fn');
358  var addrs = proxyaddr.all(this, trust);
359  return addrs.slice(1).reverse();
360});
361
362/**
363 * Return subdomains as an array.
364 *
365 * Subdomains are the dot-separated parts of the host before the main domain of
366 * the app. By default, the domain of the app is assumed to be the last two
367 * parts of the host. This can be changed by setting "subdomain offset".
368 *
369 * For example, if the domain is "tobi.ferrets.example.com":
370 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
371 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
372 *
373 * @return {Array}
374 * @public
375 */
376
377defineGetter(req, 'subdomains', function subdomains() {
378  var hostname = this.hostname;
379
380  if (!hostname) return [];
381
382  var offset = this.app.get('subdomain offset');
383  var subdomains = !isIP(hostname)
384    ? hostname.split('.').reverse()
385    : [hostname];
386
387  return subdomains.slice(offset);
388});
389
390/**
391 * Short-hand for `url.parse(req.url).pathname`.
392 *
393 * @return {String}
394 * @public
395 */
396
397defineGetter(req, 'path', function path() {
398  return parse(this).pathname;
399});
400
401/**
402 * Parse the "Host" header field to a hostname.
403 *
404 * When the "trust proxy" setting trusts the socket
405 * address, the "X-Forwarded-Host" header field will
406 * be trusted.
407 *
408 * @return {String}
409 * @public
410 */
411
412defineGetter(req, 'hostname', function hostname(){
413  var trust = this.app.get('trust proxy fn');
414  var host = this.get('X-Forwarded-Host');
415
416  if (!host || !trust(this.connection.remoteAddress, 0)) {
417    host = this.get('Host');
418  }
419
420  if (!host) return;
421
422  // IPv6 literal support
423  var offset = host[0] === '['
424    ? host.indexOf(']') + 1
425    : 0;
426  var index = host.indexOf(':', offset);
427
428  return index !== -1
429    ? host.substring(0, index)
430    : host;
431});
432
433// TODO: change req.host to return host in next major
434
435defineGetter(req, 'host', deprecate.function(function host(){
436  return this.hostname;
437}, 'req.host: Use req.hostname instead'));
438
439/**
440 * Check if the request is fresh, aka
441 * Last-Modified and/or the ETag
442 * still match.
443 *
444 * @return {Boolean}
445 * @public
446 */
447
448defineGetter(req, 'fresh', function(){
449  var method = this.method;
450  var s = this.res.statusCode;
451
452  // GET or HEAD for weak freshness validation only
453  if ('GET' !== method && 'HEAD' !== method) return false;
454
455  // 2xx or 304 as per rfc2616 14.26
456  if ((s >= 200 && s < 300) || 304 === s) {
457    return fresh(this.headers, (this.res._headers || {}));
458  }
459
460  return false;
461});
462
463/**
464 * Check if the request is stale, aka
465 * "Last-Modified" and / or the "ETag" for the
466 * resource has changed.
467 *
468 * @return {Boolean}
469 * @public
470 */
471
472defineGetter(req, 'stale', function stale(){
473  return !this.fresh;
474});
475
476/**
477 * Check if the request was an _XMLHttpRequest_.
478 *
479 * @return {Boolean}
480 * @public
481 */
482
483defineGetter(req, 'xhr', function xhr(){
484  var val = this.get('X-Requested-With') || '';
485  return val.toLowerCase() === 'xmlhttprequest';
486});
487
488/**
489 * Helper function for creating a getter on an object.
490 *
491 * @param {Object} obj
492 * @param {String} name
493 * @param {Function} getter
494 * @private
495 */
496function defineGetter(obj, name, getter) {
497  Object.defineProperty(obj, name, {
498    configurable: true,
499    enumerable: true,
500    get: getter
501  });
502};