905086
2026-11-07 7fd2270570811c0d29f0d5d87d11bfc4612e0743
feat: 实现用户密码找回功能及相关配套功能
2 files added
18 files modified
522 ■■■■■ changed files
files/提示词.md 24 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/api/api_service.dart 8 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/pages/detail_page.dart 15 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/pages/favorites_page.dart 19 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/pages/library_page.dart 9 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/pages/login_page.dart 19 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/pages/store_page.dart 3 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/utils/util.dart 49 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/widgets/auth_dialogs.dart 78 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/widgets/download_manager.dart 69 ●●●●● patch | view | raw | blame | history
fluttergamebox/lib/widgets/game_card.dart 3 ●●●●● patch | view | raw | blame | history
server/admin/index.html 71 ●●●●● patch | view | raw | blame | history
server/config/db.go 2 ●●●●● patch | view | raw | blame | history
server/handlers/admin.go 22 ●●●●● patch | view | raw | blame | history
server/handlers/auth.go 13 ●●●●● patch | view | raw | blame | history
server/handlers/reset_request.go 82 ●●●●● patch | view | raw | blame | history
server/main.go 7 ●●●●● patch | view | raw | blame | history
server/middleware/auth.go 14 ●●●●● patch | view | raw | blame | history
server/models/models.go 11 ●●●●● patch | view | raw | blame | history
server/tmp_restart.ps1 4 ●●●●● patch | view | raw | blame | history
files/提示词.md
@@ -62,3 +62,27 @@
<br />
1. 打开客户端到登录页面以后,要在账号密码输入框中自动填充之前输入过的账号和密码。
2. 在找回密码中提交申请以后,弹出提示,联系管理员来重置密码。管理后台要有同意用户找回密码的功能。
3. 用户安装游戏的时候,要自动根据这个游戏的磁盘占用中设置磁盘大小与用户选择的保存的文件夹所在磁盘的剩余大小做对比。太大则弹出提示,让用户选择其他磁盘,并且不能下载。磁盘占用和游戏大小的单位统一设置为GB。只输入数字即可。不要再输入单位了。要做校验。
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
fluttergamebox/lib/api/api_service.dart
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:fluttergamebox/api/api_client.dart';
import 'package:fluttergamebox/utils/util.dart' show parseGb;
class Game {
  final int id;
@@ -89,6 +90,13 @@
  }
  String get platformLabel => platform == 'switch' ? 'Switch资源' : 'PC资源';
  /// 下载所需磁盘空间(GB):优先"磁盘占用",未设置时回退"游戏大小"
  double get requiredDiskGb {
    final install = parseGb(installSize);
    if (install > 0) return install;
    return parseGb(size);
  }
}
class GameFile {
fluttergamebox/lib/pages/detail_page.dart
@@ -72,6 +72,8 @@
    final res = await ApiService.toggleFavorite(widget.gameId);
    if (res['code'] == 0 && mounted) {
      setState(() => isFavorite = !isFavorite);
      // 通知收藏页实时刷新
      AppState.instance.bumpFavorites();
      _toast(res['msg'] ?? '操作成功');
    }
  }
@@ -80,6 +82,8 @@
    final res = await ApiService.addToLibrary(widget.gameId);
    if (res['code'] == 0 && mounted) {
      setState(() => inLibrary = true);
      // 通知资源库页实时刷新
      AppState.instance.bumpLibrary();
      _showConfirmDialog(
          '兑换成功!', '游戏已加入资源库,请在资源库页面查看。');
    } else if (mounted) {
@@ -111,11 +115,14 @@
    }
  }
  /// 下载前选择下载安装路径
  /// 下载前选择下载安装路径(并校验磁盘剩余空间)
  Future<bool> _askDownloadPath() async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => DownloadPathDialog(gameTitle: game!.title),
      builder: (context) => DownloadPathDialog(
        gameTitle: game!.title,
        requiredGb: game!.requiredDiskGb,
      ),
    );
    return result == true;
  }
@@ -487,8 +494,8 @@
            ],
          ),
          const SizedBox(height: 18),
          _infoRow('游戏大小', game!.size),
          _infoRow('磁盘占用', game!.installSize),
          _infoRow('游戏大小', sizeWithGb(game!.size)),
          _infoRow('磁盘占用', sizeWithGb(game!.installSize)),
          const Divider(color: AppColors.bgLighter, height: 28),
          _infoRow('操作系统', game!.osReq),
          _infoRow('CPU', game!.cpuReq),
