Spaces:
Sleeping
Sleeping
File size: 1,182 Bytes
f0953a4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// filepath: /D:/code/CloudDiskDown/backend/src/middleware/auth.ts
import { Request, Response, NextFunction } from "express";
import jwt, { JwtPayload } from "jsonwebtoken";
import User from "../models/User";
import { config } from "../config";
interface AuthenticatedRequest extends Request {
user?: {
userId: string;
role: number;
};
}
export const authMiddleware = async (
req: AuthenticatedRequest,
res: Response,
next: NextFunction
): Promise<void | Response> => {
if (req.path === "/user/login" || req.path === "/user/register" || req.path === "/tele-images/") {
return next();
}
const token = req.headers.authorization?.split(" ")[1];
if (!token) {
return res.status(401).json({ message: "未提供 token" });
}
try {
const decoded = jwt.verify(token, config.jwtSecret) as JwtPayload;
req.user = {
userId: decoded.userId,
role: decoded.role,
};
const user = await User.findOne({ where: { userId: decoded.userId } });
if (!user) {
return res.status(401).json({ message: "无效的 token" });
}
next();
} catch (error) {
res.status(401).json({ message: "无效的 token" });
}
};
|