-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
44 lines (36 loc) · 1.07 KB
/
Copy pathauth.js
File metadata and controls
44 lines (36 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const jwt = require('jsonwebtoken');
const User = require('./User');
// Protect routes - only logged-in users can access
const protect = async (req, res, next) => {
let token;
// Check if Authorization header exists
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
// Extract token from "Bearer <token>"
token = req.headers.authorization.split(' ')[1];
// Verify token is valid
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Get user from database
req.user = await User.findById(decoded.id).select('-password');
if (!req.user) {
return res.status(401).json({
success: false,
message: 'User not found'
});
}
next();
} catch (error) {
return res.status(401).json({
success: false,
message: 'Not authorized, token failed'
});
}
}
if (!token) {
return res.status(401).json({
success: false,
message: 'Not authorized, no token provided'
});
}
};
module.exports = { protect };