-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-jwt.js
More file actions
160 lines (134 loc) · 5.6 KB
/
test-jwt.js
File metadata and controls
160 lines (134 loc) · 5.6 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
// ================================================
// JWT TEST SCRIPT
// Save as: backend/test-jwt.js
// Run with: node backend/test-jwt.js
// ================================================
const jwt = require('jsonwebtoken');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '.env') });
console.log('\n========================================');
console.log('JWT CONFIGURATION TEST');
console.log('========================================\n');
// Test 1: Check if JWT_SECRET exists
console.log('Test 1: JWT_SECRET Configuration');
console.log('--------------------------------');
if (!process.env.JWT_SECRET) {
console.log('❌ FAILED: JWT_SECRET not found in .env file');
console.log(' Please add JWT_SECRET=your_secret_key to .env');
process.exit(1);
} else {
console.log('✅ PASSED: JWT_SECRET found');
console.log(' Length:', process.env.JWT_SECRET.length, 'characters');
console.log(' Value:', process.env.JWT_SECRET);
}
console.log('\n');
// Test 2: Generate a test token
console.log('Test 2: Token Generation');
console.log('--------------------------------');
try {
const testPayload = {
id: '507f1f77bcf86cd799439011',
username: 'testuser',
role: 'Admin'
};
const token = jwt.sign(testPayload, process.env.JWT_SECRET, { expiresIn: '8h' });
console.log('✅ PASSED: Token generated successfully');
console.log(' Token length:', token.length);
console.log(' Token parts:', token.split('.').length, '(should be 3)');
console.log(' Token preview:', token.substring(0, 50) + '...');
// Store for next test
global.testToken = token;
} catch (error) {
console.log('❌ FAILED: Could not generate token');
console.log(' Error:', error.message);
process.exit(1);
}
console.log('\n');
// Test 3: Verify the token
console.log('Test 3: Token Verification');
console.log('--------------------------------');
try {
const decoded = jwt.verify(global.testToken, process.env.JWT_SECRET);
console.log('✅ PASSED: Token verified successfully');
console.log(' Decoded payload:', JSON.stringify(decoded, null, 2));
// Check payload fields
if (decoded.id && decoded.username && decoded.role) {
console.log(' ✅ All expected fields present');
} else {
console.log(' ⚠️ Some fields missing from payload');
}
} catch (error) {
console.log('❌ FAILED: Token verification failed');
console.log(' Error:', error.message);
process.exit(1);
}
console.log('\n');
// Test 4: Test malformed token handling
console.log('Test 4: Malformed Token Handling');
console.log('--------------------------------');
const malformedTokens = [
{ name: 'Empty string', value: '' },
{ name: 'Invalid format', value: 'not.a.valid.token' },
{ name: 'Missing parts', value: 'onlyonepart' },
{ name: 'Random string', value: 'randomstring123' }
];
let malformedTestsPassed = 0;
malformedTokens.forEach(test => {
try {
jwt.verify(test.value, process.env.JWT_SECRET);
console.log(` ❌ ${test.name}: Should have failed but didn't`);
} catch (error) {
console.log(` ✅ ${test.name}: Correctly rejected (${error.name})`);
malformedTestsPassed++;
}
});
console.log(` ${malformedTestsPassed}/${malformedTokens.length} malformed tokens correctly rejected`);
console.log('\n');
// Test 5: Bearer token format handling
console.log('Test 5: Bearer Format Handling');
console.log('--------------------------------');
const bearerToken = `Bearer ${global.testToken}`;
const extractedToken = bearerToken.substring(7);
if (extractedToken === global.testToken) {
console.log('✅ PASSED: Bearer prefix extraction works');
console.log(' Original:', bearerToken.substring(0, 50) + '...');
console.log(' Extracted:', extractedToken.substring(0, 50) + '...');
} else {
console.log('❌ FAILED: Bearer prefix extraction failed');
}
console.log('\n');
// Test 6: Expiration check
console.log('Test 6: Token Expiration');
console.log('--------------------------------');
try {
const decoded = jwt.verify(global.testToken, process.env.JWT_SECRET);
const now = Math.floor(Date.now() / 1000);
const expiresAt = new Date(decoded.exp * 1000);
const timeUntilExpiry = decoded.exp - now;
console.log('✅ PASSED: Expiration data correct');
console.log(' Issued at:', new Date(decoded.iat * 1000).toLocaleString());
console.log(' Expires at:', expiresAt.toLocaleString());
console.log(' Time until expiry:', Math.floor(timeUntilExpiry / 3600), 'hours');
if (timeUntilExpiry > 0) {
console.log(' ✅ Token is still valid');
} else {
console.log(' ❌ Token is expired');
}
} catch (error) {
console.log('❌ FAILED: Could not check expiration');
console.log(' Error:', error.message);
}
console.log('\n========================================');
console.log('TEST SUMMARY');
console.log('========================================\n');
console.log('All tests passed! ✅');
console.log('\nYour JWT configuration is working correctly.');
console.log('If you still have auth issues, the problem is likely in:');
console.log(' 1. How the token is being saved after login');
console.log(' 2. How the token is being sent in API requests');
console.log(' 3. How the auth middleware is extracting the token');
console.log('\nNext steps:');
console.log(' 1. Replace backend/middleware/auth.js with auth-debug.js');
console.log(' 2. Clear browser localStorage');
console.log(' 3. Login again and check server logs');
console.log('\n========================================\n');