Delete user working from user table (#1938)

Comment in helper
This commit is contained in:
Ozzieisaacs 2021-04-10 11:32:11 +02:00
parent 2d73f541c0
commit ae97e87506
3 changed files with 64 additions and 38 deletions

View File

@ -31,7 +31,7 @@ from datetime import datetime, timedelta
from babel import Locale as LC from babel import Locale as LC
from babel.dates import format_datetime from babel.dates import format_datetime
from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, send_from_directory, g from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, send_from_directory, g, Response
from flask_login import login_required, current_user, logout_user, confirm_login from flask_login import login_required, current_user, logout_user, confirm_login
from flask_babel import gettext as _ from flask_babel import gettext as _
from sqlalchemy import and_ from sqlalchemy import and_
@ -277,12 +277,19 @@ def list_users():
response.headers["Content-Type"] = "application/json; charset=utf-8" response.headers["Content-Type"] = "application/json; charset=utf-8"
return response return response
@admi.route("/ajax/deleteuser") @admi.route("/ajax/deleteuser", methods=['POST'])
@login_required @login_required
@admin_required @admin_required
def delete_user(): def delete_user():
# ToDo User delete check also not last one user_id = request.values.get('userid', -1)
return "" content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).one_or_none()
try:
message = _delete_user(content)
return Response(json.dumps({'type': "success", 'message': message}), mimetype='application/json')
except Exception as ex:
return Response(json.dumps({'type': "danger", 'message':str(ex)}), mimetype='application/json')
log.error("User not found")
return Response(json.dumps({'type': "danger", 'message':_("User not found")}), mimetype='application/json')
@admi.route("/ajax/getlocale") @admi.route("/ajax/getlocale")
@login_required @login_required
@ -1194,22 +1201,29 @@ def _handle_new_user(to_save, content, languages, translations, kobo_support):
ub.session.rollback() ub.session.rollback()
flash(_(u"Settings DB is not Writeable"), category="error") flash(_(u"Settings DB is not Writeable"), category="error")
def _delete_user(content):
if ub.session.query(ub.User).filter(ub.User.role.op('&')(constants.ROLE_ADMIN) == constants.ROLE_ADMIN,
ub.User.id != content.id).count():
if content.name != "Guest":
ub.session.query(ub.User).filter(ub.User.id == content.id).delete()
ub.session_commit()
log.info(u"User {} deleted".format(content.name))
return(_(u"User '%(nick)s' deleted", nick=content.name))
else:
log.warning(_(u"Can't delete Guest User"))
raise Exception(_(u"Can't delete Guest User"))
else:
log.warning(u"No admin user remaining, can't delete user")
raise Exception(_(u"No admin user remaining, can't delete user"))
def _handle_edit_user(to_save, content, languages, translations, kobo_support): def _handle_edit_user(to_save, content, languages, translations, kobo_support):
if to_save.get("delete"): if to_save.get("delete"):
if ub.session.query(ub.User).filter(ub.User.role.op('&')(constants.ROLE_ADMIN) == constants.ROLE_ADMIN, try:
ub.User.id != content.id).count(): flash(_delete_user(content), category="success")
if content.name != "Guest": except Exception as ex:
ub.session.query(ub.User).filter(ub.User.id == content.id).delete() flash(str(ex), category="error")
ub.session_commit() return redirect(url_for('admin.admin'))
flash(_(u"User '%(nick)s' deleted", nick=content.name), category="success")
return redirect(url_for('admin.admin'))
else:
flash(_(u"Can't delete Guest User"), category="error")
return redirect(url_for('admin.admin'))
else:
flash(_(u"No admin user remaining, can't delete user", nick=content.name), category="error")
return redirect(url_for('admin.admin'))
else: else:
if not ub.session.query(ub.User).filter(ub.User.role.op('&')(constants.ROLE_ADMIN) == constants.ROLE_ADMIN, if not ub.session.query(ub.User).filter(ub.User.role.op('&')(constants.ROLE_ADMIN) == constants.ROLE_ADMIN,
ub.User.id != content.id).count() and 'admin_role' not in to_save: ub.User.id != content.id).count() and 'admin_role' not in to_save:

