87 lines
2.8 KiB
JavaScript
87 lines
2.8 KiB
JavaScript
const express = require('express');
|
|
const bcrypt = require('bcryptjs');
|
|
const jwt = require('jsonwebtoken');
|
|
const { db } = require('../database');
|
|
const { JWT_SECRET } = require('../config');
|
|
const { authenticateToken } = require('../middleware/auth');
|
|
|
|
const router = express.Router();
|
|
|
|
router.post('/register', async (req, res) => {
|
|
try {
|
|
const { username, password } = req.body;
|
|
|
|
if (!username || !password) {
|
|
return res.status(400).json({ success: false, error: '用户名和密码不能为空' });
|
|
}
|
|
|
|
if (username.length < 3) {
|
|
return res.status(400).json({ success: false, error: '用户名至少需要3个字符' });
|
|
}
|
|
|
|
if (password.length < 6) {
|
|
return res.status(400).json({ success: false, error: '密码至少需要6个字符' });
|
|
}
|
|
|
|
const passwordHash = await bcrypt.hash(password, 10);
|
|
|
|
db.run(
|
|
'INSERT INTO users (username, password_hash) VALUES (?, ?)',
|
|
[username, passwordHash],
|
|
function (err) {
|
|
if (err) {
|
|
if (err.message.includes('UNIQUE constraint failed')) {
|
|
return res.status(400).json({ success: false, error: '用户名已存在' });
|
|
}
|
|
return res.status(500).json({ success: false, error: '注册失败' });
|
|
}
|
|
|
|
const token = jwt.sign({ userId: this.lastID, username }, JWT_SECRET, { expiresIn: '7d' });
|
|
res.json({ success: true, token, userId: this.lastID, username });
|
|
}
|
|
);
|
|
} catch (error) {
|
|
res.status(500).json({ success: false, error: error.message });
|
|
}
|
|
});
|
|
|
|
router.post('/login', (req, res) => {
|
|
try {
|
|
const { username, password } = req.body;
|
|
|
|
if (!username || !password) {
|
|
return res.status(400).json({ success: false, error: '用户名和密码不能为空' });
|
|
}
|
|
|
|
db.get(
|
|
'SELECT * FROM users WHERE username = ?',
|
|
[username],
|
|
async (err, user) => {
|
|
if (err) {
|
|
return res.status(500).json({ success: false, error: '登录失败' });
|
|
}
|
|
|
|
if (!user) {
|
|
return res.status(401).json({ success: false, error: '用户名或密码错误' });
|
|
}
|
|
|
|
const validPassword = await bcrypt.compare(password, user.password_hash);
|
|
if (!validPassword) {
|
|
return res.status(401).json({ success: false, error: '用户名或密码错误' });
|
|
}
|
|
|
|
const token = jwt.sign({ userId: user.id, username: user.username }, JWT_SECRET, { expiresIn: '7d' });
|
|
res.json({ success: true, token, userId: user.id, username: user.username });
|
|
}
|
|
);
|
|
} catch (error) {
|
|
res.status(500).json({ success: false, error: error.message });
|
|
}
|
|
});
|
|
|
|
router.get('/me', authenticateToken, (req, res) => {
|
|
res.json({ success: true, userId: req.user.userId, username: req.user.username });
|
|
});
|
|
|
|
module.exports = router;
|