Fixed following SonarQube issues:

- Refactor functions to not always return the same value.
  - Rename "cls" to "self" or add the missing "self" parameter.
  - Remove useless assignment to variables.
This commit is contained in:
Aditya Toshniwal
2020-07-30 14:04:22 +05:30
committed by Akshay Joshi
parent dd7eb54e90
commit 56cf64ad22
17 changed files with 624 additions and 663 deletions
+3 -3
View File
@@ -27,13 +27,13 @@ class AuthSourceRegistry(ABCMeta):
registry = None registry = None
auth_sources = dict() auth_sources = dict()
def __init__(cls, name, bases, d): def __init__(self, name, bases, d):
# Register this type of auth_sources, based on the module name # Register this type of auth_sources, based on the module name
# Avoid registering the BaseAuthentication itself # Avoid registering the BaseAuthentication itself
AuthSourceRegistry.registry[_decorate_cls_name(d['__module__'])] = cls AuthSourceRegistry.registry[_decorate_cls_name(d['__module__'])] = self
ABCMeta.__init__(cls, name, bases, d) ABCMeta.__init__(self, name, bases, d)
@classmethod @classmethod
def create(cls, name, **kwargs): def create(cls, name, **kwargs):
@@ -333,42 +333,39 @@ define('pgadmin.node.fts_configuration', [
var self = this, var self = this,
token = self.headerData.get('token'); token = self.headerData.get('token');
if (!token || token == '') { if (token && token != '') {
return false; var coll = self.model.get(self.field.get('name')),
} m = new (self.field.get('model'))(
self.headerData.toJSON(), {
silent: true, top: self.model.top,
collection: coll, handler: coll,
}),
checkVars = ['token'],
idx = -1;
var coll = self.model.get(self.field.get('name')), // Find if token exists in grid
m = new (self.field.get('model'))( self.collection.each(function(local_model) {
self.headerData.toJSON(), { _.each(checkVars, function(v) {
silent: true, top: self.model.top, var val = local_model.get(v);
collection: coll, handler: coll, if(val == token) {
}), idx = coll.indexOf(local_model);
checkVars = ['token'], }
idx = -1; });
// Find if token exists in grid
self.collection.each(function(local_model) {
_.each(checkVars, function(v) {
var val = local_model.get(v);
if(val == token) {
idx = coll.indexOf(local_model);
}
}); });
});
// remove 'm' if duplicate value found. // remove 'm' if duplicate value found.
if (idx == -1) { if (idx == -1) {
coll.add(m); coll.add(m);
idx = coll.indexOf(m); idx = coll.indexOf(m);
}
self.$grid.find('.new').removeClass('new');
var newRow = self.grid.body.rows[idx].$el;
newRow.addClass('new');
//$(newRow).pgMakeVisible('table-bordered');
$(newRow).pgMakeVisible('backform-tab');
} }
self.$grid.find('.new').removeClass('new');
var newRow = self.grid.body.rows[idx].$el;
newRow.addClass('new');
//$(newRow).pgMakeVisible('table-bordered');
$(newRow).pgMakeVisible('backform-tab');
return false; return false;
}, },
@@ -64,30 +64,28 @@ define('pgadmin.node.check_constraint', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) { if (d) {
return false; var data = d;
} $.ajax({
var data = d; url: obj.generate_url(i, 'validate', d, true),
$.ajax({ type:'GET',
url: obj.generate_url(i, 'validate', d, true),
type:'GET',
})
.done(function(res) {
if (res.success == 1) {
alertify.success(res.info);
t.removeIcon(i);
data.valid = true;
data.icon = 'icon-check_constraint';
t.addIcon(i, {icon: data.icon});
setTimeout(function() {t.deselect(i);}, 10);
setTimeout(function() {t.select(i);}, 100);
}
}) })
.fail(function(xhr, status, error) { .done(function(res) {
alertify.pgRespErrorNotify(xhr, error); if (res.success == 1) {
t.unload(i); alertify.success(res.info);
}); t.removeIcon(i);
data.valid = true;
data.icon = 'icon-check_constraint';
t.addIcon(i, {icon: data.icon});
setTimeout(function() {t.deselect(i);}, 10);
setTimeout(function() {t.select(i);}, 100);
}
})
.fail(function(xhr, status, error) {
alertify.pgRespErrorNotify(xhr, error);
t.unload(i);
});
}
return false; return false;
}, },
}, },
@@ -541,41 +541,39 @@ define('pgadmin.node.exclusion_constraint', [
var self = this, var self = this,
column = self.headerData.get('column'); column = self.headerData.get('column');
if (!column || column == '') { if (column && column != '') {
return false; var coll = self.model.get(self.field.get('name')),
} m = new (self.field.get('model'))(
self.headerData.toJSON(), {
silent: true, top: self.model.top,
collection: coll, handler: coll,
}),
col_types =self.field.get('col_types') || [];
var coll = self.model.get(self.field.get('name')), for(var i=0; i < col_types.length; i++) {
m = new (self.field.get('model'))( var col_type = col_types[i];
self.headerData.toJSON(), { if (col_type['name'] == m.get('column')) {
silent: true, top: self.model.top, m.set({'col_type':col_type['type']});
collection: coll, handler: coll, break;
}), }
col_types =self.field.get('col_types') || [];
for(var i=0; i < col_types.length; i++) {
var col_type = col_types[i];
if (col_type['name'] == m.get('column')) {
m.set({'col_type':col_type['type']});
break;
} }
}
coll.add(m); coll.add(m);
var idx = coll.indexOf(m); var idx = coll.indexOf(m);
// idx may not be always > -1 because our UniqueColCollection may // idx may not be always > -1 because our UniqueColCollection may
// remove 'm' if duplicate value found. // remove 'm' if duplicate value found.
if (idx > -1) { if (idx > -1) {
self.$grid.find('.new').removeClass('new'); self.$grid.find('.new').removeClass('new');
var newRow = self.grid.body.rows[idx].$el; var newRow = self.grid.body.rows[idx].$el;
newRow.addClass('new'); newRow.addClass('new');
$(newRow).pgMakeVisible('backform-tab'); $(newRow).pgMakeVisible('backform-tab');
} else { } else {
//delete m; //delete m;
}
} }
return false; return false;
@@ -27,7 +27,7 @@ define('pgadmin.node.foreign_key', [
return opt.text; return opt.text;
} else { } else {
return $( return $(
'<span><span class="wcTabIcon ' + optimage + '"/>' + opt.text + '</span>' '<span><span class="wcTabIcon ' + optimage + '"/></span><span>' + opt.text + '</span></span>'
); );
} }
}, },
@@ -487,32 +487,28 @@ define('pgadmin.node.foreign_key', [
local_column = self.headerData.get('local_column'), local_column = self.headerData.get('local_column'),
referenced = self.headerData.get('referenced'); referenced = self.headerData.get('referenced');
if (!local_column || local_column == '' || if (local_column && local_column != '' && referenced && referenced != '') {
!referenced || referenced =='') { var m = new (self.field.get('model'))(
return false; self.headerData.toJSON()),
coll = self.model.get(self.field.get('name'));
coll.add(m);
var idx = coll.indexOf(m);
// idx may not be always > -1 because our UniqueColCollection may
// remove 'm' if duplicate value found.
if (idx > -1) {
self.$grid.find('.new').removeClass('new');
var newRow = self.grid.body.rows[idx].$el;
newRow.addClass('new');
$(newRow).pgMakeVisible('backform-tab');
} else {
//delete m;
}
} }
var m = new (self.field.get('model'))(
self.headerData.toJSON()),
coll = self.model.get(self.field.get('name'));
coll.add(m);
var idx = coll.indexOf(m);
// idx may not be always > -1 because our UniqueColCollection may
// remove 'm' if duplicate value found.
if (idx > -1) {
self.$grid.find('.new').removeClass('new');
var newRow = self.grid.body.rows[idx].$el;
newRow.addClass('new');
$(newRow).pgMakeVisible('backform-tab');
} else {
//delete m;
}
return false; return false;
}, },
@@ -663,30 +659,28 @@ define('pgadmin.node.foreign_key', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) { if (d) {
return false; var data = d;
} $.ajax({
var data = d; url: obj.generate_url(i, 'validate', d, true),
$.ajax({ type:'GET',
url: obj.generate_url(i, 'validate', d, true),
type:'GET',
})
.done(function(res) {
if (res.success == 1) {
Alertify.success(res.info);
t.removeIcon(i);
data.valid = true;
data.icon = 'icon-foreign_key';
t.addIcon(i, {icon: data.icon});
setTimeout(function() {t.deselect(i);}, 10);
setTimeout(function() {t.select(i);}, 100);
}
}) })
.fail(function(xhr, status, error) { .done(function(res) {
Alertify.pgRespErrorNotify(xhr, error); if (res.success == 1) {
t.unload(i); Alertify.success(res.info);
}); t.removeIcon(i);
data.valid = true;
data.icon = 'icon-foreign_key';
t.addIcon(i, {icon: data.icon});
setTimeout(function() {t.deselect(i);}, 10);
setTimeout(function() {t.select(i);}, 100);
}
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
t.unload(i);
});
}
return false; return false;
}, },
}, },
@@ -172,10 +172,9 @@ define('pgadmin.node.database', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d || d.label == 'template0') if (d && d.label != 'template0') {
return false; connect_to_database(obj, d, t, i, true);
}
connect_to_database(obj, d, t, i, true);
return false; return false;
}, },
/* Disconnect the database */ /* Disconnect the database */
@@ -186,54 +185,53 @@ define('pgadmin.node.database', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) if (d) {
return false; Alertify.confirm(
gettext('Disconnect the database'),
Alertify.confirm( gettext('Are you sure you want to disconnect the database - %s?', d.label),
gettext('Disconnect the database'), function() {
gettext('Are you sure you want to disconnect the database - %s?', d.label), var data = d;
function() { $.ajax({
var data = d; url: obj.generate_url(i, 'connect', d, true),
$.ajax({ type:'DELETE',
url: obj.generate_url(i, 'connect', d, true),
type:'DELETE',
})
.done(function(res) {
if (res.success == 1) {
var prv_i = t.parent(i);
if(res.data.info_prefix) {
res.info = `${_.escape(res.data.info_prefix)} - ${res.info}`;
}
Alertify.success(res.info);
t.removeIcon(i);
data.connected = false;
data.icon = 'icon-database-not-connected';
t.addIcon(i, {icon: data.icon});
t.unload(i);
t.setInode(i);
setTimeout(function() {
t.select(prv_i);
}, 10);
} else {
try {
Alertify.error(res.errormsg);
} catch (e) {
console.warn(e.stack || e);
}
t.unload(i);
}
}) })
.fail(function(xhr, status, error) { .done(function(res) {
Alertify.pgRespErrorNotify(xhr, error); if (res.success == 1) {
t.unload(i); var prv_i = t.parent(i);
}); if(res.data.info_prefix) {
}, res.info = `${_.escape(res.data.info_prefix)} - ${res.info}`;
function() { return true; } }
).set('labels', { Alertify.success(res.info);
ok: gettext('Yes'), t.removeIcon(i);
cancel: gettext('No'), data.connected = false;
}); data.icon = 'icon-database-not-connected';
t.addIcon(i, {icon: data.icon});
t.unload(i);
t.setInode(i);
setTimeout(function() {
t.select(prv_i);
}, 10);
} else {
try {
Alertify.error(res.errormsg);
} catch (e) {
console.warn(e.stack || e);
}
t.unload(i);
}
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
t.unload(i);
});
},
function() { return true; }
).set('labels', {
ok: gettext('Yes'),
cancel: gettext('No'),
});
}
return false; return false;
}, },
@@ -177,20 +177,19 @@ define('pgadmin.node.pga_job', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) if (d) {
return false; $.ajax({
url: obj.generate_url(i, 'run_now', d, true),
$.ajax({ method:'PUT',
url: obj.generate_url(i, 'run_now', d, true), })
method:'PUT', // 'pgagent.pga_job' table updated with current time to run the job
}) // now.
// 'pgagent.pga_job' table updated with current time to run the job .done(function() { t.unload(i); })
// now. .fail(function(xhr, status, error) {
.done(function() { t.unload(i); }) alertify.pgRespErrorNotify(xhr, error);
.fail(function(xhr, status, error) { t.unload(i);
alertify.pgRespErrorNotify(xhr, error); });
t.unload(i); }
});
return false; return false;
}, },
@@ -199,10 +199,9 @@ define('pgadmin.node.server', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) if (d) {
return false; connect_to_server(obj, d, t, i, false);
}
connect_to_server(obj, d, t, i, false);
return false; return false;
}, },
/* Disconnect the server */ /* Disconnect the server */
@@ -213,59 +212,58 @@ define('pgadmin.node.server', [
i = 'item' in input ? input.item : t.selected(), i = 'item' in input ? input.item : t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) if (d) {
return false; notify = notify || _.isUndefined(notify) || _.isNull(notify);
notify = notify || _.isUndefined(notify) || _.isNull(notify); var disconnect = function() {
$.ajax({
var disconnect = function() { url: obj.generate_url(i, 'connect', d, true),
$.ajax({ type:'DELETE',
url: obj.generate_url(i, 'connect', d, true),
type:'DELETE',
})
.done(function(res) {
if (res.success == 1) {
Alertify.success(res.info);
d = t.itemData(i);
t.removeIcon(i);
d.connected = false;
d.icon = 'icon-server-not-connected';
t.addIcon(i, {icon: d.icon});
obj.callbacks.refresh.apply(obj, [null, i]);
if (pgBrowser.serverInfo && d._id in pgBrowser.serverInfo) {
delete pgBrowser.serverInfo[d._id];
}
pgBrowser.enable_disable_menus(i);
// Trigger server disconnect event
pgBrowser.Events.trigger(
'pgadmin:server:disconnect',
{item: i, data: d}, false
);
}
else {
try {
Alertify.error(res.errormsg);
} catch (e) {
console.warn(e.stack || e);
}
t.unload(i);
}
}) })
.fail(function(xhr, status, error) { .done(function(res) {
Alertify.pgRespErrorNotify(xhr, error); if (res.success == 1) {
t.unload(i); Alertify.success(res.info);
}); d = t.itemData(i);
}; t.removeIcon(i);
d.connected = false;
d.icon = 'icon-server-not-connected';
t.addIcon(i, {icon: d.icon});
obj.callbacks.refresh.apply(obj, [null, i]);
if (pgBrowser.serverInfo && d._id in pgBrowser.serverInfo) {
delete pgBrowser.serverInfo[d._id];
}
pgBrowser.enable_disable_menus(i);
// Trigger server disconnect event
pgBrowser.Events.trigger(
'pgadmin:server:disconnect',
{item: i, data: d}, false
);
}
else {
try {
Alertify.error(res.errormsg);
} catch (e) {
console.warn(e.stack || e);
}
t.unload(i);
}
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
t.unload(i);
});
};
if (notify) { if (notify) {
Alertify.confirm( Alertify.confirm(
gettext('Disconnect server'), gettext('Disconnect server'),
gettext('Are you sure you want to disconnect the server %s?', d.label), gettext('Are you sure you want to disconnect the server %s?', d.label),
function() { disconnect(); }, function() { disconnect(); },
function() { return true;} function() { return true;}
); );
} else { } else {
disconnect(); disconnect();
}
} }
return false; return false;
@@ -306,32 +304,31 @@ define('pgadmin.node.server', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) if (d) {
return false; Alertify.confirm(
gettext('Reload server configuration'),
Alertify.confirm( gettext('Are you sure you want to reload the server configuration on %s?', d.label),
gettext('Reload server configuration'), function() {
gettext('Are you sure you want to reload the server configuration on %s?', d.label), $.ajax({
function() { url: obj.generate_url(i, 'reload', d, true),
$.ajax({ method:'GET',
url: obj.generate_url(i, 'reload', d, true),
method:'GET',
})
.done(function(res) {
if (res.data.status) {
Alertify.success(res.data.result);
}
else {
Alertify.error(res.data.result);
}
}) })
.fail(function(xhr, status, error) { .done(function(res) {
Alertify.pgRespErrorNotify(xhr, error); if (res.data.status) {
t.unload(i); Alertify.success(res.data.result);
}); }
}, else {
function() { return true; } Alertify.error(res.data.result);
); }
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
t.unload(i);
});
},
function() { return true; }
);
}
return false; return false;
}, },
@@ -387,174 +384,173 @@ define('pgadmin.node.server', [
is_pgpass_file_used = false, is_pgpass_file_used = false,
check_pgpass_url = obj.generate_url(i, 'check_pgpass', d, true); check_pgpass_url = obj.generate_url(i, 'check_pgpass', d, true);
if (!d) if (d) {
return false; if(!Alertify.changeServerPassword) {
var newPasswordModel = Backbone.Model.extend({
if(!Alertify.changeServerPassword) { defaults: {
var newPasswordModel = Backbone.Model.extend({ user_name: undefined,
defaults: { password: undefined,
user_name: undefined, newPassword: undefined,
password: undefined, confirmPassword: undefined,
newPassword: undefined, },
confirmPassword: undefined, validate: function() {
}, return null;
validate: function() { },
return null; }),
}, passwordChangeFields = [{
}), name: 'user_name', label: gettext('User'),
passwordChangeFields = [{ type: 'text', readonly: true, control: 'input',
name: 'user_name', label: gettext('User'), },{
type: 'text', readonly: true, control: 'input', name: 'password', label: gettext('Current Password'),
},{ type: 'password', disabled: function() { return is_pgpass_file_used; },
name: 'password', label: gettext('Current Password'), control: 'input', required: true,
type: 'password', disabled: function() { return is_pgpass_file_used; }, },{
control: 'input', required: true, name: 'newPassword', label: gettext('New Password'),
},{ type: 'password', disabled: false, control: 'input',
name: 'newPassword', label: gettext('New Password'), required: true,
type: 'password', disabled: false, control: 'input', },{
required: true, name: 'confirmPassword', label: gettext('Confirm Password'),
},{ type: 'password', disabled: false, control: 'input',
name: 'confirmPassword', label: gettext('Confirm Password'), required: true,
type: 'password', disabled: false, control: 'input', }];
required: true,
}];
Alertify.dialog('changeServerPassword' ,function factory() { Alertify.dialog('changeServerPassword' ,function factory() {
return { return {
main: function(params) { main: function(params) {
var title = gettext('Change Password'); var title = gettext('Change Password');
this.set('title', title); this.set('title', title);
this.user_name = params.user.name; this.user_name = params.user.name;
}, },
setup:function() { setup:function() {
return { return {
buttons: [{ buttons: [{
text: gettext('Cancel'), key: 27, text: gettext('Cancel'), key: 27,
className: 'btn btn-secondary fa fa-times pg-alertify-button', attrs: {name: 'cancel'}, className: 'btn btn-secondary fa fa-times pg-alertify-button', attrs: {name: 'cancel'},
},{ },{
text: gettext('OK'), key: 13, className: 'btn btn-primary fa fa-check pg-alertify-button', text: gettext('OK'), key: 13, className: 'btn btn-primary fa fa-check pg-alertify-button',
attrs: {name:'submit'}, attrs: {name:'submit'},
}], }],
// Set options for dialog // Set options for dialog
options: { options: {
padding : !1, padding : !1,
overflow: !1, overflow: !1,
modal:false, modal:false,
resizable: true, resizable: true,
maximizable: true, maximizable: true,
pinnable: false, pinnable: false,
closableByDimmer: false, closableByDimmer: false,
},
};
},
hooks: {
// triggered when the dialog is closed
onclose: function() {
if (this.view) {
this.view.remove({data: true, internal: true, silent: true});
}
}, },
}; },
}, prepare: function() {
hooks: { var self = this;
// triggered when the dialog is closed // Disable Ok button until user provides input
onclose: function() { this.__internal.buttons[1].element.disabled = true;
if (this.view) {
this.view.remove({data: true, internal: true, silent: true}); var $container = $('<div class=\'change_password\'></div>'),
newpasswordmodel = new newPasswordModel(
{'user_name': self.user_name}
),
view = this.view = new Backform.Form({
el: $container,
model: newpasswordmodel,
fields: passwordChangeFields,
});
view.render();
this.elements.content.appendChild($container.get(0));
// Listen to model & if filename is provided then enable Backup button
this.view.model.on('change', function() {
var that = this,
password = this.get('password'),
newPassword = this.get('newPassword'),
confirmPassword = this.get('confirmPassword');
// Only check password field if pgpass file is not available
if ((!is_pgpass_file_used &&
(_.isUndefined(password) || _.isNull(password) || password == '')) ||
_.isUndefined(newPassword) || _.isNull(newPassword) || newPassword == '' ||
_.isUndefined(confirmPassword) || _.isNull(confirmPassword) || confirmPassword == '') {
self.__internal.buttons[1].element.disabled = true;
} else if (newPassword != confirmPassword) {
self.__internal.buttons[1].element.disabled = true;
this.errorTimeout && clearTimeout(this.errorTimeout);
this.errorTimeout = setTimeout(function() {
that.errorModel.set('confirmPassword', gettext('Passwords do not match.'));
} ,400);
}else {
that.errorModel.clear();
self.__internal.buttons[1].element.disabled = false;
}
});
},
// Callback functions when click on the buttons of the Alertify dialogs
callback: function(e) {
if (e.button.element.name == 'submit') {
var self = this,
alertArgs = this.view.model.toJSON();
e.cancel = true;
$.ajax({
url: url,
method:'POST',
data:{'data': JSON.stringify(alertArgs) },
})
.done(function(res) {
if (res.success) {
// Notify user to update pgpass file
if(is_pgpass_file_used) {
Alertify.alert(
gettext('Change Password'),
gettext('Please make sure to disconnect the server'
+ ' and update the new password in the pgpass file'
+ ' before performing any other operation')
);
}
Alertify.success(res.info);
self.close();
} else {
Alertify.error(res.errormsg);
}
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
});
} }
}, },
}, };
prepare: function() { });
var self = this; }
// Disable Ok button until user provides input
this.__internal.buttons[1].element.disabled = true;
var $container = $('<div class=\'change_password\'></div>'), // Call to check if server is using pgpass file or not
newpasswordmodel = new newPasswordModel( $.ajax({
{'user_name': self.user_name} url: check_pgpass_url,
), method:'GET',
view = this.view = new Backform.Form({
el: $container,
model: newpasswordmodel,
fields: passwordChangeFields,
});
view.render();
this.elements.content.appendChild($container.get(0));
// Listen to model & if filename is provided then enable Backup button
this.view.model.on('change', function() {
var that = this,
password = this.get('password'),
newPassword = this.get('newPassword'),
confirmPassword = this.get('confirmPassword');
// Only check password field if pgpass file is not available
if ((!is_pgpass_file_used &&
(_.isUndefined(password) || _.isNull(password) || password == '')) ||
_.isUndefined(newPassword) || _.isNull(newPassword) || newPassword == '' ||
_.isUndefined(confirmPassword) || _.isNull(confirmPassword) || confirmPassword == '') {
self.__internal.buttons[1].element.disabled = true;
} else if (newPassword != confirmPassword) {
self.__internal.buttons[1].element.disabled = true;
this.errorTimeout && clearTimeout(this.errorTimeout);
this.errorTimeout = setTimeout(function() {
that.errorModel.set('confirmPassword', gettext('Passwords do not match.'));
} ,400);
}else {
that.errorModel.clear();
self.__internal.buttons[1].element.disabled = false;
}
});
},
// Callback functions when click on the buttons of the Alertify dialogs
callback: function(e) {
if (e.button.element.name == 'submit') {
var self = this,
alertArgs = this.view.model.toJSON();
e.cancel = true;
$.ajax({
url: url,
method:'POST',
data:{'data': JSON.stringify(alertArgs) },
})
.done(function(res) {
if (res.success) {
// Notify user to update pgpass file
if(is_pgpass_file_used) {
Alertify.alert(
gettext('Change Password'),
gettext('Please make sure to disconnect the server'
+ ' and update the new password in the pgpass file'
+ ' before performing any other operation')
);
}
Alertify.success(res.info);
self.close();
} else {
Alertify.error(res.errormsg);
}
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
});
}
},
};
});
}
// Call to check if server is using pgpass file or not
$.ajax({
url: check_pgpass_url,
method:'GET',
})
.done(function(res) {
if (res.success && res.data.is_pgpass) {
is_pgpass_file_used = true;
}
Alertify.changeServerPassword(d).resizeTo('40%','52%');
}) })
.fail(function(xhr, status, error) { .done(function(res) {
Alertify.pgRespErrorNotify(xhr, error); if (res.success && res.data.is_pgpass) {
}); is_pgpass_file_used = true;
}
Alertify.changeServerPassword(d).resizeTo('40%','52%');
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
});
}
return false; return false;
}, },
@@ -637,32 +633,31 @@ define('pgadmin.node.server', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) if (d) {
return false; Alertify.confirm(
gettext('Clear saved password'),
Alertify.confirm( gettext('Are you sure you want to clear the saved password for server %s?', d.label),
gettext('Clear saved password'), function() {
gettext('Are you sure you want to clear the saved password for server %s?', d.label), $.ajax({
function() { url: obj.generate_url(i, 'clear_saved_password', d, true),
$.ajax({ method:'PUT',
url: obj.generate_url(i, 'clear_saved_password', d, true),
method:'PUT',
})
.done(function(res) {
if (res.success == 1) {
Alertify.success(res.info);
t.itemData(i).is_password_saved=res.data.is_password_saved;
}
else {
Alertify.error(res.info);
}
}) })
.fail(function(xhr, status, error) { .done(function(res) {
Alertify.pgRespErrorNotify(xhr, error); if (res.success == 1) {
}); Alertify.success(res.info);
}, t.itemData(i).is_password_saved=res.data.is_password_saved;
function() { return true; } }
); else {
Alertify.error(res.info);
}
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
});
},
function() { return true; }
);
}
return false; return false;
}, },
@@ -675,32 +670,31 @@ define('pgadmin.node.server', [
i = input.item || t.selected(), i = input.item || t.selected(),
d = i && i.length == 1 ? t.itemData(i) : undefined; d = i && i.length == 1 ? t.itemData(i) : undefined;
if (!d) if (d) {
return false; Alertify.confirm(
gettext('Clear SSH Tunnel password'),
Alertify.confirm( gettext('Are you sure you want to clear the saved password of SSH Tunnel for server %s?', d.label),
gettext('Clear SSH Tunnel password'), function() {
gettext('Are you sure you want to clear the saved password of SSH Tunnel for server %s?', d.label), $.ajax({
function() { url: obj.generate_url(i, 'clear_sshtunnel_password', d, true),
$.ajax({ method:'PUT',
url: obj.generate_url(i, 'clear_sshtunnel_password', d, true),
method:'PUT',
})
.done(function(res) {
if (res.success == 1) {
Alertify.success(res.info);
t.itemData(i).is_tunnel_password_saved=res.data.is_tunnel_password_saved;
}
else {
Alertify.error(res.info);
}
}) })
.fail(function(xhr, status, error) { .done(function(res) {
Alertify.pgRespErrorNotify(xhr, error); if (res.success == 1) {
}); Alertify.success(res.info);
}, t.itemData(i).is_tunnel_password_saved=res.data.is_tunnel_password_saved;
function() { return true; } }
); else {
Alertify.error(res.info);
}
})
.fail(function(xhr, status, error) {
Alertify.pgRespErrorNotify(xhr, error);
});
},
function() { return true; }
);
}
return false; return false;
}, },
-1
View File
@@ -31,7 +31,6 @@ define('pgadmin.browser', [
// Generally the one, which do no have AMD support. // Generally the one, which do no have AMD support.
var wcDocker = window.wcDocker; var wcDocker = window.wcDocker;
$ = $ || window.jQuery || window.$; $ = $ || window.jQuery || window.$;
Bootstrap = Bootstrap || window.Bootstrap;
var CodeMirror = codemirror.default; var CodeMirror = codemirror.default;
var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {}; var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {};
+128 -146
View File
@@ -154,7 +154,6 @@ define([
if (_.isUndefined(options) || _.isNull(options)) { if (_.isUndefined(options) || _.isNull(options)) {
options = attributes || {}; options = attributes || {};
attributes = null;
} }
self.sessAttrs = {}; self.sessAttrs = {};
@@ -1029,129 +1028,125 @@ define([
return (_.findIndex(this.sessAttrs[type], comparator)); return (_.findIndex(this.sessAttrs[type], comparator));
}, },
onModelAdd: function(obj) { onModelAdd: function(obj) {
if (!this.trackChanges) if (this.trackChanges) {
return true; var self = this,
msg,
idx = self.objFindInSession(obj, 'deleted');
var self = this, // Hmm.. - it was originally deleted from this collection, we should
msg, // remove it from the 'deleted' list.
idx = self.objFindInSession(obj, 'deleted'); if (idx >= 0) {
var origObj = self.sessAttrs['deleted'][idx];
// Hmm.. - it was originally deleted from this collection, we should obj.origSessAttrs = _.clone(origObj.origSessAttrs);
// remove it from the 'deleted' list. obj.attributes = _.extend(obj.attributes, origObj.attributes);
if (idx >= 0) { obj.sessAttrs = _.clone(origObj.sessAttrs);
var origObj = self.sessAttrs['deleted'][idx];
obj.origSessAttrs = _.clone(origObj.origSessAttrs); self.sessAttrs['deleted'].splice(idx, 1);
obj.attributes = _.extend(obj.attributes, origObj.attributes);
obj.sessAttrs = _.clone(origObj.sessAttrs);
self.sessAttrs['deleted'].splice(idx, 1); // It has been changed originally!
if ((!('sessChanged' in obj)) || obj.sessChanged()) {
// It has been changed originally! self.sessAttrs['changed'].push(obj);
if ((!('sessChanged' in obj)) || obj.sessChanged()) {
self.sessAttrs['changed'].push(obj);
}
(self.handler || self).trigger('pgadmin-session:added', self, obj);
if ('default_validate' in obj && typeof(obj.default_validate) == 'function') {
msg = obj.default_validate();
}
if (_.isString(msg)) {
(self.sessAttrs['invalid'])[obj.cid] = msg;
} else if ('validate' in obj && typeof(obj.validate) === 'function') {
msg = obj.validate();
if (msg) {
(self.sessAttrs['invalid'])[obj.cid] = msg;
} }
}
} else {
if ('default_validate' in obj && typeof(obj.default_validate) == 'function') { (self.handler || self).trigger('pgadmin-session:added', self, obj);
msg = obj.default_validate();
}
if (_.isString(msg)) {
(self.sessAttrs['invalid'])[obj.cid] = msg;
} else if ('validate' in obj && typeof(obj.validate) === 'function') {
msg = obj.validate();
if (msg) { if ('default_validate' in obj && typeof(obj.default_validate) == 'function') {
(self.sessAttrs['invalid'])[obj.cid] = msg; msg = obj.default_validate();
} }
}
self.sessAttrs['added'].push(obj);
/* if (_.isString(msg)) {
* Session has been changed (self.sessAttrs['invalid'])[obj.cid] = msg;
*/ } else if ('validate' in obj && typeof(obj.validate) === 'function') {
(self.handler || self).trigger('pgadmin-session:added', self, obj); msg = obj.validate();
if (msg) {
(self.sessAttrs['invalid'])[obj.cid] = msg;
}
}
} else {
if ('default_validate' in obj && typeof(obj.default_validate) == 'function') {
msg = obj.default_validate();
}
if (_.isString(msg)) {
(self.sessAttrs['invalid'])[obj.cid] = msg;
} else if ('validate' in obj && typeof(obj.validate) === 'function') {
msg = obj.validate();
if (msg) {
(self.sessAttrs['invalid'])[obj.cid] = msg;
}
}
self.sessAttrs['added'].push(obj);
/*
* Session has been changed
*/
(self.handler || self).trigger('pgadmin-session:added', self, obj);
}
// Let the parent/listener know about my status (valid/invalid).
this.triggerValidationEvent.apply(this);
} }
// Let the parent/listener know about my status (valid/invalid).
this.triggerValidationEvent.apply(this);
return true; return true;
}, },
onModelRemove: function(obj) { onModelRemove: function(obj) {
if (!this.trackChanges) if (this.trackChanges) {
return true; /* Once model is removed from collection clear its errorModel as it's no longer relevant
* for us. Otherwise it creates problem in 'clearInvalidSessionIfModelValid' function.
*/
obj.errorModel.clear();
/* Once model is removed from collection clear its errorModel as it's no longer relevant var self = this,
* for us. Otherwise it creates problem in 'clearInvalidSessionIfModelValid' function. invalidModels = self.sessAttrs['invalid'],
*/ copy = _.clone(obj),
obj.errorModel.clear(); idx = self.objFindInSession(obj, 'added');
var self = this, // We need to remove it from the invalid object list first.
invalidModels = self.sessAttrs['invalid'], if (obj.cid in invalidModels) {
copy = _.clone(obj), delete invalidModels[obj.cid];
idx = self.objFindInSession(obj, 'added'); }
// We need to remove it from the invalid object list first. // Hmm - it was newly added, we can safely remove it.
if (obj.cid in invalidModels) { if (idx >= 0) {
delete invalidModels[obj.cid]; self.sessAttrs['added'].splice(idx, 1);
(self.handler || self).trigger('pgadmin-session:removed', self, copy);
self.checkDuplicateWithModel(copy);
// Let the parent/listener know about my status (valid/invalid).
this.triggerValidationEvent.apply(this);
} else {
// Hmm - it was changed in this session, we should remove it from the
// changed models.
idx = self.objFindInSession(obj, 'changed');
if (idx >= 0) {
self.sessAttrs['changed'].splice(idx, 1);
(self.handler || self).trigger('pgadmin-session:removed', self, copy);
} else {
(self.handler || self).trigger('pgadmin-session:removed', self, copy);
}
self.sessAttrs['deleted'].push(obj);
self.checkDuplicateWithModel(obj);
// Let the parent/listener know about my status (valid/invalid).
this.triggerValidationEvent.apply(this);
}
/*
* This object has been remove, we need to check (if we still have any
* other invalid message pending).
*/
} }
// Hmm - it was newly added, we can safely remove it.
if (idx >= 0) {
self.sessAttrs['added'].splice(idx, 1);
(self.handler || self).trigger('pgadmin-session:removed', self, copy);
self.checkDuplicateWithModel(copy);
// Let the parent/listener know about my status (valid/invalid).
this.triggerValidationEvent.apply(this);
return true;
}
// Hmm - it was changed in this session, we should remove it from the
// changed models.
idx = self.objFindInSession(obj, 'changed');
if (idx >= 0) {
self.sessAttrs['changed'].splice(idx, 1);
(self.handler || self).trigger('pgadmin-session:removed', self, copy);
} else {
(self.handler || self).trigger('pgadmin-session:removed', self, copy);
}
self.sessAttrs['deleted'].push(obj);
self.checkDuplicateWithModel(obj);
// Let the parent/listener know about my status (valid/invalid).
this.triggerValidationEvent.apply(this);
/*
* This object has been remove, we need to check (if we still have any
* other invalid message pending).
*/
return true; return true;
}, },
triggerValidationEvent: function() { triggerValidationEvent: function() {
@@ -1194,52 +1189,39 @@ define([
onModelChange: function(obj) { onModelChange: function(obj) {
var self = this; var self = this;
if (!this.trackChanges || !(obj instanceof pgBrowser.Node.Model)) if (this.trackChanges && obj instanceof pgBrowser.Node.Model) {
return true; var idx = self.objFindInSession(obj, 'added');
var idx = self.objFindInSession(obj, 'added');
// It was newly added model, we don't need to add into the changed
// list.
if (idx >= 0) {
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
return true;
}
idx = self.objFindInSession(obj, 'changed');
if (!('sessChanged' in obj)) {
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
// It was newly added model, we don't need to add into the changed
// list.
if (idx >= 0) { if (idx >= 0) {
return true;
}
self.sessAttrs['changed'].push(obj);
return true;
}
if (idx >= 0) {
if (!obj.sessChanged()) {
// This object is no more updated, removing it from the changed
// models list.
self.sessAttrs['changed'].splice(idx, 1);
(self.handler || self).trigger('pgadmin-session:changed', self, obj); (self.handler || self).trigger('pgadmin-session:changed', self, obj);
return true; } else {
idx = self.objFindInSession(obj, 'changed');
if (!('sessChanged' in obj)) {
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
if (idx < 0) {
self.sessAttrs['changed'].push(obj);
}
} else {
if (idx >= 0) {
if (!obj.sessChanged()) {
// This object is no more updated, removing it from the changed
// models list.
self.sessAttrs['changed'].splice(idx, 1);
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
} else {
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
}
} else if (obj.sessChanged()) {
self.sessAttrs['changed'].push(obj);
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
}
}
} }
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
return true;
}
if (obj.sessChanged()) {
self.sessAttrs['changed'].push(obj);
(self.handler || self).trigger('pgadmin-session:changed', self, obj);
} }
return true; return true;
@@ -320,7 +320,7 @@ define('pgadmin.preferences', [
switch (eventName) { switch (eventName) {
case 'selected': case 'selected':
if (!d) if (!d)
return true; break;
if (d.preferences) { if (d.preferences) {
/* /*
@@ -330,14 +330,14 @@ define('pgadmin.preferences', [
renderPreferencePanel(d.preferences); renderPreferencePanel(d.preferences);
return true; break;
} else { } else {
selectFirstCategory(api, item); selectFirstCategory(api, item);
} }
break; break;
case 'added': case 'added':
if (!d) if (!d)
return true; break;
// We will add the preferences in to the preferences data // We will add the preferences in to the preferences data
// collection. // collection.
@@ -136,7 +136,6 @@ define([
} }
} catch (e) { } catch (e) {
// Do nothing // Do nothing
options = [];
console.warn(e.stack || e); console.warn(e.stack || e);
} }
} else { } else {
+3 -3
View File
@@ -45,15 +45,15 @@ class ObjectRegistry(ABCMeta):
registry = dict() registry = dict()
def __init__(cls, name, bases, d): def __init__(self, name, bases, d):
""" """
This method is used to register the objects based on object type. This method is used to register the objects based on object type.
""" """
if d and 'object_type' in d: if d and 'object_type' in d:
ObjectRegistry.registry[d['object_type']] = cls ObjectRegistry.registry[d['object_type']] = self
ABCMeta.__init__(cls, name, bases, d) ABCMeta.__init__(self, name, bases, d)
@classmethod @classmethod
def get_object(cls, name, **kwargs): def get_object(cls, name, **kwargs):
@@ -953,28 +953,31 @@ define([
this.$content.find('button.add').first().on('click',(e) => { this.$content.find('button.add').first().on('click',(e) => {
e.preventDefault(); e.preventDefault();
// There should be only one empty row. // There should be only one empty row.
let anyNew = false;
for(const [idx, model] of userCollection.models.entries()) { for(const [idx, model] of userCollection.models.entries()) {
if(model.isNew()) { if(model.isNew()) {
let row = view.body.rows[idx].$el; let row = view.body.rows[idx].$el;
row.addClass('new'); row.addClass('new');
$(row).pgMakeVisible('backgrid'); $(row).pgMakeVisible('backgrid');
$(row).find('.email').trigger('click'); $(row).find('.email').trigger('click');
return false; anyNew = true;
} }
} }
$(view.body.$el.find($('tr.new'))).removeClass('new'); if(!anyNew) {
var m = new(UserModel)(null, { $(view.body.$el.find($('tr.new'))).removeClass('new');
handler: userCollection, var m = new(UserModel)(null, {
top: userCollection, handler: userCollection,
collection: userCollection, top: userCollection,
}); collection: userCollection,
userCollection.add(m); });
userCollection.add(m);
var newRow = view.body.rows[userCollection.indexOf(m)].$el; var newRow = view.body.rows[userCollection.indexOf(m)].$el;
newRow.addClass('new'); newRow.addClass('new');
$(newRow).pgMakeVisible('backgrid'); $(newRow).pgMakeVisible('backgrid');
$(newRow).find('.email').trigger('click'); $(newRow).find('.email').trigger('click');
}
return false; return false;
}); });
@@ -120,7 +120,7 @@ class Driver(BaseDriver):
return managers[str(sid)] return managers[str(sid)]
def version(cls): def version(self):
""" """
version(...) version(...)
@@ -135,7 +135,7 @@ class Driver(BaseDriver):
"Driver Version information for psycopg2 is not available!" "Driver Version information for psycopg2 is not available!"
) )
def libpq_version(cls): def libpq_version(self):
""" """
Returns the loaded libpq version Returns the loaded libpq version
""" """
+3 -3
View File
@@ -50,15 +50,15 @@ class DriverRegistry(ABCMeta):
registry = None registry = None
drivers = dict() drivers = dict()
def __init__(cls, name, bases, d): def __init__(self, name, bases, d):
# Register this type of driver, based on the module name # Register this type of driver, based on the module name
# Avoid registering the BaseDriver itself # Avoid registering the BaseDriver itself
if name != 'BaseDriver': if name != 'BaseDriver':
DriverRegistry.registry[_decorate_cls_name(d['__module__'])] = cls DriverRegistry.registry[_decorate_cls_name(d['__module__'])] = self
ABCMeta.__init__(cls, name, bases, d) ABCMeta.__init__(self, name, bases, d)
@classmethod @classmethod
def create(cls, name, **kwargs): def create(cls, name, **kwargs):
+4 -4
View File
@@ -42,7 +42,7 @@ class TestsGeneratorRegistry(ABCMeta):
registry = dict() registry = dict()
def __init__(cls, name, bases, d): def __init__(self, name, bases, d):
# Register this type of module, based on the module name # Register this type of module, based on the module name
# Avoid registering the BaseDriver itself # Avoid registering the BaseDriver itself
@@ -51,11 +51,11 @@ class TestsGeneratorRegistry(ABCMeta):
# Store/append test classes in 'registry' if test modules has # Store/append test classes in 'registry' if test modules has
# multiple classes # multiple classes
if d['__module__'] in TestsGeneratorRegistry.registry: if d['__module__'] in TestsGeneratorRegistry.registry:
TestsGeneratorRegistry.registry[d['__module__']].append(cls) TestsGeneratorRegistry.registry[d['__module__']].append(self)
else: else:
TestsGeneratorRegistry.registry[d['__module__']] = [cls] TestsGeneratorRegistry.registry[d['__module__']] = [self]
ABCMeta.__init__(cls, name, bases, d) ABCMeta.__init__(self, name, bases, d)
@classmethod @classmethod
def load_generators(cls, pkg_root, exclude_pkgs, for_modules=[], def load_generators(cls, pkg_root, exclude_pkgs, for_modules=[],