View File

@ -795,8 +795,8 @@ def tags_filters():
# checks if domain is in database (including wildcards) # checks if domain is in database (including wildcards)
# example SELECT * FROM @TABLE WHERE 'abcdefg' LIKE Name; # example SELECT * FROM @TABLE WHERE 'abcdefg' LIKE Name;
# from https://code.luasoftware.com/tutorials/flask/execute-raw-sql-in-flask-sqlalchemy/ # from https://code.luasoftware.com/tutorials/flask/execute-raw-sql-in-flask-sqlalchemy/
# in all calls the email address is checked for validity
def check_valid_domain(domain_text): def check_valid_domain(domain_text):
# domain_text = domain_text.split('@', 1)[-1].lower()
sql = "SELECT * FROM registration WHERE (:domain LIKE domain and allow = 1);" sql = "SELECT * FROM registration WHERE (:domain LIKE domain and allow = 1);"
result = ub.session.query(ub.Registration).from_statement(text(sql)).params(domain=domain_text).all() result = ub.session.query(ub.Registration).from_statement(text(sql)).params(domain=domain_text).all()
if not len(result): if not len(result):

View File

@ -525,7 +525,6 @@ $(function() {
}); });
} }
$("#user-table").on("click-cell.bs.table", function (field, value, row, $element) { $("#user-table").on("click-cell.bs.table", function (field, value, row, $element) {
if (value === "denied_column_value") { if (value === "denied_column_value") {
ConfirmDialog("btndeluser", "GeneralDeleteModal", $element.id, user_handle); ConfirmDialog("btndeluser", "GeneralDeleteModal", $element.id, user_handle);
@ -563,7 +562,6 @@ $(function() {
$(".button_head").removeClass("disabled"); $(".button_head").removeClass("disabled");
$(".header_select").removeAttr("disabled"); $(".header_select").removeAttr("disabled");
} }
}); });
}); });
@ -603,7 +601,7 @@ function EbookActions (value, row) {
/* Function for deleting books */ /* Function for deleting books */
function UserActions (value, row) { function UserActions (value, row) {
return [ return [
"<div class=\"user-remove\" data-pk=\"" + row.id + "\" data-target=\"#GeneralDeleteModal\" title=\"Remove\">", "<div class=\"user-remove\" data-value=\"delete\" onclick=\"deleteUser(this, '" + row.id + "')\" data-pk=\"" + row.id + "\" title=\"Remove\">",
"<i class=\"glyphicon glyphicon-trash\"></i>", "<i class=\"glyphicon glyphicon-trash\"></i>",
"</div>" "</div>"
].join(""); ].join("");
@ -715,26 +713,40 @@ function checkboxHeader(CheckboxState, field, field_index) {
}); });
} }
function user_handle (userId) { function deleteUser(a,b){
$.ajax({ confirmDialog(
method:"post", "btndeluser",
url: window.location.pathname + "/../../ajax/deleteuser", "GeneralDeleteModal",
data: {"userid":userId} 0,
}); function() {
$.ajax({ $.ajax({
method:"get", method:"post",
url: window.location.pathname + "/../../ajax/listusers", url: window.location.pathname + "/../../ajax/deleteuser",
async: true, data: {"userid":b},
timeout: 900, success:function(data) {
success:function(data) { $("#flash_success").remove();
$("#user-table").bootstrapTable("load", data); $("#flash_danger").remove();
if (!jQuery.isEmptyObject(data)) {
$( ".navbar" ).after( '<div class="row-fluid text-center" style="margin-top: -20px;">' +
'<div id="flash_'+data.type+'" class="alert alert-'+data.type+'">'+data.message+'</div>' +
'</div>');
}
$.ajax({
method: "get",
url: window.location.pathname + "/../../ajax/listusers",
async: true,
timeout: 900,
success: function (data) {
$("#user-table").bootstrapTable("load", data);
}
});
}
});
} }
}); );
} }
function checkboxSorter(a, b, c, d) function user_handle (userId) {
{
return a - b
} }
function test(){ function test(){