Skip to content

Commit 51bcffc

Browse files
committed
feat : protect middlewear
1 parent 8962445 commit 51bcffc

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

.env

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
PORT = 5050 #Your Port
2-
MONGOURI = <your-mongodb>
2+
# MONGOURI = <your-mongodb>
3+
MONGOURI ="mongodb+srv://puskarroy300:[email protected]/?retryWrites=true&w=majority"
34

45
MODE = DEV # DEV = devlopment or PROD = production
56

src/controllers/authController.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const validator = require('validator')
66
const { config } = require('../configs/config')
77

88
const testRoute = catchError(async (req, res) => {
9-
res.json({ success: true })
9+
res.json({ success: true, message: 'API IS WORKING 🥳' })
1010
})
1111

1212
const login = catchError(async (req, res) => {

src/middlewear/authMiddlewear.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const jwt = require('jsonwebtoken')
2+
const config = require('../configs/config')
3+
4+
const protect = (req, res, next) => {
5+
try {
6+
const token = req.headers.authorization?.split(' ')[1]
7+
if (!token) {
8+
return res.status(401).json({
9+
success: false,
10+
message: 'Unauthorized: No token provided',
11+
})
12+
}
13+
14+
const decoded = jwt.verify(token, config.JWT_SECRET)
15+
req.userId = decoded.userId
16+
next()
17+
} catch (error) {
18+
console.error('Authentication error:', error)
19+
return res.status(401).json({
20+
success: false,
21+
message: 'Unauthorized: Invalid token',
22+
})
23+
}
24+
}
25+
26+
module.exports = protect

0 commit comments

Comments
 (0)