import { Request, Response } from 'express' import jwt from 'jsonwebtoken' const JWT_SECRET = process.env.JWT_SECRET || 'jewelry-mall-secret' const ADMIN_USERNAME = process.env.ADMIN_USERNAME || 'admin' const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'admin123' export function adminLogin(req: Request, res: Response): void { const { username, password } = req.body if (!username || !password) { res.status(400).json({ code: 400, message: '用户名和密码不能为空' }) return } if (username !== ADMIN_USERNAME || password !== ADMIN_PASSWORD) { res.status(401).json({ code: 401, message: '用户名或密码错误' }) return } const token = jwt.sign({ role: 'admin', username }, JWT_SECRET, { expiresIn: '24h' }) res.json({ code: 0, data: { token } }) } export function verifyAdmin(req: Request, res: Response, next: Function): void { const authHeader = req.headers.authorization if (!authHeader || !authHeader.startsWith('Bearer ')) { res.status(401).json({ code: 401, message: '未授权' }) return } try { const decoded = jwt.verify(authHeader.slice(7), JWT_SECRET) as { role: string } if (decoded.role !== 'admin') { res.status(403).json({ code: 403, message: '权限不足' }) return } next() } catch { res.status(401).json({ code: 401, message: 'token 无效或已过期' }) } }