fluttergamebox/lib/pages/favorites_page.dart
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:fluttergamebox/api/api_client.dart';
import 'package:fluttergamebox/api/api_service.dart';
import 'package:fluttergamebox/common/theme.dart';
import 'package:fluttergamebox/store/app_state.dart';
import 'package:fluttergamebox/widgets/game_card.dart';
class FavoritesPage extends StatefulWidget {
@@ -14,6 +14,7 @@
    with AutomaticKeepAliveClientMixin {
  List<Game> games = [];
  bool _loading = true;
  int _lastFavVersion = -1;
  @override
  bool get wantKeepAlive => true;
@@ -21,9 +22,25 @@
  @override
  void initState() {
    super.initState();
    _lastFavVersion = AppState.instance.favoritesVersion;
    // 详情页收藏/取消收藏时实时刷新
    AppState.instance.addListener(_onAppStateChange);
    _load();
  }
  @override
  void dispose() {
    AppState.instance.removeListener(_onAppStateChange);
    super.dispose();
  }
  void _onAppStateChange() {
    if (AppState.instance.favoritesVersion != _lastFavVersion) {
      _lastFavVersion = AppState.instance.favoritesVersion;
      _load();
    }
  }
  Future<void> _load() async {
    final g = await ApiService.favorites();
    if (!mounted) return;
fluttergamebox/lib/pages/library_page.dart
@@ -389,10 +389,13 @@
  /// 安装(未安装时):选择路径后下载并安装
  Future<void> _install() async {
    // 选择下载安装路径
    // 选择下载安装路径(并校验磁盘剩余空间)
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) => DownloadPathDialog(gameTitle: widget.game.title),
      builder: (context) => DownloadPathDialog(
        gameTitle: widget.game.title,
        requiredGb: widget.game.requiredDiskGb,
      ),
    );
    if (ok != true) return;
    try {
@@ -760,7 +763,7 @@
                          color: Colors.black.withOpacity(0.6),
                          borderRadius: BorderRadius.circular(3),
                        ),
                        child: Text(widget.game.size,
                        child: Text(sizeWithGb(widget.game.size),
                            style: const TextStyle(
                                color: Colors.white, fontSize: 11)),
                      ),
fluttergamebox/lib/pages/login_page.dart
@@ -3,6 +3,7 @@
import 'package:fluttergamebox/api/api_service.dart';
import 'package:fluttergamebox/common/theme.dart';
import 'package:fluttergamebox/store/app_state.dart';
import 'package:fluttergamebox/utils/util.dart';
import 'package:fluttergamebox/widgets/auth_dialogs.dart';
import 'package:fluttergamebox/widgets/window_controls.dart';
@@ -18,6 +19,22 @@
  bool _loading = false;
  String? _error;
  @override
  void initState() {
    super.initState();
    _fillSavedCredentials();
  }
  /// 自动填充上次登录成功的账号密码
  Future<void> _fillSavedCredentials() async {
    final (phone, pwd) = await AppPrefs.getLoginCredentials();
    if (!mounted || phone.isEmpty) return;
    setState(() {
      _phoneCtrl.text = phone;
      _pwdCtrl.text = pwd;
    });
  }
  // 检查更新提示
  void _checkUpdate() {
    showToast(context, '当前已是最新版本!');
@@ -39,6 +56,8 @@
      if (!mounted) return;
      if (res['code'] == 0) {
        await ApiClient.saveToken(res['data']['token']);
        // 登录成功后记住账号密码,下次打开自动填充
        await AppPrefs.saveLoginCredentials(phone, pwd);
        await AppState.instance.refreshUserInfo();
        // 公告改为进入首页时统一弹出(见 main_shell)
      } else {
fluttergamebox/lib/pages/store_page.dart
@@ -5,6 +5,7 @@
import 'package:fluttergamebox/api/api_service.dart';
import 'package:fluttergamebox/common/theme.dart';
import 'package:fluttergamebox/pages/main_shell.dart';
import 'package:fluttergamebox/utils/util.dart';
import 'package:fluttergamebox/widgets/game_card.dart';
class StorePage extends StatefulWidget {
@@ -169,7 +170,7 @@
                            children: [
                              _bannerTag(game.platformLabel),
                              const SizedBox(width: 8),
                              _bannerTag(game.size),
                              _bannerTag(sizeWithGb(game.size)),
                            ],
                          ),
                        ],
fluttergamebox/lib/utils/util.dart
@@ -21,7 +21,7 @@
  return fallback;
}
/// 本地持久化:下载/安装路径
/// 本地持久化:下载/安装路径 + 记住账号密码
class AppPrefs {
  static Future<String> getDownloadPath() async {
    final sp = await SharedPreferences.getInstance();
@@ -38,6 +38,53 @@
    await sp.setString('download_path', dl);
    await sp.setString('install_path', ins);
  }
  /// 保存登录账号密码(登录成功后调用,用于下次自动填充)
  static Future<void> saveLoginCredentials(String phone, String password) async {
    final sp = await SharedPreferences.getInstance();
    await sp.setString('saved_phone', phone);
    await sp.setString('saved_password', password);
  }
  /// 读取上次登录成功的账号密码
  static Future<(String, String)> getLoginCredentials() async {
    final sp = await SharedPreferences.getInstance();
    return (sp.getString('saved_phone') ?? '', sp.getString('saved_password') ?? '');
  }
}
/// 大小展示:统一 GB 单位(纯数字自动追加 GB,兼容旧的 "82 GB" 格式)
String sizeWithGb(String s) {
  if (s.isEmpty) return '';
  final t = s.trim();
  if (RegExp(r'[a-zA-Z]').hasMatch(t)) return t; // 已带单位(GB/MB等)
  return '$t GB';
}
/// 解析 GB 数值("232.6"、"232.6 GB" 均可;解析失败返回 0)
double parseGb(String s) {
  if (s.isEmpty) return 0;
  final m = RegExp(r'([\d.]+)').firstMatch(s);
  if (m == null) return 0;
  return double.tryParse(m.group(1)!) ?? 0;
}
/// 获取磁盘剩余空间(字节)。path 形如 "D:\xxx";返回 -1 表示无法获取(如 UNC 路径)
/// 注意:内部调用 PowerShell(启动较慢),请异步调用避免阻塞 UI
Future<double> getDiskFreeBytes(String path) async {
  try {
    if (path.length < 3 || path[1] != ':') return -1;
    final drive = path[0].toUpperCase();
    final r = await Process.run('powershell', [
      '-NoProfile',
      '-Command',
      '(Get-PSDrive -Name $drive).Free'
    ]);
    final v = double.tryParse(r.stdout.toString().trim());
    return v ?? -1;
  } catch (_) {
    return -1;
  }
}
/// 简单格式化字节数
fluttergamebox/lib/widgets/auth_dialogs.dart
@@ -85,6 +85,7 @@
    }
    setState(() => _loading = true);
    try {
      // 找回密码:提交重置申请(含期望的新密码),由管理员在后台同意后生效
      final res = isRegister
          ? await ApiService.register({
              'phone': phone.text.trim(),
@@ -102,8 +103,13 @@
            });
      if (!mounted) return;
      if (res['code'] == 0) {
        if (!isRegister) {
          // 弹出提示:联系管理员重置密码
          _showContactAdminDialog();
        } else {
        showToast(context, res['msg'] ?? '操作成功');
        Navigator.pop(context);
        }
      } else {
        showToast(context, res['msg'] ?? '操作失败', error: true);
        _refreshCaptcha();
@@ -115,6 +121,36 @@
    }
  }
  /// 找回密码申请提交成功后的提示弹窗
  void _showContactAdminDialog() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: const Color(0xFF1B1E2E),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        title: const Row(
          children: [
            Icon(Icons.info_outline, color: AppColors.yellow, size: 20),
            SizedBox(width: 8),
            Text('申请已提交', style: TextStyle(color: Colors.white, fontSize: 15)),
          ],
        ),
        content: const Text('找回密码申请已提交,请联系管理员重置密码!',
            style: TextStyle(color: AppColors.textGray, fontSize: 13, height: 1.6)),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(ctx); // 关闭提示
              Navigator.pop(context, true); // 关闭找回密码弹窗
            },
            child: const Text('知道了',
                style: TextStyle(color: AppColors.accent, fontSize: 13)),
          ),
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Dialog(
@@ -137,8 +173,8 @@
              ),
              child: Row(
                children: [
                  Icon(isRegister ? Icons.person_add_alt : Icons.lock_reset,
                      size: 16, color: AppColors.textGray),
                  Icon(isRegister ? Icons.person_add_alt : Icons.person_outline,
                      size: 16, color: Colors.white),
                  const SizedBox(width: 8),
                  Text(isRegister ? '注册账号' : '找回密码',
                      style: const TextStyle(
@@ -160,12 +196,12 @@
                  // Logo
                  ClipOval(
                    child: Image.asset('assets/images/logo.png',
                        width: 60,
                        height: 60,
                        width: 72,
                        height: 72,
                        fit: BoxFit.cover,
                        errorBuilder: (_, __, ___) => Container(
                            width: 60,
                            height: 60,
                            width: 72,
                            height: 72,
                            color: AppColors.pink,
                            child: const Center(
                                child: Text('99',
@@ -173,7 +209,7 @@
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold))))),
                  ),
                  const SizedBox(height: 24),
                  const SizedBox(height: 26),
                  _field(phone, '手机号', Icons.phone_iphone),
                  const SizedBox(height: 14),
                  _field(pwd, isRegister ? '密码' : '请输入新密码',
@@ -185,22 +221,19 @@
                      Icons.lock_outline,
                      obscure: true),
                  const SizedBox(height: 14),
                  // 验证码
                  Row(
                    children: [
                      Expanded(child: _field(captcha, '图形验证码', Icons.verified_outlined)),
                      const SizedBox(width: 10),
                      GestureDetector(
                  // 图形验证码(输入框内右侧嵌验证码图,点击图片可刷新)
                  _field(captcha, '图形验证码', Icons.verified_outlined,
                      suffix: GestureDetector(
                        onTap: _refreshCaptcha,
                        child: Container(
                          width: 110,
                          height: 46,
                          width: 90,
                          height: 32,
                          margin: const EdgeInsets.only(right: 7),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(6),
                            color: const Color(0xFF14161F),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 6, vertical: 4),
                          padding: const EdgeInsets.symmetric(horizontal: 4),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(3),
                            child: captchaImage ??
@@ -211,9 +244,7 @@
                                            fontSize: 11))),
                          ),
                        ),
                      ),
                    ],
                  ),
                      )),
                  const SizedBox(height: 24),
                  SizedBox(
                    width: double.infinity,
@@ -247,7 +278,7 @@
  }
  Widget _field(TextEditingController ctrl, String hint, IconData icon,
      {bool obscure = false}) {
      {bool obscure = false, Widget? suffix}) {
    return Container(
      height: 46,
      decoration: BoxDecoration(
@@ -273,6 +304,7 @@
              ),
            ),
          ),
          if (suffix != null) suffix,
        ],
      ),
    );
