Last change
on this file was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.5 KB
|
Line | |
---|
1 | /*!
|
---|
2 | * forwarded
|
---|
3 | * Copyright(c) 2014-2017 Douglas Christopher Wilson
|
---|
4 | * MIT Licensed
|
---|
5 | */
|
---|
6 |
|
---|
7 | 'use strict'
|
---|
8 |
|
---|
9 | /**
|
---|
10 | * Module exports.
|
---|
11 | * @public
|
---|
12 | */
|
---|
13 |
|
---|
14 | module.exports = forwarded
|
---|
15 |
|
---|
16 | /**
|
---|
17 | * Get all addresses in the request, using the `X-Forwarded-For` header.
|
---|
18 | *
|
---|
19 | * @param {object} req
|
---|
20 | * @return {array}
|
---|
21 | * @public
|
---|
22 | */
|
---|
23 |
|
---|
24 | function forwarded (req) {
|
---|
25 | if (!req) {
|
---|
26 | throw new TypeError('argument req is required')
|
---|
27 | }
|
---|
28 |
|
---|
29 | // simple header parsing
|
---|
30 | var proxyAddrs = parse(req.headers['x-forwarded-for'] || '')
|
---|
31 | var socketAddr = getSocketAddr(req)
|
---|
32 | var addrs = [socketAddr].concat(proxyAddrs)
|
---|
33 |
|
---|
34 | // return all addresses
|
---|
35 | return addrs
|
---|
36 | }
|
---|
37 |
|
---|
38 | /**
|
---|
39 | * Get the socket address for a request.
|
---|
40 | *
|
---|
41 | * @param {object} req
|
---|
42 | * @return {string}
|
---|
43 | * @private
|
---|
44 | */
|
---|
45 |
|
---|
46 | function getSocketAddr (req) {
|
---|
47 | return req.socket
|
---|
48 | ? req.socket.remoteAddress
|
---|
49 | : req.connection.remoteAddress
|
---|
50 | }
|
---|
51 |
|
---|
52 | /**
|
---|
53 | * Parse the X-Forwarded-For header.
|
---|
54 | *
|
---|
55 | * @param {string} header
|
---|
56 | * @private
|
---|
57 | */
|
---|
58 |
|
---|
59 | function parse (header) {
|
---|
60 | var end = header.length
|
---|
61 | var list = []
|
---|
62 | var start = header.length
|
---|
63 |
|
---|
64 | // gather addresses, backwards
|
---|
65 | for (var i = header.length - 1; i >= 0; i--) {
|
---|
66 | switch (header.charCodeAt(i)) {
|
---|
67 | case 0x20: /* */
|
---|
68 | if (start === end) {
|
---|
69 | start = end = i
|
---|
70 | }
|
---|
71 | break
|
---|
72 | case 0x2c: /* , */
|
---|
73 | if (start !== end) {
|
---|
74 | list.push(header.substring(start, end))
|
---|
75 | }
|
---|
76 | start = end = i
|
---|
77 | break
|
---|
78 | default:
|
---|
79 | start = i
|
---|
80 | break
|
---|
81 | }
|
---|
82 | }
|
---|
83 |
|
---|
84 | // final address
|
---|
85 | if (start !== end) {
|
---|
86 | list.push(header.substring(start, end))
|
---|
87 | }
|
---|
88 |
|
---|
89 | return list
|
---|
90 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.