Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: authenticate user token
  • Loading branch information
himanshu-contentstack committed Jan 4, 2024
commit 60e95bce1a8c981801f3c46c936c2566019818ae
1 change: 1 addition & 0 deletions .env.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SECRET_KEY_DEV=MIGRATION_API_V2_DEV;
1 change: 1 addition & 0 deletions .env.prod
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SECRET_KEY_PROD=MIGRATION_API_V2_PROD;
26 changes: 21 additions & 5 deletions src/middlewares/auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
// middleware/authentication.middleware.ts
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";

export const authenticateUser = (
req: Request,
res: Response,
next: NextFunction
): void => {
) => {
// Simulate authentication logic (e.g., check for a token)
const isAuthenticated = /* Your authentication logic here */ true;
if (isAuthenticated) {
next(); // User is authenticated, proceed to the next middleware or route handler
const token = req.headers.authorization?.split(" ")[1];
const secretKey =
process.env.NODE_ENV === "dev" ?
process.env.SECRET_KEY_DEV!
: process.env.SECRET_KEY_PROD!;
if (token) {
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return res
.status(401)
.json({ message: "Unauthorized - Invalid token" });
}

// Attach the decoded token to the request object for later use
(req as any).decodedToken = decoded;

next();
});
} else {
res.status(401).json({ message: "Authentication failed" });
return res.status(401).json({ message: "Unauthorized - Token missing" });
}
};