fluttergamebox/lib/widgets/download_manager.dart
@@ -556,9 +556,12 @@
}
/// 下载路径选择弹窗(详情页下载、资源库安装共用)
/// [requiredGb] 游戏所需磁盘空间(GB),所选下载目录所在磁盘剩余空间不足时禁止下载
class DownloadPathDialog extends StatefulWidget {
  final String gameTitle;
  const DownloadPathDialog({super.key, required this.gameTitle});
  final double requiredGb;
  const DownloadPathDialog(
      {super.key, required this.gameTitle, this.requiredGb = 0});
  @override
  State<DownloadPathDialog> createState() => _DownloadPathDialogState();
}
@@ -566,15 +569,26 @@
class _DownloadPathDialogState extends State<DownloadPathDialog> {
  final _dlCtrl = TextEditingController();
  final _insCtrl = TextEditingController();
  double _freeBytes = -2; // -2 未检查,-1 无法获取
  bool _checking = false;
  /// 需要的空间(字节):优先"磁盘占用",未设置时回退"游戏大小"
  double get _requiredBytes =>
      widget.requiredGb > 0 ? widget.requiredGb * 1024 * 1024 * 1024 : 0;
  bool get _insufficient =>
      _requiredBytes > 0 && _freeBytes >= 0 && _freeBytes < _requiredBytes;
  @override
  void initState() {
    super.initState();
    _dlCtrl.addListener(_checkFreeSpace);
    _load();
  }
  @override
  void dispose() {
    _dlCtrl.removeListener(_checkFreeSpace);
    _dlCtrl.dispose();
    _insCtrl.dispose();
    super.dispose();
@@ -587,6 +601,32 @@
      _dlCtrl.text = dl.isEmpty ? 'C:\\99GameBox\\99GameD' : dl;
      _insCtrl.text = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
    });
    _checkFreeSpace();
  }
  /// 检查下载目录所在磁盘的剩余空间
  void _checkFreeSpace() {
    final path = _dlCtrl.text.trim();
    if (path.isEmpty || _checking) return;
    _checking = true;
    getDiskFreeBytes(path).then((free) {
      _checking = false;
      if (!mounted) return;
      // 检查期间路径又变了则重新检查
      final cur = _dlCtrl.text.trim();
      if (cur != path) {
        _checkFreeSpace();
        return;
      }
      setState(() => _freeBytes = free);
    });
  }
  String get _freeInfo {
    if (_checking) return '正在检查磁盘剩余空间...';
    if (_freeBytes < 0) return '';
    final freeGb = _freeBytes / 1024 / 1024 / 1024;
    return '下载目录所在磁盘剩余空间:${freeGb.toStringAsFixed(1)} GB';
  }
  @override
