nopaque/app/admin/views.py

70 lines
2.4 KiB
Python
Raw Normal View History

from app import db
from app.decorators import admin_required
from app.models import Role, User
2019-11-14 12:40:05 +00:00
from app.profile.background_functions import delete_user_
2019-09-23 14:25:26 +00:00
from flask import current_app, flash, redirect, render_template, url_for
from flask_login import login_required
2019-11-15 10:45:04 +00:00
from threading import Thread
from . import admin
2019-09-23 14:25:26 +00:00
from .forms import EditProfileAdminForm
2019-11-15 11:57:01 +00:00
from .tables import AdminUserItem, AdminUserTable
2019-11-15 11:51:53 +00:00
@admin.route('/')
@login_required
@admin_required
2019-11-15 11:51:53 +00:00
def index():
2019-11-15 10:45:04 +00:00
users = User.query.all()
2019-09-23 14:25:26 +00:00
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)
2019-11-15 11:51:53 +00:00
return render_template('admin/index.html.j2', table=table,
title='Administration tools')
2019-11-15 10:45:04 +00:00
@admin.route('/user/<int:user_id>')
@login_required
@admin_required
2019-11-15 10:45:04 +00:00
def user(user_id):
user = User.query.get_or_404(user_id)
2019-11-15 11:51:53 +00:00
return render_template('admin/user.html.j2', title='Administration: User',
2019-11-15 10:45:04 +00:00
user=user)
2019-11-15 10:45:04 +00:00
@admin.route('/user/<int:user_id>/delete')
@login_required
@admin_required
2019-11-15 10:45:04 +00:00
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!')
2019-11-15 11:51:53 +00:00
return redirect(url_for('admin.index'))
2019-11-15 10:45:04 +00:00
@admin.route('/user/<int:user_id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
2019-11-15 10:45:04 +00:00
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.')
2019-11-15 10:45:04 +00:00
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
2019-11-15 10:45:04 +00:00
return render_template('admin/edit_user.html.j2', form=form,
2019-11-15 11:51:53 +00:00
title='Administration: Edit user', user=user)