# XUX-koa-admin-pro **Repository Path**: leheya/xux-react-admin-pro ## Basic Information - **Project Name**: XUX-koa-admin-pro - **Description**: 基于nodejs后端接口 - **Primary Language**: JavaScript - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-11-04 - **Last Updated**: 2025-11-15 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 多租户 SaaS 平台后端 基于 Koa.js + TypeScript + MySQL 构建的企业级多租户 SaaS 平台后端系统。 ## ✨ 核心特性 - **多租户架构**:基于子域名的租户识别,完整的数据隔离 - **权限管理**:RBAC 权限模型,支持角色、权限、按钮级权限控制 - **用户体系**:超级管理员、租户管理员、普通用户三级用户体系 - **套餐管理**:灵活的套餐配置,支持功能限制和计费管理 - **安全机制**:JWT 认证、密码加密、SQL 注入防护 - **审计日志**:完整的操作日志记录 - **TypeScript**:完整的类型检查,代码更规范更安全 - **数据库迁移**:使用 Sequelize 进行数据库版本管理 ## 技术栈 - **运行时**:Node.js 16+ - **框架**:Koa.js 2.x - **语言**:TypeScript 5.x - **数据库**:MySQL 8.0 - **ORM**:Sequelize + Sequelize-TypeScript - **缓存**:Redis - **认证**:JWT - **日志**:Winston - **验证**:Joi ## 📁 项目结构 ``` xux-react-admin-pro/ ├── src/ │ ├── app.ts # 应用入口 │ ├── config/ # 配置文件 │ │ ├── index.ts # 主配置 │ │ ├── database.ts # 数据库配置 │ │ ├── database.js # Sequelize CLI 配置 │ │ └── redis.ts # Redis 配置 │ ├── controllers/ # 控制器层 │ │ ├── AuthController.ts │ │ ├── TenantController.ts │ │ ├── UserController.ts │ │ ├── PlanController.ts │ │ └── index.ts │ ├── middlewares/ # 中间件 │ │ ├── auth.ts # 认证中间件 │ │ ├── permission.ts # 权限中间件 │ │ ├── tenantIdentifier.ts # 租户识别 │ │ ├── tenantIsolation.ts # 数据隔离 │ │ ├── errorHandler.ts # 错误处理 │ │ ├── requestLogger.ts # 请求日志 │ │ └── index.ts │ ├── models/ # 数据模型 │ │ ├── Tenant.ts # 租户模型 │ │ ├── Plan.ts # 套餐模型 │ │ ├── User.ts # 用户模型 │ │ ├── Role.ts # 角色模型 │ │ ├── Permission.ts # 权限模型 │ │ ├── RolePermission.ts │ │ ├── AuditLog.ts # 审计日志 │ │ └── index.ts │ ├── services/ # 业务逻辑层 │ │ ├── AuthService.ts │ │ ├── TenantService.ts │ │ ├── UserService.ts │ │ ├── PlanService.ts │ │ └── index.ts │ ├── routes/ # 路由 │ │ ├── auth.ts │ │ ├── tenants.ts │ │ ├── users.ts │ │ ├── plans.ts │ │ └── index.ts │ ├── utils/ # 工具函数 │ │ ├── logger.ts # 日志工具 │ │ ├── jwt.ts # JWT 工具 │ │ ├── crypto.ts # 加密工具 │ │ ├── validator.ts # 验证工具 │ │ ├── response.ts # 响应工具 │ │ └── helpers.ts # 辅助函数 │ ├── types/ # TypeScript 类型定义 │ │ └── index.ts │ └── database/ # 数据库相关 │ ├── migrations/ # 迁移文件 │ └── seeders/ # 种子数据 ├── logs/ # 日志目录 ├── .env # 环境变量 ├── .env.example # 环境变量示例 ├── package.json ├── tsconfig.json ├── .eslintrc.json └── README.md ``` ## 前端层 frontend/ 基于react + antd ## 🚀 快速开始 ### 1. 安装依赖 ```bash npm install ``` ### 2. 配置环境变量 复制 `.env.example` 到 `.env` 并配置: ```env # 应用配置 NODE_ENV=development PORT=3000 # MySQL 数据库配置 DB_HOST=host DB_PORT=3306 DB_NAME=saas_platform DB_USER=root DB_PASSWORD=密码 # Redis 配置 REDIS_HOST=localhost REDIS_PORT=6379 # JWT 配置 JWT_SECRET=your-super-secret-jwt-key-change-this-in-production-2024 JWT_EXPIRES_IN=7d # 超级管理员账号 SUPER_ADMIN_EMAIL=admin@saas.com SUPER_ADMIN_PASSWORD=Admin@123456 ``` ### 3. 数据库初始化 ```bash # 运行数据库迁移 npm run db:migrate # 运行种子数据(创建初始套餐、权限、超级管理员) npm run db:seed ``` ### 4. 启动服务 ```bash # 开发模式(热重载) npm run dev # 生产模式 npm run build npm start ``` 服务将在 `http://localhost:3000` 启动 ## 🔑 默认账号 初始化后会创建超级管理员账号: - **邮箱**:`admin@saas.com` - **密码**:`Admin@123456` ## 📡 API 文档 ### 认证相关 #### 登录 ```http POST /api/auth/login Content-Type: application/json { "email": "admin@saas.com", "password": "Admin@123456" } ``` #### 获取当前用户信息 ```http GET /api/auth/me Authorization: Bearer ``` #### 获取当前用户权限 ```http GET /api/auth/permissions Authorization: Bearer ``` ### 租户管理(超级管理员) #### 创建租户 ```http POST /api/admin/tenants Authorization: Bearer { "name": "测试公司", "subdomain": "test", "planId": "uuid", "adminEmail": "admin@test.com", "adminPassword": "Test@123456" } ``` #### 获取租户列表 ```http GET /api/admin/tenants?page=1&pageSize=20 Authorization: Bearer ``` ### 用户管理 #### 创建用户 ```http POST /api/users Authorization: Bearer { "email": "user@example.com", "password": "User@123456", "firstName": "张", "lastName": "三" } ``` #### 获取用户列表 ```http GET /api/users?page=1&pageSize=20 Authorization: Bearer ``` ## 🛡️ 权限系统 ### 权限模型 系统采用 RBAC(基于角色的访问控制)模型: - **用户(User)**:系统使用者 - **角色(Role)**:用户的身份(如:管理员、编辑、查看者) - **权限(Permission)**:具体的操作权限(如:user:create, user:read) ### 超级管理员特权 ⭐ **超级管理员拥有所有权限,无需分配角色和权限** 在权限检查中,超级管理员会自动通过所有权限验证: ```typescript // 权限检查时自动识别超管 if (isSuperAdmin(user.type)) { // 直接放行,不做权限检查 await next(); return; } ``` ### 权限格式 权限格式:`resource:action` - **资源(resource)**:user, role, tenant, plan, permission, audit, dashboard - **操作(action)**:create, read, update, delete, manage 示例: - `user:create` - 创建用户 - `user:read` - 查看用户 - `user:update` - 更新用户 - `user:delete` - 删除用户 - `user:manage` - 管理用户(包含所有操作) ### 使用权限中间件 ```typescript import { requirePermission, requireSuperAdmin, requireTenantAdmin } from '@/middlewares'; // 要求特定权限 router.get('/users', auth, requirePermission('user', 'read'), UserController.list); // 要求超级管理员 router.post('/tenants', auth, requireSuperAdmin, TenantController.create); // 要求租户管理员(超管也可访问) router.post('/users/reset-password', auth, requireTenantAdmin, UserController.resetPassword); // 要求任一权限 router.get('/dashboard', auth, requireAnyPermission([ { resource: 'dashboard', action: 'read' }, { resource: 'tenant', action: 'manage' } ]), DashboardController.index); ``` ## 多租户机制 ### 租户识别 系统通过子域名识别租户: - `admin.saas.com` - 超级管理员后台 - `company1.saas.com` - 公司1的租户 - `company2.saas.com` - 公司2的租户 ### 数据隔离 所有业务表都包含 `tenant_id` 字段,确保数据完全隔离: ```sql SELECT * FROM users WHERE tenant_id = 'xxx'; ``` 超级管理员可以跨租户访问数据(tenant_id 为 NULL)。 ## 数据库设计 ### 核心表结构 1. **plans** - 套餐表 2. **tenants** - 租户表 3. **users** - 用户表 4. **roles** - 角色表 5. **permissions** - 权限表 6. **role_permissions** - 角色权限关联表 7. **audit_logs** - 审计日志表 ### 关系说明 ``` plans 1-N tenants (一个套餐可以有多个租户) tenants 1-N users (一个租户可以有多个用户) roles N-N permissions (角色和权限多对多) users N-1 roles (用户属于一个角色) ``` ## 🔧 开发命令 ```bash # 开发模式 npm run dev # 构建 npm run build # 生产运行 npm start # 类型检查 npm run type-check # 代码检查 npm run lint # 代码修复 npm run lint:fix # 数据库迁移 npm run db:migrate # 数据库回滚 npm run db:migrate:undo # 运行种子数据 npm run db:seed # 重置数据库 npm run db:reset ``` ## 日志系统 日志文件位于 `logs/` 目录: - `error.log` - 错误日志 - `combined.log` - 所有日志 日志级别:error > warn > info > debug ## 安全特性 - ✅ JWT 认证 - ✅ 密码 bcrypt 加密 - ✅ SQL 注入防护(参数化查询) - ✅ XSS 防护(helmet) - ✅ CORS 配置 - ✅ 请求频率限制 - ✅ 数据租户隔离 - ✅ 审计日志 ## 性能优化 - 数据库连接池 - Redis 缓存 - 响应压缩 - 查询优化(索引)