@@ -623,6 +663,22 @@
            _pathRow('下载路径', _dlCtrl),
            const SizedBox(height: 12),
            _pathRow('安装路径', _insCtrl),
            // 磁盘剩余空间提示
            if (_requiredBytes > 0) ...[
              const SizedBox(height: 10),
              Text(
                _insufficient
                    ? '磁盘剩余空间不足(需要 ${widget.requiredGb.toStringAsFixed(1)} GB,'
                      '当前剩余 ${(_freeBytes / 1024 / 1024 / 1024).toStringAsFixed(1)} GB),'
                      '请选择其他磁盘!'
                    : _freeInfo,
                style: TextStyle(
                    color: _insufficient
                        ? AppColors.red
                        : AppColors.textGray,
                    fontSize: 12),
              ),
            ],
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
@@ -639,12 +695,19 @@
                ),
                const SizedBox(width: 12),
                ElevatedButton(
                  onPressed: () async {
                  // 磁盘空间不足时禁止下载
                  onPressed: (_checking || _insufficient)
                      ? null
                      : () async {
                    await AppPrefs.setPaths(_dlCtrl.text, _insCtrl.text);
                    if (context.mounted) Navigator.pop(context, true);
                          if (context.mounted) {
                            Navigator.pop(context, true);
                          }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.accent,
                    disabledBackgroundColor: AppColors.bgLighter,
                    disabledForegroundColor: AppColors.textDim,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(
                        horizontal: 22, vertical: 10),
fluttergamebox/lib/widgets/game_card.dart
@@ -3,6 +3,7 @@
import 'package:fluttergamebox/api/api_service.dart';
import 'package:fluttergamebox/common/theme.dart';
import 'package:fluttergamebox/pages/main_shell.dart';
import 'package:fluttergamebox/utils/util.dart';
/// 首页游戏卡片
class GameCard extends StatelessWidget {
@@ -90,7 +91,7 @@
                          color: Colors.black.withOpacity(0.6),
                          borderRadius: BorderRadius.circular(3),
                        ),
                        child: Text(game.size,
                        child: Text(sizeWithGb(game.size),
                            style: const TextStyle(
                                color: Colors.white, fontSize: 11)),
                      ),
server/admin/index.html
@@ -99,6 +99,7 @@
      <button data-tab="tools" onclick="switchTab('tools')">工具管理</button>
      <button data-tab="cats" onclick="switchTab('cats')">类别管理</button>
      <button data-tab="ann" onclick="switchTab('ann')">公告设置</button>
      <button data-tab="reset" onclick="switchTab('reset')">密码重置</button>
    </div>
    <button id="logoutBtn" onclick="logout()">退出登录</button>
  </div>
@@ -175,6 +176,16 @@
        <tbody id="toolTable"></tbody>
      </table>
    </div>
    <!-- 密码重置申请 -->
    <div id="tab-reset" class="panel hidden">
      <h2>找回密码申请</h2>
      <p style="color:#888;font-size:12px;margin-bottom:14px">用户在客户端"找回密码"中提交的申请。点击"同意并重置"为该用户设置新密码(可自定义,至少6位),重置后请将新密码告知用户。</p>
      <table>
        <thead><tr><th>ID</th><th>手机号</th><th>期望新密码</th><th>申请时间</th><th>状态</th><th>新密码</th><th>处理时间</th><th>操作</th></tr></thead>
        <tbody id="resetTable"></tbody>
      </table>
    </div>
  </div>
</div>
@@ -188,8 +199,8 @@
      <div class="form-row"><label>类别</label><select id="g_category"></select></div>
      <div class="form-row"><label>平台</label><select id="g_platform"><option value="pc">PC资源(单机)</option><option value="switch">Switch资源</option></select></div>
      <div class="form-row"><label>标签(逗号分隔,如: 即时战略,经典怀旧)</label><input id="g_tags"></div>
      <div class="form-row"><label>游戏大小(如 232.6 GB)</label><input id="g_size"></div>
      <div class="form-row"><label>安装磁盘占用(如 411.6 GB)</label><input id="g_install_size"></div>
      <div class="form-row"><label>游戏大小(GB,纯数字,如 232.6)*</label><input id="g_size" type="number" step="any" min="0" placeholder="232.6"></div>
      <div class="form-row"><label>磁盘占用(GB,纯数字,如 411.6)*</label><input id="g_install_size" type="number" step="any" min="0" placeholder="411.6"></div>
      <div class="form-row"><label>系统要求</label><input id="g_os" placeholder="Windows 10 64bit"></div>
      <div class="form-row"><label>CPU要求</label><input id="g_cpu" placeholder="Intel i5-4460"></div>
      <div class="form-row"><label>显卡要求</label><input id="g_gpu" placeholder="GTX 1060 6GB"></div>
@@ -298,11 +309,11 @@
function enterPanel() {
  document.getElementById('loginPage').style.display = 'none';
  document.getElementById('mainPage').style.display = 'flex';
  loadStats(); loadKeys(1); loadGames(); loadCategories(); loadAnnouncement(); loadTools();
  loadStats(); loadKeys(1); loadGames(); loadCategories(); loadAnnouncement(); loadTools(); loadResetRequests();
}
function switchTab(tab) {
  document.querySelectorAll('.nav-tabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
  ['keys','games','cats','ann','tools'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab));
  ['keys','games','cats','ann','tools','reset'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab));
}
async function loadStats() {
@@ -394,7 +405,7 @@
    <td>${g.title}</td>
    <td>${g.category_name || '-'}</td>
    <td><span class="tag ${g.platform==='pc'?'tag-blue':'tag-green'}">${g.platform==='pc'?'PC':'Switch'}</span></td>
    <td>${g.size}</td>
    <td>${/^[0-9.]+$/.test(g.size) ? g.size + ' GB' : (g.size || '-')}</td>
    <td>${g.download_count}</td>
    <td>
      <button class="btn btn-sm" onclick='showGameModal(${JSON.stringify(g).replace(/'/g,"&#39;")})'>修改</button>
