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 = getattr(g, 'user', None)
# user = None # user = None
if user is not None and hasattr(user, "locale"): 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 return user.locale
preferred = list() 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) all_user = all_user.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS)
total_count = all_user.count() total_count = all_user.count()
if search: 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.kindle_mail).ilike("%" + search + "%"),
func.lower(ub.User.email).ilike("%" + search + "%")))\ func.lower(ub.User.email).ilike("%" + search + "%")))\
.offset(off).limit(limit).all() .offset(off).limit(limit).all()
@ -332,9 +332,9 @@ def edit_list_user(param):
else: else:
return "" return ""
for user in users: for user in users:
if param =='nickname': if param =='name':
if not ub.session.query(ub.User).filter(ub.User.nickname == vals['value']).scalar(): if not ub.session.query(ub.User).filter(ub.User.name == vals['value']).scalar():
user.nickname = vals['value'] user.name = vals['value']
else: else:
log.error(u"This username is already taken") log.error(u"This username is already taken")
return _(u"This username is already taken"), 400 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 = usr.list_allowed_tags()
elementlist[int(element['id'][1:])] = element['Element'] elementlist[int(element['id'][1:])] = element['Element']
usr.allowed_tags = ','.join(elementlist) 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 res_type == 3: # CColumn per user
if isinstance(user_id, int): if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() 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 = usr.list_allowed_column_values()
elementlist[int(element['id'][1:])] = element['Element'] elementlist[int(element['id'][1:])] = element['Element']
usr.allowed_column_value = ','.join(elementlist) 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 element['id'].startswith('d'):
if res_type == 0: # Tags as template if res_type == 0: # Tags as template
elementlist = config.list_denied_tags() elementlist = config.list_denied_tags()
@ -561,7 +561,7 @@ def edit_restriction(res_type, user_id):
elementlist = usr.list_denied_tags() elementlist = usr.list_denied_tags()
elementlist[int(element['id'][1:])] = element['Element'] elementlist[int(element['id'][1:])] = element['Element']
usr.denied_tags = ','.join(elementlist) 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 res_type == 3: # CColumn per user
if isinstance(user_id, int): if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() 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 = usr.list_denied_column_values()
elementlist[int(element['id'][1:])] = element['Element'] elementlist[int(element['id'][1:])] = element['Element']
usr.denied_column_value = ','.join(elementlist) 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 "" return ""
@ -617,10 +617,10 @@ def add_restriction(res_type, user_id):
usr = current_user usr = current_user
if 'submit_allow' in element: if 'submit_allow' in element:
usr.allowed_tags = restriction_addition(element, usr.list_allowed_tags) 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: elif 'submit_deny' in element:
usr.denied_tags = restriction_addition(element, usr.list_denied_tags) 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 res_type == 3: # CustomC per user
if isinstance(user_id, int): if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() 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 usr = current_user
if 'submit_allow' in element: if 'submit_allow' in element:
usr.allowed_column_value = restriction_addition(element, usr.list_allowed_column_values) 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)) usr.list_allowed_column_values))
elif 'submit_deny' in element: elif 'submit_deny' in element:
usr.denied_column_value = restriction_addition(element, usr.list_denied_column_values) 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)) usr.list_denied_column_values))
return "" return ""
@ -664,10 +664,10 @@ def delete_restriction(res_type, user_id):
usr = current_user usr = current_user
if element['id'].startswith('a'): if element['id'].startswith('a'):
usr.allowed_tags = restriction_deletion(element, usr.list_allowed_tags) 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'): elif element['id'].startswith('d'):
usr.denied_tags = restriction_deletion(element, usr.list_denied_tags) 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 elif res_type == 3: # Columns per user
if isinstance(user_id, int): if isinstance(user_id, int):
usr = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() 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 usr = current_user
if element['id'].startswith('a'): if element['id'].startswith('a'):
usr.allowed_column_value = restriction_deletion(element, usr.list_allowed_column_values) 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)) usr.list_allowed_column_values))
elif element['id'].startswith('d'): elif element['id'].startswith('d'):
usr.denied_column_value = restriction_deletion(element, usr.list_denied_column_values) 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)) usr.list_denied_column_values))
return "" return ""
@ -1156,18 +1156,18 @@ def _handle_new_user(to_save, content, languages, translations, kobo_support):
content.role = constants.selected_roles(to_save) 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") flash(_(u"Please fill out all fields!"), category="error")
return render_title_template("user_edit.html", new_user=1, content=content, translations=translations, return render_title_template("user_edit.html", new_user=1, content=content, translations=translations,
registered_oauth=oauth_check, kobo_support=kobo_support, registered_oauth=oauth_check, kobo_support=kobo_support,
title=_(u"Add new user")) title=_(u"Add new user"))
content.password = generate_password_hash(to_save["password"]) 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() .first()
existing_email = ub.session.query(ub.User).filter(ub.User.email == to_save["email"].lower()) \ existing_email = ub.session.query(ub.User).filter(ub.User.email == to_save["email"].lower()) \
.first() .first()
if not existing_user and not existing_email: 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"]): if config.config_public_reg and not check_valid_domain(to_save["email"]):
flash(_(u"E-mail is not from valid domain"), category="error") 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, 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: else:
content.email = to_save["email"] content.email = to_save["email"]
else: 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, return render_title_template("user_edit.html", new_user=1, content=content, translations=translations,
languages=languages, title=_(u"Add new user"), page="newuser", languages=languages, title=_(u"Add new user"), page="newuser",
kobo_support=kobo_support, registered_oauth=oauth_check) 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 content.denied_column_value = config.config_denied_column_value
ub.session.add(content) ub.session.add(content)
ub.session.commit() 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')) return redirect(url_for('admin.admin'))
except IntegrityError: except IntegrityError:
ub.session.rollback() 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: except OperationalError:
ub.session.rollback() ub.session.rollback()
flash(_(u"Settings DB is not Writeable"), category="error") 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.User.id != content.id).count():
ub.session.query(ub.User).filter(ub.User.id == content.id).delete() ub.session.query(ub.User).filter(ub.User.id == content.id).delete()
ub.session_commit() 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')) return redirect(url_for('admin.admin'))
else: 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')) 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:
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')) return redirect(url_for('admin.admin'))
if "password" in to_save and to_save["password"]: 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, new_user=0,
content=content, content=content,
registered_oauth=oauth_check, registered_oauth=oauth_check,
title=_(u"Edit User %(nick)s", nick=content.nickname), page="edituser") title=_(u"Edit User %(nick)s", nick=content.name), page="edituser")
if "nickname" in to_save and to_save["nickname"] != content.nickname: if "name" in to_save and to_save["name"] != content.name:
# Query User nickname, if not existing, change # Query User name, if not existing, change
if not ub.session.query(ub.User).filter(ub.User.nickname == to_save["nickname"]).scalar(): if not ub.session.query(ub.User).filter(ub.User.name == to_save["name"]).scalar():
content.nickname = to_save["nickname"] content.name = to_save["name"]
else: else:
flash(_(u"This username is already taken"), category="error") flash(_(u"This username is already taken"), category="error")
return render_title_template("user_edit.html", 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, new_user=0, content=content,
registered_oauth=oauth_check, registered_oauth=oauth_check,
kobo_support=kobo_support, kobo_support=kobo_support,
title=_(u"Edit User %(nick)s", nick=content.nickname), title=_(u"Edit User %(nick)s", nick=content.name),
page="edituser") page="edituser")
if "kindle_mail" in to_save and to_save["kindle_mail"] != content.kindle_mail: if "kindle_mail" in to_save and to_save["kindle_mail"] != content.kindle_mail:
content.kindle_mail = to_save["kindle_mail"] content.kindle_mail = to_save["kindle_mail"]
try: try:
ub.session_commit() 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: except IntegrityError:
ub.session.rollback() ub.session.rollback()
flash(_(u"An unknown error occured."), category="error") flash(_(u"An unknown error occured."), category="error")
@ -1337,7 +1337,7 @@ def update_mailsettings():
if to_save.get("test"): if to_save.get("test"):
if current_user.email: 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: if result is None:
flash(_(u"Test e-mail successfully send to %(kindlemail)s", kindlemail=current_user.email), flash(_(u"Test e-mail successfully send to %(kindlemail)s", kindlemail=current_user.email),
category="success") category="success")
@ -1356,7 +1356,7 @@ def update_mailsettings():
@admin_required @admin_required
def edit_user(user_id): def edit_user(user_id):
content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User 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") flash(_(u"User not found"), category="error")
return redirect(url_for('admin.admin')) return redirect(url_for('admin.admin'))
languages = calibre_db.speaking_language() languages = calibre_db.speaking_language()
@ -1373,7 +1373,7 @@ def edit_user(user_id):
registered_oauth=oauth_check, registered_oauth=oauth_check,
mail_configured=config.get_mail_server_configured(), mail_configured=config.get_mail_server_configured(),
kobo_support=kobo_support, 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>") @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') username = user_data[user_login_field][0].decode('utf-8')
# check for duplicate username # 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(func.lower(ub.User.name) == username.lower()).first():
# if ub.session.query(ub.User).filter(ub.User.nickname == username).first(): # if ub.session.query(ub.User).filter(ub.User.name == username).first():
log.warning("LDAP User %s Already in Database", user_data) log.warning("LDAP User %s Already in Database", user_data)
return 0, None 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) log.warning("LDAP Email %s Already in Database", user_data)
return 0, None return 0, None
content = ub.User() content = ub.User()
content.nickname = username content.name = username
content.password = '' # dummy password which will be replaced by ldap one content.password = '' # dummy password which will be replaced by ldap one
content.email = useremail content.email = useremail
content.kindle_mail = kindlemail content.kindle_mail = kindlemail

