Repository navigation
Expand file tree
/
Copy pathauthMiddleware.js
More file actions
238 lines (204 loc) · 6.04 KB
/
Copy pathauthMiddleware.js
File metadata and controls
238 lines (204 loc) · 6.04 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// middleware/authMiddleware.js
// const { PrismaClient } = require('@prisma/client');
// const prisma = new PrismaClient();
import jwt from 'jsonwebtoken';
import { Prisma } from './src/config/db.js';
/**
* JWT Authentication Middleware
*/
// export const authenticateToken = (req, res, next) => {
// const authHeader = req.headers['authorization'];
// const token = authHeader && authHeader.split(' ')[1];
// console.error('JWT token:', token);
// if (!token) {
// return res.status(401).json({
// status: 'error',
// message: 'Access token required'
// });
// }
// try {
// const decoded = jwt.verify(token, process.env.JWT_SECRET);
// req.user = decoded;
// next();
// } catch (err) {
// console.error('JWT verification error:', err.message);
// return res.status(403).json({
// status: 'error',
// message: 'Invalid or expired token'
// });
// }
// };
export const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
// console.log('Authorization header:', authHeader);
// console.log('Token extracted:', token ? 'Yes' : 'No');
if (!token) {
return res.status(401).json({
status: 'error',
message: 'Access token required'
});
}
try {
// Decode without verification first to check payload
const decodedWithoutVerify = jwt.decode(token);
// console.log('Decoded token payload:', decodedWithoutVerify);
// Check if token is from future
const currentTime = Math.floor(Date.now() / 1000);
// console.log('Current time:', currentTime);
// if (decodedWithoutVerify.iat > currentTime) {
// console.error('Token issued in the future!');
// console.error('Token iat:', decodedWithoutVerify.iat);
// console.error('Current time:', currentTime);
// console.error('Difference:', decodedWithoutVerify.iat - currentTime, 'seconds');
// }
// Now verify with secret
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
// console.error('JWT verification error:', err.message);
// console.error('Error name:', err.name);
if (err.name === 'TokenExpiredError') {
return res.status(403).json({
status: 'error',
message: 'Token has expired',
expiredAt: err.expiredAt
});
} else if (err.name === 'JsonWebTokenError') {
return res.status(403).json({
status: 'error',
message: 'Invalid token'
});
}
return res.status(403).json({
status: 'error',
message: 'Invalid or expired token'
});
}
};
/**
* Verify admin role
*/
export const verifyAdmin = async (req, res, next) => {
try {
// Get token from Authorization header
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
status: 'error',
message: 'Authentication token required. Format: Bearer <token>'
});
}
const token = authHeader.replace('Bearer ', '');
if (!token) {
return res.status(401).json({
status: 'error',
message: 'Token is missing'
});
}
// Find admin by token
const admin = await Prisma.ci_admin.findFirst({
where: {
token: token,
is_active: 1 // Only active admins
}
});
if (!admin) {
return res.status(401).json({
status: 'error',
message: 'Invalid or expired token. Please login again.'
});
}
// Attach admin to request object for use in routes
req.admin = {
admin_id: admin.admin_id,
username: admin.username,
email: admin.email,
firstname: admin.firstname,
lastname: admin.lastname,
admin_role_id: admin.admin_role_id,
is_supper: admin.is_supper
};
// Continue to the next middleware/route
next();
} catch (error) {
console.error('Auth middleware error:', error);
// Handle specific Prisma errors
if (error.name === 'PrismaClientKnownRequestError') {
return res.status(500).json({
status: 'error',
message: 'Database error during authentication'
});
}
return res.status(500).json({
status: 'error',
message: 'Authentication failed'
});
}
};
/**
* Check specific permission
* Optional: Middleware to check admin role/permissions
*/
export const checkPermission = (requiredRole = null) => {
return (req, res, next) => {
if (!req.admin) {
return res.status(401).json({
status: 'error',
message: 'Authentication required'
});
}
// Super admin has all permissions
if (req.admin.is_supper === 1) {
return next();
}
// Check specific role if required
if (requiredRole && req.admin.admin_role_id !== requiredRole) {
return res.status(403).json({
status: 'error',
message: 'Insufficient permissions'
});
}
next();
};
};
/**
* Optional authentication
* Optional: Public routes that don't require authentication
*/
export const optionalAuth = async (req, res, next) => {
try {
const authHeader = req.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ')) {
const token = authHeader.replace('Bearer ', '');
const admin = await Prisma.ci_admin.findFirst({
where: {
token: token,
is_active: 1
}
});
if (admin) {
req.admin = {
admin_id: admin.admin_id,
username: admin.username,
email: admin.email,
firstname: admin.firstname,
lastname: admin.lastname,
admin_role_id: admin.admin_role_id,
is_supper: admin.is_supper
};
}
}
next();
} catch (error) {
// Don't block request for optional auth
console.error('Optional auth error:', error);
next();
}
};
// module.exports = {
// verifyAdmin,
// checkPermission,
// optionalAuth
// };