@@ -407,7 +418,9 @@
  if (g) {
    document.getElementById('gameModalTitle').innerText = '修改游戏';
    g_id.value = g.id; g_title.value = g.title; g_tags.value = g.tags || '';
    g_size.value = g.size || ''; g_install_size.value = g.install_size || '';
    // 大小统一为 GB 纯数字,历史数据如 "232.6 GB" 去掉单位后填入
    g_size.value = (g.size || '').replace(/\s*GB$/i, '').trim();
    g_install_size.value = (g.install_size || '').replace(/\s*GB$/i, '').trim();
    g_os.value = g.os_req || ''; g_cpu.value = g.cpu_req || ''; g_gpu.value = g.gpu_req || ''; g_ram.value = g.ram_req || '';
    g_version_note.value = g.version_note || ''; g_description.value = g.description || '';
    g_launch_exe.value = g.launch_exe || '';
@@ -502,6 +515,11 @@
    `<div class="file-item"><span>${f.name}(${f.size})</span><button class="btn btn-sm btn-danger" onclick="editingFiles.splice(${i},1);renderFiles()">移除</button></div>`).join('');
}
async function saveGame() {
  // 大小/磁盘占用统一为 GB 纯数字,必须校验
  const sizeVal = g_size.value.trim();
  const installVal = g_install_size.value.trim();
  if (!/^\d+(\.\d+)?$/.test(sizeVal)) return toast('游戏大小请填写纯数字(单位GB),如 232.6', true);
  if (!/^\d+(\.\d+)?$/.test(installVal)) return toast('磁盘占用请填写纯数字(单位GB),如 411.6', true);
  const body = {
    id: parseInt(g_id.value) || 0,
    title: g_title.value.trim(), category_id: parseInt(g_category.value) || 0,
@@ -626,6 +644,47 @@
  loadTools();
}
/* ---------- 密码重置申请 ---------- */
async function loadResetRequests() {
  const res = await api('/admin/api/reset_requests');
  if (res.code !== 0) return;
  const rows = res.data.map(r => `<tr>
    <td>${r.id}</td>
    <td>${r.phone}</td>
    <td>${r.proposed_password ? `<code style="color:#4a92ff">${r.proposed_password}</code>` : '-'}</td>
    <td>${(r.created_at || '').replace('T', ' ').slice(0, 19)}</td>
    <td>${r.status === 1 ? '<span class="tag tag-green">已同意</span>' : '<span class="tag" style="background:#8a6d1a;color:#ffd700">待处理</span>'}</td>
    <td>${r.status === 1 ? `<code style="color:#ffd700">${r.new_password || '-'}</code>` : '-'}</td>
    <td>${r.handled_at ? (r.handled_at + '').replace('T', ' ').slice(0, 19) : '-'}</td>
    <td>
      ${r.status === 0 ? `<button class="btn btn-sm" onclick="approveReset(${r.id}, '${r.phone}', '${r.proposed_password || ''}')">同意并重置</button>` : ''}
      <button class="btn btn-sm btn-danger" onclick="deleteReset(${r.id})">删除</button>
    </td></tr>`).join('');
  document.getElementById('resetTable').innerHTML = rows || '<tr><td colspan="8" style="text-align:center;color:#666">暂无申请</td></tr>';
}
async function approveReset(id, phone, proposed) {
  const input = prompt(`同意 ${phone} 的找回密码申请。\n请输入要设置的新密码(至少6位,留空则使用用户填写的密码):`, proposed || '');
  if (input === null) return; // 取消
  const body = input.trim() ? {new_password: input.trim()} : {};
  const res = await api(`/admin/api/reset_requests/${id}/approve`, {method: 'POST', body});
  if (res.code !== 0) return toast(res.msg, true);
  const newPwd = res.data.new_password;
  const w = document.createElement('div');
  w.className = 'modal-mask';
  w.innerHTML = `<div class="modal" style="width:420px"><h3>重置成功</h3>
    <p style="margin:10px 0">手机号 <b style="color:#4a92ff">${phone}</b> 的密码已重置为:</p>
    <p style="font-size:20px;color:#ffd700;text-align:center;margin:14px 0">${newPwd}</p>
    <p style="color:#888;font-size:12px">请将新密码告知该用户。</p>
    <div style="text-align:right;margin-top:14px"><button class="btn" onclick="copyText('${newPwd}');this.closest('.modal-mask').remove();loadResetRequests()">复制并关闭</button></div></div>`;
  document.body.appendChild(w);
}
async function deleteReset(id) {
  if (!confirm('确定删除该申请?')) return;
  const res = await api(`/admin/api/reset_requests/${id}`, {method: 'DELETE'});
  toast(res.msg, res.code !== 0);
  loadResetRequests();
}
document.getElementById('adminPwd').addEventListener('keydown', e => { if (e.key === 'Enter') adminLogin(); });
if (token) enterPanel();
</script>
server/config/db.go
@@ -28,7 +28,7 @@
    err = DB.AutoMigrate(
        &models.Admin{}, &models.User{}, &models.Category{}, &models.Game{},
        &models.Tool{}, &models.MemberKey{}, &models.Favorite{},
        &models.LibraryItem{}, &models.Announcement{},
        &models.LibraryItem{}, &models.Announcement{}, &models.PasswordResetRequest{},
    )
    if err != nil {
        log.Fatalf("数据库迁移失败: %v", err)
server/handlers/admin.go
@@ -233,6 +233,19 @@
// ---------- 游戏管理 ----------
// isPlainNumber 校验非空纯数字(支持小数,如 232.6)
func isPlainNumber(s string) bool {
    if s == "" {
        return false
    }
    for _, r := range s {
        if (r < '0' || r > '9') && r != '.' {
            return false
        }
    }
    return true
}
func AdminListGames(c *gin.Context) {
    var games []models.Game
    config.DB.Order("id DESC").Find(&games)
@@ -250,6 +263,15 @@
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写游戏名称"})
        return
    }
    // 游戏大小/磁盘占用统一为GB,只允许纯数字(如 232.6)
    if !isPlainNumber(game.Size) {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "游戏大小请填写纯数字(单位GB),如 232.6"})
        return
    }
    if !isPlainNumber(game.InstallSize) {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "磁盘占用请填写纯数字(单位GB),如 411.6"})
        return
    }
    if game.Screenshots == "" {
        game.Screenshots = "[]"
    }
