forked from geturbackend/urBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthMiddleware.js
More file actions
41 lines (33 loc) · 1.17 KB
/
Copy pathauthMiddleware.js
File metadata and controls
41 lines (33 loc) · 1.17 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
const jwt = require('jsonwebtoken');
const { AppError } = require('@urbackend/common');
module.exports = function (req, res, next) {
// Check for token in cookies (Primary for Web)
let token = req.cookies && req.cookies.accessToken;
// Fallback to Authorization header (For CLI/API)
if (!token) {
const authHeader = req.header('Authorization');
if (authHeader) {
const parts = authHeader.trim().split(/\s+/);
if (parts.length === 2 && parts[0].toLowerCase() === 'bearer') {
token = parts[1];
}
}
}
// Check if any token was provided
if (!token) {
return next(new AppError(401, 'Access Denied: No Token Provided'));
}
try {
// Verify the token using the secret key
const verified = jwt.verify(token, process.env.JWT_SECRET);
// Attach decoded token data to request object
req.user = verified;
// Proceed to the next middleware or route handler
next();
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
return next(new AppError(401, 'Invalid Token'));
}
};