Skip to content

Commit

Permalink
Now using X-Real-IP header in docker
Browse files Browse the repository at this point in the history
  • Loading branch information
DimaCrafter committed Dec 8, 2019
1 parent 669dd47 commit 7049a48
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dc-api-core",
"version": "0.2.2-7",
"version": "0.2.2-8",
"description": "Simple API core for your projects",
"author": "DimaCrafter",
"homepage": "https://github.com/DimaCrafter/dc-api-core",
Expand Down
30 changes: 21 additions & 9 deletions utils.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,41 @@
const log = require('./log');
const session = require('./session');
const getBase = (req, res) => {
// Parsing IP
const ipRaw = Buffer.from(res.getRemoteAddress()).toString('hex');

function getIP (req, res) {
// Parsing
let ipRaw = Buffer.from(res.getRemoteAddress()).toString('hex');

// Using X-Real-IP in docker container (172.18.XXX.XXX -> AC12XXXX)
if (ipRaw.slice(24, 28) == 'ac12' && req.headers['x-real-ip']) {
ipRaw = req.headers['x-real-ip'];
return {
type: ~ipRaw.indexOf('.') ? 'ipv4' : 'ipv6',
value: ipRaw
};
}

// Formatting
const ipParts = [];
for (let i = 0; i < ipRaw.length; i += 4) ipParts.push(ipRaw.slice(i, i + 4));

let address;
if (ipParts[ipParts.length - 3] == 'ffff') {
const ipv4 = [];
ipv4.push(parseInt(ipParts[ipParts.length - 2].slice(0, 2), 16));
ipv4.push(parseInt(ipParts[ipParts.length - 2].slice(2), 16));
ipv4.push(parseInt(ipParts[ipParts.length - 1].slice(0, 2), 16));
ipv4.push(parseInt(ipParts[ipParts.length - 1].slice(2), 16));
address = {
return {
type: 'ipv4',
value: ipv4.join('.')
};
} else {
address = {
return {
type: 'ipv6',
value: ipParts.join(':')
};
}
}

function getBase (req, res) {
let controllerProxy;
const ctx = {
get db () { log.warn('`this.db` is deprecated, use require(\'dc-api-core/DB\') instead'); },
Expand All @@ -34,7 +46,7 @@ const getBase = (req, res) => {
res.writeHeader('Location', url);
res.end();
},
address,
address: getIP(req, res),

set controller (controller) {
controllerProxy = new Proxy(controller, {
Expand All @@ -48,7 +60,7 @@ const getBase = (req, res) => {
};

return ctx;
};
}

module.exports = {
async getHTTP (req, res) {
Expand Down

0 comments on commit 7049a48

Please sign in to comment.