nopaque/app/admin/views.py

76 lines
3.2 KiB
Python
Raw Normal View History

from flask import (abort, current_app, flash, redirect, request,
render_template, url_for, send_from_directory)
from flask_login import current_user, login_required
from .forms import EditProfileAdminForm
from ..models import Corpus, User, Role, Job
from ..tables import AdminUserTable, AdminUserItem
from . import admin
from ..decorators import admin_required
from .. import db
import threading
from app.utils import background_delete_user
@admin.route('/overview', methods=['GET', 'POST'])
@login_required
@admin_required
def for_admins_only():
users = User.query.order_by(User.username).all()
items = [AdminUserItem(u.username, u.email, u.role_id, u.confirmed, u.id) for u in users]
table = AdminUserTable(items).__html__() # converts table object to html string
table = table.replace('tbody', 'tbody class="list"', 1) # add class list to tbody element. Needed by list.js
return render_template('admin/admin.html.j2', title='Administration tools',
table=table)
@admin.route('/overview/admin_user_page/<int:user_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def admin_user_page(user_id):
selected_user = User.query.filter_by(id=user_id).first()
title = 'Administration of user {} with ID: {}'.format(selected_user.username,
selected_user.id)
registration_date = selected_user.registration_date.strftime('%A, %e %B %H:%M')
return render_template('admin/admin_user_page.html.j2',
title=title, selected_user=selected_user,
registration_date=registration_date)
@admin.route('/overview/admin_user_page/delete/<int:user_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def admin_delete_user(user_id):
delete_thread = threading.Thread(target=background_delete_user,
args=(current_app._get_current_object(),
user_id))
delete_thread.start()
flash('User {} has been deleted!'.format(user_id))
return redirect(url_for('admin.for_admins_only'))
@admin.route('/overview/admin_user_page/edit_profile_admin/<int:user_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(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_profile_admin', 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
title = 'Edit profile of user {} with ID {}'.format(user.username,
user.id)
return render_template('admin/edit_profile_admin.html.j2',
form=form,
user=user,
title=title)