""" Servboard - 服务导航仪表盘 """ import os from functools import wraps from flask import Flask, request, redirect, session, g, flash, render_template_string, render_template, url_for, jsonify from werkzeug.security import generate_password_hash, check_password_hash from flask_wtf.csrf import CSRFProtect from models import db, User, Service, init_app app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production') app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'dashboard.db')}" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['WTF_CSRF_ENABLED'] = False # Disable CSRF for simplicity # Initialize CSRF protection csrf = CSRFProtect(app) # Initialize database (must be done after CSRF) init_app(app) # Ensure data and icons directory exists os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'icons'), exist_ok=True) def login_required(f): """登录验证装饰器.""" @wraps(f) def decorated_function(*args, **kwargs): if 'user_id' not in session: flash('请先登录后再访问。', 'warning') return redirect(url_for('login')) return f(*args, **kwargs) return decorated_function def admin_required(f): """管理员权限装饰器(已废弃).""" return f def get_host_from_request(): """从请求头中提取 Host,优先使用 X-Forwarded-Host 用于反向代理场景.""" host = request.headers.get('X-Forwarded-Host') if not host: host = request.host # 移除端口号 import re host = re.sub(r':\d+$', '', host) return host @app.route('/') def home(): """仪表盘主页,显示所有已启用的服务.""" if 'user_id' not in session: return redirect(url_for('login')) current_user = db.session.get(User, session['user_id']) services = Service.query.filter_by(enabled=True).order_by(Service.name).all() return render_template('pages/index.html', services=services, current_user=current_user) @app.route('/login', methods=['GET', 'POST']) def login(): """登录页面.""" if 'user_id' in session: return redirect(url_for('home')) if request.method == 'POST': username = request.form.get('username', '').strip() password = request.form.get('password', '') if not username or not password: flash('请输入用户名和密码。', 'error') return render_template('pages/login.html') user = User.query.filter_by(username=username).first() if user and user.check_password(password): session['user_id'] = user.id session['username'] = user.username flash(f'欢迎回来,{username}!', 'success') return redirect(url_for('home')) flash('用户名或密码错误。', 'error') return render_template('pages/login.html') @app.route('/logout') def logout(): """退出登录并清空会话.""" session.clear() flash('您已退出登录。', 'info') return redirect(url_for('login')) @app.route('/profile', methods=['GET', 'POST']) @login_required def profile(): """用户密码设置页面.""" if request.method == 'POST': old_password = request.form.get('old_password', '').strip() new_password = request.form.get('new_password', '').strip() confirm_password = request.form.get('confirm_password', '').strip() user = User.query.get(session['user_id']) # 验证旧密码 if not user.check_password(old_password): flash('当前密码错误。', 'error') return render_template('pages/profile.html') # 检查新密码是否为空 if not new_password: flash('请输入新密码。', 'error') return render_template('pages/profile.html') # 验证新密码长度 if len(new_password) < 6: flash('密码长度至少为 6 位。', 'error') return render_template('pages/profile.html') # 验证确认密码 if new_password != confirm_password: flash('两次输入的新密码不一致。', 'error') return render_template('pages/profile.html') # 更新密码 user.password_hash = generate_password_hash(new_password) db.session.commit() # 修改密码后清空会话,需要重新登录 session.clear() return redirect(url_for('login')) current_user = db.session.get(User, session['user_id']) return render_template('pages/profile.html', current_user=current_user) # ============ 已移除的管理员功能 ============ # 移除的接口:/manage-users, /manage-services, /api/users/*, /api/services/* @app.route('/health') def health(): """健康检查端点.""" return {'status': 'ok'}, 200 @app.route('/icons/') def serve_icon(filename): """提供 data/icons 目录下图片的访问.""" import os from flask import send_from_directory icons_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'icons') return send_from_directory(icons_dir, filename) # Initialize database on application startup with app.app_context(): db.create_all() # 检查并迁移旧数据库(移除 role 列,添加 path 列) from sqlalchemy import text try: # 检查 role 列是否存在,如果存在则删除 result = db.session.execute(text("PRAGMA table_info(users)")) columns = [row[1] for row in result] if 'role' in columns: db.session.execute(text("ALTER TABLE users DROP COLUMN role")) # 检查 services 表是否存在 path 列,如果不存在则添加 result = db.session.execute(text("PRAGMA table_info(services)")) columns = [row[1] for row in result] if 'path' not in columns: db.session.execute(text("ALTER TABLE services ADD COLUMN path TEXT")) db.session.commit() except Exception: db.session.rollback() # 创建默认管理员用户如果用户表为空 if User.query.count() == 0: admin = User(username='admin', password='changeme') admin.created_at = db.func.datetime('now') db.session.add(admin) db.session.commit() if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)