first commit
This commit is contained in:
21
backend/src/middleware/auth.ts
Normal file
21
backend/src/middleware/auth.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
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" });
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user