Initial commit
This commit is contained in:
74
.gitignore
vendored
Normal file
74
.gitignore
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Log files
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage/
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Dependency directories
|
||||
jspm_packages/
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env.test
|
||||
|
||||
# IDE files
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Database files
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# Temporary files
|
||||
tmp/
|
||||
temp/
|
||||
*.tmp
|
||||
*.temp
|
||||
|
||||
# Build files
|
||||
dist/
|
||||
106
README.md
Normal file
106
README.md
Normal file
@@ -0,0 +1,106 @@
|
||||
# 授权管理系统 - 后端服务
|
||||
|
||||
浙江贝凡企业授权管理系统的后端服务,基于 Node.js + Express + SQLite。
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **Node.js**: 运行时环境
|
||||
- **Express**: Web 框架
|
||||
- **SQLite**: 数据库
|
||||
- **JWT**: 身份认证
|
||||
- **bcryptjs**: 密码加密
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
backend/
|
||||
├── routes/ # API 路由
|
||||
│ ├── auth.js # 认证路由
|
||||
│ ├── serials.js # 序列号路由
|
||||
│ └── companies.js # 企业路由
|
||||
├── middleware/ # 中间件
|
||||
│ └── auth.js # 认证中间件
|
||||
├── scripts/ # 脚本
|
||||
│ └── init-db.js # 数据库初始化
|
||||
├── utils/ # 工具函数
|
||||
│ └── database.js # 数据库连接
|
||||
├── data/ # 数据文件
|
||||
│ └── database.sqlite
|
||||
├── server.js # 服务器入口
|
||||
├── .env # 环境变量
|
||||
└── package.json # 项目配置
|
||||
```
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
## 开发
|
||||
|
||||
启动开发服务器(支持热重载):
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
服务器将在 http://localhost:3000 运行
|
||||
|
||||
## 生产
|
||||
|
||||
启动生产服务器:
|
||||
|
||||
```bash
|
||||
pnpm start
|
||||
```
|
||||
|
||||
## 数据库初始化
|
||||
|
||||
初始化数据库和默认管理员账户:
|
||||
|
||||
```bash
|
||||
pnpm init-db
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
创建 `.env` 文件:
|
||||
|
||||
```env
|
||||
PORT=3000
|
||||
JWT_SECRET=your-secret-key-here
|
||||
```
|
||||
|
||||
## 默认账户
|
||||
|
||||
初始化后默认创建的管理员账户:
|
||||
- 用户名: admin
|
||||
- 密码: Beifan@2026
|
||||
|
||||
## API 接口
|
||||
|
||||
### 认证接口
|
||||
|
||||
- `POST /api/auth/login` - 用户登录
|
||||
- `POST /api/auth/logout` - 用户登出
|
||||
- `POST /api/auth/change-password` - 修改密码
|
||||
|
||||
### 序列号接口
|
||||
|
||||
- `POST /api/serials/generate` - 生成序列号
|
||||
- `GET /api/serials/:serialNumber/query` - 查询序列号
|
||||
- `POST /api/serials/:serialNumber/revoke` - 吊销序列号
|
||||
- `GET /api/serials/` - 获取序列号列表
|
||||
|
||||
### 企业接口
|
||||
|
||||
- `GET /api/companies/` - 获取企业列表
|
||||
- `GET /api/companies/:companyName` - 获取企业详情
|
||||
- `POST /api/companies/:companyName/revoke` - 吊销企业
|
||||
- `DELETE /api/companies/:companyName` - 删除企业
|
||||
- `GET /api/companies/stats/overview` - 获取统计数据
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
46
middleware/auth.js
Normal file
46
middleware/auth.js
Normal file
@@ -0,0 +1,46 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const db = require('../utils/database');
|
||||
|
||||
// 验证JWT令牌
|
||||
const authenticateToken = async (req, res, next) => {
|
||||
// 从请求头获取令牌
|
||||
const authHeader = req.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: '访问令牌缺失' });
|
||||
}
|
||||
|
||||
try {
|
||||
// 验证令牌
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
// 获取用户信息
|
||||
const user = await db.get('SELECT id, username, name, role FROM users WHERE id = ?', [decoded.userId]);
|
||||
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: '用户不存在' });
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
} catch (error) {
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
return res.status(401).json({ error: '令牌已过期' });
|
||||
}
|
||||
return res.status(403).json({ error: '无效的令牌' });
|
||||
}
|
||||
};
|
||||
|
||||
// 验证管理员权限
|
||||
const requireAdmin = (req, res, next) => {
|
||||
if (req.user.role !== 'admin') {
|
||||
return res.status(403).json({ error: '需要管理员权限' });
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
authenticateToken,
|
||||
requireAdmin
|
||||
};
|
||||
24
package.json
Normal file
24
package.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "trace-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "浙江贝凡企业授权管理系统 - 后端服务",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "nodemon server.js",
|
||||
"init-db": "node scripts/init-db.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^17.2.3",
|
||||
"express": "^5.2.1",
|
||||
"jsonwebtoken": "^9.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "MIT"
|
||||
}
|
||||
1149
pnpm-lock.yaml
generated
Normal file
1149
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
139
routes/auth.js
Normal file
139
routes/auth.js
Normal file
@@ -0,0 +1,139 @@
|
||||
const express = require('express');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const db = require('../utils/database');
|
||||
const { authenticateToken } = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 用户登录
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: '用户名和密码不能为空' });
|
||||
}
|
||||
|
||||
// 查询用户
|
||||
const user = await db.get('SELECT * FROM users WHERE username = ?', [username]);
|
||||
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: '用户名或密码错误' });
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
return res.status(401).json({ error: '用户名或密码错误' });
|
||||
}
|
||||
|
||||
// 生成JWT令牌
|
||||
const token = jwt.sign(
|
||||
{ userId: user.id, username: user.username, role: user.role },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '24h' }
|
||||
);
|
||||
|
||||
// 返回用户信息和令牌
|
||||
res.json({
|
||||
accessToken: token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('登录错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取用户信息
|
||||
router.get('/profile', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const user = await db.get('SELECT id, username, name, email, role, created_at FROM users WHERE id = ?', [req.user.id]);
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: '用户不存在' });
|
||||
}
|
||||
|
||||
res.json(user);
|
||||
} catch (error) {
|
||||
console.error('获取用户信息错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 修改密码
|
||||
router.post('/change-password', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { currentPassword, newPassword } = req.body;
|
||||
|
||||
if (!currentPassword || !newPassword) {
|
||||
return res.status(400).json({ error: '当前密码和新密码不能为空' });
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
return res.status(400).json({ error: '新密码长度至少为6位' });
|
||||
}
|
||||
|
||||
// 查询用户
|
||||
const user = await db.get('SELECT password FROM users WHERE id = ?', [req.user.id]);
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: '用户不存在' });
|
||||
}
|
||||
|
||||
// 验证当前密码
|
||||
const isValidPassword = await bcrypt.compare(currentPassword, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
return res.status(401).json({ error: '当前密码错误' });
|
||||
}
|
||||
|
||||
// 哈希新密码
|
||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||
|
||||
// 更新密码
|
||||
await db.run('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [hashedPassword, req.user.id]);
|
||||
|
||||
res.json({ message: '密码修改成功' });
|
||||
} catch (error) {
|
||||
console.error('修改密码错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 更新用户资料
|
||||
router.put('/profile', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { name, email } = req.body;
|
||||
|
||||
// 验证输入
|
||||
if (!name) {
|
||||
return res.status(400).json({ error: '姓名不能为空' });
|
||||
}
|
||||
|
||||
if (email && !email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
|
||||
return res.status(400).json({ error: '邮箱格式不正确' });
|
||||
}
|
||||
|
||||
// 更新用户资料
|
||||
await db.run('UPDATE users SET name = ?, email = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [name, email, req.user.id]);
|
||||
|
||||
// 获取更新后的用户资料
|
||||
const updatedUser = await db.get('SELECT id, username, name, email, role, created_at FROM users WHERE id = ?', [req.user.id]);
|
||||
|
||||
res.json(updatedUser);
|
||||
} catch (error) {
|
||||
console.error('更新用户资料错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
407
routes/companies.js
Normal file
407
routes/companies.js
Normal file
@@ -0,0 +1,407 @@
|
||||
const express = require('express');
|
||||
const db = require('../utils/database');
|
||||
const { authenticateToken, requireAdmin } = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 获取企业列表
|
||||
router.get('/', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { page = 1, limit = 20, search = '' } = req.query;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
let query = `
|
||||
SELECT c.company_name, c.created_at as first_created, c.updated_at as last_created, c.is_active,
|
||||
(SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name) as serial_count,
|
||||
(SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name AND s.is_active = 1) as active_count
|
||||
FROM companies c
|
||||
`;
|
||||
let countQuery = 'SELECT COUNT(*) as total FROM companies';
|
||||
let params = [];
|
||||
|
||||
if (search) {
|
||||
query += ' WHERE c.company_name LIKE ?';
|
||||
countQuery += ' WHERE company_name LIKE ?';
|
||||
params.push(`%${search}%`);
|
||||
}
|
||||
|
||||
query += ' ORDER BY c.updated_at DESC LIMIT ? OFFSET ?';
|
||||
params.push(parseInt(limit), parseInt(offset));
|
||||
|
||||
const [companies, countResult] = await Promise.all([
|
||||
db.all(query, params),
|
||||
db.get(countQuery, params.slice(0, -2))
|
||||
]);
|
||||
|
||||
const total = countResult ? countResult.total : 0;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
res.json({
|
||||
message: '获取企业列表成功',
|
||||
data: companies.map(company => ({
|
||||
companyName: company.company_name,
|
||||
firstCreated: company.first_created,
|
||||
lastCreated: company.last_created,
|
||||
serialCount: company.serial_count,
|
||||
activeCount: company.active_count,
|
||||
status: company.is_active ? 'active' : 'disabled'
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取企业列表错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取企业详情
|
||||
router.get('/:companyName', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { companyName } = req.params;
|
||||
const decodedCompanyName = decodeURIComponent(companyName);
|
||||
const { page = 1, limit = 20 } = req.query;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
// 获取企业基本信息
|
||||
const companyInfo = await db.get('SELECT * FROM companies WHERE company_name = ?', [decodedCompanyName]);
|
||||
|
||||
if (!companyInfo) {
|
||||
return res.status(404).json({ error: '企业不存在' });
|
||||
}
|
||||
|
||||
// 获取序列号统计信息
|
||||
const serialStats = await db.get(`
|
||||
SELECT COUNT(*) as serial_count,
|
||||
SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_count,
|
||||
SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as disabled_count,
|
||||
SUM(CASE WHEN valid_until IS NOT NULL AND valid_until <= datetime('now') THEN 1 ELSE 0 END) as expired_count
|
||||
FROM serials
|
||||
WHERE company_name = ?
|
||||
`, [decodedCompanyName]);
|
||||
|
||||
// 获取企业的序列号列表
|
||||
const serials = await db.all(`
|
||||
SELECT s.*, u.name as created_by_name
|
||||
FROM serials s
|
||||
LEFT JOIN users u ON s.created_by = u.id
|
||||
WHERE s.company_name = ?
|
||||
ORDER BY s.created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, [decodedCompanyName, parseInt(limit), parseInt(offset)]);
|
||||
|
||||
// 获取统计数据
|
||||
const stats = await db.all(`
|
||||
SELECT strftime('%Y-%m', created_at) as month,
|
||||
COUNT(*) as count
|
||||
FROM serials
|
||||
WHERE company_name = ?
|
||||
GROUP BY strftime('%Y-%m', created_at)
|
||||
ORDER BY month DESC
|
||||
LIMIT 12
|
||||
`, [decodedCompanyName]);
|
||||
|
||||
res.json({
|
||||
message: '获取企业详情成功',
|
||||
data: {
|
||||
companyName: decodedCompanyName,
|
||||
serialCount: serialStats?.serial_count || 0,
|
||||
activeCount: serialStats?.active_count || 0,
|
||||
disabledCount: serialStats?.disabled_count || 0,
|
||||
expiredCount: serialStats?.expired_count || 0,
|
||||
firstCreated: companyInfo.created_at,
|
||||
lastCreated: companyInfo.updated_at,
|
||||
status: companyInfo.is_active ? 'active' : 'disabled',
|
||||
serials: serials.map(s => ({
|
||||
serialNumber: s.serial_number,
|
||||
validUntil: s.valid_until,
|
||||
isActive: s.is_active,
|
||||
createdAt: s.created_at,
|
||||
createdBy: s.created_by_name
|
||||
})),
|
||||
monthlyStats: stats.map(stat => ({
|
||||
month: stat.month,
|
||||
count: stat.count
|
||||
}))
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取企业详情错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 更新企业信息
|
||||
router.patch('/:companyName', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { companyName } = req.params;
|
||||
const decodedCompanyName = decodeURIComponent(companyName);
|
||||
const { newCompanyName } = req.body;
|
||||
|
||||
if (!newCompanyName || newCompanyName.trim() === '') {
|
||||
return res.status(400).json({ error: '新企业名称不能为空' });
|
||||
}
|
||||
|
||||
// 检查企业是否存在
|
||||
const existingCompany = db.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[decodedCompanyName]
|
||||
);
|
||||
|
||||
if (!existingCompany || existingCompany.count === 0) {
|
||||
return res.status(404).json({ error: '企业不存在' });
|
||||
}
|
||||
|
||||
// 检查新企业名称是否已存在
|
||||
const duplicateCompany = db.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[newCompanyName]
|
||||
);
|
||||
|
||||
if (duplicateCompany && duplicateCompany.count > 0) {
|
||||
return res.status(400).json({ error: '企业名称已存在' });
|
||||
}
|
||||
|
||||
// 更新企业名称
|
||||
db.run(
|
||||
'UPDATE serials SET company_name = ?, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[newCompanyName, decodedCompanyName]
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: '企业名称更新成功',
|
||||
data: {
|
||||
oldCompanyName: decodedCompanyName,
|
||||
newCompanyName
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('更新企业信息错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 删除企业(物理删除,完全删除企业和所有序列号)
|
||||
router.delete('/:companyName', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { companyName } = req.params;
|
||||
console.log('原始参数:', companyName);
|
||||
const decodedCompanyName = decodeURIComponent(companyName);
|
||||
console.log('解码后参数:', decodedCompanyName);
|
||||
|
||||
// 检查企业是否存在
|
||||
const existingCompany = await db.get(
|
||||
'SELECT * FROM companies WHERE company_name = ?',
|
||||
[decodedCompanyName]
|
||||
);
|
||||
|
||||
if (!existingCompany) {
|
||||
return res.status(404).json({ error: '企业不存在' });
|
||||
}
|
||||
|
||||
// 开始事务
|
||||
db.run('BEGIN TRANSACTION');
|
||||
|
||||
try {
|
||||
// 删除该企业的所有序列号
|
||||
const serialDeleteResult = db.run(
|
||||
'DELETE FROM serials WHERE company_name = ?',
|
||||
[decodedCompanyName]
|
||||
);
|
||||
console.log('删除序列号结果:', serialDeleteResult);
|
||||
|
||||
// 删除企业记录
|
||||
const companyDeleteResult = db.run(
|
||||
'DELETE FROM companies WHERE company_name = ?',
|
||||
[decodedCompanyName]
|
||||
);
|
||||
console.log('删除企业结果:', companyDeleteResult);
|
||||
|
||||
if (companyDeleteResult.changes === 0) {
|
||||
db.run('ROLLBACK');
|
||||
return res.status(404).json({ error: '企业不存在' });
|
||||
}
|
||||
|
||||
db.run('COMMIT');
|
||||
|
||||
res.json({
|
||||
message: '企业已完全删除,所有相关序列号已删除',
|
||||
data: {
|
||||
companyName: decodedCompanyName,
|
||||
deletedSerialCount: serialDeleteResult.changes,
|
||||
deletedCompanyCount: companyDeleteResult.changes
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('删除企业过程中错误:', error);
|
||||
db.run('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除企业错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取企业统计数据
|
||||
router.get('/stats/overview', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
// 获取总企业数
|
||||
const companyCount = await db.get('SELECT COUNT(*) as count FROM companies');
|
||||
|
||||
// 获取总序列号数
|
||||
const serialCount = await db.get('SELECT COUNT(*) as count FROM serials');
|
||||
|
||||
// 获取活跃序列号数
|
||||
const activeCount = await db.get(`
|
||||
SELECT COUNT(*) as count FROM serials
|
||||
WHERE is_active = 1 AND (valid_until IS NULL OR valid_until > datetime('now'))
|
||||
`);
|
||||
|
||||
// 按月份统计 - 使用正确的日期格式
|
||||
const monthlyStats = await db.all(`
|
||||
SELECT strftime('%Y-%m', created_at) as month,
|
||||
COUNT(DISTINCT company_name) as company_count,
|
||||
COUNT(*) as serial_count
|
||||
FROM serials
|
||||
WHERE created_at >= strftime('%Y-%m-%d', datetime('now', '-12 months'))
|
||||
GROUP BY strftime('%Y-%m', created_at)
|
||||
ORDER BY month ASC
|
||||
`);
|
||||
|
||||
// 获取最新添加的企业
|
||||
const recentCompanies = await db.all(`
|
||||
SELECT c.company_name, c.created_at as last_created, c.is_active
|
||||
FROM companies c
|
||||
ORDER BY c.updated_at DESC
|
||||
LIMIT 10
|
||||
`);
|
||||
|
||||
// 获取最近生成的序列号
|
||||
const recentSerials = await db.all(`
|
||||
SELECT s.serial_number, s.company_name, s.is_active, s.created_at
|
||||
FROM serials s
|
||||
ORDER BY s.created_at DESC
|
||||
LIMIT 10
|
||||
`);
|
||||
|
||||
// 如果没有数据,生成过去12个月的空数据
|
||||
if (monthlyStats.length === 0) {
|
||||
const now = new Date();
|
||||
for (let i = 11; i >=0; i--) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const month = date.toISOString().substr(0, 7);
|
||||
monthlyStats.push({
|
||||
month,
|
||||
company_count: 0,
|
||||
serial_count: 0
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
message: '获取统计数据成功',
|
||||
data: {
|
||||
overview: {
|
||||
totalCompanies: companyCount.count || 0,
|
||||
totalSerials: serialCount.count || 0,
|
||||
activeSerials: activeCount.count || 0,
|
||||
inactiveSerials: (serialCount.count || 0) - (activeCount.count || 0)
|
||||
},
|
||||
monthlyStats: monthlyStats.map(stat => ({
|
||||
month: stat.month,
|
||||
company_count: stat.company_count,
|
||||
serial_count: stat.serial_count
|
||||
})),
|
||||
recentCompanies: recentCompanies.map(c => ({
|
||||
companyName: c.company_name,
|
||||
lastCreated: c.last_created,
|
||||
status: c.is_active ? 'active' : 'disabled'
|
||||
})),
|
||||
recentSerials: recentSerials.map(s => ({
|
||||
serialNumber: s.serial_number,
|
||||
companyName: s.company_name,
|
||||
isActive: s.is_active,
|
||||
createdAt: s.created_at
|
||||
}))
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取统计数据错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 吊销单个序列号
|
||||
router.delete('/:companyName/serials/:serialNumber', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { companyName, serialNumber } = req.params;
|
||||
|
||||
// 检查序列号是否存在且属于该企业
|
||||
const serial = await db.get(
|
||||
'SELECT * FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
|
||||
if (!serial) {
|
||||
return res.status(404).json({ error: '序列号不存在或不属于该企业' });
|
||||
}
|
||||
|
||||
// 物理删除序列号
|
||||
await db.run(
|
||||
'DELETE FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: '序列号已成功吊删除',
|
||||
data: {
|
||||
serialNumber: serial.serial_number,
|
||||
companyName
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('吊销序列号错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 吊销企业
|
||||
router.post('/:companyName/revoke', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { companyName } = req.params;
|
||||
const decodedCompanyName = decodeURIComponent(companyName);
|
||||
|
||||
// 检查企业是否存在
|
||||
const existingCompany = await db.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[decodedCompanyName]
|
||||
);
|
||||
|
||||
if (!existingCompany || existingCompany.count === 0) {
|
||||
return res.status(404).json({ error: '企业不存在' });
|
||||
}
|
||||
|
||||
// 吊销该企业的所有序列号(将 is_active 设为 0)
|
||||
await db.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[decodedCompanyName]
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: '企业已吊销,所有序列号已失效',
|
||||
data: {
|
||||
companyName: decodedCompanyName
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('吊销企业错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
407
routes/serials.js
Normal file
407
routes/serials.js
Normal file
@@ -0,0 +1,407 @@
|
||||
const express = require('express');
|
||||
const QRCode = require('qrcode');
|
||||
const db = require('../utils/database');
|
||||
const { authenticateToken, requireAdmin } = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 生成序列号
|
||||
router.post('/generate', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { companyName, quantity = 1, validDays = 365 } = req.body;
|
||||
|
||||
if (!companyName) {
|
||||
return res.status(400).json({ error: '企业名称不能为空' });
|
||||
}
|
||||
|
||||
if (quantity < 1 || quantity > 100) {
|
||||
return res.status(400).json({ error: '生成数量必须在1-100之间' });
|
||||
}
|
||||
|
||||
// 计算有效期
|
||||
const validUntil = new Date();
|
||||
validUntil.setDate(validUntil.getDate() + validDays);
|
||||
|
||||
// 确保企业存在
|
||||
const existingCompany = await db.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||
if (!existingCompany) {
|
||||
await db.run('INSERT INTO companies (company_name, is_active) VALUES (?, 1)', [companyName]);
|
||||
}
|
||||
|
||||
// 生成序列号
|
||||
const serials = [];
|
||||
const prefix = 'BF';
|
||||
const datePart = new Date().getFullYear().toString().substr(2);
|
||||
|
||||
// 批量插入序列号
|
||||
const insertPromises = [];
|
||||
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
// 使用随机数生成序列号,避免重复
|
||||
const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
|
||||
const serialNumber = `${prefix}${datePart}${randomPart}`;
|
||||
|
||||
insertPromises.push(
|
||||
db.run(
|
||||
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
||||
[serialNumber, companyName, validUntil.toISOString().slice(0, 19).replace('T', ' '), req.user.id]
|
||||
)
|
||||
);
|
||||
|
||||
serials.push({
|
||||
serialNumber,
|
||||
companyName,
|
||||
validUntil: validUntil.toISOString(),
|
||||
createdAt: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all(insertPromises);
|
||||
|
||||
res.json({
|
||||
message: `成功生成${quantity}个序列号`,
|
||||
serials
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('生成序列号错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 生成二维码
|
||||
router.post('/:serialNumber/qrcode', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { serialNumber } = req.params;
|
||||
let { baseUrl } = req.body;
|
||||
|
||||
if (!serialNumber) {
|
||||
return res.status(400).json({ error: '序列号不能为空' });
|
||||
}
|
||||
|
||||
// 验证序列号是否存在
|
||||
const serial = await db.get(
|
||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
if (!serial) {
|
||||
return res.status(404).json({ error: '序列号不存在' });
|
||||
}
|
||||
|
||||
if (!serial.is_active) {
|
||||
return res.status(400).json({ error: '序列号已被禁用' });
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
return res.status(400).json({ error: '序列号已过期' });
|
||||
}
|
||||
|
||||
// 生成查询URL
|
||||
if (!baseUrl) {
|
||||
baseUrl = `${req.protocol}://${req.get('host')}/query.html`;
|
||||
}
|
||||
|
||||
const queryUrl = baseUrl.includes('?')
|
||||
? `${baseUrl}&serial=${serial.serial_number}`
|
||||
: `${baseUrl}?serial=${serial.serial_number}`;
|
||||
|
||||
// 生成二维码
|
||||
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
||||
width: 200,
|
||||
color: {
|
||||
dark: '#165DFF',
|
||||
light: '#ffffff'
|
||||
}
|
||||
});
|
||||
|
||||
res.json({
|
||||
message: '二维码生成成功',
|
||||
qrCodeData,
|
||||
queryUrl,
|
||||
serialNumber: serial.serial_number,
|
||||
companyName: serial.company_name,
|
||||
validUntil: serial.valid_until
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('生成二维码错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 查询序列号
|
||||
router.get('/:serialNumber/query', async (req, res) => {
|
||||
try {
|
||||
const { serialNumber } = req.params;
|
||||
|
||||
if (!serialNumber) {
|
||||
return res.status(400).json({ error: '序列号不能为空' });
|
||||
}
|
||||
|
||||
// 查询序列号
|
||||
const serial = await db.get(
|
||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
if (!serial) {
|
||||
return res.status(404).json({ error: '序列号不存在' });
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
return res.status(400).json({ error: '序列号已过期' });
|
||||
}
|
||||
|
||||
res.json({
|
||||
message: '查询成功',
|
||||
serial: {
|
||||
serialNumber: serial.serial_number,
|
||||
companyName: serial.company_name,
|
||||
validUntil: serial.valid_until,
|
||||
status: serial.is_active ? 'active' : 'disabled',
|
||||
isActive: serial.is_active,
|
||||
createdAt: serial.created_at,
|
||||
createdBy: serial.created_by_name
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('查询序列号错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取序列号列表
|
||||
router.get('/', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { page = 1, limit = 20, search = '' } = req.query;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
let query = `
|
||||
SELECT s.*, u.name as created_by_name
|
||||
FROM serials s
|
||||
LEFT JOIN users u ON s.created_by = u.id
|
||||
`;
|
||||
let countQuery = 'SELECT COUNT(*) as total FROM serials s';
|
||||
let params = [];
|
||||
|
||||
if (search) {
|
||||
query += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||
countQuery += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||
const searchParam = `%${search}%`;
|
||||
params.push(searchParam, searchParam);
|
||||
}
|
||||
|
||||
query += ' ORDER BY s.created_at DESC LIMIT ? OFFSET ?';
|
||||
params.push(parseInt(limit), parseInt(offset));
|
||||
|
||||
const [serials, countResult] = await Promise.all([
|
||||
db.all(query, params),
|
||||
db.get(countQuery, params.slice(0, -2))
|
||||
]);
|
||||
|
||||
const total = countResult ? countResult.total : 0;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
res.json({
|
||||
message: '获取序列号列表成功',
|
||||
data: serials.map(s => ({
|
||||
serialNumber: s.serial_number,
|
||||
companyName: s.company_name,
|
||||
validUntil: s.valid_until,
|
||||
isActive: s.is_active,
|
||||
createdAt: s.created_at,
|
||||
createdBy: s.created_by_name
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取序列号列表错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 更新序列号
|
||||
router.patch('/:serialNumber', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { serialNumber } = req.params;
|
||||
const { companyName, validUntil, isActive } = req.body;
|
||||
|
||||
if (!serialNumber) {
|
||||
return res.status(400).json({ error: '序列号不能为空' });
|
||||
}
|
||||
|
||||
// 检查序列号是否存在
|
||||
const existingSerial = await db.get('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
|
||||
if (!existingSerial) {
|
||||
return res.status(404).json({ error: '序列号不存在' });
|
||||
}
|
||||
|
||||
// 构建更新字段
|
||||
const updateFields = [];
|
||||
const params = [];
|
||||
|
||||
if (companyName !== undefined) {
|
||||
updateFields.push('company_name = ?');
|
||||
params.push(companyName);
|
||||
}
|
||||
|
||||
if (validUntil !== undefined) {
|
||||
updateFields.push('valid_until = ?');
|
||||
params.push(validUntil);
|
||||
}
|
||||
|
||||
if (isActive !== undefined) {
|
||||
updateFields.push('is_active = ?');
|
||||
params.push(isActive ? 1 : 0);
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
return res.status(400).json({ error: '没有提供更新字段' });
|
||||
}
|
||||
|
||||
updateFields.push('updated_at = CURRENT_TIMESTAMP');
|
||||
params.push(serialNumber.toUpperCase());
|
||||
|
||||
await db.run(
|
||||
`UPDATE serials SET ${updateFields.join(', ')} WHERE serial_number = ?`,
|
||||
params
|
||||
);
|
||||
|
||||
// 获取更新后的序列号信息
|
||||
const updatedSerial = await db.get(
|
||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: '序列号更新成功',
|
||||
serial: {
|
||||
serialNumber: updatedSerial.serial_number,
|
||||
companyName: updatedSerial.company_name,
|
||||
validUntil: updatedSerial.valid_until,
|
||||
isActive: updatedSerial.is_active,
|
||||
createdAt: updatedSerial.created_at,
|
||||
updatedAt: updatedSerial.updated_at,
|
||||
createdBy: updatedSerial.created_by_name
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('更新序列号错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 吊销序列号
|
||||
router.post('/:serialNumber/revoke', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { serialNumber } = req.params;
|
||||
|
||||
if (!serialNumber) {
|
||||
return res.status(400).json({ error: '序列号不能为空' });
|
||||
}
|
||||
|
||||
// 检查序列号是否存在
|
||||
const existingSerial = await db.get(
|
||||
'SELECT * FROM serials WHERE serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
if (!existingSerial) {
|
||||
return res.status(404).json({ error: '序列号不存在' });
|
||||
}
|
||||
|
||||
// 如果已经吊销,返回提示
|
||||
if (!existingSerial.is_active) {
|
||||
return res.status(400).json({ error: '序列号已被吊销' });
|
||||
}
|
||||
|
||||
// 吊销序列号(将 is_active 设为 0)
|
||||
await db.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: '序列号已吊销',
|
||||
data: {
|
||||
serialNumber: serialNumber.toUpperCase()
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('吊销序列号错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 自定义前缀生成序列号(管理员权限)
|
||||
router.post('/generate-with-prefix', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { companyName, quantity = 1, validDays = 365, serialPrefix } = req.body;
|
||||
|
||||
if (!companyName) {
|
||||
return res.status(400).json({ error: '企业名称不能为空' });
|
||||
}
|
||||
|
||||
if (!serialPrefix || serialPrefix.length > 10) {
|
||||
return res.status(400).json({ error: '自定义前缀不能为空且不能超过10个字符' });
|
||||
}
|
||||
|
||||
if (quantity < 1 || quantity > 100) {
|
||||
return res.status(400).json({ error: '生成数量必须在1-100之间' });
|
||||
}
|
||||
|
||||
// 计算有效期
|
||||
const validUntil = new Date();
|
||||
validUntil.setDate(validUntil.getDate() + validDays);
|
||||
|
||||
// 生成序列号
|
||||
const serials = [];
|
||||
const prefix = serialPrefix.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
|
||||
if (!prefix) {
|
||||
return res.status(400).json({ error: '自定义前缀包含无效字符,只能包含字母和数字' });
|
||||
}
|
||||
|
||||
// 批量插入序列号
|
||||
const insertPromises = [];
|
||||
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
// 使用随机数生成序列号,避免重复
|
||||
const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
|
||||
const serialNumber = `${prefix}${randomPart}`;
|
||||
|
||||
insertPromises.push(
|
||||
db.run(
|
||||
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
||||
[serialNumber, companyName, validUntil.toISOString(), req.user.id]
|
||||
)
|
||||
);
|
||||
|
||||
serials.push({
|
||||
serialNumber,
|
||||
companyName,
|
||||
validUntil: validUntil.toISOString(),
|
||||
createdAt: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all(insertPromises);
|
||||
|
||||
res.json({
|
||||
message: `成功生成${quantity}个序列号`,
|
||||
serials
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('生成序列号错误:', error);
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
97
scripts/init-db.js
Normal file
97
scripts/init-db.js
Normal file
@@ -0,0 +1,97 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const path = require('path');
|
||||
|
||||
// 创建数据库连接
|
||||
const dbPath = path.join(__dirname, '../data/database.sqlite');
|
||||
const db = new Database(dbPath, { verbose: console.log });
|
||||
|
||||
// 创建表
|
||||
const createTables = () => {
|
||||
// 用户表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT,
|
||||
role TEXT DEFAULT 'user',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// 企业表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS companies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
company_name TEXT UNIQUE NOT NULL,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// 序列号表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS serials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
serial_number TEXT UNIQUE NOT NULL,
|
||||
company_name TEXT NOT NULL,
|
||||
valid_until DATETIME,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
created_by INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (created_by) REFERENCES users (id),
|
||||
FOREIGN KEY (company_name) REFERENCES companies (company_name)
|
||||
)
|
||||
`);
|
||||
|
||||
// 创建索引
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_companies ON companies (company_name)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_serial_number ON serials (serial_number)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_serials ON serials (company_name)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_created_by ON serials (created_by)');
|
||||
|
||||
console.log('数据库表创建完成');
|
||||
};
|
||||
|
||||
// 创建默认管理员用户
|
||||
const createDefaultUser = async () => {
|
||||
const username = 'admin';
|
||||
const password = 'Beifan@2026';
|
||||
const name = '系统管理员';
|
||||
|
||||
// 检查用户是否已存在
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
||||
|
||||
if (!user) {
|
||||
// 哈希密码
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
|
||||
// 创建用户
|
||||
db.prepare(
|
||||
'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)'
|
||||
).run(username, hashedPassword, name, 'admin@example.com', 'admin');
|
||||
|
||||
console.log('默认管理员用户创建完成:');
|
||||
console.log('用户名:', username);
|
||||
console.log('密码:', password);
|
||||
} else {
|
||||
console.log('默认管理员用户已存在');
|
||||
}
|
||||
};
|
||||
|
||||
// 初始化数据库
|
||||
const initDatabase = async () => {
|
||||
createTables();
|
||||
await createDefaultUser();
|
||||
|
||||
// 关闭数据库连接
|
||||
db.close();
|
||||
console.log('数据库连接已关闭');
|
||||
};
|
||||
|
||||
initDatabase();
|
||||
75
server.js
Normal file
75
server.js
Normal file
@@ -0,0 +1,75 @@
|
||||
require('dotenv').config({ path: __dirname + '/.env' });
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
|
||||
// 导入路由
|
||||
const authRoutes = require('./routes/auth');
|
||||
const serialRoutes = require('./routes/serials');
|
||||
const companyRoutes = require('./routes/companies');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// 中间件
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
// 设置响应编码
|
||||
app.use((req, res, next) => {
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
next();
|
||||
});
|
||||
|
||||
// API路由(必须在静态文件服务之前)
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/serials', serialRoutes);
|
||||
app.use('/api/companies', companyRoutes);
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/health', (req, res) => {
|
||||
res.json({ status: 'ok', message: '服务器运行正常' });
|
||||
});
|
||||
|
||||
// 静态文件服务
|
||||
const frontendPath = path.join(__dirname, '..', 'frontend');
|
||||
const distPath = path.join(frontendPath, 'dist');
|
||||
const publicPath = path.join(frontendPath, 'public');
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
app.use(express.static(distPath));
|
||||
} else {
|
||||
app.use(express.static(publicPath));
|
||||
}
|
||||
|
||||
// 404处理
|
||||
app.use((req, res) => {
|
||||
if (req.path.startsWith('/api/')) {
|
||||
res.status(404).json({ error: 'API接口不存在' });
|
||||
} else {
|
||||
// 对于非API请求,返回index.html(用于React Router)
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
res.sendFile(path.join(distPath, 'index.html'));
|
||||
} else {
|
||||
res.sendFile(path.join(publicPath, 'index.html'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 错误处理中间件
|
||||
app.use((error, req, res, next) => {
|
||||
console.error('服务器错误:', error);
|
||||
|
||||
if (req.path.startsWith('/api/')) {
|
||||
res.status(500).json({ error: '服务器内部错误' });
|
||||
} else {
|
||||
res.status(500).send('服务器内部错误');
|
||||
}
|
||||
});
|
||||
|
||||
// 启动服务器
|
||||
app.listen(PORT, () => {
|
||||
console.log(`服务器运行在 http://localhost:${PORT}`);
|
||||
console.log(`API文档: http://localhost:${PORT}/api/health`);
|
||||
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
|
||||
});
|
||||
50
utils/database.js
Normal file
50
utils/database.js
Normal file
@@ -0,0 +1,50 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
|
||||
class DatabaseWrapper {
|
||||
constructor() {
|
||||
this.dbPath = process.env.DB_PATH || path.join(__dirname, '../data/database.sqlite');
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
}
|
||||
|
||||
// 查询单个记录
|
||||
get(sql, params = []) {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params);
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 查询多个记录
|
||||
all(sql, params = []) {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params);
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行插入、更新、删除操作
|
||||
run(sql, params = []) {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭数据库连接
|
||||
close() {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new DatabaseWrapper();
|
||||
Reference in New Issue
Block a user