View file

@ -430,12 +430,12 @@ def load_configuration(session):
session.commit() session.commit()
conf = _ConfigSQL(session) conf = _ConfigSQL(session)
# Migrate from global restrictions to user based restrictions # Migrate from global restrictions to user based restrictions
if bool(conf.config_default_show & constants.MATURE_CONTENT) and conf.config_denied_tags == "": #if bool(conf.config_default_show & constants.MATURE_CONTENT) and conf.config_denied_tags == "":
conf.config_denied_tags = conf.config_mature_content_tags # conf.config_denied_tags = conf.config_mature_content_tags
conf.save() # conf.save()
session.query(ub.User).filter(ub.User.mature_content != True). \ # session.query(ub.User).filter(ub.User.mature_content != True). \
update({"denied_tags": conf.config_mature_content_tags}, synchronize_session=False) # update({"denied_tags": conf.config_mature_content_tags}, synchronize_session=False)
session.commit() # session.commit()
return conf return conf
def get_flask_session_key(session): 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 import relationship, sessionmaker, scoped_session
from sqlalchemy.orm.collections import InstrumentedList from sqlalchemy.orm.collections import InstrumentedList
from sqlalchemy.ext.declarative import DeclarativeMeta from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.exc import OperationalError
try: try:
# Compability with sqlalchemy 2.0 # Compability with sqlalchemy 2.0
from sqlalchemy.orm import declarative_base from sqlalchemy.orm import declarative_base
@ -331,7 +332,6 @@ class Books(Base):
has_cover = Column(Integer, default=0) has_cover = Column(Integer, default=0)
uuid = Column(String) uuid = Column(String)
isbn = Column(String(collation='NOCASE'), default="") isbn = Column(String(collation='NOCASE'), default="")
# Iccn = Column(String(collation='NOCASE'), default="")
flags = Column(Integer, nullable=False, default=1) flags = Column(Integer, nullable=False, default=1)
authors = relationship('Authors', secondary=books_authors_link, backref='books') authors = relationship('Authors', secondary=books_authors_link, backref='books')
@ -551,8 +551,11 @@ class CalibreDB():
config.db_configured = True config.db_configured = True
if not cc_classes: if not cc_classes:
cc = conn.execute("SELECT id, datatype FROM custom_columns") try:
cls.setup_db_cc_classes(cc) 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, cls.session_factory = scoped_session(sessionmaker(autocommit=False,
autoflush=True, autoflush=True,

View file

@ -618,7 +618,7 @@ def upload_single_file(request, book, book_id):
# Queue uploader info # Queue uploader info
uploadText=_(u"File format %(ext)s added to %(book)s", ext=file_ext.upper(), book=book.title) 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>")) "<a href=\"" + url_for('web.show_book', book_id=book.id) + "\">" + uploadText + "</a>"))
return uploader.process( return uploader.process(
@ -997,7 +997,7 @@ def upload():
if error: if error:
flash(error, category="error") flash(error, category="error")
uploadText=_(u"File %(file)s uploaded", file=title) 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>")) "<a href=\"" + url_for('web.show_book', book_id=book_id) + "\">" + uploadText + "</a>"))
if len(request.files.getlist("btn-upload")) < 2: 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) 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(), 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: if rtn is None:
flash(_(u"Book successfully queued for converting to %(book_format)s", 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() password = generate_random_password()
existing_user.password = generate_password_hash(password) existing_user.password = generate_password_hash(password)
ub.session.commit() ub.session.commit()
send_registration_mail(existing_user.email, existing_user.nickname, password, True) send_registration_mail(existing_user.email, existing_user.name, password, True)
return 1, existing_user.nickname return 1, existing_user.name
except Exception: except Exception:
ub.session.rollback() ub.session.rollback()
return 0, None return 0, None
@ -731,7 +731,7 @@ def format_runtime(runtime):
def render_task_status(tasklist): def render_task_status(tasklist):
renderedtasklist = list() renderedtasklist = list()
for __, user, __, task in tasklist: 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 = {} ret = {}
if task.start_time: if task.start_time:
ret['starttime'] = format_datetime(task.start_time, format='short', locale=get_locale()) 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: except AttributeError as e:
log.error('Babel error: %s, Current user locale: %s, Current User: %s', e, log.error('Babel error: %s, Current user locale: %s, Current User: %s', e,
current_user.locale, current_user.locale,
current_user.nickname current_user.name
) )
return val return val

View file

@ -177,7 +177,7 @@ def HandleSyncRequest():
for book in changed_entries: for book in changed_entries:
formats = [data.format for data in book.Books.data] formats = [data.format for data in book.Books.data]
if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats: 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) kobo_reading_state = get_or_create_reading_state(book.Books.id)
entitlement = { entitlement = {

View file

@ -155,7 +155,7 @@ def generate_auth_token(user_id):
for book in books: for book in books:
formats = [data.format for data in book.data] formats = [data.format for data in book.data]
if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats: 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( return render_title_template(
"generate_kobo_auth_url.html", "generate_kobo_auth_url.html",

View file

@ -87,7 +87,7 @@ def register_user_with_oauth(user=None):
except NoResultFound: except NoResultFound:
# no found, return error # no found, return error
return 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(): 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 # already bind with user, just login
if oauth_entry.user: if oauth_entry.user:
login_user(oauth_entry.user) login_user(oauth_entry.user)
log.debug(u"You are now logged in as: '%s'", 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.nickname), flash(_(u"you are now logged in as: '%(nickname)s'", nickname= oauth_entry.user.name),
category="success") category="success")
return redirect(url_for('web.index')) return redirect(url_for('web.index'))
else: else:

View file

@ -428,7 +428,7 @@ def check_auth(username, password):
username = username.encode('windows-1252') username = username.encode('windows-1252')
except UnicodeEncodeError: except UnicodeEncodeError:
username = username.encode('utf-8') 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() username.decode('utf-8').lower()).first()
if bool(user and check_password_hash(str(user.password), password)): if bool(user and check_password_hash(str(user.password), password)):
return True return True

View file

@ -126,11 +126,11 @@ def token_verified():
login_user(user) login_user(user)
ub.session.delete(auth_token) 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' data['status'] = 'success'
log.debug(u"Remote Login for userid %s succeded", user.id) 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 = make_response(json.dumps(data, ensure_ascii=False))
response.headers["Content-Type"] = "application/json; charset=utf-8" 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", sidebar.append({"glyph": "glyphicon-fire", "text": _('Hot Books'), "link": 'web.books_list', "id": "hot",
"visibility": constants.SIDEBAR_HOT, 'public': True, "page": "hot", "visibility": constants.SIDEBAR_HOT, 'public': True, "page": "hot",
"show_text": _('Show Hot Books'), "config_show": True}) "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), "id": "download", "visibility": constants.SIDEBAR_DOWNLOAD, 'public': (not g.user.is_anonymous),
"page": "download", "show_text": _('Show Downloaded Books'), "page": "download", "show_text": _('Show Downloaded Books'),
"config_show": content}) "config_show": content})

