diff --git a/deploy.sh b/deploy.sh index f68488c..34e25a6 100644 --- a/deploy.sh +++ b/deploy.sh @@ -11,37 +11,59 @@ if ! command -v docker &> /dev/null; then exit 1 fi -# 检查是否安装了Docker Compose - echo "检查Docker Compose是否安装..." - if ! command -v docker-compose &> /dev/null; then +# 检查并更新Docker Compose和Buildx + echo "检查并更新Docker工具..." + + # 检查是否安装了Docker Compose + if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then echo "Docker Compose未安装,正在安装..." - # 安装Docker Compose - curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose - # 添加执行权限 + # 使用Daocloud镜像加速安装 + curl -L "https://get.daocloud.io/docker/compose/releases/download/latest/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose - # 检查安装是否成功 - if ! command -v docker-compose &> /dev/null; then - echo "错误: Docker Compose安装失败,请手动安装" - exit 1 - fi - echo "Docker Compose安装成功" fi + + # 更新Docker Buildx到最新版本 + echo "更新Docker Buildx..." + docker buildx install 2>/dev/null || true + docker buildx create --use 2>/dev/null || true + + echo "Docker工具检查完成" # 创建项目目录 echo "创建项目目录..." mkdir -p /opt/project_app/logs /opt/project_app/uploads /opt/project_app/mysql-data - # 克隆代码仓库或更新代码 + # 处理代码仓库或更新代码 echo "处理代码仓库..." if [ ! -d /opt/project_app/.git ]; then - # 如果目录不存在.git文件夹,则克隆仓库 - git clone http://8.137.125.67:4000/Swt29/Project_app.git /opt/project_app + # 如果目录不存在.git文件夹,检查目录是否为空 + if [ "$(ls -A /opt/project_app)" ]; then + # 目录不为空,创建临时目录克隆后复制文件 + echo "目标目录已存在且不为空,使用临时目录克隆代码..." + git clone http://8.137.125.67:4000/Swt29/Project_app.git /tmp/project_app_temp + # 复制.git文件夹和docker相关文件 + cp -r /tmp/project_app_temp/.git /opt/project_app/ + cp -r /tmp/project_app_temp/docker-compose.yml /opt/project_app/ 2>/dev/null || true + cp -r /tmp/project_app_temp/Dockerfile /opt/project_app/ 2>/dev/null || true + # 清理临时目录 + rm -rf /tmp/project_app_temp + else + # 目录为空,直接克隆仓库 + git clone http://8.137.125.67:4000/Swt29/Project_app.git /opt/project_app + fi + cd /opt/project_app else # 如果目录已存在.git文件夹,则更新代码 cd /opt/project_app git pull origin BOSS fi - cd /opt/project_app + + # 检查docker-compose.yml文件是否存在 + if [ ! -f docker-compose.yml ]; then + echo "警告: docker-compose.yml文件不存在,正在从仓库重新拉取..." + git fetch origin BOSS + git checkout origin/BOSS -- docker-compose.yml Dockerfile + fi # 检查.env文件是否存在 echo "检查环境变量配置..." @@ -62,4 +84,4 @@ docker-compose up -d echo "部署完成!服务已启动并在后台运行。" echo "使用以下命令查看服务状态:docker-compose ps" -echo "使用以下命令查看日志:docker-compose logs -f" +echo "使用以下命令查看日志:docker-compose logs -f" \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index c909a53..de673e1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,3 @@ -version: '3.8' - services: app: build: . diff --git a/server-example/.env配置说明.md b/server-example/.env配置说明.md new file mode 100644 index 0000000..bc88bee --- /dev/null +++ b/server-example/.env配置说明.md @@ -0,0 +1,104 @@ +# .env文件配置说明 + +## 1. 微信小程序配置 + +### WECHAT_APPID +- **含义**:微信小程序的唯一标识 +- **获取方式**:登录微信公众平台 -> 开发管理 -> 开发设置 -> 开发者ID(AppID) +- **当前值**:`wx3da6ea0adf91cf0d`(已配置,无需修改) + +### WECHAT_APPSECRET +- **含义**:微信小程序的应用密钥,用于接口调用 +- **获取方式**:登录微信公众平台 -> 开发管理 -> 开发设置 -> 开发者密码(AppSecret)(需要管理员扫码获取) +- **当前值**:`78fd81bce5a2968a8e7c607ae68c4c0b`(已配置,无需修改) + +### WECHAT_TOKEN +- **含义**:用于微信服务器验证的随机字符串,确保安全性 +- **设置方式**:可以自定义一个复杂的随机字符串(建议包含大小写字母、数字和特殊字符) +- **示例**:`abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*` +- **当前值**:`your-random-token`(需要修改) + +## 2. MySQL数据库配置 + +### DB_HOST +- **含义**:MySQL数据库服务器的IP地址或域名 +- **设置方式**: + - 如果数据库和应用部署在同一台服务器,使用`localhost`或`127.0.0.1` + - 如果使用Docker Compose部署,使用服务名称(如`mysql`) + - 如果是远程数据库,使用数据库服务器的IP地址 +- **当前值**:`1.95.162.61`(已配置,无需修改) + +### DB_PORT +- **含义**:MySQL数据库服务的端口号 +- **默认值**:MySQL默认端口为`3306` +- **当前值**:`3306`(已配置,无需修改) + +### DB_DATABASE +- **含义**:要使用的数据库名称 +- **设置方式**:确保该数据库已在MySQL中创建 +- **当前值**:`wechat_app`(已配置,无需修改) + +### DB_USER +- **含义**:MySQL数据库的用户名 +- **设置方式**:使用具有该数据库访问权限的用户名 +- **当前值**:`root`(已配置,无需修改) + +### DB_PASSWORD +- **含义**:MySQL数据库用户的密码 +- **设置方式**: + - 如果用户有密码,填写实际密码 + - 如果没有密码,保留为空字符串(`DB_PASSWORD=""`) +- **当前值**:`schl@2025`(已配置,无需修改) + +## 3. 服务器配置 + +### PORT +- **含义**:Node.js服务器监听的端口号 +- **设置方式**:选择一个未被占用的端口(建议使用1024以上的端口) +- **当前值**:`3003`(已配置,无需修改) + +### LOG_LEVEL +- **含义**:日志记录的级别 +- **可选值**:`debug`, `info`, `warn`, `error` +- **建议**:开发环境使用`debug`,生产环境使用`info`或`warn` +- **当前值**:`debug`(已配置,建议生产环境修改为`info`) + +### NODE_ENV +- **含义**:Node.js运行环境 +- **可选值**:`development`(开发环境), `production`(生产环境) +- **当前值**:`production`(已配置,无需修改) + +### ENABLE_DETAILED_LOGGING +- **含义**:是否启用详细日志记录(用于问题排查) +- **可选值**:`true`, `false` +- **建议**:开发环境使用`true`,生产环境使用`false`以提高性能 +- **当前值**:`true`(已配置,建议生产环境修改为`false`) + +## 配置注意事项 + +1. **不要泄露敏感信息**:.env文件包含AppSecret、数据库密码等敏感信息,不要将其提交到代码仓库 + +2. **备份配置**:定期备份配置文件,以防丢失 + +3. **Docker部署时的特殊配置**: + - 如果使用Docker Compose部署,将`DB_HOST`改为`mysql`(与docker-compose.yml中的服务名称一致) + - 确保数据库端口在Docker Compose中正确映射 + +4. **环境一致性**:确保开发环境和生产环境的配置保持一致(除了敏感信息和环境特定配置) + +5. **配置验证**:配置完成后,启动服务前可以先测试数据库连接是否正常 + +## 修改示例 + +如果要修改配置,直接编辑.env文件即可: + +```bash +# 修改微信token +WECHAT_TOKEN=my-new-secure-token-2025 + +# 修改日志级别为info +LOG_LEVEL=info + +# 关闭详细日志 +ENABLE_DETAILED_LOGGING=false +``` \ No newline at end of file diff --git a/server-example/test-new-auth-mechanism.js b/server-example/test-new-auth-mechanism.js deleted file mode 100644 index 29f5b8e..0000000 --- a/server-example/test-new-auth-mechanism.js +++ /dev/null @@ -1,360 +0,0 @@ -// 测试新的身份验证机制 -const WebSocket = require('ws'); -const readline = require('readline'); -const http = require('http'); - -// 创建readline接口用于用户输入 -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); - -// 服务器地址 -const SERVER_URL = 'ws://localhost:3003'; -const API_URL = 'http://localhost:3003/api/managers'; - -// 测试用例数据 -const TEST_DATA = { - // 有效的客服ID - validManagerId: '22', - // 无效的客服ID - invalidManagerId: '9999', - // 有效的普通用户ID - validUserId: 'user_123456', - // 无效的普通用户ID - invalidUserId: 'user_999999' -}; - -console.log('===== 开始测试新的身份验证机制 ====='); -console.log('测试目标:验证新实现的用户和客服身份验证逻辑'); - -/** - * 测试场景1:有效的普通用户认证 - */ -async function testValidUserAuthentication() { - console.log('\n=== 测试场景1: 有效的普通用户认证 ==='); - - return new Promise((resolve) => { - const ws = new WebSocket(SERVER_URL); - - ws.on('open', () => { - console.log('✅ WebSocket连接已建立'); - - // 准备认证消息 - const authMessage = { - type: 'auth', - userId: TEST_DATA.validUserId, - userType: 'customer', - timestamp: Date.now() - }; - - console.log(`发送用户认证请求: ${JSON.stringify(authMessage)}`); - ws.send(JSON.stringify(authMessage)); - }); - - ws.on('message', (data) => { - const message = JSON.parse(data.toString()); - console.log('收到服务器响应:', JSON.stringify(message)); - - // 检查认证结果 - if (message.type === 'auth_success') { - console.log('✅ 测试成功: 有效的普通用户ID正确通过认证'); - resolve({ success: true, scenario: 'valid_user' }); - } else if (message.type === 'auth_error') { - console.error('❌ 测试失败: 有效的普通用户ID被错误拒绝'); - resolve({ success: false, scenario: 'valid_user', error: message.message }); - } - - // 关闭连接 - ws.close(); - }); - - ws.on('error', (error) => { - console.error('WebSocket错误:', error); - resolve({ success: false, scenario: 'valid_user', error: error.message }); - }); - - // 设置超时 - setTimeout(() => { - console.error('❌ 测试超时: 未收到服务器响应'); - ws.close(); - resolve({ success: false, scenario: 'valid_user', error: 'timeout' }); - }, 10000); - }); -} - -/** - * 测试场景2:无效的普通用户认证 - */ -async function testInvalidUserAuthentication() { - console.log('\n=== 测试场景2: 无效的普通用户认证 ==='); - - return new Promise((resolve) => { - const ws = new WebSocket(SERVER_URL); - - ws.on('open', () => { - console.log('✅ WebSocket连接已建立'); - - // 准备认证消息 - const authMessage = { - type: 'auth', - userId: TEST_DATA.invalidUserId, - userType: 'customer', - timestamp: Date.now() - }; - - console.log(`发送无效用户认证请求: ${JSON.stringify(authMessage)}`); - ws.send(JSON.stringify(authMessage)); - }); - - ws.on('message', (data) => { - const message = JSON.parse(data.toString()); - console.log('收到服务器响应:', JSON.stringify(message)); - - // 检查是否收到认证错误消息 - if (message.type === 'auth_error') { - console.log('✅ 测试成功: 无效的用户ID正确被拒绝认证'); - resolve({ success: true, scenario: 'invalid_user' }); - } else if (message.type === 'auth_success') { - console.error('❌ 测试失败: 无效的用户ID错误地通过了认证'); - resolve({ success: false, scenario: 'invalid_user', error: 'invalid_user_accepted' }); - } - - // 关闭连接 - ws.close(); - }); - - ws.on('error', (error) => { - console.error('WebSocket错误:', error); - resolve({ success: false, scenario: 'invalid_user', error: error.message }); - }); - - // 设置超时 - setTimeout(() => { - console.error('❌ 测试超时: 未收到服务器响应'); - ws.close(); - resolve({ success: false, scenario: 'invalid_user', error: 'timeout' }); - }, 10000); - }); -} - -/** - * 测试场景3:有效的客服认证 - */ -async function testValidManagerAuthentication() { - console.log('\n=== 测试场景3: 有效的客服认证 ==='); - - return new Promise((resolve) => { - const ws = new WebSocket(SERVER_URL); - - ws.on('open', () => { - console.log('✅ WebSocket连接已建立'); - - // 准备客服认证消息 - const authMessage = { - type: 'auth', - managerId: TEST_DATA.validManagerId, - userType: 'manager', - timestamp: Date.now() - }; - - console.log(`发送客服认证请求: ${JSON.stringify(authMessage)}`); - ws.send(JSON.stringify(authMessage)); - }); - - ws.on('message', (data) => { - const message = JSON.parse(data.toString()); - console.log('收到服务器响应:', JSON.stringify(message)); - - // 检查认证结果 - if (message.type === 'auth_success' && - (message.payload && message.payload.type === 'manager') || - (message.userType === 'manager')) { - console.log('✅ 测试成功: 有效的客服ID正确通过认证'); - resolve({ success: true, scenario: 'valid_manager' }); - } else if (message.type === 'auth_error') { - console.error('❌ 测试失败: 有效的客服ID被错误拒绝'); - resolve({ success: false, scenario: 'valid_manager', error: message.message }); - } - - // 关闭连接 - ws.close(); - }); - - ws.on('error', (error) => { - console.error('WebSocket错误:', error); - resolve({ success: false, scenario: 'valid_manager', error: error.message }); - }); - - // 设置超时 - setTimeout(() => { - console.error('❌ 测试超时: 未收到服务器响应'); - ws.close(); - resolve({ success: false, scenario: 'valid_manager', error: 'timeout' }); - }, 10000); - }); -} - -/** - * 测试场景4:无效的客服认证 - */ -async function testInvalidManagerAuthentication() { - console.log('\n=== 测试场景4: 无效的客服认证 ==='); - - return new Promise((resolve) => { - const ws = new WebSocket(SERVER_URL); - - ws.on('open', () => { - console.log('✅ WebSocket连接已建立'); - - // 准备无效客服认证消息 - const authMessage = { - type: 'auth', - managerId: TEST_DATA.invalidManagerId, - userType: 'manager', - timestamp: Date.now() - }; - - console.log(`发送无效客服认证请求: ${JSON.stringify(authMessage)}`); - ws.send(JSON.stringify(authMessage)); - }); - - ws.on('message', (data) => { - const message = JSON.parse(data.toString()); - console.log('收到服务器响应:', JSON.stringify(message)); - - // 检查是否收到认证错误消息 - if (message.type === 'auth_error') { - console.log('✅ 测试成功: 无效的客服ID正确被拒绝认证'); - resolve({ success: true, scenario: 'invalid_manager' }); - } else if (message.type === 'auth_success') { - console.error('❌ 测试失败: 无效的客服ID错误地通过了认证'); - resolve({ success: false, scenario: 'invalid_manager', error: 'invalid_manager_accepted' }); - } - - // 关闭连接 - ws.close(); - }); - - ws.on('error', (error) => { - console.error('WebSocket错误:', error); - resolve({ success: false, scenario: 'invalid_manager', error: error.message }); - }); - - // 设置超时 - setTimeout(() => { - console.error('❌ 测试超时: 未收到服务器响应'); - ws.close(); - resolve({ success: false, scenario: 'invalid_manager', error: 'timeout' }); - }, 10000); - }); -} - -/** - * 测试场景5:使用普通userId作为managerId的认证(应该失败) - */ -async function testUserIdAsManagerId() { - console.log('\n=== 测试场景5: 使用普通userId作为managerId的认证 ==='); - console.log('验证:取消了userId作为managerId的容错处理'); - - return new Promise((resolve) => { - const ws = new WebSocket(SERVER_URL); - - ws.on('open', () => { - console.log('✅ WebSocket连接已建立'); - - // 准备使用普通userId作为managerId的认证消息 - const authMessage = { - type: 'auth', - managerId: TEST_DATA.validUserId, // 使用普通userId作为managerId - userType: 'manager', - timestamp: Date.now() - }; - - console.log(`发送错误格式认证请求: ${JSON.stringify(authMessage)}`); - ws.send(JSON.stringify(authMessage)); - }); - - ws.on('message', (data) => { - const message = JSON.parse(data.toString()); - console.log('收到服务器响应:', JSON.stringify(message)); - - // 检查是否收到认证错误消息 - if (message.type === 'auth_error') { - console.log('✅ 测试成功: 普通userId作为managerId被正确拒绝'); - resolve({ success: true, scenario: 'userId_as_managerId' }); - } else if (message.type === 'auth_success') { - console.error('❌ 测试失败: 普通userId作为managerId错误地通过了认证'); - resolve({ success: false, scenario: 'userId_as_managerId', error: 'userId_accepted_as_managerId' }); - } - - // 关闭连接 - ws.close(); - }); - - ws.on('error', (error) => { - console.error('WebSocket错误:', error); - resolve({ success: false, scenario: 'userId_as_managerId', error: error.message }); - }); - - // 设置超时 - setTimeout(() => { - console.error('❌ 测试超时: 未收到服务器响应'); - ws.close(); - resolve({ success: false, scenario: 'userId_as_managerId', error: 'timeout' }); - }, 10000); - }); -} - -/** - * 运行所有测试 - */ -async function runAllTests() { - const results = []; - - // 按顺序运行测试 - try { - // 先测试用户认证 - results.push(await testValidUserAuthentication()); - results.push(await testInvalidUserAuthentication()); - - // 再测试客服认证 - results.push(await testValidManagerAuthentication()); - results.push(await testInvalidManagerAuthentication()); - - // 测试特殊场景 - results.push(await testUserIdAsManagerId()); - - } catch (error) { - console.error('测试过程中发生错误:', error); - } - - // 输出测试总结 - console.log('\n===== 测试结果总结 ====='); - - const passedTests = results.filter(r => r.success).length; - const totalTests = results.length; - - console.log(`总测试数: ${totalTests}`); - console.log(`通过测试: ${passedTests}`); - console.log(`失败测试: ${totalTests - passedTests}`); - - // 输出失败的测试详情 - const failedTests = results.filter(r => !r.success); - if (failedTests.length > 0) { - console.log('\n失败测试详情:'); - failedTests.forEach(test => { - console.log(`- ${test.scenario}: ${test.error || '未知错误'}`); - }); - } - - // 输出最终结果 - const overallResult = passedTests === totalTests; - console.log('\n===== 最终结果 ====='); - console.log(`整体测试结果: ${overallResult ? '✅ 通过' : '❌ 失败'}`); - - rl.close(); -} - -// 启动测试 -runAllTests(); diff --git a/server-example/test-post.js b/server-example/test-post.js deleted file mode 100644 index c824fe6..0000000 --- a/server-example/test-post.js +++ /dev/null @@ -1,37 +0,0 @@ -const http = require('http'); - -const postData = JSON.stringify({ test: 'data' }); - -const options = { - hostname: 'localhost', - port: 3003, - path: '/api/test/post', - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(postData) - } -}; - -console.log('===== 测试 /api/test/post 接口 =====\n'); - -const req = http.request(options, (res) => { - let data = ''; - - res.on('data', (chunk) => { - data += chunk; - }); - - res.on('end', () => { - console.log('响应状态码:', res.statusCode); - console.log('响应结果:'); - console.log(data); - }); -}); - -req.on('error', (e) => { - console.error('请求失败:', e.message); -}); - -req.write(postData); -req.end(); diff --git a/server-example/test-settlement.js b/server-example/test-settlement.js deleted file mode 100644 index 1811357..0000000 --- a/server-example/test-settlement.js +++ /dev/null @@ -1,67 +0,0 @@ -const http = require('http'); - -const testData = { - openid: "oAWdd15xKm5H66TNlmjYtky_Iug8", - collaborationid: "chicken", - company: "123", - province: "北京市", - city: "北京市", - district: "东城区", - detailedaddress: "123", - cooperation: "采销联盟合作", - phoneNumber: "18482694520", - businesslicenseurl: "", - proofurl: "", - brandurl: "https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/settlement/brandAuth/1766729271862_BJrCwyOx1Bugaf5545a3f0d4e140bf21f92323555688.png/image/af5545a3f0d4e140bf21f92323555688.png" -}; - -const postData = JSON.stringify(testData); - -const options = { - hostname: 'localhost', - port: 3003, - path: '/api/settlement/submit', - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(postData) - } -}; - -console.log('===== 测试立即入驻API ====='); -console.log('1. 测试数据:', JSON.stringify(testData, null, 2)); -console.log('2. 发送请求到: http://localhost:3003/api/settlement/submit\n'); - -const req = http.request(options, (res) => { - let data = ''; - - res.on('data', (chunk) => { - data += chunk; - }); - - res.on('end', () => { - console.log('3. 响应状态码:', res.statusCode); - console.log('4. 响应结果:'); - try { - const result = JSON.parse(data); - console.log(JSON.stringify(result, null, 2)); - - if (result.success && result.code === 200) { - console.log('\n✅ 入驻申请提交成功!'); - } else { - console.log('\n❌ 入驻申请提交失败:', result.message); - } - } catch (e) { - console.log('响应数据:', data); - console.log('\n❌ JSON解析失败'); - } - }); -}); - -req.on('error', (e) => { - console.error('❌ 请求失败:', e.message); - console.error('\n请确保后端服务器已启动: node server-mysql.js'); -}); - -req.write(postData); -req.end(); diff --git a/server-example/test-type-sync-fix.js b/server-example/test-type-sync-fix.js deleted file mode 100644 index ed27cb3..0000000 --- a/server-example/test-type-sync-fix.js +++ /dev/null @@ -1,166 +0,0 @@ -// 测试用户类型同步修复 -// 此脚本用于验证updateManagerOnlineStatus函数中的用户类型更新逻辑 - -const { Sequelize } = require('sequelize'); -const fs = require('fs'); -const path = require('path'); - -// 读取环境变量 -const envFile = path.join(__dirname, '.env'); -if (fs.existsSync(envFile)) { - const envContent = fs.readFileSync(envFile, 'utf8'); - envContent.split('\n').forEach(line => { - const match = line.match(/^(\w+)=(.*)$/); - if (match) { - process.env[match[1]] = match[2]; - } - }); -} - -// 数据库配置 - 使用独立的数据源连接,与server-mysql.js保持一致 -const dbConfig = { - host: process.env.DB_HOST || '1.95.162.61', - port: process.env.DB_PORT || 3306, - user: process.env.DB_USER || 'root', - password: process.env.DB_PASSWORD || '' -}; - -console.log('数据库连接配置:'); -console.log(JSON.stringify(dbConfig, null, 2)); - -// 创建独立的数据源连接 -const wechatAppSequelize = new Sequelize( - 'wechat_app', - dbConfig.user, - dbConfig.password, - { - host: dbConfig.host, - port: dbConfig.port, - dialect: 'mysql', - pool: { - max: 10, - min: 0, - acquire: 30000, - idle: 10000 - }, - logging: true, - define: { - timestamps: false - }, - timezone: '+00:00' - } -); - -const userLoginSequelize = new Sequelize( - 'userlogin', - dbConfig.user, - dbConfig.password, - { - host: dbConfig.host, - port: dbConfig.port, - dialect: 'mysql', - pool: { - max: 10, - min: 0, - acquire: 30000, - idle: 10000 - }, - logging: true, - define: { - timestamps: false - }, - timezone: '+00:00' - } -); - -// 测试电话号码 -const testPhoneNumber = '17780155537'; - -async function testTypeSyncFix() { - console.log('\n=== 开始用户类型同步修复测试 ===\n'); - - try { - // 1. 首先检查users表中当前用户类型 (使用wechatAppSequelize) - console.log('1. 检查users表中的当前用户类型...'); - const userResult = await wechatAppSequelize.query( - 'SELECT * FROM users WHERE phoneNumber = ?', - { replacements: [testPhoneNumber], type: wechatAppSequelize.QueryTypes.SELECT } - ); - - if (userResult && userResult.length > 0) { - console.log('用户信息:', userResult[0]); - console.log(`当前用户类型: ${userResult[0].type}`); - } else { - console.log('用户不存在:', testPhoneNumber); - } - - // 2. 检查personnel表中的客服信息 (使用userLoginSequelize) - console.log('\n2. 检查personnel表中的客服信息...'); - const personnelResult = await userLoginSequelize.query( - 'SELECT * FROM personnel WHERE phoneNumber = ?', - { replacements: [testPhoneNumber], type: userLoginSequelize.QueryTypes.SELECT } - ); - - if (personnelResult && personnelResult.length > 0) { - console.log('客服信息:', personnelResult[0]); - const managerId = personnelResult[0].id || personnelResult[0].userId; - console.log(`客服managerId: ${managerId}`); - - // 3. 测试用户类型更新逻辑 (使用wechatAppSequelize) - console.log('\n3. 测试用户类型更新逻辑...'); - const updateResult = await wechatAppSequelize.query( - 'UPDATE users SET type = ? WHERE phoneNumber = ? AND type = ?', - { replacements: ['manager', testPhoneNumber, 'customer'] } - ); - - const affectedRows = updateResult[1].affectedRows; - if (affectedRows > 0) { - console.log(`✓ 成功更新用户类型: 手机号=${testPhoneNumber}, 用户类型从customer更新为manager`); - } else { - console.log(`✓ 用户类型无需更新: 手机号=${testPhoneNumber}, 可能已经是manager类型`); - } - - // 4. 验证更新结果 (使用wechatAppSequelize) - console.log('\n4. 验证更新结果...'); - const updatedUserResult = await wechatAppSequelize.query( - 'SELECT * FROM users WHERE phoneNumber = ?', - { replacements: [testPhoneNumber], type: wechatAppSequelize.QueryTypes.SELECT } - ); - - if (updatedUserResult && updatedUserResult.length > 0) { - console.log('更新后的用户信息:', updatedUserResult[0]); - console.log(`更新后的用户类型: ${updatedUserResult[0].type}`); - - if (updatedUserResult[0].type === 'manager') { - console.log('✓ 验证成功: 用户类型已更新为manager'); - } else { - console.log('⚠ 验证警告: 用户类型仍为:', updatedUserResult[0].type); - } - } - - } else { - console.log('该手机号不是客服'); - } - - // 总结 - console.log('\n=== 测试总结 ==='); - console.log('1. 数据库连接: 成功'); - console.log('2. users表查询: 成功'); - console.log('3. personnel表查询: 成功'); - console.log('4. 用户类型更新逻辑: 已测试'); - console.log('5. 跨数据源操作: 已验证'); - console.log('\n提示: 服务器已重启,客服登录后将会自动更新用户类型'); - - } catch (error) { - console.error('测试过程中出现错误:', error); - console.error('错误详情:', error.stack); - } finally { - // 关闭数据库连接 - await wechatAppSequelize.close(); - await userLoginSequelize.close(); - console.log('\n数据库连接已关闭'); - } -} - -// 运行测试 -testTypeSyncFix(); diff --git a/server-example/test-user-auth-validation.js b/server-example/test-user-auth-validation.js deleted file mode 100644 index 09fd256..0000000 --- a/server-example/test-user-auth-validation.js +++ /dev/null @@ -1,85 +0,0 @@ -const WebSocket = require('ws'); -const readline = require('readline'); - -// 创建readline接口用于用户输入 -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); - -// 测试WebSocket认证验证 -async function testUserAuthValidation() { - console.log('===== 开始测试用户认证验证 ====='); - console.log('此测试将验证不存在的用户ID是否无法通过认证'); - - // 不存在的用户ID(与日志中的相同) - const nonExistentUserId = 'user_1765760444819'; - - // 服务器WebSocket地址 - const wsUrl = 'ws://localhost:3003'; - - return new Promise((resolve) => { - // 创建WebSocket连接 - const ws = new WebSocket(wsUrl); - - ws.on('open', () => { - console.log('WebSocket连接已建立'); - - // 准备认证消息 - const authMessage = { - type: 'auth', - userId: nonExistentUserId, - userType: 'customer', - timestamp: Date.now() - }; - - console.log(`发送认证请求: ${JSON.stringify(authMessage)}`); - ws.send(JSON.stringify(authMessage)); - }); - - ws.on('message', (data) => { - const message = JSON.parse(data.toString()); - console.log('收到服务器响应:', JSON.stringify(message)); - - // 检查是否收到认证错误消息 - if (message.type === 'auth_error' && message.message === '用户不存在') { - console.log('✅ 测试成功: 不存在的用户ID正确被拒绝认证'); - resolve(true); - } else if (message.type === 'auth_success') { - console.log('❌ 测试失败: 不存在的用户ID错误地通过了认证'); - resolve(false); - } - - // 关闭连接 - ws.close(); - }); - - ws.on('error', (error) => { - console.error('WebSocket错误:', error); - resolve(false); - }); - - ws.on('close', () => { - console.log('WebSocket连接已关闭'); - }); - - // 设置超时 - setTimeout(() => { - console.error('❌ 测试超时: 未收到服务器响应'); - ws.close(); - resolve(false); - }, 10000); - }); -} - -// 运行测试 -testUserAuthValidation() - .then((result) => { - console.log('===== 测试完成 ====='); - console.log('最终结果:', result ? '通过' : '失败'); - rl.close(); - }) - .catch((error) => { - console.error('测试执行错误:', error); - rl.close(); - });