server/handlers/auth.go
@@ -112,7 +112,7 @@
    }})
}
// ResetPassword 找回密码
// ResetPassword 找回密码:提交重置申请(含期望的新密码),由管理员在后台同意后生效
func ResetPassword(c *gin.Context) {
    var req struct {
        Phone     string `json:"phone"`
@@ -142,9 +142,14 @@
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "两次输入的密码不一致"})
        return
    }
    hash, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
    config.DB.Model(&user).Update("password", string(hash))
    c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密码重置成功"})
    // 已有待处理的申请则更新期望密码,不重复创建
    var apply models.PasswordResetRequest
    if err := config.DB.Where("phone = ? AND status = ?", req.Phone, 0).First(&apply).Error; err != nil {
        config.DB.Create(&models.PasswordResetRequest{Phone: req.Phone, ProposedPwd: req.Password})
    } else {
        config.DB.Model(&apply).Update("proposed_pwd", req.Password)
    }
    c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "找回密码申请已提交,请联系管理员重置密码!"})
}
// GetUserInfo 当前用户信息(含会员状态)
server/handlers/reset_request.go
New file
@@ -0,0 +1,82 @@
package handlers
import (
    "math/rand"
    "net/http"
    "time"
    "gamebox-server/config"
    "gamebox-server/models"
    "github.com/gin-gonic/gin"
    "golang.org/x/crypto/bcrypt"
)
// ListResetRequests 密码重置申请列表(管理后台)
func ListResetRequests(c *gin.Context) {
    var list []models.PasswordResetRequest
    config.DB.Order("id DESC").Find(&list)
    c.JSON(http.StatusOK, gin.H{"code": 0, "data": list})
}
// ApproveResetRequest 同意找回密码申请:为该用户设置新密码并标记已处理
// body 可传 new_password(至少6位),不传则自动生成
func ApproveResetRequest(c *gin.Context) {
    id := c.Param("id")
    var req struct {
        NewPassword string `json:"new_password"`
    }
    _ = c.ShouldBindJSON(&req)
    var apply models.PasswordResetRequest
    if err := config.DB.First(&apply, id).Error; err != nil {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "申请不存在"})
        return
    }
    if apply.Status != 0 {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该申请已处理过"})
        return
    }
    var user models.User
    if err := config.DB.Where("phone = ?", apply.Phone).First(&user).Error; err != nil {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "用户不存在"})
        return
    }
    // 新密码优先级:管理员指定 > 用户申请时填写的期望密码 > 随机生成
    newPwd := req.NewPassword
    if len(newPwd) < 6 {
        newPwd = apply.ProposedPwd
    }
    if len(newPwd) < 6 {
        newPwd = randomPassword()
    }
    hash, _ := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)
    if err := config.DB.Model(&user).Update("password", string(hash)).Error; err != nil {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "重置失败"})
        return
    }
    now := time.Now()
    config.DB.Model(&apply).Updates(map[string]interface{}{
        "status":     1,
        "new_pwd":    newPwd,
        "handled_at": &now,
    })
    c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已同意并重置密码",
        "data": gin.H{"phone": apply.Phone, "new_password": newPwd}})
}
// DeleteResetRequest 删除申请
func DeleteResetRequest(c *gin.Context) {
    config.DB.Delete(&models.PasswordResetRequest{}, c.Param("id"))
    c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
}
// randomPassword 生成8位随机密码(字母+数字)
func randomPassword() string {
    const charset = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789"
    b := make([]byte, 8)
    for i := range b {
        b[i] = charset[rand.Intn(len(charset))]
    }
    return string(b)
}
server/main.go
@@ -41,7 +41,7 @@
        api.GET("/tools", handlers.GetTools)
        api.GET("/tools/:id/download", handlers.ToolDownloadInfo)
        api.GET("/announcements", handlers.GetAnnouncements)
        api.GET("/games/:id", handlers.GetGameDetail) // 支持可选登录
        api.GET("/games/:id", middleware.OptionalUserAuth(), handlers.GetGameDetail) // 支持可选登录:登录后返回收藏/资源库状态
        auth := api.Group("", middleware.UserAuth())
        {
@@ -89,6 +89,11 @@
            a.POST("/announcement", handlers.AdminSaveAnnouncement)
            a.POST("/upload", handlers.UploadFile)
            // 密码重置申请管理
            a.GET("/reset_requests", handlers.ListResetRequests)
            a.POST("/reset_requests/:id/approve", handlers.ApproveResetRequest)
            a.DELETE("/reset_requests/:id", handlers.DeleteResetRequest)
        }
    }
