-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauth-callback.html
More file actions
317 lines (287 loc) · 14.5 KB
/
auth-callback.html
File metadata and controls
317 lines (287 loc) · 14.5 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<!DOCTYPE html>
<html>
<head>
<title>Authentication - Electrisim</title>
<meta charset="utf-8">
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f5f5f5;
}
.auth-container {
text-align: center;
background: white;
padding: 40px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #48d800;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 2s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.error {
color: #d32f2f;
background: #ffebee;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
}
.success {
color: #2e7d32;
background: #e8f5e8;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
}
</style>
</head>
<body>
<div class="auth-container">
<h2>Authenticating...</h2>
<div class="spinner"></div>
<p id="status">Processing authentication...</p>
<div id="message"></div>
</div>
<script>
// Smartlook error tracking helper
function trackAuthError(errorType, errorDetails, userContext = {}) {
try {
if (typeof smartlook !== 'undefined') {
smartlook('track', 'auth_error', {
error_type: errorType,
error_message: errorDetails.message || errorDetails,
error_code: errorDetails.code || 'unknown',
timestamp: new Date().toISOString(),
user_agent: navigator.userAgent,
url: window.location.href,
user_context: {
has_token: !!localStorage.getItem('token'),
has_user: !!localStorage.getItem('user'),
...userContext
}
});
}
} catch (e) {
console.warn('Failed to track auth error with Smartlook:', e);
}
}
// Track successful OAuth authentication
function trackAuthSuccess(authType, userData = {}) {
try {
if (typeof smartlook !== 'undefined') {
smartlook('track', 'auth_success', {
auth_type: authType,
timestamp: new Date().toISOString(),
user_agent: navigator.userAgent,
url: window.location.href,
user_context: {
user_id: userData.id || 'unknown',
user_email: userData.email || 'unknown',
has_stripe_customer: !!userData.stripeCustomerId
}
});
}
} catch (e) {
console.warn('Failed to track auth success with Smartlook:', e);
}
}
// Handle authentication callback
(function() {
console.log('🔍 AUTH CALLBACK PAGE LOADED');
console.log('🔍 Current URL:', window.location.href);
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
const error = urlParams.get('error');
const statusElement = document.getElementById('status');
const messageElement = document.getElementById('message');
console.log('🔍 URL Parameters:');
console.log('🔍 - token:', token ? 'PRESENT' : 'MISSING');
console.log('🔍 - error:', error);
console.log('🔍 - All params:', Object.fromEntries(urlParams.entries()));
if (error) {
// Track OAuth error
trackAuthError('oauth_callback_error', {
message: error,
code: 'oauth_failed'
});
statusElement.textContent = 'Authentication failed';
messageElement.innerHTML = '<div class="error">Authentication failed. Please try again.</div>';
setTimeout(() => {
const isDevelopment = window.location.hostname === '127.0.0.1' || window.location.hostname === 'localhost';
const loginUrl = isDevelopment
? 'http://127.0.0.1:5501/src/main/webapp/login.html' // Development path (Live Server)
: '/login.html'; // Production path
window.location.href = loginUrl;
}, 3000);
return;
}
if (token) {
try {
console.log('✅ TOKEN FOUND - Processing OAuth callback...');
// Test localStorage availability
try {
localStorage.setItem('test', 'test');
localStorage.removeItem('test');
console.log('✅ localStorage is available');
} catch (e) {
console.error('❌ localStorage is NOT available:', e);
throw new Error('localStorage not available');
}
// Store the token
console.log('📝 Storing token...');
localStorage.setItem('token', token);
console.log('✅ Token stored successfully');
// Decode token to get user info (basic decode, not verification)
console.log('🔓 Decoding token...');
const payload = JSON.parse(atob(token.split('.')[1]));
console.log('✅ Token decoded successfully. Payload:', payload);
if (payload.email) {
const userData = {
id: payload.id,
email: payload.email,
stripeCustomerId: payload.stripeCustomerId
};
console.log('📝 Storing user data:', userData);
localStorage.setItem('user', JSON.stringify(userData));
console.log('✅ User data stored successfully');
// Track successful OAuth authentication
trackAuthSuccess('oauth', userData);
// Double-check storage worked
const storedToken = localStorage.getItem('token');
const storedUser = localStorage.getItem('user');
console.log('🔍 Final verification:');
console.log('🔍 - Token in storage:', !!storedToken, storedToken ? '(length: ' + storedToken.length + ')' : '');
console.log('🔍 - User in storage:', !!storedUser, storedUser ? '(data: ' + storedUser + ')' : '');
// Test if we can retrieve and parse the stored data
try {
const retrievedUser = JSON.parse(storedUser);
console.log('✅ Retrieved user data:', retrievedUser);
} catch (parseError) {
console.error('❌ Error parsing stored user data:', parseError);
trackAuthError('token_parse_error', parseError, { user_id: userData.id });
}
} else {
console.warn('⚠️ No email found in token payload');
trackAuthError('token_missing_email', { message: 'No email found in token payload' });
}
statusElement.textContent = 'Authentication successful!';
messageElement.innerHTML = '<div class="success">Redirecting to application...</div>';
// Dispatch login event
document.dispatchEvent(new CustomEvent('userLoggedIn', {
detail: {
user: {
id: payload.id,
email: payload.email,
stripeCustomerId: payload.stripeCustomerId
}
}
}));
// Dispatch auth state change event
document.dispatchEvent(new CustomEvent('authStateChanged', {
detail: {
isAuthenticated: true,
user: {
id: payload.id,
email: payload.email,
stripeCustomerId: payload.stripeCustomerId
}
}
}));
// Also dispatch a specific OAuth success event
document.dispatchEvent(new CustomEvent('oauthSuccess', {
detail: {
user: {
id: payload.id,
email: payload.email,
stripeCustomerId: payload.stripeCustomerId
}
}
}));
// Redirect to main application
setTimeout(() => {
try {
// Use correct path based on environment
const isDevelopment = window.location.hostname === '127.0.0.1' || window.location.hostname === 'localhost';
const indexUrl = isDevelopment
? 'http://127.0.0.1:5501/src/main/webapp/index.html' // Development path (Live Server)
: '/index.html'; // Production path
// Use window.location.replace instead of href to avoid unload issues
window.location.replace(indexUrl);
} catch (redirectError) {
console.error('Redirect error:', redirectError);
// Fallback: try with href
window.location.href = indexUrl;
}
}, 2000);
} catch (error) {
console.error('Error processing token:', error);
// Track token processing error
trackAuthError('token_processing_error', {
message: error.message,
code: 'token_invalid'
});
statusElement.textContent = 'Authentication failed';
messageElement.innerHTML = '<div class="error">Invalid authentication token. Please try again.</div>';
setTimeout(() => {
const isDevelopment = window.location.hostname === '127.0.0.1' || window.location.hostname === 'localhost';
const loginUrl = isDevelopment
? 'http://127.0.0.1:5501/src/main/webapp/login.html' // Development path (Live Server)
: '/login.html'; // Production path
window.location.href = loginUrl;
}, 3000);
}
} else {
console.log('❌ NO TOKEN FOUND');
console.log('🔍 Checking for alternative token sources...');
// Track missing token error
trackAuthError('missing_token', {
message: 'No authentication token found in callback URL',
code: 'no_token'
});
// Check for token in hash (some OAuth implementations use this)
const hashParams = new URLSearchParams(window.location.hash.slice(1));
const hashToken = hashParams.get('token') || hashParams.get('access_token');
// Check for token in other common parameter names
const altToken = urlParams.get('access_token') || urlParams.get('jwt') || urlParams.get('authtoken');
console.log('🔍 Hash token:', hashToken ? 'FOUND' : 'NOT FOUND');
console.log('🔍 Alternative token names:', altToken ? 'FOUND' : 'NOT FOUND');
console.log('🔍 Full hash:', window.location.hash);
console.log('🔍 Full search:', window.location.search);
if (hashToken || altToken) {
console.log('✅ Found token in alternative location, retrying...');
// Retry with found token
const foundToken = hashToken || altToken;
urlParams.set('token', foundToken);
// Recursively call the same logic
window.location.search = urlParams.toString();
return;
}
statusElement.textContent = 'No authentication token received';
messageElement.innerHTML = '<div class="error">No authentication token received. Please try again.</div>';
console.log('❌ Redirecting back to login page...');
setTimeout(() => {
const isDevelopment = window.location.hostname === '127.0.0.1' || window.location.hostname === 'localhost';
const loginUrl = isDevelopment
? 'http://127.0.0.1:5501/src/main/webapp/login.html' // Development path (Live Server)
: '/login.html'; // Production path
window.location.href = loginUrl;
}, 3000);
}
})();
</script>
</body>
</html>