from flask import flash, redirect, render_template, url_for from flask_login import login_required from . import bp from .forms import EditGeneralSettingsAdminForm from .. import db from ..decorators import admin_required from ..models import Role, User from ..settings import tasks as settings_tasks @bp.before_request @login_required @admin_required def before_request(): ''' Ensures that the routes in this package can be visited only by users with administrator privileges (login_required and admin_required). ''' pass @bp.route('/') def index(): return redirect(url_for('.users')) @bp.route('/users') def users(): dict_users = {user.id: user.to_dict(backrefs=True, relationships=False) for user in User.query.all()} return render_template( 'admin/users.html.j2', title='Users', dict_users=dict_users) @bp.route('/users/') def user(user_id): user = User.query.get_or_404(user_id) return render_template('admin/user.html.j2', title='User', user=user) @bp.route('/users//delete') def delete_user(user_id): settings_tasks.delete_user(user_id) flash('User has been marked for deletion!') return redirect(url_for('.users')) @bp.route('/users//edit', methods=['GET', 'POST']) # noqa def edit_user(user_id): user = User.query.get_or_404(user_id) form = EditGeneralSettingsAdminForm(user) if form.validate_on_submit(): user.setting_dark_mode = form.dark_mode.data user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) db.session.commit() flash('Settings have been updated.') return redirect(url_for('.edit_user', user_id=user.id)) form.confirmed.data = user.confirmed form.dark_mode.data = user.setting_dark_mode form.email.data = user.email form.role.data = user.role_id form.username.data = user.username return render_template( 'admin/edit_user.html.j2', form=form, title='Edit user', user=user)