from flask import render_template, request, redirect, url_for, flash from flask_login import login_required, current_user from scripts.models import db, User, Device def init_user_routes(app): def is_admin_user(): """允许统计员/管理员或名称为 Admin 的用户管理账号""" return current_user.role in ['统计员', '管理员', 'admin'] or current_user.name == 'Admin' @app.route('/users', methods=['GET']) @login_required def user_list(): if not is_admin_user(): app.logger.warning(f'未授权访问:用户 {current_user.name} 尝试访问用户管理') flash('您没有权限访问此页面') return redirect(url_for('dashboard')) users = User.query.order_by(User.name).all() branch_options = [b[0] for b in db.session.query(Device.branch).distinct().all() if b[0]] role_options = ['统计员', '装维员', '管理员'] return render_template( 'users.html', users=users, branch_options=branch_options, role_options=role_options ) @app.route('/users/', methods=['POST']) @login_required def update_user(phone): if not is_admin_user(): app.logger.warning(f'未授权访问:用户 {current_user.name} 尝试修改用户 {phone}') flash('您没有权限执行此操作') return redirect(url_for('dashboard')) user = User.query.filter_by(phone=phone).first() if not user: flash('用户不存在') return redirect(url_for('user_list')) new_branch = request.form.get('branch', '').strip() new_role = request.form.get('role', '').strip() if new_role and new_role not in ['统计员', '装维员', '管理员']: flash('角色不合法') return redirect(url_for('user_list')) user.branch = new_branch user.role = new_role db.session.commit() app.logger.info(f'用户信息已更新: {user.name}({user.phone}) -> branch={user.branch}, role={user.role}') flash('用户信息已更新') return redirect(url_for('user_list'))