2026-01-02 22:57:33 +08:00
|
|
|
import { Request, Response, NextFunction } from 'express';
|
|
|
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
|
import { config } from '../config';
|
2026-01-02 23:04:49 +08:00
|
|
|
import type { SessionPayload } from '../types';
|
2026-01-02 22:57:33 +08:00
|
|
|
import logger from '../utils/logger';
|
|
|
|
|
|
|
|
|
|
// 扩展 Express Request 类型
|
|
|
|
|
declare global {
|
|
|
|
|
namespace Express {
|
|
|
|
|
interface Request {
|
2026-01-02 23:04:49 +08:00
|
|
|
session?: SessionPayload;
|
2026-01-02 22:57:33 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-02 23:20:19 +08:00
|
|
|
export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
|
2026-01-02 22:57:33 +08:00
|
|
|
const authHeader = req.headers.authorization;
|
|
|
|
|
|
|
|
|
|
if (!authHeader) {
|
2026-01-02 23:20:19 +08:00
|
|
|
res.status(401).json({ error: '未提供认证令牌' });
|
|
|
|
|
return;
|
2026-01-02 22:57:33 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const token = authHeader.replace('Bearer ', '');
|
|
|
|
|
|
|
|
|
|
try {
|
2026-01-02 23:04:49 +08:00
|
|
|
const decoded = jwt.verify(token, config.accessPassword) as SessionPayload;
|
|
|
|
|
|
|
|
|
|
if (!decoded.authenticated) {
|
2026-01-02 23:20:19 +08:00
|
|
|
res.status(401).json({ error: '无效的认证令牌' });
|
|
|
|
|
return;
|
2026-01-02 23:04:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req.session = decoded;
|
2026-01-02 22:57:33 +08:00
|
|
|
next();
|
|
|
|
|
} catch (error: any) {
|
|
|
|
|
logger.error('Token 验证失败', error);
|
2026-01-02 23:20:19 +08:00
|
|
|
res.status(401).json({ error: '无效的认证令牌' });
|
2026-01-02 22:57:33 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 可选认证(不强制要求登录)
|
2026-01-02 23:20:19 +08:00
|
|
|
export function optionalAuth(req: Request, _res: Response, next: NextFunction): void {
|
2026-01-02 22:57:33 +08:00
|
|
|
const authHeader = req.headers.authorization;
|
|
|
|
|
|
|
|
|
|
if (!authHeader) {
|
2026-01-02 23:20:19 +08:00
|
|
|
next();
|
|
|
|
|
return;
|
2026-01-02 22:57:33 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const token = authHeader.replace('Bearer ', '');
|
|
|
|
|
|
|
|
|
|
try {
|
2026-01-02 23:04:49 +08:00
|
|
|
const decoded = jwt.verify(token, config.accessPassword) as SessionPayload;
|
|
|
|
|
if (decoded.authenticated) {
|
|
|
|
|
req.session = decoded;
|
|
|
|
|
}
|
2026-01-02 22:57:33 +08:00
|
|
|
} catch (error) {
|
|
|
|
|
// 忽略错误,继续处理请求
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
next();
|
|
|
|
|
}
|