server/middleware/auth.go
@@ -28,6 +28,20 @@
    }
}
// OptionalUserAuth 可选用户认证:带合法token时注入user_id,无token/无效token不拦截
// 用于游戏详情等公开接口,登录后可返回 is_favorite / in_library 等用户维度信息
func OptionalUserAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
        token := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
        if token != "" {
            if claims, err := utils.ParseToken(token); err == nil && claims.Role == "user" {
                c.Set("user_id", claims.UserID)
            }
        }
        c.Next()
    }
}
// AdminAuth 管理员JWT认证
func AdminAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
server/models/models.go
@@ -107,3 +107,14 @@
    Content   string    `gorm:"type:text" json:"content"`
    CreatedAt time.Time `json:"created_at"`
}
// PasswordResetRequest 用户找回密码申请(客户端提交,管理员在后台同意并重置)
type PasswordResetRequest struct {
    ID         uint       `gorm:"primaryKey" json:"id"`
    Phone      string     `gorm:"size:20;index" json:"phone"`
    ProposedPwd string     `gorm:"size:20" json:"proposed_password"` // 用户期望的新密码(管理员同意后默认采用)
    Status     int        `gorm:"default:0" json:"status"` // 0待处理 1已同意
    NewPwd     string     `gorm:"size:20" json:"new_password"` // 同意时实际设置的新密码(明文,便于管理员告知用户)
    HandledAt  *time.Time `json:"handled_at"`
    CreatedAt  time.Time  `json:"created_at"`
}
server/tmp_restart.ps1
New file
@@ -0,0 +1,4 @@
Get-NetTCPConnection -LocalPort 8080 -State Listen -ErrorAction SilentlyContinue | ForEach-Object {
  Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue
}
Write-Host "stopped"