from app import db from app.decorators import admin_required from app.models import Role, User from app.profile.background_functions import delete_user_ from flask import current_app, flash, redirect, render_template, url_for from flask_login import login_required from threading import Thread from . import admin from .forms import EditProfileAdminForm from .tables import AdminUserItem, AdminUserTable @admin.route('/') @login_required @admin_required def index(): users = User.query.all() items = [AdminUserItem(u.username, u.email, u.role_id, u.confirmed, u.id) for u in users] # Convert table object to html string table = AdminUserTable(items).__html__() # Add class "list" to tbody element. Needed for "List.js" table = table.replace('tbody', 'tbody class="list"', 1) return render_template('admin/index.html.j2', table=table, title='Administration tools') @admin.route('/user/') @login_required @admin_required def user(user_id): user = User.query.get_or_404(user_id) return render_template('admin/user.html.j2', title='Administration: User', user=user) @admin.route('/user//delete') @login_required @admin_required def delete_user(user_id): user = User.query.get_or_404(user_id) thread = Thread(target=delete_user_, args=(current_app._get_current_object(), user.id)) thread.start() flash('User has been deleted!') return redirect(url_for('admin.index')) @admin.route('/user//edit', methods=['GET', 'POST']) @login_required @admin_required def edit_user(user_id): user = User.query.get_or_404(user_id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): 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.add(user) db.session.commit() flash('The profile has been updated.') return redirect(url_for('admin.edit_user', user_id=user.id)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id return render_template('admin/edit_user.html.j2', form=form, title='Administration: Edit user', user=user)