diff --git a/backend/src/middleware/auth.js b/backend/src/middleware/auth.js index a83d6e2..7ae24af 100644 --- a/backend/src/middleware/auth.js +++ b/backend/src/middleware/auth.js @@ -1,10 +1,10 @@ import jwt from 'jsonwebtoken'; -import db from '../database.js'; +import { pool } from '../database.js'; const SECRET = process.env.JWT_SECRET || 'yx-nav-secret-2026'; /** JWT 认证中间件 */ -export function authenticate(req, res, next) { +export async function authenticate(req, res, next) { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { return res.status(401).json({ status: 401, message: '未登录' }); @@ -12,7 +12,8 @@ export function authenticate(req, res, next) { try { const token = authHeader.slice(7); const payload = jwt.verify(token, SECRET); - const user = db.prepare('SELECT id, username, nickname, role FROM users WHERE id = ?').get(payload.userId); + const [rows] = await pool.query('SELECT id, username, nickname, role FROM users WHERE id = ?', [payload.userId]); + const user = rows[0]; if (!user) return res.status(401).json({ status: 401, message: '用户不存在' }); req.user = user; next();