Refactoring the code

- Use Flask blueprint
- Split model and views into smaller parts
- Bug fixes
- API adjustment
This commit is contained in:
Khanh Ngo
2019-12-02 10:32:03 +07:00
parent 0b2eb0fbf8
commit 8ea00b9484
99 changed files with 15183 additions and 6386 deletions

View File

@ -0,0 +1,37 @@
.length-break {
word-break: break-all !important;
}
table td {
font-family:'Roboto Mono' !important;
}
/*Fit default macbook screen*/
.small-box .icon {
font-size: 70px !important;
}
.btn {
padding: 5px 4px !important;
}
/* Pretty JSON */
.json-pre {
background-color: ghostwhite;
border: 1px solid silver;
padding: 10px 20px;
margin: 20px;
}
.json-key {
color: brown;
}
.json-value {
color: navy;
}
.json-string {
color: olive;
}
.user-footer {
background-color: #222d32 !important;
}

View File

@ -0,0 +1,262 @@
var dnssecKeyList = []
function applyChanges(data, url, showResult, refreshPage) {
$.ajax({
type : "POST",
url : url,
data : JSON.stringify(data),// now data come in this function
contentType : "application/json; charset=utf-8",
crossDomain : true,
dataType : "json",
success : function(data, status, jqXHR) {
console.log("Applied changes successfully.")
if (showResult) {
var modal = $("#modal_success");
modal.find('.modal-body p').text("Applied changes successfully");
modal.modal('show');
}
if (refreshPage) {
location.reload(true);
}
},
error : function(jqXHR, status) {
// console.log(jqXHR);
// var modal = $("#modal_error");
// modal.find('.modal-body p').text(jqXHR["responseText"]);
// modal.modal('show');
console.log(jqXHR);
var modal = $("#modal_error");
var responseJson = jQuery.parseJSON(jqXHR.responseText);
modal.find('.modal-body p').text(responseJson['msg']);
modal.modal('show');
}
});
}
function applyRecordChanges(data, domain) {
$.ajax({
type : "POST",
url : $SCRIPT_ROOT + '/domain/' + domain + '/apply',
data : JSON.stringify(data),// now data come in this function
contentType : "application/json; charset=utf-8",
crossDomain : true,
dataType : "json",
success : function(data, status, jqXHR) {
// update Apply button value
$.getJSON($SCRIPT_ROOT + '/domain/' + domain + '/info', function(data) {
$(".button_apply_changes").val(data['serial']);
});
console.log("Applied changes successfully.")
var modal = $("#modal_success");
modal.find('.modal-body p').text("Applied changes successfully");
modal.modal('show');
},
error : function(jqXHR, status) {
console.log(jqXHR);
var modal = $("#modal_error");
var responseJson = jQuery.parseJSON(jqXHR.responseText);
modal.find('.modal-body p').text(responseJson['msg']);
modal.modal('show');
}
});
}
function getTableData(table) {
// reformat - pretty format
var records = []
table.rows().every(function() {
var r = this.data();
var record = {}
record["record_name"] = r[0].trim();
record["record_type"] = r[1].trim();
record["record_status"] = r[2].trim();
record["record_ttl"] = r[3].trim();
record["record_data"] = r[4].trim();
records.push(record);
});
return records
}
function saveRow(oTable, nRow) {
var status = 'Disabled';
var jqInputs = $(oTable.row(nRow).node()).find("input");
var jqSelect = $(oTable.row(nRow).node()).find("select");
if (jqSelect[1].value == 'false') {
status = 'Active';
}
oTable.cell(nRow,0).data(jqInputs[0].value);
oTable.cell(nRow,1).data(jqSelect[0].value);
oTable.cell(nRow,2).data(status);
oTable.cell(nRow,3).data(jqSelect[2].value);
oTable.cell(nRow,4).data(jqInputs[1].value);
var record = jqInputs[0].value;
var button_edit = "<button type=\"button\" class=\"btn btn-flat btn-warning button_edit\" id=\"" + record + "\">Edit&nbsp;<i class=\"fa fa-edit\"></i></button>"
var button_delete = "<button type=\"button\" class=\"btn btn-flat btn-danger button_delete\" id=\"" + record + "\">Delete&nbsp;<i class=\"fa fa-trash\"></i></button>"
oTable.cell(nRow,5).data(button_edit);
oTable.cell(nRow,6).data(button_delete);
oTable.draw();
}
function restoreRow(oTable, nRow) {
var aData = oTable.row(nRow).data();
oTable.row(nRow).data(aData);
oTable.draw();
}
function sec2str(t){
var d = Math.floor(t/86400),
h = Math.floor(t/3600) % 24,
m = Math.floor(t/60) % 60,
s = t % 60;
return (d>0?d+' days ':'')+(h>0?h+' hours ':'')+(m>0?m+' minutes ':'')+(s>0?s+' seconds':'');
}
function editRow(oTable, nRow) {
var isDisabled = 'true';
var aData = oTable.row(nRow).data();
var jqTds = oTable.cells(nRow,'').nodes();
var record_types = "";
var ttl_opts = "";
var ttl_not_found = true;
for(var i = 0; i < records_allow_edit.length; i++) {
var record_type = records_allow_edit[i];
record_types += "<option value=\"" + record_type + "\">" + record_type + "</option>";
}
for(var i = 0; i < ttl_options.length; i++) {
ttl_opts += "<option value=\"" + ttl_options[i][0] + "\">" + ttl_options[i][1] + "</option>";
if (ttl_options[i][0] == aData[3]) {
ttl_not_found = false;
}
}
if (ttl_not_found) {
ttl_opts += "<option value=\"" + aData[3] + "\">" + sec2str(aData[3]) + "</option>";
}
jqTds[0].innerHTML = '<input type="text" id="edit-row-focus" class="form-control input-small" value="' + aData[0] + '">';
jqTds[1].innerHTML = '<select class="form-control" id="record_type" name="record_type" value="' + aData[1] + '">' + record_types + '</select>';
jqTds[2].innerHTML = '<select class="form-control" id="record_status" name="record_status" value="' + aData[2] + '"><option value="false">Active</option><option value="true">Disabled</option></select>';
jqTds[3].innerHTML = '<select class="form-control" id="record_ttl" name="record_ttl" value="' + aData[3] + '">' + ttl_opts + '</select>';
jqTds[4].innerHTML = '<input type="text" style="display:table-cell; width:100% !important" id="current_edit_record_data" name="current_edit_record_data" class="form-control input-small advance-data" value="' + aData[4].replace(/\"/g,"&quot;") + '">';
jqTds[5].innerHTML = '<button type="button" class="btn btn-flat btn-primary button_save">Save</button>';
jqTds[6].innerHTML = '<button type="button" class="btn btn-flat btn-primary button_cancel">Cancel</button>';
// set current value of dropdown column
if (aData[2] == 'Active'){
isDisabled = 'false';
}
SelectElement('record_type', aData[1]);
SelectElement('record_status', isDisabled);
SelectElement('record_ttl', aData[3]);
}
function SelectElement(elementID, valueToSelect)
{
var element = document.getElementById(elementID);
element.value = valueToSelect;
}
function enable_dns_sec(url, csrf_token) {
$.post(url, {'_csrf_token': csrf_token}, function(data) {
var modal = $("#modal_dnssec_info");
if (data['status'] == 'error'){
modal.find('.modal-body p').text(data['msg']);
}
else {
modal.modal('hide');
//location.reload();
window.location.reload(true);
}
}, 'json')
}
function getdnssec(url, domain){
$.getJSON(url, function(data) {
var dnssec_footer = '';
var modal = $("#modal_dnssec_info");
if (data['status'] == 'error'){
modal.find('.modal-body p').text(data['msg']);
}
else {
var dnssec_msg = '';
var dnssec = data['dnssec'];
if (dnssec.length == 0 && parseFloat(PDNS_VERSION) >= 4.1) {
dnssec_msg = '<h3>DNSSEC is disabled. Click on Enable to activate it.';
modal.find('.modal-body p').html(dnssec_msg);
dnssec_footer = '<button type="button" class="btn btn-flat btn-success button_dnssec_enable pull-left" id="'+domain+'">Enable</button><button type="button" class="btn btn-flat btn-default pull-right" data-dismiss="modal">Cancel</button>';
modal.find('.modal-footer ').html(dnssec_footer);
}
else {
if (parseFloat(PDNS_VERSION) >= 4.1) {
dnssec_footer = '<button type="button" class="btn btn-flat btn-danger button_dnssec_disable pull-left" id="'+domain+'">Disable DNSSEC</button><button type="button" class="btn btn-flat btn-default pull-right" data-dismiss="modal">Close</button>';
modal.find('.modal-footer ').html(dnssec_footer);
}
for (var i = 0; i < dnssec.length; i++) {
if (dnssec[i]['active']){
dnssec_msg += '<form>'+
'<h3><strong>'+dnssec[i]['keytype']+'</strong></h3>'+
'<strong>DNSKEY</strong>'+
'<input class="form-control" autocomplete="off" type="text" readonly="true" value="'+dnssec[i]['dnskey']+'">'+
'</form>'+
'<br/>';
if(dnssec[i]['ds']){
var dsList = dnssec[i]['ds'];
dnssec_msg += '<strong>DS</strong>';
for (var j = 0; j < dsList.length; j++){
dnssec_msg += '<input class="form-control" autocomplete="off" type="text" readonly="true" value="'+dsList[j]+'">';
}
}
dnssec_msg += '</form>';
}
}
}
modal.find('.modal-body p').html(dnssec_msg);
}
modal.modal('show');
});
}
function reload_domains(url) {
$.getJSON(url, function(data) {
$('#modal_bg_reload_content').html("<i class=\"fa fa-check\"></i> Finished: " + data['result']['msg']);
})
}
// pretty JSON
json_library = {
replacer: function(match, pIndent, pKey, pVal, pEnd) {
var key = '<span class=json-key>';
var val = '<span class=json-value>';
var str = '<span class=json-string>';
var r = pIndent || '';
if (pKey){
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
}
if (pVal){
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
}
return r + (pEnd || '');
},
prettyPrint: function(obj) {
obj = obj.replace(/u'/g, "\'").replace(/'/g, "\"").replace(/(False|None)/g, "\"$1\"");
var jsonData = JSON.parse(obj);
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(jsonData, null, 3)
.replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(jsonLine, json_library.replacer);
}
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 894 B

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,394 @@
/*!
* Validator v0.11.9 for Bootstrap 3, by @1000hz
* Copyright 2017 Cina Saffary
* Licensed under http://opensource.org/licenses/MIT
*
* https://github.com/1000hz/bootstrap-validator
*/
+function ($) {
'use strict';
// VALIDATOR CLASS DEFINITION
// ==========================
function getValue($el) {
return $el.is('[type="checkbox"]') ? $el.prop('checked') :
$el.is('[type="radio"]') ? !!$('[name="' + $el.attr('name') + '"]:checked').length :
$el.is('select[multiple]') ? ($el.val() || []).length :
$el.val()
}
var Validator = function (element, options) {
this.options = options
this.validators = $.extend({}, Validator.VALIDATORS, options.custom)
this.$element = $(element)
this.$btn = $('button[type="submit"], input[type="submit"]')
.filter('[form="' + this.$element.attr('id') + '"]')
.add(this.$element.find('input[type="submit"], button[type="submit"]'))
this.update()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.on('reset.bs.validator', $.proxy(this.reset, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.attr('data-match')
$(target).on('input.bs.validator', function (e) {
getValue($this) && $this.trigger('input.bs.validator')
})
})
// run validators for fields with values, but don't clobber server-side errors
this.$inputs.filter(function () {
return getValue($(this)) && !$(this).closest('.has-error').length
}).trigger('focusout')
this.$element.attr('novalidate', true) // disable automatic native validation
}
Validator.VERSION = '0.11.9'
Validator.INPUT_SELECTOR = ':input:not([type="hidden"], [type="submit"], [type="reset"], button)'
Validator.FOCUS_OFFSET = 20
Validator.DEFAULTS = {
delay: 500,
html: false,
disable: true,
focus: true,
custom: {},
errors: {
match: 'Does not match',
minlength: 'Not long enough'
},
feedback: {
success: 'glyphicon-ok',
error: 'glyphicon-remove'
}
}
Validator.VALIDATORS = {
'native': function ($el) {
var el = $el[0]
if (el.checkValidity) {
return !el.checkValidity() && !el.validity.valid && (el.validationMessage || "error!")
}
},
'match': function ($el) {
var target = $el.attr('data-match')
return $el.val() !== $(target).val() && Validator.DEFAULTS.errors.match
},
'minlength': function ($el) {
var minlength = $el.attr('data-minlength')
return $el.val().length < minlength && Validator.DEFAULTS.errors.minlength
}
}
Validator.prototype.update = function () {
var self = this
this.$inputs = this.$element.find(Validator.INPUT_SELECTOR)
.add(this.$element.find('[data-validate="true"]'))
.not(this.$element.find('[data-validate="false"]')
.each(function () { self.clearErrors($(this)) })
)
this.toggleSubmit()
return this
}
Validator.prototype.onInput = function (e) {
var self = this
var $el = $(e.target)
var deferErrors = e.type !== 'focusout'
if (!this.$inputs.is($el)) return
this.validateInput($el, deferErrors).done(function () {
self.toggleSubmit()
})
}
Validator.prototype.validateInput = function ($el, deferErrors) {
var value = getValue($el)
var prevErrors = $el.data('bs.validator.errors')
if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
var e = $.Event('validate.bs.validator', {relatedTarget: $el[0]})
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
var self = this
return this.runValidators($el).done(function (errors) {
$el.data('bs.validator.errors', errors)
errors.length
? deferErrors ? self.defer($el, self.showErrors) : self.showErrors($el)
: self.clearErrors($el)
if (!prevErrors || errors.toString() !== prevErrors.toString()) {
e = errors.length
? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
: $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
self.$element.trigger(e)
}
self.toggleSubmit()
self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
})
}
Validator.prototype.runValidators = function ($el) {
var errors = []
var deferred = $.Deferred()
$el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
$el.data('bs.validator.deferred', deferred)
function getValidatorSpecificError(key) {
return $el.attr('data-' + key + '-error')
}
function getValidityStateError() {
var validity = $el[0].validity
return validity.typeMismatch ? $el.attr('data-type-error')
: validity.patternMismatch ? $el.attr('data-pattern-error')
: validity.stepMismatch ? $el.attr('data-step-error')
: validity.rangeOverflow ? $el.attr('data-max-error')
: validity.rangeUnderflow ? $el.attr('data-min-error')
: validity.valueMissing ? $el.attr('data-required-error')
: null
}
function getGenericError() {
return $el.attr('data-error')
}
function getErrorMessage(key) {
return getValidatorSpecificError(key)
|| getValidityStateError()
|| getGenericError()
}
$.each(this.validators, $.proxy(function (key, validator) {
var error = null
if ((getValue($el) || $el.attr('required')) &&
($el.attr('data-' + key) !== undefined || key == 'native') &&
(error = validator.call(this, $el))) {
error = getErrorMessage(key) || error
!~errors.indexOf(error) && errors.push(error)
}
}, this))
if (!errors.length && getValue($el) && $el.attr('data-remote')) {
this.defer($el, function () {
var data = {}
data[$el.attr('name')] = getValue($el)
$.get($el.attr('data-remote'), data)
.fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
.always(function () { deferred.resolve(errors)})
})
} else deferred.resolve(errors)
return deferred.promise()
}
Validator.prototype.validate = function () {
var self = this
$.when(this.$inputs.map(function (el) {
return self.validateInput($(this), false)
})).then(function () {
self.toggleSubmit()
self.focusError()
})
return this
}
Validator.prototype.focusError = function () {
if (!this.options.focus) return
var $input = this.$element.find(".has-error:first :input")
if ($input.length === 0) return
$('html, body').animate({scrollTop: $input.offset().top - Validator.FOCUS_OFFSET}, 250)
$input.focus()
}
Validator.prototype.showErrors = function ($el) {
var method = this.options.html ? 'html' : 'text'
var errors = $el.data('bs.validator.errors')
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
if (!errors.length) return
errors = $('<ul/>')
.addClass('list-unstyled')
.append($.map(errors, function (error) { return $('<li/>')[method](error) }))
$block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
$block.empty().append(errors)
$group.addClass('has-error has-danger')
$group.hasClass('has-feedback')
&& $feedback.removeClass(this.options.feedback.success)
&& $feedback.addClass(this.options.feedback.error)
&& $group.removeClass('has-success')
}
Validator.prototype.clearErrors = function ($el) {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
$block.html($block.data('bs.validator.originalContent'))
$group.removeClass('has-error has-danger has-success')
$group.hasClass('has-feedback')
&& $feedback.removeClass(this.options.feedback.error)
&& $feedback.removeClass(this.options.feedback.success)
&& getValue($el)
&& $feedback.addClass(this.options.feedback.success)
&& $group.addClass('has-success')
}
Validator.prototype.hasErrors = function () {
function fieldErrors() {
return !!($(this).data('bs.validator.errors') || []).length
}
return !!this.$inputs.filter(fieldErrors).length
}
Validator.prototype.isIncomplete = function () {
function fieldIncomplete() {
var value = getValue($(this))
return !(typeof value == "string" ? $.trim(value) : value)
}
return !!this.$inputs.filter('[required]').filter(fieldIncomplete).length
}
Validator.prototype.onSubmit = function (e) {
this.validate()
if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
}
Validator.prototype.toggleSubmit = function () {
if (!this.options.disable) return
this.$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
}
Validator.prototype.defer = function ($el, callback) {
callback = $.proxy(callback, this, $el)
if (!this.options.delay) return callback()
window.clearTimeout($el.data('bs.validator.timeout'))
$el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
}
Validator.prototype.reset = function () {
this.$element.find('.form-control-feedback')
.removeClass(this.options.feedback.error)
.removeClass(this.options.feedback.success)
this.$inputs
.removeData(['bs.validator.errors', 'bs.validator.deferred'])
.each(function () {
var $this = $(this)
var timeout = $this.data('bs.validator.timeout')
window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
})
this.$element.find('.help-block.with-errors')
.each(function () {
var $this = $(this)
var originalContent = $this.data('bs.validator.originalContent')
$this
.removeData('bs.validator.originalContent')
.html(originalContent)
})
this.$btn.removeClass('disabled')
this.$element.find('.has-error, .has-danger, .has-success').removeClass('has-error has-danger has-success')
return this
}
Validator.prototype.destroy = function () {
this.reset()
this.$element
.removeAttr('novalidate')
.removeData('bs.validator')
.off('.bs.validator')
this.$inputs
.off('.bs.validator')
this.options = null
this.validators = null
this.$element = null
this.$btn = null
this.$inputs = null
return this
}
// VALIDATOR PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
var data = $this.data('bs.validator')
if (!data && option == 'destroy') return
if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.validator
$.fn.validator = Plugin
$.fn.validator.Constructor = Validator
// VALIDATOR NO CONFLICT
// =====================
$.fn.validator.noConflict = function () {
$.fn.validator = old
return this
}
// VALIDATOR DATA-API
// ==================
$(window).on('load', function () {
$('form[data-toggle="validator"]').each(function () {
var $form = $(this)
Plugin.call($form, $form.data())
})
})
}(jQuery);