Skip to content

Feature/custom locations #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Mar 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 61 additions & 15 deletions src/backend/internal/nginx.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,35 @@ const internalNginx = {
return '/data/nginx/' + host_type + '/' + host_id + '.conf';
},

/**
* Generates custom locations
* @param {Object} host
* @returns {Promise}
*/
renderLocations: (host) => {
return new Promise((resolve, reject) => {
let template;

try {
template = fs.readFileSync(__dirname + '/../templates/_location.conf', {encoding: 'utf8'});
} catch (err) {
reject(new error.ConfigurationError(err.message));
return;
}

let renderer = new Liquid();
let renderedLocations = '';

const locationRendering = async () => {
for (let i = 0; i < host.locations.length; i++) {
renderedLocations += await renderer.parseAndRender(template, host.locations[i]);
}
}

locationRendering().then(() => resolve(renderedLocations));
});
},

/**
* @param {String} host_type
* @param {Object} host
Expand Down Expand Up @@ -157,6 +186,9 @@ const internalNginx = {
return;
}

let locationsPromise;
let origLocations;

// Manipulate the data a bit before sending it to the template
if (host_type !== 'default') {
host.use_default_location = true;
Expand All @@ -165,24 +197,38 @@ const internalNginx = {
}
}

renderEngine
.parseAndRender(template, host)
.then(config_text => {
fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
if (host.locations) {
origLocations = [].concat(host.locations);
locationsPromise = internalNginx.renderLocations(host).then((renderedLocations) => {
host.locations = renderedLocations;
});
} else {
locationsPromise = Promise.resolve();
}

if (debug_mode) {
logger.success('Wrote config:', filename, config_text);
}
locationsPromise.then(() => {
renderEngine
.parseAndRender(template, host)
.then(config_text => {
fs.writeFileSync(filename, config_text, {encoding: 'utf8'});

resolve(true);
})
.catch(err => {
if (debug_mode) {
logger.warn('Could not write ' + filename + ':', err.message);
}
if (debug_mode) {
logger.success('Wrote config:', filename, config_text);
}

reject(new error.ConfigurationError(err.message));
});
// Restore locations array
host.locations = origLocations;

resolve(true);
})
.catch(err => {
if (debug_mode) {
logger.warn('Could not write ' + filename + ':', err.message);
}

reject(new error.ConfigurationError(err.message));
});
});
});
},

Expand Down
37 changes: 37 additions & 0 deletions src/backend/migrations/20190215115310_customlocations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const migrate_name = 'custom_locations';
const logger = require('../logger').migrate;

/**
* Migrate
* Extends proxy_host table with locations field
*
* @see http://knexjs.org/#Schema
*
* @param {Object} knex
* @param {Promise} Promise
* @returns {Promise}
*/
exports.up = function (knex/*, Promise*/) {
logger.info('[' + migrate_name + '] Migrating Up...');

return knex.schema.table('proxy_host', function (proxy_host) {
proxy_host.json('locations');
})
.then(() => {
logger.info('[' + migrate_name + '] proxy_host Table altered');
})
};

/**
* Undo Migrate
*
* @param {Object} knex
* @param {Promise} Promise
* @returns {Promise}
*/
exports.down = function (knex, Promise) {
logger.warn('[' + migrate_name + '] You can\'t migrate down this one.');
return Promise.resolve(true);
};
2 changes: 1 addition & 1 deletion src/backend/models/proxy_host.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class ProxyHost extends Model {
}

static get jsonAttributes () {
return ['domain_names', 'meta'];
return ['domain_names', 'meta', 'locations'];
}