View file

@ -26,7 +26,7 @@
{% for user in allUser %} {% for user in allUser %}
{% if not user.role_anonymous() or config.config_anonbrowse %} {% if not user.role_anonymous() or config.config_anonbrowse %}
<tr> <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.email}}</td>
<td>{{user.kindle_mail}}</td> <td>{{user.kindle_mail}}</td>
<td>{{user.downloads.count()}}</td> <td>{{user.downloads.count()}}</td>

View file

@ -76,7 +76,7 @@
{% if g.user.role_admin() %} {% 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> <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 %} {% 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 %} {% 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> <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 %} {% endif %}

View file

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

View file

@ -4,10 +4,10 @@
<h1>{{title}}</h1> <h1>{{title}}</h1>
<form role="form" method="POST" autocomplete="off"> <form role="form" method="POST" autocomplete="off">
<div class="col-md-10 col-lg-8"> <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"> <div class="form-group required">
<label for="nickname">{{_('Username')}}</label> <label for="name">{{_('Username')}}</label>
<input type="text" class="form-control" name="nickname" id="nickname" value="{{ content.nickname if content.nickname != None }}" autocomplete="off"> <input type="text" class="form-control" name="name" id="name" value="{{ content.name if content.name != None }}" autocomplete="off">
</div> </div>
{% endif %} {% endif %}
<div class="form-group"> <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="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="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> <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('email', _('Enter E-mail Address'), _('E-mail Address'), true) }}
{{ user_table_row('kindle_mail', _('Enter Kindle E-mail Address'), _('Kindle E-mail'), 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) }} {{ user_select_translations('locale', url_for('admin.table_get_locale'), _('Locale'), true) }}

View file

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

View file

@ -41,7 +41,7 @@ def login_required_if_no_ano(func):
def _fetch_user_by_name(username): 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 @lm.user_loader

View file

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