Changed user.nickname to user.name

Added function to view downloads of all users for admins
This commit is contained in:
Ozzie Isaacs 2021-03-21 18:55:02 +01:00
parent 436f60caa9
commit 9864d932e0
21 changed files with 147 additions and 123 deletions

View file

@ -127,7 +127,7 @@ def get_locale():
user = getattr(g, 'user', None)
# user = None
if user is not None and hasattr(user, "locale"):
if user.nickname != 'Guest': # if the account is the guest account bypass the config lang settings
if user.name != 'Guest': # if the account is the guest account bypass the config lang settings
return user.locale
preferred = list()

View file

@ -248,7 +248,7 @@ def list_users():
all_user = all_user.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS)
total_count = all_user.count()
if search:
users = all_user.filter(or_(func.lower(ub.User.nickname).ilike("%" + search + "%"),
users = all_user.filter(or_(func.lower(ub.User.name).ilike("%" + search + "%"),
func.lower(ub.User.kindle_mail).ilike("%" + search + "%"),
func.lower(ub.User.email).ilike("%" + search + "%")))\
.offset(off).limit(limit).all()
@ -332,9 +332,9 @@ def edit_list_user(param):
else:
return ""
for user in users:
if param =='nickname':
if not ub.session.query(ub.User).filter(ub.User.nickname == vals['value']).scalar():
user.nickname = vals['value']
if param =='name':
if not ub.session.query(ub.User).filter(ub.User.name == vals['value']).scalar():
user.name = vals['value']
else:
log.error(u"This username is already taken")
return _(u"This username is already taken"), 400
@ -532,7 +532,7 @@ def edit_restriction(res_type, user_id):
elementlist = usr.list_allowed_tags()
elementlist[int(element['id'][1:])] = element['Element']
usr.allowed_tags = ','.join(elementlist)
ub.session_commit("Changed allowed tags of user {} to {}".format(usr.nickname, usr.allowed_tags))
ub.session_commit("Changed allowed tags of user {} to {}".format(usr.name, usr.allowed_tags))
if res_type == 3: # CColumn per user
if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first()
@ -541,7 +541,7 @@ def edit_restriction(res_type, user_id):
elementlist = usr.list_allowed_column_values()
elementlist[int(element['id'][1:])] = element['Element']
usr.allowed_column_value = ','.join(elementlist)
ub.session_commit("Changed allowed columns of user {} to {}".format(usr.nickname, usr.allowed_column_value))
ub.session_commit("Changed allowed columns of user {} to {}".format(usr.name, usr.allowed_column_value))
if element['id'].startswith('d'):
if res_type == 0: # Tags as template
elementlist = config.list_denied_tags()
@ -561,7 +561,7 @@ def edit_restriction(res_type, user_id):
elementlist = usr.list_denied_tags()
elementlist[int(element['id'][1:])] = element['Element']
usr.denied_tags = ','.join(elementlist)
ub.session_commit("Changed denied tags of user {} to {}".format(usr.nickname, usr.denied_tags))
ub.session_commit("Changed denied tags of user {} to {}".format(usr.name, usr.denied_tags))
if res_type == 3: # CColumn per user
if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first()
@ -570,7 +570,7 @@ def edit_restriction(res_type, user_id):
elementlist = usr.list_denied_column_values()
elementlist[int(element['id'][1:])] = element['Element']
usr.denied_column_value = ','.join(elementlist)
ub.session_commit("Changed denied columns of user {} to {}".format(usr.nickname, usr.denied_column_value))
ub.session_commit("Changed denied columns of user {} to {}".format(usr.name, usr.denied_column_value))
return ""
@ -617,10 +617,10 @@ def add_restriction(res_type, user_id):
usr = current_user
if 'submit_allow' in element:
usr.allowed_tags = restriction_addition(element, usr.list_allowed_tags)
ub.session_commit("Changed allowed tags of user {} to {}".format(usr.nickname, usr.list_allowed_tags))
ub.session_commit("Changed allowed tags of user {} to {}".format(usr.name, usr.list_allowed_tags))
elif 'submit_deny' in element:
usr.denied_tags = restriction_addition(element, usr.list_denied_tags)
ub.session_commit("Changed denied tags of user {} to {}".format(usr.nickname, usr.list_denied_tags))
ub.session_commit("Changed denied tags of user {} to {}".format(usr.name, usr.list_denied_tags))
if res_type == 3: # CustomC per user
if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first()
@ -628,11 +628,11 @@ def add_restriction(res_type, user_id):
usr = current_user
if 'submit_allow' in element:
usr.allowed_column_value = restriction_addition(element, usr.list_allowed_column_values)
ub.session_commit("Changed allowed columns of user {} to {}".format(usr.nickname,
ub.session_commit("Changed allowed columns of user {} to {}".format(usr.name,
usr.list_allowed_column_values))
elif 'submit_deny' in element:
usr.denied_column_value = restriction_addition(element, usr.list_denied_column_values)
ub.session_commit("Changed denied columns of user {} to {}".format(usr.nickname,
ub.session_commit("Changed denied columns of user {} to {}".format(usr.name,
usr.list_denied_column_values))
return ""
@ -664,10 +664,10 @@ def delete_restriction(res_type, user_id):
usr = current_user
if element['id'].startswith('a'):
usr.allowed_tags = restriction_deletion(element, usr.list_allowed_tags)
ub.session_commit("Deleted allowed tags of user {}: {}".format(usr.nickname, usr.list_allowed_tags))
ub.session_commit("Deleted allowed tags of user {}: {}".format(usr.name, usr.list_allowed_tags))
elif element['id'].startswith('d'):
usr.denied_tags = restriction_deletion(element, usr.list_denied_tags)
ub.session_commit("Deleted denied tags of user {}: {}".format(usr.nickname, usr.list_allowed_tags))
ub.session_commit("Deleted denied tags of user {}: {}".format(usr.name, usr.list_allowed_tags))
elif res_type == 3: # Columns per user
if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first()
@ -675,12 +675,12 @@ def delete_restriction(res_type, user_id):
usr = current_user
if element['id'].startswith('a'):
usr.allowed_column_value = restriction_deletion(element, usr.list_allowed_column_values)
ub.session_commit("Deleted allowed columns of user {}: {}".format(usr.nickname,
ub.session_commit("Deleted allowed columns of user {}: {}".format(usr.name,
usr.list_allowed_column_values))
elif element['id'].startswith('d'):
usr.denied_column_value = restriction_deletion(element, usr.list_denied_column_values)
ub.session_commit("Deleted denied columns of user {}: {}".format(usr.nickname,
ub.session_commit("Deleted denied columns of user {}: {}".format(usr.name,
usr.list_denied_column_values))
return ""
@ -1156,18 +1156,18 @@ def _handle_new_user(to_save, content, languages, translations, kobo_support):
content.role = constants.selected_roles(to_save)
if not to_save["nickname"] or not to_save["email"] or not to_save["password"]:
if not to_save["name"] or not to_save["email"] or not to_save["password"]:
flash(_(u"Please fill out all fields!"), category="error")
return render_title_template("user_edit.html", new_user=1, content=content, translations=translations,
registered_oauth=oauth_check, kobo_support=kobo_support,
title=_(u"Add new user"))
content.password = generate_password_hash(to_save["password"])
existing_user = ub.session.query(ub.User).filter(func.lower(ub.User.nickname) == to_save["nickname"].lower()) \
existing_user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == to_save["name"].lower()) \
.first()
existing_email = ub.session.query(ub.User).filter(ub.User.email == to_save["email"].lower()) \
.first()
if not existing_user and not existing_email:
content.nickname = to_save["nickname"]
content.name = to_save["name"]
if config.config_public_reg and not check_valid_domain(to_save["email"]):
flash(_(u"E-mail is not from valid domain"), category="error")
return render_title_template("user_edit.html", new_user=1, content=content, translations=translations,
@ -1176,7 +1176,7 @@ def _handle_new_user(to_save, content, languages, translations, kobo_support):
else:
content.email = to_save["email"]
else:
flash(_(u"Found an existing account for this e-mail address or nickname."), category="error")
flash(_(u"Found an existing account for this e-mail address or name."), category="error")
return render_title_template("user_edit.html", new_user=1, content=content, translations=translations,
languages=languages, title=_(u"Add new user"), page="newuser",
kobo_support=kobo_support, registered_oauth=oauth_check)
@ -1187,11 +1187,11 @@ def _handle_new_user(to_save, content, languages, translations, kobo_support):
content.denied_column_value = config.config_denied_column_value
ub.session.add(content)
ub.session.commit()
flash(_(u"User '%(user)s' created", user=content.nickname), category="success")
flash(_(u"User '%(user)s' created", user=content.name), category="success")
return redirect(url_for('admin.admin'))
except IntegrityError:
ub.session.rollback()
flash(_(u"Found an existing account for this e-mail address or nickname."), category="error")
flash(_(u"Found an existing account for this e-mail address or name."), category="error")
except OperationalError:
ub.session.rollback()
flash(_(u"Settings DB is not Writeable"), category="error")
@ -1203,15 +1203,15 @@ def _handle_edit_user(to_save, content, languages, translations, kobo_support):
ub.User.id != content.id).count():
ub.session.query(ub.User).filter(ub.User.id == content.id).delete()
ub.session_commit()
flash(_(u"User '%(nick)s' deleted", nick=content.nickname), category="success")
flash(_(u"User '%(nick)s' deleted", nick=content.name), category="success")
return redirect(url_for('admin.admin'))
else:
flash(_(u"No admin user remaining, can't delete user", nick=content.nickname), category="error")
flash(_(u"No admin user remaining, can't delete user", nick=content.name), category="error")
return redirect(url_for('admin.admin'))
else:
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:
flash(_(u"No admin user remaining, can't remove admin role", nick=content.nickname), category="error")
flash(_(u"No admin user remaining, can't remove admin role", nick=content.name), category="error")
return redirect(url_for('admin.admin'))
if "password" in to_save and to_save["password"]:
@ -1256,11 +1256,11 @@ def _handle_edit_user(to_save, content, languages, translations, kobo_support):
new_user=0,
content=content,
registered_oauth=oauth_check,
title=_(u"Edit User %(nick)s", nick=content.nickname), page="edituser")
if "nickname" in to_save and to_save["nickname"] != content.nickname:
# Query User nickname, if not existing, change
if not ub.session.query(ub.User).filter(ub.User.nickname == to_save["nickname"]).scalar():
content.nickname = to_save["nickname"]
title=_(u"Edit User %(nick)s", nick=content.name), page="edituser")
if "name" in to_save and to_save["name"] != content.name:
# Query User name, if not existing, change
if not ub.session.query(ub.User).filter(ub.User.name == to_save["name"]).scalar():
content.name = to_save["name"]
else:
flash(_(u"This username is already taken"), category="error")
return render_title_template("user_edit.html",
@ -1270,14 +1270,14 @@ def _handle_edit_user(to_save, content, languages, translations, kobo_support):
new_user=0, content=content,
registered_oauth=oauth_check,
kobo_support=kobo_support,
title=_(u"Edit User %(nick)s", nick=content.nickname),
title=_(u"Edit User %(nick)s", nick=content.name),
page="edituser")
if "kindle_mail" in to_save and to_save["kindle_mail"] != content.kindle_mail:
content.kindle_mail = to_save["kindle_mail"]
try:
ub.session_commit()
flash(_(u"User '%(nick)s' updated", nick=content.nickname), category="success")
flash(_(u"User '%(nick)s' updated", nick=content.name), category="success")
except IntegrityError:
ub.session.rollback()
flash(_(u"An unknown error occured."), category="error")
@ -1337,7 +1337,7 @@ def update_mailsettings():
if to_save.get("test"):
if current_user.email:
result = send_test_mail(current_user.email, current_user.nickname)
result = send_test_mail(current_user.email, current_user.name)
if result is None:
flash(_(u"Test e-mail successfully send to %(kindlemail)s", kindlemail=current_user.email),
category="success")
@ -1356,7 +1356,7 @@ def update_mailsettings():
@admin_required
def edit_user(user_id):
content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User
if not content or (not config.config_anonbrowse and content.nickname == "Guest"):
if not content or (not config.config_anonbrowse and content.name == "Guest"):
flash(_(u"User not found"), category="error")
return redirect(url_for('admin.admin'))
languages = calibre_db.speaking_language()
@ -1373,7 +1373,7 @@ def edit_user(user_id):
registered_oauth=oauth_check,
mail_configured=config.get_mail_server_configured(),
kobo_support=kobo_support,
title=_(u"Edit User %(nick)s", nick=content.nickname), page="edituser")
title=_(u"Edit User %(nick)s", nick=content.name), page="edituser")
@admi.route("/admin/resetpassword/<int:user_id>")
@ -1500,8 +1500,8 @@ def ldap_import_create_user(user, user_data):
username = user_data[user_login_field][0].decode('utf-8')
# check for duplicate username
if ub.session.query(ub.User).filter(func.lower(ub.User.nickname) == username.lower()).first():
# if ub.session.query(ub.User).filter(ub.User.nickname == username).first():
if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).first():
# if ub.session.query(ub.User).filter(ub.User.name == username).first():
log.warning("LDAP User %s Already in Database", user_data)
return 0, None
@ -1519,7 +1519,7 @@ def ldap_import_create_user(user, user_data):
log.warning("LDAP Email %s Already in Database", user_data)
return 0, None
content = ub.User()
content.nickname = username
content.name = username
content.password = '' # dummy password which will be replaced by ldap one
content.email = useremail
content.kindle_mail = kindlemail

View file

@ -430,12 +430,12 @@ def load_configuration(session):
session.commit()
conf = _ConfigSQL(session)
# Migrate from global restrictions to user based restrictions
if bool(conf.config_default_show & constants.MATURE_CONTENT) and conf.config_denied_tags == "":
conf.config_denied_tags = conf.config_mature_content_tags
conf.save()
session.query(ub.User).filter(ub.User.mature_content != True). \
update({"denied_tags": conf.config_mature_content_tags}, synchronize_session=False)
session.commit()
#if bool(conf.config_default_show & constants.MATURE_CONTENT) and conf.config_denied_tags == "":
# conf.config_denied_tags = conf.config_mature_content_tags
# conf.save()
# session.query(ub.User).filter(ub.User.mature_content != True). \
# update({"denied_tags": conf.config_mature_content_tags}, synchronize_session=False)
# session.commit()
return conf
def get_flask_session_key(session):

View file

@ -31,6 +31,7 @@ from sqlalchemy import String, Integer, Boolean, TIMESTAMP, Float
from sqlalchemy.orm import relationship, sessionmaker, scoped_session
from sqlalchemy.orm.collections import InstrumentedList
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.exc import OperationalError
try:
# Compability with sqlalchemy 2.0
from sqlalchemy.orm import declarative_base
@ -331,7 +332,6 @@ class Books(Base):
has_cover = Column(Integer, default=0)
uuid = Column(String)
isbn = Column(String(collation='NOCASE'), default="")
# Iccn = Column(String(collation='NOCASE'), default="")
flags = Column(Integer, nullable=False, default=1)
authors = relationship('Authors', secondary=books_authors_link, backref='books')
@ -551,8 +551,11 @@ class CalibreDB():
config.db_configured = True
if not cc_classes:
cc = conn.execute("SELECT id, datatype FROM custom_columns")
cls.setup_db_cc_classes(cc)
try:
cc = conn.execute("SELECT id, datatype FROM custom_columns")
cls.setup_db_cc_classes(cc)
except OperationalError as e:
log.debug_or_exception(e)
cls.session_factory = scoped_session(sessionmaker(autocommit=False,
autoflush=True,

View file

@ -618,7 +618,7 @@ def upload_single_file(request, book, book_id):
# Queue uploader info
uploadText=_(u"File format %(ext)s added to %(book)s", ext=file_ext.upper(), book=book.title)
WorkerThread.add(current_user.nickname, TaskUpload(
WorkerThread.add(current_user.name, TaskUpload(
"<a href=\"" + url_for('web.show_book', book_id=book.id) + "\">" + uploadText + "</a>"))
return uploader.process(
@ -997,7 +997,7 @@ def upload():
if error:
flash(error, category="error")
uploadText=_(u"File %(file)s uploaded", file=title)
WorkerThread.add(current_user.nickname, TaskUpload(
WorkerThread.add(current_user.name, TaskUpload(
"<a href=\"" + url_for('web.show_book', book_id=book_id) + "\">" + uploadText + "</a>"))
if len(request.files.getlist("btn-upload")) < 2:
@ -1027,7 +1027,7 @@ def convert_bookformat(book_id):
log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to)
rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(),
book_format_to.upper(), current_user.nickname)
book_format_to.upper(), current_user.name)
if rtn is None:
flash(_(u"Book successfully queued for converting to %(book_format)s",

View file

@ -480,8 +480,8 @@ def reset_password(user_id):
password = generate_random_password()
existing_user.password = generate_password_hash(password)
ub.session.commit()
send_registration_mail(existing_user.email, existing_user.nickname, password, True)
return 1, existing_user.nickname
send_registration_mail(existing_user.email, existing_user.name, password, True)
return 1, existing_user.name
except Exception:
ub.session.rollback()
return 0, None
@ -731,7 +731,7 @@ def format_runtime(runtime):
def render_task_status(tasklist):
renderedtasklist = list()
for __, user, __, task in tasklist:
if user == current_user.nickname or current_user.role_admin():
if user == current_user.name or current_user.role_admin():
ret = {}
if task.start_time:
ret['starttime'] = format_datetime(task.start_time, format='short', locale=get_locale())

View file

@ -82,7 +82,7 @@ def formatdate_filter(val):
except AttributeError as e:
log.error('Babel error: %s, Current user locale: %s, Current User: %s', e,
current_user.locale,
current_user.nickname
current_user.name
)
return val

View file

@ -177,7 +177,7 @@ def HandleSyncRequest():
for book in changed_entries:
formats = [data.format for data in book.Books.data]
if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats:
helper.convert_book_format(book.Books.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.nickname)
helper.convert_book_format(book.Books.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name)
kobo_reading_state = get_or_create_reading_state(book.Books.id)
entitlement = {

View file

@ -155,7 +155,7 @@ def generate_auth_token(user_id):
for book in books:
formats = [data.format for data in book.data]
if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats:
helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.nickname)
helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name)
return render_title_template(
"generate_kobo_auth_url.html",

View file

@ -87,7 +87,7 @@ def register_user_with_oauth(user=None):
except NoResultFound:
# no found, return error
return
ub.session_commit("User {} with OAuth for provider {} registered".format(user.nickname, oauth_key))
ub.session_commit("User {} with OAuth for provider {} registered".format(user.name, oauth_key))
def logout_oauth_user():
@ -133,8 +133,8 @@ def bind_oauth_or_register(provider_id, provider_user_id, redirect_url, provider
# already bind with user, just login
if oauth_entry.user:
login_user(oauth_entry.user)
log.debug(u"You are now logged in as: '%s'", oauth_entry.user.nickname)
flash(_(u"you are now logged in as: '%(nickname)s'", nickname= oauth_entry.user.nickname),
log.debug(u"You are now logged in as: '%s'", oauth_entry.user.name)
flash(_(u"you are now logged in as: '%(nickname)s'", nickname= oauth_entry.user.name),
category="success")
return redirect(url_for('web.index'))
else:

View file

@ -428,7 +428,7 @@ def check_auth(username, password):
username = username.encode('windows-1252')
except UnicodeEncodeError:
username = username.encode('utf-8')
user = ub.session.query(ub.User).filter(func.lower(ub.User.nickname) ==
user = ub.session.query(ub.User).filter(func.lower(ub.User.name) ==
username.decode('utf-8').lower()).first()
if bool(user and check_password_hash(str(user.password), password)):
return True

View file

@ -126,11 +126,11 @@ def token_verified():
login_user(user)
ub.session.delete(auth_token)
ub.session_commit("User {} logged in via remotelogin, token deleted".format(user.nickname))
ub.session_commit("User {} logged in via remotelogin, token deleted".format(user.name))
data['status'] = 'success'
log.debug(u"Remote Login for userid %s succeded", user.id)
flash(_(u"you are now logged in as: '%(nickname)s'", nickname=user.nickname), category="success")
flash(_(u"you are now logged in as: '%(nickname)s'", nickname=user.name), category="success")
response = make_response(json.dumps(data, ensure_ascii=False))
response.headers["Content-Type"] = "application/json; charset=utf-8"

View file

@ -42,7 +42,7 @@ def get_sidebar_config(kwargs=None):
sidebar.append({"glyph": "glyphicon-fire", "text": _('Hot Books'), "link": 'web.books_list', "id": "hot",
"visibility": constants.SIDEBAR_HOT, 'public': True, "page": "hot",
"show_text": _('Show Hot Books'), "config_show": True})
sidebar.append({"glyph": "glyphicon-download", "text": _('Downloaded Books'), "link": 'web.books_list',
sidebar.append({"glyph": "glyphicon-download", "text": _('Downloaded Books'), "link": 'web.download_list',
"id": "download", "visibility": constants.SIDEBAR_DOWNLOAD, 'public': (not g.user.is_anonymous),
"page": "download", "show_text": _('Show Downloaded Books'),
"config_show": content})

View file

@ -26,7 +26,7 @@
{% for user in allUser %}
{% if not user.role_anonymous() or config.config_anonbrowse %}
<tr>
<td><a href="{{url_for('admin.edit_user', user_id=user.id)}}">{{user.nickname}}</a></td>
<td><a href="{{url_for('admin.edit_user', user_id=user.id)}}">{{user.name}}</a></td>
<td>{{user.email}}</td>
<td>{{user.kindle_mail}}</td>
<td>{{user.downloads.count()}}</td>

View file

@ -76,7 +76,7 @@
{% if g.user.role_admin() %}
<li><a id="top_admin" data-text="{{_('Settings')}}" href="{{url_for('admin.admin')}}"><span class="glyphicon glyphicon-dashboard"></span> <span class="hidden-sm">{{_('Admin')}}</span></a></li>
{% endif %}
<li><a id="top_user" data-text="{{_('Account')}}" href="{{url_for('web.profile')}}"><span class="glyphicon glyphicon-user"></span> <span class="hidden-sm">{{g.user.nickname}}</span></a></li>
<li><a id="top_user" data-text="{{_('Account')}}" href="{{url_for('web.profile')}}"><span class="glyphicon glyphicon-user"></span> <span class="hidden-sm">{{g.user.name}}</span></a></li>
{% if not g.user.is_anonymous %}
<li><a id="logout" href="{{url_for('web.logout')}}"><span class="glyphicon glyphicon-log-out"></span> <span class="hidden-sm">{{_('Logout')}}</span></a></li>
{% endif %}

View file

@ -5,8 +5,8 @@
<form method="POST" role="form">
{% if not config.config_register_email %}
<div class="form-group required">
<label for="nickname">{{_('Username')}}</label>
<input type="text" class="form-control" id="nickname" name="nickname" placeholder="{{_('Choose a username')}}" required>
<label for="name">{{_('Username')}}</label>
<input type="text" class="form-control" id="name" name="name" placeholder="{{_('Choose a username')}}" required>
</div>
{% endif %}
<div class="form-group required">

View file

@ -4,10 +4,10 @@
<h1>{{title}}</h1>
<form role="form" method="POST" autocomplete="off">
<div class="col-md-10 col-lg-8">
{% if new_user or ( g.user and content.nickname != "Guest" and g.user.role_admin() ) %}
{% if new_user or ( g.user and content.name != "Guest" and g.user.role_admin() ) %}
<div class="form-group required">
<label for="nickname">{{_('Username')}}</label>
<input type="text" class="form-control" name="nickname" id="nickname" value="{{ content.nickname if content.nickname != None }}" autocomplete="off">
<label for="name">{{_('Username')}}</label>
<input type="text" class="form-control" name="name" id="name" value="{{ content.name if content.name != None }}" autocomplete="off">
</div>
{% endif %}
<div class="form-group">

View file

@ -99,7 +99,7 @@
<th data-name="edit" data-buttontext="{{_('Edit User')}}" data-visible="{{visiblility.get('edit')}}" data-formatter="singleUserFormatter">{{_('Edit')}}</th>
<th data-name="state" data-field="state" data-checkbox="true" data-visible="{{visiblility.get('state')}}" data-sortable="true"></th>
<th data-name="id" data-field="id" id="id" data-visible="false" data-switchable="false"></th>
{{ user_table_row('nickname', _('Enter Username'), _('Username'), true) }}
{{ user_table_row('name', _('Enter Username'), _('Username'), true) }}
{{ user_table_row('email', _('Enter E-mail Address'), _('E-mail Address'), true) }}
{{ user_table_row('kindle_mail', _('Enter Kindle E-mail Address'), _('Kindle E-mail'), true) }}
{{ user_select_translations('locale', url_for('admin.table_get_locale'), _('Locale'), true) }}

View file

@ -162,7 +162,7 @@ class UserBase:
# ToDo: Error message
def __repr__(self):
return '<User %r>' % self.nickname
return '<User %r>' % self.name
# Baseclass for Users in Calibre-Web, settings which are depending on certain users are stored here. It is derived from
@ -172,7 +172,7 @@ class User(UserBase, Base):
__table_args__ = {'sqlite_autoincrement': True}
id = Column(Integer, primary_key=True)
nickname = Column(String(64), unique=True)
name = Column(String(64), unique=True)
email = Column(String(120), unique=True, default="")
role = Column(SmallInteger, default=constants.ROLE_USER)
password = Column(String)
@ -182,7 +182,6 @@ class User(UserBase, Base):
locale = Column(String(2), default="en")
sidebar_view = Column(Integer, default=1)
default_language = Column(String(3), default="all")
mature_content = Column(Boolean, default=True)
denied_tags = Column(String, default="")
allowed_tags = Column(String, default="")
denied_column_value = Column(String, default="")
@ -218,13 +217,12 @@ class Anonymous(AnonymousUserMixin, UserBase):
def loadSettings(self):
data = session.query(User).filter(User.role.op('&')(constants.ROLE_ANONYMOUS) == constants.ROLE_ANONYMOUS)\
.first() # type: User
self.nickname = data.nickname
self.name = data.name
self.role = data.role
self.id=data.id
self.sidebar_view = data.sidebar_view
self.default_language = data.default_language
self.locale = data.locale
# self.mature_content = data.mature_content
self.kindle_mail = data.kindle_mail
self.denied_tags = data.denied_tags
self.allowed_tags = data.allowed_tags
@ -488,7 +486,7 @@ def migrate_registration_table(engine, session):
def migrate_guest_password(engine, session):
try:
with engine.connect() as conn:
conn.execute(text("UPDATE user SET password='' where nickname = 'Guest' and password !=''"))
conn.execute(text("UPDATE user SET password='' where name = 'Guest' and password !=''"))
session.commit()
except exc.OperationalError:
print('Settings database is not writeable. Exiting...')
@ -594,37 +592,42 @@ def migrate_Database(session):
with engine.connect() as conn:
conn.execute("ALTER TABLE user ADD column `view_settings` VARCHAR(10) DEFAULT '{}'")
session.commit()
if session.query(User).filter(User.role.op('&')(constants.ROLE_ANONYMOUS) == constants.ROLE_ANONYMOUS).first() \
is None:
create_anonymous_user(session)
try:
# check if one table with autoincrement is existing (should be user table)
with engine.connect() as conn:
conn.execute(text("SELECT COUNT(*) FROM sqlite_sequence WHERE name='user'"))
# check if name is in User table instead of nickname
session.query(exists().where(User.name)).scalar()
except exc.OperationalError:
# Create new table user_id and copy contents of table user into it
with engine.connect() as conn:
conn.execute(text("CREATE TABLE user_id (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"
"nickname VARCHAR(64),"
"name VARCHAR(64),"
"email VARCHAR(120),"
"role SMALLINT,"
"password VARCHAR,"
"kindle_mail VARCHAR(120),"
"locale VARCHAR(2),"
"sidebar_view INTEGER,"
"default_language VARCHAR(3),"
"view_settings VARCHAR,"
"UNIQUE (nickname),"
"default_language VARCHAR(3),"
"denied_tags VARCHAR,"
"allowed_tags VARCHAR,"
"denied_column_value VARCHAR,"
"allowed_column_value VARCHAR,"
"view_settings JSON,"
"UNIQUE (name),"
"UNIQUE (email))"))
conn.execute(text("INSERT INTO user_id(id, nickname, email, role, password, kindle_mail,locale,"
"sidebar_view, default_language, view_settings) "
conn.execute(text("INSERT INTO user_id(id, name, email, role, password, kindle_mail,locale,"
"sidebar_view, default_language, denied_tags, allowed_tags, denied_column_value, "
"allowed_column_value, view_settings)"
"SELECT id, nickname, email, role, password, kindle_mail, locale,"
"sidebar_view, default_language FROM user"))
"sidebar_view, default_language, denied_tags, allowed_tags, denied_column_value, "
"allowed_column_value, view_settings FROM user"))
# delete old user table and rename new user_id table to user:
conn.execute(text("DROP TABLE user"))
conn.execute(text("ALTER TABLE user_id RENAME TO user"))
session.commit()
if session.query(User).filter(User.role.op('&')(constants.ROLE_ANONYMOUS) == constants.ROLE_ANONYMOUS).first() \
is None:
create_anonymous_user(session)
migrate_guest_password(engine, session)
@ -660,7 +663,7 @@ def delete_download(book_id):
# Generate user Guest (translated text), as anonymous user, no rights
def create_anonymous_user(session):
user = User()
user.nickname = "Guest"
user.name = "Guest"
user.email = 'no@email'
user.role = constants.ROLE_ANONYMOUS
user.password = ''
@ -675,7 +678,7 @@ def create_anonymous_user(session):
# Generate User admin with admin123 password, and access to everything
def create_admin_user(session):
user = User()
user.nickname = "admin"
user.name = "admin"
user.role = constants.ADMIN_USER_ROLES
user.sidebar_view = constants.ADMIN_USER_SIDEBAR
@ -711,7 +714,7 @@ def init_db(app_db_path):
if cli.user_credentials:
username, password = cli.user_credentials.split(':')
user = session.query(User).filter(func.lower(User.nickname) == username.lower()).first()
user = session.query(User).filter(func.lower(User.name) == username.lower()).first()
if user:
user.password = generate_password_hash(password)
if session_commit() == "":

View file

@ -41,7 +41,7 @@ def login_required_if_no_ano(func):
def _fetch_user_by_name(username):
return ub.session.query(ub.User).filter(func.lower(ub.User.nickname) == username.lower()).first()
return ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).first()
@lm.user_loader

View file

@ -371,7 +371,6 @@ def get_sort_function(sort, data):
def render_books_list(data, sort, book_id, page):
order = get_sort_function(sort, data)
if data == "rated":
return render_rated_books(page, book_id, order=order)
elif data == "discover":
@ -383,7 +382,7 @@ def render_books_list(data, sort, book_id, page):
elif data == "hot":
return render_hot_books(page)
elif data == "download":
return render_downloaded_books(page, order)
return render_downloaded_books(page, order, book_id)
elif data == "author":
return render_author_books(page, book_id, order)
elif data == "publisher":
@ -463,7 +462,8 @@ def render_hot_books(page):
abort(404)
def render_downloaded_books(page, order):
def render_downloaded_books(page, order, user_id):
user_id = int(user_id)
if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD):
if current_user.show_detail_random():
random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \
@ -474,19 +474,19 @@ def render_downloaded_books(page, order):
entries, __, pagination = calibre_db.fill_indexpage(page,
0,
db.Books,
ub.Downloads.user_id == int(current_user.id),
ub.Downloads.user_id == user_id,
order,
ub.Downloads, db.Books.id == ub.Downloads.book_id)
for book in entries:
if not calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \
.filter(db.Books.id == book.id).first():
ub.delete_download(book.id)
user = ub.session.query(ub.User).filter(ub.User.id == user_id).first()
return render_title_template('index.html',
random=random,
entries=entries,
pagination=pagination,
title=_(u"Downloaded books by %(user)s",user=current_user.nickname),
title=_(u"Downloaded books by %(user)s",user=user.name),
page="download")
else:
abort(404)
@ -814,6 +814,24 @@ def author_list():
else:
abort(404)
@web.route("/downloadlist")
@login_required_if_no_ano
def download_list():
if current_user.get_view_property('download', 'dir') == 'desc':
order = ub.User.name.desc() # ToDo
else:
order = ub.User.name.asc() # ToDo
if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin():
entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\
.join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all()
charlist = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \
.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \
.group_by(func.upper(func.substr(ub.User.name, 1, 1))).all()
return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
title=_(u"Downloads"), page="downloadlist", data="download")
else:
abort(404)
@web.route("/publisher")
@login_required_if_no_ano
@ -1320,7 +1338,7 @@ def send_to_kindle(book_id, book_format, convert):
flash(_(u"Please configure the SMTP mail settings first..."), category="error")
elif current_user.kindle_mail:
result = send_mail(book_id, book_format, convert, current_user.kindle_mail, config.config_calibre_dir,
current_user.nickname)
current_user.name)
if result is None:
flash(_(u"Book successfully queued for sending to %(kindlemail)s", kindlemail=current_user.kindle_mail),
category="success")
@ -1353,7 +1371,7 @@ def register():
if config.config_register_email:
nickname = to_save["email"]
else:
nickname = to_save.get('nickname', None)
nickname = to_save.get('name', None)
if not nickname or not to_save.get("email", None):
flash(_(u"Please fill out all fields!"), category="error")
return render_title_template('register.html', title=_(u"register"), page="register")
@ -1365,13 +1383,13 @@ def register():
log.warning('Registering failed for user "%s" e-mail address: %s', nickname, to_save["email"])
return render_title_template('register.html', title=_(u"register"), page="register")
existing_user = ub.session.query(ub.User).filter(func.lower(ub.User.nickname) == nickname
existing_user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == nickname
.lower()).first()
existing_email = ub.session.query(ub.User).filter(ub.User.email == to_save["email"].lower()).first()
if not existing_user and not existing_email:
content = ub.User()
if check_valid_domain(to_save["email"]):
content.nickname = nickname
content.name = nickname
content.email = to_save["email"]
password = generate_random_password()
content.password = generate_password_hash(password)
@ -1414,22 +1432,22 @@ def login():
flash(_(u"Cannot activate LDAP authentication"), category="error")
if request.method == "POST":
form = request.form.to_dict()
user = ub.session.query(ub.User).filter(func.lower(ub.User.nickname) == form['username'].strip().lower()) \
user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == form['username'].strip().lower()) \
.first()
if config.config_login_type == constants.LOGIN_LDAP and services.ldap and user and form['password'] != "":
login_result, error = services.ldap.bind_user(form['username'], form['password'])
if login_result:
login_user(user, remember=bool(form.get('remember_me')))
log.debug(u"You are now logged in as: '%s'", user.nickname)
flash(_(u"you are now logged in as: '%(nickname)s'", nickname=user.nickname),
log.debug(u"You are now logged in as: '%s'", user.name)
flash(_(u"you are now logged in as: '%(nickname)s'", nickname=user.name),
category="success")
return redirect_back(url_for("web.index"))
elif login_result is None and user and check_password_hash(str(user.password), form['password']) \
and user.nickname != "Guest":
and user.name != "Guest":
login_user(user, remember=bool(form.get('remember_me')))
log.info("Local Fallback Login as: '%s'", user.nickname)
log.info("Local Fallback Login as: '%s'", user.name)
flash(_(u"Fallback Login as: '%(nickname)s', LDAP Server not reachable, or user not known",
nickname=user.nickname),
nickname=user.name),
category="warning")
return redirect_back(url_for("web.index"))
elif login_result is None:
@ -1442,7 +1460,7 @@ def login():
else:
ipAdress = request.headers.get('X-Forwarded-For', request.remote_addr)
if 'forgot' in form and form['forgot'] == 'forgot':
if user != None and user.nickname != "Guest":
if user != None and user.name != "Guest":
ret, __ = reset_password(user.id)
if ret == 1:
flash(_(u"New Password was send to your email address"), category="info")
@ -1454,10 +1472,10 @@ def login():
flash(_(u"Please enter valid username to reset password"), category="error")
log.warning('Username missing for password reset IP-address: %s', ipAdress)
else:
if user and check_password_hash(str(user.password), form['password']) and user.nickname != "Guest":
if user and check_password_hash(str(user.password), form['password']) and user.name != "Guest":
login_user(user, remember=bool(form.get('remember_me')))
log.debug(u"You are now logged in as: '%s'", user.nickname)
flash(_(u"You are now logged in as: '%(nickname)s'", nickname=user.nickname), category="success")
log.debug(u"You are now logged in as: '%s'", user.name)
flash(_(u"You are now logged in as: '%(nickname)s'", nickname=user.name), category="success")
config.config_is_initial = False
return redirect_back(url_for("web.index"))
else:
@ -1495,16 +1513,16 @@ def change_profile_email(to_save, kobo_support, local_oauth_check, oauth_status)
if config.config_public_reg and not check_valid_domain(to_save["email"]):
flash(_(u"E-mail is not from valid domain"), category="error")
return render_title_template("user_edit.html", content=current_user,
title=_(u"%(name)s's profile", name=current_user.nickname), page="me",
title=_(u"%(name)s's profile", name=current_user.name), page="me",
kobo_support=kobo_support,
registered_oauth=local_oauth_check, oauth_status=oauth_status)
current_user.email = to_save["email"]
def change_profile_nickname(to_save, kobo_support, local_oauth_check, translations, languages):
if "nickname" in to_save and to_save["nickname"] != current_user.nickname:
# Query User nickname, if not existing, change
if not ub.session.query(ub.User).filter(ub.User.nickname == to_save["nickname"]).scalar():
current_user.nickname = to_save["nickname"]
if "name" in to_save and to_save["name"] != current_user.name:
# Query User name, if not existing, change
if not ub.session.query(ub.User).filter(ub.User.name == to_save["name"]).scalar():
current_user.name = to_save["name"]
else:
flash(_(u"This username is already taken"), category="error")
return render_title_template("user_edit.html",
@ -1514,7 +1532,7 @@ def change_profile_nickname(to_save, kobo_support, local_oauth_check, translatio
new_user=0, content=current_user,
registered_oauth=local_oauth_check,
title=_(u"Edit User %(nick)s",
nick=current_user.nickname),
nick=current_user.name),
page="edituser")
@ -1580,7 +1598,7 @@ def profile():
languages=languages,
content=current_user,
kobo_support=kobo_support,
title=_(u"%(name)s's profile", name=current_user.nickname),
title=_(u"%(name)s's profile", name=current_user.name),
page="me",
registered_oauth=local_oauth_check,
oauth_status=oauth_status)