Files
cc-cloud/backend/src/middleware/auth.middleware.ts
T

63 lines
1.5 KiB
TypeScript
Raw Normal View History

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';
import logger from '../utils/logger';
// 扩展 Express Request 类型
declare global {
namespace Express {
interface Request {
2026-01-02 23:04:49 +08:00
session?: SessionPayload;
}
}
}
export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
const authHeader = req.headers.authorization;
if (!authHeader) {
res.status(401).json({ error: '未提供认证令牌' });
return;
}
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) {
res.status(401).json({ error: '无效的认证令牌' });
return;
2026-01-02 23:04:49 +08:00
}
req.session = decoded;
next();
} catch (error: any) {
logger.error('Token 验证失败', error);
res.status(401).json({ error: '无效的认证令牌' });
}
}
// 可选认证(不强制要求登录)
export function optionalAuth(req: Request, _res: Response, next: NextFunction): void {
const authHeader = req.headers.authorization;
if (!authHeader) {
next();
return;
}
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;
}
} catch (error) {
// 忽略错误,继续处理请求
}
next();
}