返回列表 发布新帖

个人理念结合deepseek+个人整改后做的html版网页密码管理系统

3599 1
小K网牛逼 发表于 2026-4-23 00:00:17 | 查看全部 阅读模式 <

马上注册,结交更多好友,享用更多功能,让你轻松玩转小K网。

您需要 登录 才可以下载或查看,没有账号?立即注册 微信登录

×
因公司销售助理对接客户后,客户提供的ERP系统过多,导致销售助理在网页密码管理上一直都用的excel来实现管理,最近公司销售助理主管找我让编写一个HTML版网页密码管理系统。
为了尽快让销售助理使用上HTML版的网页密码管理系统,我根据个人理念结合deepseek加个人整改后将网页密码管理系统做出来转交给了销售助理使用。
主要功能:
员工门户:
用于销售助理平时点击添加后客户的ERP的网页进入客户的ERP系统,并有对应的ERP登陆用户名,如忘记密码,可点右上角验证显示密码来查看对应ERP系统的用户密码。
管理员后台:
主要用于添加客户的ERP网页和用户名及密码,其中为了防止密码泄露,特管理员后台需要输入密码进入。管理员后台还增加了导入及导出excel功能、员工门户的验证显示的密码修改、管理员后台密码修改。
管理员后台密码默认: admin123,员工查看密码默认: employee2024
支持 Excel (.xls, .xlsx) 导入导出
所有数据持久化存储在浏览器 SQLite 数据库中,刷新页面不会丢失
可点击「备份数据库」下载完整数据库文件


个人理念结合deepseek+个人整改后做的html版网页密码管理系统

个人理念结合deepseek+个人整改后做的html版网页密码管理系统

个人理念结合deepseek+个人整改后做的html版网页密码管理系统

