39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
import * as Jwt from 'jsonwebtoken'; // Correct way to import jsonwebtoken
|
|
|
|
// Define a new interface extending Request
|
|
interface AuthenticatedRequest extends Request {
|
|
user?: {
|
|
email: string;
|
|
// Add more fields as needed based on your JWT payload
|
|
};
|
|
}
|
|
const tokenGenerator = (email: string) => {
|
|
const token = Jwt.sign({ email: email }, "Milestone", {
|
|
expiresIn: "3hours",
|
|
});
|
|
return token;
|
|
};
|
|
|
|
const tokenValidator = (req: AuthenticatedRequest, res: Response, next: NextFunction): void => {
|
|
const token: string | undefined = req.headers.token as string | undefined;
|
|
if (!token) {
|
|
res.status(403).json({
|
|
msg: "No token present",
|
|
});
|
|
return; // Make sure to return after sending a response
|
|
}
|
|
|
|
try {
|
|
const decoded = Jwt.verify(token,"Milestone") as { email: string }; // adjust if your JWT payload has more fields
|
|
req.user = decoded;
|
|
next();
|
|
} catch (err) {
|
|
res.status(401).json({
|
|
msg: "Invalid Token",
|
|
});
|
|
}
|
|
};
|
|
|
|
export { tokenValidator,tokenGenerator };
|