static get relationMappings () {
Expand Down
44 changes: 44 additions & 0 deletions src/backend/schema/endpoints/proxy-hosts.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,41 @@
},
"meta": {
"type": "object"
},
"locations": {
"type": "array",
"minItems": 0,
"items": {
"type": "object",
"required": [
"forward_scheme",
"forward_host",
"forward_port",
"path"
],
"additionalProperties": false,
"properties": {
"id": {
"type": ["integer", "null"]
},
"path": {
"type": "string",
"minLength": 1
},
"forward_scheme": {
"$ref": "#/definitions/forward_scheme"
},
"forward_host": {
"$ref": "#/definitions/forward_host"
},
"forward_port": {
"$ref": "#/definitions/forward_port"
},
"advanced_config": {
"type": "string"
}
}
}
}
},
"properties": {
Expand Down Expand Up @@ -128,6 +163,9 @@
},
"meta": {
"$ref": "#/definitions/meta"
},
"locations": {
"$ref": "#/definitions/locations"
}
},
"links": [
Expand Down Expand Up @@ -215,6 +253,9 @@
},
"meta": {
"$ref": "#/definitions/meta"
},
"locations": {
"$ref": "#/definitions/locations"
}
}
},
Expand Down Expand Up @@ -285,6 +326,9 @@
},
"meta": {
"$ref": "#/definitions/meta"
},
"locations": {
"$ref": "#/definitions/locations"
}
}
},
Expand Down
8 changes: 8 additions & 0 deletions src/backend/templates/_location.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
___location {{ path }} {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Scheme $scheme;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass {{ forward_scheme }}://{{ forward_host }}:{{ forward_port }};
{{ advanced_config }}
}
3 changes: 3 additions & 0 deletions src/backend/templates/proxy_host.conf
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ server {

{{ advanced_config }}

{{ locations }}

{% if use_default_location %}

___location / {
{%- if access_list_id > 0 -%}
# Access List
Expand Down
12 changes: 12 additions & 0 deletions src/frontend/js/app/nginx/proxy/form.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,22 @@
<form>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="nav-item"><a href="#details" aria-controls="tab1" role="tab" data-toggle="tab" class="nav-link active"><i class="fe fe-zap"></i> <%- i18n('all-hosts', 'details') %></a></li>
<li role="presentation" class="nav-item"><a href="#locations" aria-controls="tab4" role="tab" data-toggle="tab" class="nav-link"><i class="fe fe-layers"></i> <%- i18n('all-hosts', 'locations') %></a></li>
<li role="presentation" class="nav-item"><a href="#ssl-options" aria-controls="tab2" role="tab" data-toggle="tab" class="nav-link"><i class="fe fe-shield"></i> <%- i18n('str', 'ssl') %></a></li>
<li role="presentation" class="nav-item"><a href="#advanced" aria-controls="tab3" role="tab" data-toggle="tab" class="nav-link"><i class="fe fe-settings"></i> <%- i18n('all-hosts', 'advanced') %></a></li>
</ul>
<div class="tab-content">

<!-- Locations -->
<div class="tab-pane" id="locations">
<div class="row">
<div class="col-sm-12">
<button type="button" class="btn btn-secondary add_location"><%- i18n('locations', 'new_location') %></button>
<div class="locations_container mt-3"></div>
</div>
</div>
</div>

<!-- Details -->
<div role="tabpanel" class="tab-pane active" id="details">
<div class="row">
Expand Down
43 changes: 43 additions & 0 deletions src/frontend/js/app/nginx/proxy/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,32 @@
const Mn = require('backbone.marionette');
const App = require('../../main');
const ProxyHostModel = require('../../../models/proxy-host');
const ProxyLocationModel = require('../../../models/proxy-host-___location');
const template = require('./form.ejs');
const certListItemTemplate = require('../certificates-list-item.ejs');
const accessListItemTemplate = require('./access-list-item.ejs');
const CustomLocation = require('./___location');
const Helpers = require('../../../lib/helpers');


require('jquery-serializejson');
require('selectize');

module.exports = Mn.View.extend({
template: template,
className: 'modal-dialog',

locationsCollection: new ProxyLocationModel.Collection(),

ui: {
form: 'form',
domain_names: 'input[name="domain_names"]',
forward_host: 'input[name="forward_host"]',
buttons: '.modal-footer button',
cancel: 'button.cancel',
save: 'button.save',
add_location_btn: 'button.add_location',
locations_container:'.locations_container',
certificate_select: 'select[name="certificate_id"]',
access_list_select: 'select[name="access_list_id"]',
ssl_forced: 'input[name="ssl_forced"]',
Expand All @@ -32,6 +39,10 @@ module.exports = Mn.View.extend({
letsencrypt: '.letsencrypt'
},

regions: {
locations_regions: '@ui.locations_container'
},

events: {
'change @ui.certificate_select': function () {
let id = this.ui.certificate_select.val();
Expand Down Expand Up @@ -82,6 +93,13 @@ module.exports = Mn.View.extend({
}
},

'click @ui.add_location_btn': function (e) {
e.preventDefault();

const model = new ProxyLocationModel.Model();
this.locationsCollection.add(model);
},

'click @ui.save': function (e) {
e.preventDefault();

Expand All @@ -93,6 +111,16 @@ module.exports = Mn.View.extend({
let view = this;
let data = this.ui.form.serializeJSON();

// Add locations
data.locations = [];
this.locationsCollection.models.forEach((___location) => {
data.locations.push(___location.toJSON());
});

// Serialize collects path from custom locations
// This field must be removed from root object
delete data.path;

// Manipulate
data.forward_port = parseInt(data.forward_port, 10);
data.block_exploits = !!data.block_exploits;
Expand Down Expand Up @@ -246,5 +274,20 @@ module.exports = Mn.View.extend({
if (typeof options.model === 'undefined' || !options.model) {
this.model = new ProxyHostModel.Model();
}

this.locationsCollection = new ProxyLocationModel.Collection();

// Custom locations
this.showChildView('locations_regions', new CustomLocation.LocationCollectionView({
collection: this.locationsCollection
}));

// Check wether there are any ___location defined
if (options.model && Array.isArray(options.model.attributes.locations)) {
options.model.attributes.locations.forEach((___location) => {
let m = new ProxyLocationModel.Model(___location);
this.locationsCollection.add(m);
});
}
}
});
Loading