个人理念结合deepseek+个人整改后做的html版网页密码管理系统

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  6.     <title>企业密码管理系统 | SQLite持久化存储</title>
  7.     <!-- SQL.js (WebAssembly 版 SQLite) -->
  8.     <script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/sql-wasm.js"></script>
  9.     <!-- SheetJS (XLS 导入导出) -->
  10.     <script src="https://cdn.sheetjs.com/xlsx-0.20.2/package/dist/xlsx.full.min.js"></script>
  11.     <!-- CryptoJS 用于 SHA-256 哈希加密 -->
  12.     <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js"></script>
  13.     <style>
  14.         * { margin: 0; padding: 0; box-sizing: border-box; }
  15.         body { font-family: 'Segoe UI', system-ui; background: #f1f5f9; padding: 24px 20px; }
  16.         .app-container { max-width: 1400px; margin: 0 auto; }
  17.         .tab-bar { display: flex; gap: 12px; margin-bottom: 28px; background: white; padding: 8px 20px; border-radius: 60px; width: fit-content; }
  18.         .tab-btn { border: none; background: transparent; padding: 12px 28px; font-size: 1rem; font-weight: 600; border-radius: 40px; cursor: pointer; color: #475569; }
  19.         .tab-btn.active { background: #1e3c72; color: white; }
  20.         .card { background: white; border-radius: 28px; border: 1px solid #e9edf2; overflow: hidden; margin-bottom: 24px; }
  21.         .card-header { padding: 18px 24px; border-bottom: 1px solid #edf2f7; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; }
  22.         .card-header h2 { font-size: 1.4rem; font-weight: 600; }
  23.         .btn { border: none; background: #f1f5f9; padding: 8px 20px; border-radius: 40px; font-weight: 500; cursor: pointer; transition: 0.2s; }
  24.         .btn-primary { background: #1e3c72; color: white; }
  25.         .btn-primary:hover { background: #0f2b4f; }
  26.         .btn-outline { background: white; border: 1px solid #cbd5e1; }
  27.         .btn-success { background: #10b981; color: white; }
  28.         .btn-warning { background: #f59e0b; color: white; }
  29.         .btn-danger { background: #fff0f0; color: #b91c1c; }
  30.         table { width: 100%; border-collapse: collapse; }
  31.         th, td { text-align: left; padding: 14px 16px; border-bottom: 1px solid #ecf3fa; vertical-align: middle; }
  32.         th { background: #fafcff; font-weight: 600; }
  33.         .url-link { color: #2563eb; text-decoration: none; font-weight: 500; }
  34.         .url-link:hover { text-decoration: underline; }
  35.         .password-masked { font-family: monospace; background: #f1f5f9; padding: 4px 12px; border-radius: 30px; display: inline-block; }
  36.         .password-plain { font-family: monospace; background: #eef2ff; padding: 4px 12px; border-radius: 30px; display: inline-block; }
  37.         .input-group { margin-bottom: 16px; display: flex; flex-direction: column; gap: 6px; }
  38.         input { padding: 10px 14px; border-radius: 20px; border: 1px solid #cfdfed; font-family: inherit; }
  39.         input:focus { outline: none; border-color: #1e3c72; }
  40.         .modal { display: none; position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(0,0,0,0.5); align-items: center; justify-content: center; z-index: 1000; }
  41.         .modal-content { background: white; max-width: 500px; width: 90%; border-radius: 32px; padding: 28px; }
  42.         .toast-msg { position: fixed; bottom: 24px; right: 24px; background: #1f2937; color: white; padding: 10px 20px; border-radius: 40px; opacity: 0; transition: 0.2s; z-index: 1100; pointer-events: none; }
  43.         .toast-msg.show { opacity: 1; }
  44.         .empty-row td { text-align: center; padding: 48px; color: #6c757d; }
  45.         .hidden { display: none; }
  46.         .flex-btns { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
  47.         .admin-auth-overlay { position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(0,0,0,0.75); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; z-index: 2000; }
  48.         .admin-auth-box { background: white; border-radius: 32px; padding: 32px; width: 90%; max-width: 400px; text-align: center; }
  49.         .admin-auth-box input { width: 100%; margin: 12px 0; }
  50.         .error-text { color: #b91c1c; font-size: 0.8rem; margin-top: 8px; }
  51.         .verify-panel { display: flex; gap: 8px; align-items: center; }
  52.         .file-input-label { background: #f1f5f9; border: 1px solid #cbd5e1; padding: 8px 18px; border-radius: 40px; cursor: pointer; font-size: 0.85rem; }
  53.         input[type="file"] { display: none; }
  54.         .settings-group { background: #f8fafc; border-radius: 20px; padding: 16px 20px; margin: 12px 24px 20px 24px; border: 1px solid #e2e8f0; }
  55.         .settings-group h4 { margin-bottom: 12px; color: #1e293b; }
  56.         .settings-row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-bottom: 8px; }
  57.         .db-status { font-size: 0.7rem; color: #10b981; margin-left: 12px; }
  58.         .export-db-btn { background: #6b7280; color: white; }
  59.         .export-db-btn:hover { background: #4b5563; }
  60.     </style>
  61. </head>
  62. <body>
  63. <div class="app-container">
  64.     <div class="tab-bar">
  65.         <button class="tab-btn active" data-tab="employee">&#128101; 员工门户 (首页)</button>
  66.         <button class="tab-btn" data-tab="admin">&#128272; 管理员后台</button>
  67.     </div>
  68.     <!-- 员工门户界面 -->
  69.     <div id="employeePanel" class="tab-panel">
  70.         <div class="card">
  71.             <div class="card-header">
  72.                 <h2>&#127760; 员工门户 · 快捷访问</h2>
  73.                 <div class="verify-panel">
  74.                     <input type="password" id="empViewPwd" placeholder="请输入查看密码" style="width: 180px;" autocomplete="off">
  75.                     <button class="btn btn-primary" id="verifyEmpBtn">&#128275; 验证并显示密码</button>
  76.                 </div>
  77.             </div>
  78.             <div style="overflow-x: auto;">
  79.                 <table id="employeeTable">
  80.                     <thead><tr><th>网址链接 (可点击)</th><th>用户名</th><th>密码</th></thead>
  81.                     <tbody id="employeeTableBody">
  82.                         <tr class="empty-row"><td colspan="3">&#128274; 请输入查看密码以显示密码明文</td></tr>
  83.                     </tbody>
  84.                 </table>
  85.             </div>
  86.             <div style="padding: 12px 20px; border-top:1px solid #edf2f7; font-size:0.75rem; color:#475569;">
  87.                 &#128272; 员工查看密码默认: <strong>employee2024</strong> — 输入后点击验证,密码列将显示明文。所有数据持久化存储于SQLite数据库,刷新页面数据不丢失。
  88.             </div>
  89.         </div>
  90.     </div>
  91.     <!-- 管理员后台界面 -->
  92.     <div id="adminPanel" class="tab-panel hidden">
  93.         <div class="card">
  94.             <div class="card-header">
  95.                 <h2>&#128203; 凭证管理 · 后台 (密码明文)</h2>
  96.                 <div class="flex-btns">
  97.                     <button class="btn btn-primary" id="openAddCredBtn">+ 新增凭证</button>
  98.                     <button class="btn btn-success" id="exportExcelBtn">&#128206; 导出为 XLS</button>
  99.                     <label class="file-input-label" for="importExcelInput">&#128194; 导入 XLS 文件</label>
  100.                     <input type="file" id="importExcelInput" accept=".xls, .xlsx">
  101.                     <button class="btn export-db-btn" id="exportDbBtn">&#128190; 备份数据库</button>
  102.                 </div>
  103.             </div>
  104.             <div style="overflow-x: auto;">
  105.                 <table id="adminTable">
  106.                     <thead><tr><th>网站/系统</th><th>用户名</th><th>密码 (明文)</th><th>操作</th></tr></thead>
  107.                     <tbody id="adminTableBody"><tr class="empty-row"><td colspan="4">请先验证管理员权限</td></tr></tbody>
  108.                 </table>
  109.             </div>
  110.             
  111.             <div class="settings-group">
  112.                 <h4>&#9881;&#65039; 系统安全设置 (数据持久化存储于SQLite)</h4>
  113.                 <div class="settings-row">
  114.                     <span style="width: 140px;">&#128272; 员工查看密码:</span>
  115.                     <input type="password" id="newEmployeePwd" placeholder="新员工查看密码" style="width: 180px;" autocomplete="off">
  116.                     <button class="btn btn-warning" id="updateEmployeePwdBtn">修改员工密码</button>
  117.                     <span style="font-size: 0.7rem; color: #64748b;">SHA-256加密存储·修改后立即生效</span>
  118.                 </div>
  119.                 <div class="settings-row">
  120.                     <span style="width: 140px;">&#128273; 管理员登录密码:</span>
  121.                     <input type="password" id="newAdminPwd" placeholder="新管理员密码" style="width: 180px;" autocomplete="off">
  122.                     <button class="btn btn-warning" id="updateAdminPwdBtn">修改管理员密码</button>
  123.                     <span style="font-size: 0.7rem; color: #64748b;">SHA-256加密存储·修改后立即生效</span>
  124.                 </div>
  125.                 <div class="settings-row">
  126.                     <span style="width: 140px;"></span>
  127.                     <span style="font-size: 0.7rem; color: #94a3b8;">&#9888;&#65039; 修改密码后自动保存到数据库,刷新页面不会丢失!</span>
  128.                 </div>
  129.             </div>
  130.             
  131.             <div class="card-header" style="border-top:1px solid #edf2f7;"><h2>&#128204; 说明</h2></div>
  132.             <div style="padding: 16px 24px; color: #334155;">
  133.                 &#8226; 管理员后台密码默认: <strong>admin123</strong>,员工查看密码默认: <strong>employee2024</strong><br>
  134.                 &#8226; 支持 Excel (.xls, .xlsx) 导入导出<br>
  135.                 &#8226; 所有数据持久化存储在浏览器 SQLite 数据库中,刷新页面不会丢失<br>
  136.                 &#8226; 可点击「备份数据库」下载完整数据库文件
  137.             </div>
  138.         </div>
  139.     </div>
  140. </div>
  141. <!-- 模态框 -->
  142. <div id="credModal" class="modal">
  143.     <div class="modal-content">
  144.         <h3 id="modalTitle">&#10133; 添加凭证</h3>
  145.         <div class="input-group"><label>&#128279; 网址 (URL)</label><input type="text" id="credUrl" placeholder="https://..."></div>
  146.         <div class="input-group"><label>&#128100; 用户名</label><input type="text" id="credUsername" placeholder="账号"></div>
  147.         <div class="input-group"><label>&#128273; 密码</label><input type="text" id="credPassword" placeholder="密码"></div>
  148.         <input type="hidden" id="editId" value="">
  149.         <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
  150.             <button class="btn btn-outline" id="closeModalBtn">取消</button>
  151.             <button class="btn btn-primary" id="saveCredBtn">保存</button>
  152.         </div>
  153.     </div>
  154. </div>
  155. <div id="toastMsg" class="toast-msg">&#10004;&#65039; 操作成功</div>
  156. <script>
  157.     // ==================== SHA-256 哈希 ====================
  158.     function hashPassword(plain) { return CryptoJS.SHA256(plain).toString(); }
  159.      
  160.     // ==================== 全局变量 ====================
  161.     let db = null;
  162.     let SQL = null;
  163.     let employeePasswordVisible = false;
  164.     let adminAuthenticated = false;
  165.     let adminAuthActive = false;
  166.     let currentEmployeePwdHash = "";
  167.     let currentAdminPwdHash = "";
  168.      
  169.     // localStorage 存储键名
  170.     const DB_STORAGE_KEY = 'password_manager_sqlite_db';
  171.      
  172.     // ==================== 数据库持久化操作 ====================
  173.     // 保存数据库到 localStorage
  174.     function saveDatabaseToLocalStorage() {
  175.         if (!db) return;
  176.         try {
  177.             const exportedData = db.export();
  178.             const buffer = new Uint8Array(exportedData);
  179.             const base64 = btoa(String.fromCharCode.apply(null, buffer));
  180.             localStorage.setItem(DB_STORAGE_KEY, base64);
  181.             console.log("数据库已自动保存到 localStorage");
  182.         } catch(e) {
  183.             console.error("保存数据库失败:", e);
  184.         }
  185.     }
  186.      
  187.     // 从 localStorage 加载数据库
  188.     async function loadDatabaseFromLocalStorage() {
  189.         const saved = localStorage.getItem(DB_STORAGE_KEY);
  190.         if (saved) {
  191.             try {
  192.                 const binary = atob(saved);
  193.                 const buffer = new Uint8Array(binary.length);
  194.                 for (let i = 0; i < binary.length; i++) {
  195.                     buffer[i] = binary.charCodeAt(i);
  196.                 }
  197.                 db = new SQL.Database(buffer);
  198.                 console.log("从 localStorage 恢复数据库成功");
  199.                 return true;
  200.             } catch(e) {
  201.                 console.error("恢复数据库失败:", e);
  202.                 return false;
  203.             }
  204.         }
  205.         return false;
  206.     }
  207.      
  208.     // 创建新数据库并初始化表结构
  209.     function createNewDatabase() {
  210.         db = new SQL.Database();
  211.          
  212.         // 创建凭证表
  213.         db.run(`CREATE TABLE IF NOT EXISTS credentials (
  214.             id INTEGER PRIMARY KEY AUTOINCREMENT,
  215.             url TEXT NOT NULL UNIQUE,
  216.             username TEXT NOT NULL,
  217.             password TEXT NOT NULL,
  218.             created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  219.         )`);
  220.          
  221.         // 创建系统配置表
  222.         db.run(`CREATE TABLE IF NOT EXISTS system_config (
  223.             key TEXT PRIMARY KEY,
  224.             value TEXT NOT NULL
  225.         )`);
  226.          
  227.         // 检查凭证表是否有数据
  228.         let credCount = db.exec("SELECT COUNT(*) as cnt FROM credentials");
  229.         if(credCount.length && credCount[0].values.length && credCount[0].values[0][0] === 0) {
  230.             const demo = [
  231.                 ['https://mail.company.com', 'zhang.san@company.com', 'Mail@2024Secure'],
  232.                 ['https://hrsystem.company.com', 'hr_admin', 'HrP@ss#2024'],
  233.                 ['https://gitlab.company.com', 'dev_lihua', 'GitLab!7890'],
  234.                 ['https://jira.company.com', 'project_manager', 'Jira@2025']
  235.             ];
  236.             const stmt = db.prepare("INSERT INTO credentials (url, username, password) VALUES (?, ?, ?)");
  237.             for(let row of demo) stmt.run(row);
  238.             stmt.free();
  239.         }
  240.          
  241.         // 初始化员工查看密码哈希
  242.         let empHashRes = db.exec("SELECT value FROM system_config WHERE key = 'employee_view_password_hash'");
  243.         if(!empHashRes.length || !empHashRes[0].values.length) {
  244.             const defaultEmpHash = hashPassword("employee2024");
  245.             db.run("INSERT INTO system_config (key, value) VALUES ('employee_view_password_hash', ?)", [defaultEmpHash]);
  246.         }
  247.          
  248.         // 初始化管理员密码哈希
  249.         let adminHashRes = db.exec("SELECT value FROM system_config WHERE key = 'admin_login_password_hash'");
  250.         if(!adminHashRes.length || !adminHashRes[0].values.length) {
  251.             const defaultAdminHash = hashPassword("admin123");
  252.             db.run("INSERT INTO system_config (key, value) VALUES ('admin_login_password_hash', ?)", [defaultAdminHash]);
  253.         }
  254.          
  255.         saveDatabaseToLocalStorage();
  256.     }
  257.      
  258.     // 初始化数据库(优先从 localStorage 恢复)
  259.     async function initDatabase() {
  260.         return new Promise((resolve, reject) => {
  261.             if (typeof window.initSqlJs !== 'undefined') {
  262.                 window.initSqlJs({ locateFile: () => "https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/sql-wasm.wasm" })
  263.                     .then(async function(SQLite) {
  264.                         SQL = SQLite;
  265.                         const restored = await loadDatabaseFromLocalStorage();
  266.                         if (!restored) {
  267.                             createNewDatabase();
  268.                         }
  269.                         // 刷新密码哈希缓存
  270.                         refreshPasswordHashes();
  271.                         resolve();
  272.                     })
  273.                     .catch(err => reject(err));
  274.             } else {
  275.                 reject("sql.js not loaded");
  276.             }
  277.         });
  278.     }
  279.      
  280.     // 获取配置值
  281.     function getConfigValue(key) {
  282.         if(!db) return null;
  283.         let res = db.exec(`SELECT value FROM system_config WHERE key = '${key}'`);
  284.         if(res.length && res[0].values.length) return res[0].values[0][0];
  285.         return null;
  286.     }
  287.      
  288.     // 设置配置值并自动保存数据库
  289.     function setConfigValue(key, value) {
  290.         if(!db) return false;
  291.         try {
  292.             db.run(`INSERT OR REPLACE INTO system_config (key, value) VALUES (?, ?)`, [key, value]);
  293.             saveDatabaseToLocalStorage();  // 立即保存
  294.             return true;
  295.         } catch(e) { return false; }
  296.     }
  297.      
  298.     // 刷新缓存的密码哈希
  299.     function refreshPasswordHashes() {
  300.         let empHash = getConfigValue('employee_view_password_hash');
  301.         if(empHash) currentEmployeePwdHash = empHash;
  302.         let adminHash = getConfigValue('admin_login_password_hash');
  303.         if(adminHash) currentAdminPwdHash = adminHash;
  304.     }
  305.      
  306.     // 修改员工查看密码
  307.     function updateEmployeePassword(newPlainPwd) {
  308.         if(!newPlainPwd || newPlainPwd.trim().length < 4) {
  309.             showToast("密码长度至少4位", true);
  310.             return false;
  311.         }
  312.         const newHash = hashPassword(newPlainPwd.trim());
  313.         if(setConfigValue('employee_view_password_hash', newHash)) {
  314.             refreshPasswordHashes();
  315.             employeePasswordVisible = false;
  316.             renderEmployeeTable();
  317.             showToast("员工查看密码已修改,员工需重新验证(刷新页面密码依然有效)");
  318.             return true;
  319.         }
  320.         showToast("修改失败", true);
  321.         return false;
  322.     }
  323.      
  324.     // 修改管理员登录密码
  325.     function updateAdminPassword(newPlainPwd) {
  326.         if(!newPlainPwd || newPlainPwd.trim().length < 4) {
  327.             showToast("密码长度至少4位", true);
  328.             return false;
  329.         }
  330.         const newHash = hashPassword(newPlainPwd.trim());
  331.         if(setConfigValue('admin_login_password_hash', newHash)) {
  332.             refreshPasswordHashes();
  333.             showToast("管理员密码已修改,下次登录请使用新密码(刷新页面密码依然有效)");
  334.             return true;
  335.         }
  336.         showToast("修改失败", true);
  337.         return false;
  338.     }
  339.      
  340.     // 验证员工密码
  341.     function verifyEmployeePassword(plainPwd) {
  342.         return hashPassword(plainPwd) === currentEmployeePwdHash;
  343.     }
  344.      
  345.     // 验证管理员密码
  346.     function verifyAdminPassword(plainPwd) {
  347.         return hashPassword(plainPwd) === currentAdminPwdHash;
  348.     }
  349.      
  350.     // ==================== 凭证数据操作 ====================
  351.     function getAllCredentials() {
  352.         if(!db) return [];
  353.         const result = db.exec("SELECT id, url, username, password FROM credentials ORDER BY id DESC");
  354.         if(result.length === 0) return [];
  355.         return result[0].values.map(row => ({
  356.             id: row[0],
  357.             url: row[1],
  358.             username: row[2],
  359.             password: row[3]
  360.         }));
  361.     }
  362.      
  363.     function upsertCredential(id, url, username, password) {
  364.         if(!db) return false;
  365.         try {
  366.             if(id === null) {
  367.                 const stmt = db.prepare("INSERT OR REPLACE INTO credentials (url, username, password) VALUES (?, ?, ?)");
  368.                 stmt.run([url, username, password]);
  369.                 stmt.free();
  370.             } else {
  371.                 const stmt = db.prepare("UPDATE credentials SET url = ?, username = ?, password = ? WHERE id = ?");
  372.                 stmt.run([url, username, password, id]);
  373.                 stmt.free();
  374.             }
  375.             saveDatabaseToLocalStorage();
  376.             return true;
  377.         } catch(e) { console.error(e); return false; }
  378.     }
  379.      
  380.     function deleteCredentialById(id) {
  381.         if(!db) return false;
  382.         try {
  383.             db.run("DELETE FROM credentials WHERE id = ?", [id]);
  384.             saveDatabaseToLocalStorage();
  385.             return true;
  386.         } catch(e) { return false; }
  387.     }
  388.      
  389.     function batchUpsertCredentials(records) {
  390.         if(!db) return 0;
  391.         let successCount = 0;
  392.         const stmt = db.prepare("INSERT OR REPLACE INTO credentials (url, username, password) VALUES (?, ?, ?)");
  393.         for(let rec of records) {
  394.             if(rec.url && rec.username && rec.password) {
  395.                 try { stmt.run([rec.url, rec.username, rec.password]); successCount++; } catch(e) {}
  396.             }
  397.         }
  398.         stmt.free();
  399.         saveDatabaseToLocalStorage();
  400.         return successCount;
  401.     }
  402.      
  403.     // 备份数据库
  404.     function exportDatabase() {
  405.         if(!db) { showToast("数据库未就绪", true); return; }
  406.         try {
  407.             const exportedData = db.export();
  408.             const buffer = new Uint8Array(exportedData);
  409.             const blob = new Blob([buffer], {type: "application/x-sqlite3"});
  410.             const url = URL.createObjectURL(blob);
  411.             const a = document.createElement('a');
  412.             a.href = url;
  413.             a.download = `password_manager_backup_${new Date().toISOString().slice(0,19).replace(/:/g, '-')}.db`;
  414.             a.click();
  415.             URL.revokeObjectURL(url);
  416.             showToast("数据库备份成功");
  417.         } catch(e) {
  418.             showToast("备份失败", true);
  419.         }
  420.     }
  421.      
  422.     // ==================== 员工门户渲染 ====================
  423.     function renderEmployeeTable() {
  424.         const tbody = document.getElementById('employeeTableBody');
  425.         const creds = getAllCredentials();
  426.         if(!creds.length) {
  427.             tbody.innerHTML = '<tr class="empty-row"><td colspan="3">暂无凭证数据</td></tr>';
  428.             return;
  429.         }
  430.          
  431.         let html = '';
  432.         creds.forEach(item => {
  433.             let pwdDisplay = employeePasswordVisible ?
  434.                 `<span class="password-plain">${escapeHtml(item.password)}</span>` :
  435.                 `<span class="password-masked">●●●●●●●●</span>`;
  436.             html += `<tr>
  437.                         <td><a href="${escapeHtml(item.url)}" target="_blank" class="url-link">&#128279; ${escapeHtml(item.url)}</a></td>
  438.                         <td>${escapeHtml(item.username)}</td>
  439.                         <td>${pwdDisplay}</td>
  440.                       </tr>`;
  441.         });
  442.         tbody.innerHTML = html;
  443.     }
  444.      
  445.     function verifyEmployeeAccess() {
  446.         const inputPwd = document.getElementById('empViewPwd');
  447.         if(verifyEmployeePassword(inputPwd.value)) {
  448.             employeePasswordVisible = true;
  449.             showToast("验证成功!密码列已显示明文");
  450.             renderEmployeeTable();
  451.         } else {
  452.             employeePasswordVisible = false;
  453.             renderEmployeeTable();
  454.             showToast("查看密码错误,密码保持隐藏", true);
  455.         }
  456.         inputPwd.value = '';
  457.     }
  458.      
  459.     // ==================== 管理员后台渲染 ====================
  460.     function renderAdminTable() {
  461.         const tbody = document.getElementById('adminTableBody');
  462.         if(!adminAuthenticated) {
  463.             tbody.innerHTML = '<tr class="empty-row"><td colspan="4">&#128274; 请先验证管理员权限</td></tr>';
  464.             return;
  465.         }
  466.         const creds = getAllCredentials();
  467.         if(!creds.length) {
  468.             tbody.innerHTML = '<tr class="empty-row"><td colspan="4">暂无凭证,点击"新增凭证"添加</td></tr>';
  469.             return;
  470.         }
  471.         let html = '';
  472.         creds.forEach(item => {
  473.             html += `<tr>
  474.                         <td><a href="${escapeHtml(item.url)}" target="_blank" class="url-link">${escapeHtml(item.url)}</a></td>
  475.                         <td>${escapeHtml(item.username)}</td>
  476.                         <td><span class="password-plain">${escapeHtml(item.password)}</span></td>
  477.                         <td class="flex-btns">
  478.                             <button class="btn btn-outline edit-admin-btn" data-id="${item.id}">&#9999;&#65039; 编辑</button>
  479.                             <button class="btn btn-danger delete-admin-btn" data-id="${item.id}">&#128465;&#65039; 删除</button>
  480.                         </td>
  481.                       </tr>`;
  482.         });
  483.         tbody.innerHTML = html;
  484.          
  485.         document.querySelectorAll('.edit-admin-btn').forEach(btn => {
  486.             btn.addEventListener('click', () => openEditById(parseInt(btn.dataset.id)));
  487.         });
  488.         document.querySelectorAll('.delete-admin-btn').forEach(btn => {
  489.             btn.addEventListener('click', () => {
  490.                 if(confirm('确定删除该凭证吗?')) {
  491.                     deleteCredentialById(parseInt(btn.dataset.id));
  492.                     renderAdminTable();
  493.                     renderEmployeeTable();
  494.                     showToast("已删除");
  495.                 }
  496.             });
  497.         });
  498.     }
  499.      
  500.     function openEditById(id) {
  501.         const creds = getAllCredentials();
  502.         const entry = creds.find(c => c.id === id);
  503.         if(entry) openModalForEdit(entry);
  504.     }
  505.      
  506.     // ==================== Excel 导入导出 ====================
  507.     function exportToExcel() {
  508.         if(!adminAuthenticated) { showToast("请先登录管理员后台", true); return; }
  509.         const creds = getAllCredentials();
  510.         if(creds.length === 0) { showToast("没有数据可导出", true); return; }
  511.         const sheetData = [["网址", "用户名", "密码"]];
  512.         creds.forEach(item => sheetData.push([item.url, item.username, item.password]));
  513.         const ws = XLSX.utils.aoa_to_sheet(sheetData);
  514.         const wb = XLSX.utils.book_new();
  515.         XLSX.utils.book_append_sheet(wb, ws, "Credentials");
  516.         XLSX.writeFile(wb, `password_export_${new Date().toISOString().slice(0,19).replace(/:/g, '-')}.xls`, { bookType: 'xls' });
  517.         showToast("导出成功");
  518.     }
  519.      
  520.     function importExcel(file) {
  521.         if(!adminAuthenticated) { showToast("请先登录管理员后台", true); return; }
  522.         const reader = new FileReader();
  523.         reader.onload = function(e) {
  524.             const data = new Uint8Array(e.target.result);
  525.             const workbook = XLSX.read(data, { type: 'array' });
  526.             const sheet = workbook.Sheets[workbook.SheetNames[0]];
  527.             const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: "" });
  528.             if(!rows || rows.length < 2) { showToast("文件无有效数据", true); return; }
  529.             const headers = rows[0];
  530.             let urlIdx = -1, userIdx = -1, pwdIdx = -1;
  531.             headers.forEach((h, idx) => {
  532.                 const str = String(h).toLowerCase();
  533.                 if(str.includes('网址') || str.includes('url')) urlIdx = idx;
  534.                 if(str.includes('用户名') || str.includes('账号') || str.includes('username')) userIdx = idx;
  535.                 if(str.includes('密码') || str.includes('password')) pwdIdx = idx;
  536.             });
  537.             if(urlIdx === -1 || userIdx === -1 || pwdIdx === -1) {
  538.                 showToast("文件缺少必要列(网址/用户名/密码)", true);
  539.                 return;
  540.             }
  541.             const records = [];
  542.             for(let i=1; i<rows.length; i++) {
  543.                 const row = rows[i];
  544.                 if(row && row.length > Math.max(urlIdx, userIdx, pwdIdx)) {
  545.                     const url = row[urlIdx] ? String(row[urlIdx]).trim() : '';
  546.                     const username = row[userIdx] ? String(row[userIdx]).trim() : '';
  547.                     const password = row[pwdIdx] ? String(row[pwdIdx]).trim() : '';
  548.                     if(url && username && password && (url.startsWith('http://') || url.startsWith('https://'))) {
  549.                         records.push({ url, username, password });
  550.                     }
  551.                 }
  552.             }
  553.             if(records.length === 0) { showToast("未找到有效数据行", true); return; }
  554.             const successCount = batchUpsertCredentials(records);
  555.             renderAdminTable();
  556.             renderEmployeeTable();
  557.             showToast(`导入完成!成功更新/添加 ${successCount} 条记录`);
  558.         };
  559.         reader.readAsArrayBuffer(file);
  560.     }
  561.      
  562.     // ==================== 管理员登录弹窗 ====================
  563.     function showAdminAuthModal() {
  564.         if(adminAuthenticated) return;
  565.         if(adminAuthActive) return;
  566.         adminAuthActive = true;
  567.         const overlay = document.createElement('div');
  568.         overlay.className = 'admin-auth-overlay';
  569.         overlay.innerHTML = `<div class="admin-auth-box">
  570.             <h3>&#128272; 管理员身份验证</h3>
  571.             <input type="password" id="adminAuthPwd" placeholder="管理员密码" autocomplete="off">
  572.             <div id="adminAuthError" class="error-text"></div>
  573.             <div style="display:flex; gap:12px; margin-top:20px;">
  574.                 <button class="btn btn-outline" id="adminAuthCancelBtn">取消</button>
  575.                 <button class="btn btn-primary" id="adminAuthConfirmBtn">确认</button>
  576.             </div>
  577.         </div>`;
  578.         document.body.appendChild(overlay);
  579.         const pwdInput = document.getElementById('adminAuthPwd');
  580.         pwdInput.focus();
  581.          
  582.         const doAuth = () => {
  583.             if(verifyAdminPassword(pwdInput.value)) {
  584.                 adminAuthenticated = true;
  585.                 document.body.removeChild(overlay);
  586.                 adminAuthActive = false;
  587.                 showToast("管理员验证成功");
  588.                 renderAdminTable();
  589.             } else {
  590.                 document.getElementById('adminAuthError').innerText = "密码错误,无权访问后台";
  591.                 pwdInput.value = '';
  592.                 pwdInput.focus();
  593.             }
  594.         };
  595.          
  596.         const closeModal = () => {
  597.             if(document.getElementById('adminAuthOverlay')) document.body.removeChild(overlay);
  598.             adminAuthActive = false;
  599.             if(!adminAuthenticated) {
  600.                 const activeTab = document.querySelector('.tab-btn.active');
  601.                 if(activeTab && activeTab.getAttribute('data-tab') === 'admin') {
  602.                     document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
  603.                     document.querySelector('.tab-btn[data-tab="employee"]').classList.add('active');
  604.                     switchTab('employee');
  605.                     showToast("未通过验证,已返回员工门户", true);
  606.                 }
  607.             }
  608.         };
  609.          
  610.         document.getElementById('adminAuthConfirmBtn').addEventListener('click', doAuth);
  611.         document.getElementById('adminAuthCancelBtn').addEventListener('click', closeModal);
  612.         pwdInput.addEventListener('keypress', (e) => { if(e.key === 'Enter') doAuth(); });
  613.     }
  614.      
  615.     // ==================== 标签页切换 ====================
  616.     function switchTab(tabId) {
  617.         const adminDiv = document.getElementById('adminPanel');
  618.         const empDiv = document.getElementById('employeePanel');
  619.          
  620.         if(tabId === 'employee') {
  621.             adminDiv.classList.add('hidden');
  622.             empDiv.classList.remove('hidden');
  623.             renderEmployeeTable();
  624.             document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
  625.             document.querySelector('.tab-btn[data-tab="employee"]').classList.add('active');
  626.         } else if(tabId === 'admin') {
  627.             if(!adminAuthenticated) {
  628.                 showAdminAuthModal();
  629.                 const checkInterval = setInterval(() => {
  630.                     if(adminAuthenticated) {
  631.                         clearInterval(checkInterval);
  632.                         adminDiv.classList.remove('hidden');
  633.                         empDiv.classList.add('hidden');
  634.                         renderAdminTable();
  635.                         document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
  636.                         document.querySelector('.tab-btn[data-tab="admin"]').classList.add('active');
  637.                     }
  638.                 }, 200);
  639.                 setTimeout(() => clearInterval(checkInterval), 10000);
  640.                 return;
  641.             } else {
  642.                 adminDiv.classList.remove('hidden');
  643.                 empDiv.classList.add('hidden');
  644.                 renderAdminTable();
  645.                 document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
  646.                 document.querySelector('.tab-btn[data-tab="admin"]').classList.add('active');
  647.             }
  648.         }
  649.     }
  650.      
  651.     // ==================== 模态框 ====================
  652.     const modal = document.getElementById('credModal');
  653.     const urlInput = document.getElementById('credUrl');
  654.     const userInput = document.getElementById('credUsername');
  655.     const pwdInputField = document.getElementById('credPassword');
  656.     const editIdField = document.getElementById('editId');
  657.     const modalTitle = document.getElementById('modalTitle');
  658.      
  659.     function openModalForAdd() {
  660.         if(!adminAuthenticated) { showToast("请先登录管理员后台", true); return; }
  661.         modalTitle.innerText = '&#10133; 新增凭证';
  662.         urlInput.value = '';
  663.         userInput.value = '';
  664.         pwdInputField.value = '';
  665.         editIdField.value = '';
  666.         modal.style.display = 'flex';
  667.     }
  668.      
  669.     function openModalForEdit(entry) {
  670.         modalTitle.innerText = '&#9999;&#65039; 编辑凭证';
  671.         urlInput.value = entry.url;
  672.         userInput.value = entry.username;
  673.         pwdInputField.value = entry.password;
  674.         editIdField.value = entry.id;
  675.         modal.style.display = 'flex';
  676.     }
  677.      
  678.     function closeModal() { modal.style.display = 'none'; }
  679.      
  680.     function saveCredentialHandler() {
  681.         if(!adminAuthenticated) { showToast("未授权", true); return; }
  682.         const url = urlInput.value.trim();
  683.         const username = userInput.value.trim();
  684.         const password = pwdInputField.value.trim();
  685.         if(!url || !username || !password) { showToast("请填写完整信息", true); return; }
  686.         if(!url.startsWith('http://') && !url.startsWith('https://')) { showToast("网址需以 http:// 或 https:// 开头", true); return; }
  687.         const editId = editIdField.value;
  688.         const success = upsertCredential(editId ? parseInt(editId) : null, url, username, password);
  689.         if(success) {
  690.             showToast(editId ? "修改成功" : "添加成功");
  691.             closeModal();
  692.             renderAdminTable();
  693.             renderEmployeeTable();
  694.         } else {
  695.             showToast("操作失败", true);
  696.         }
  697.     }
  698.      
  699.     // ==================== 辅助函数 ====================
  700.     function showToast(msg, isError = false) {
  701.         const toast = document.getElementById('toastMsg');
  702.         toast.textContent = msg;
  703.         toast.style.backgroundColor = isError ? '#b91c1c' : '#1f2937';
  704.         toast.classList.add('show');
  705.         setTimeout(() => toast.classList.remove('show'), 2200);
  706.     }
  707.      
  708.     function escapeHtml(str) {
  709.         if(!str) return '';
  710.         return str.replace(/[&<>]/g, m => ({ '&':'&', '<':'<', '>':'>' }[m]));
  711.     }
  712.      
  713.     // ==================== 事件绑定 ====================
  714.     document.getElementById('openAddCredBtn')?.addEventListener('click', openModalForAdd);
  715.     document.getElementById('closeModalBtn')?.addEventListener('click', closeModal);
  716.     document.getElementById('saveCredBtn')?.addEventListener('click', saveCredentialHandler);
  717.     document.getElementById('verifyEmpBtn')?.addEventListener('click', verifyEmployeeAccess);
  718.     document.getElementById('empViewPwd')?.addEventListener('keypress', (e) => { if(e.key === 'Enter') verifyEmployeeAccess(); });
  719.     document.getElementById('exportExcelBtn')?.addEventListener('click', exportToExcel);
  720.     document.getElementById('exportDbBtn')?.addEventListener('click', exportDatabase);
  721.     document.getElementById('importExcelInput')?.addEventListener('change', (e) => { if(e.target.files.length) importExcel(e.target.files[0]); e.target.value = ''; });
  722.      
  723.     // 修改密码按钮事件
  724.     document.getElementById('updateEmployeePwdBtn')?.addEventListener('click', () => {
  725.         const inp = document.getElementById('newEmployeePwd');
  726.         const newPwd = inp.value;
  727.         if(updateEmployeePassword(newPwd)) inp.value = '';
  728.     });
  729.     document.getElementById('updateAdminPwdBtn')?.addEventListener('click', () => {
  730.         const inp = document.getElementById('newAdminPwd');
  731.         const newPwd = inp.value;
  732.         if(updateAdminPassword(newPwd)) inp.value = '';
  733.     });
  734.      
  735.     document.querySelectorAll('.tab-btn').forEach(btn => btn.addEventListener('click', () => switchTab(btn.getAttribute('data-tab'))));
  736.     window.onclick = (e) => { if(e.target === modal) closeModal(); };
  737.      
  738.     // ==================== 启动应用 ====================
  739.     async function bootstrap() {
  740.         try {
  741.             await initDatabase();
  742.             employeePasswordVisible = false;
  743.             adminAuthenticated = false;
  744.             renderEmployeeTable();
  745.             renderAdminTable();
  746.             switchTab('employee');
  747.             console.log("SQLite数据库已初始化,数据持久化存储于localStorage,刷新页面不丢失");
  748.         } catch(err) {
  749.             console.error(err);
  750.             showToast("初始化失败,请刷新页面重试", true);
  751.         }
  752.     }
  753.     bootstrap();
  754. </script>
  755. </body>
  756. </html>
复制代码


评论1

手机用户wD66996 发表于 2026-4-25 15:21:02 | 查看全部 <
提示: 作者被禁止或删除 内容自动屏蔽
回复

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 立即注册 微信登录

本版积分规则

您需要 登录 后才可以回复,轻松玩转社区,没有帐号?立即注册
快速回复
关灯 在本版发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表