Files
notify/backend/src/middleware/auth.ts
Michael Dong a98e12f286 first commit
2026-02-05 11:24:40 +08:00

22 lines
732 B
TypeScript

import type { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
export type AuthRequest = Request & { userId?: string };
export const requireAuth = (req: AuthRequest, res: Response, next: NextFunction) => {
const header = req.headers.authorization;
if (!header?.startsWith("Bearer ")) {
return res.status(401).json({ error: "Unauthorized" });
}
const token = header.slice("Bearer ".length);
try {
const payload = jwt.verify(token, process.env.JWT_SECRET || "dev-secret") as {
userId: string;
};
req.userId = payload.userId;
return next();
} catch {
return res.status(401).json({ error: "Unauthorized" });
}
};