Skip to content

Commit 37ef28a

Browse files
committed
refactor(auth): replace fetch with JSONP for OTP request handling
The OTP request handling in the auth.js file was refactored to use JSONP instead of fetch to improve cross-origin compatibility. This change aligns with the updates made in the edit.gs file, which now supports JSONP responses. Additionally, debug logging was removed to clean up the code.
1 parent 2fedf4d commit 37ef28a

File tree

3 files changed

+56
-46
lines changed

3 files changed

+56
-46
lines changed

Assets/js/auth.js

Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ export function setupOtpInputs() {
2424

2525
export async function requestOtp() {
2626
const email = DOM.loginEmail.value.trim();
27-
console.log("Email value:", email);
2827

2928
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
3029
await showAlert('error', 'Invalid Email', 'Please enter a valid email address');
@@ -34,37 +33,44 @@ export async function requestOtp() {
3433
try {
3534
DOM.requestOtpBtn.disabled = true;
3635
DOM.requestOtpBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
37-
console.log("Request URL:", `${CONFIG.googleScriptUrl}?action=request_otp&email=${encodeURIComponent(email)}`);
38-
const formData = new FormData();
39-
formData.append('action', 'request_otp');
40-
formData.append('email', email);
4136

42-
const response = await fetch(CONFIG.googleScriptUrl, {
43-
method: 'POST',
44-
body: formData
45-
});
46-
47-
const data = await response.json();
48-
console.log("Response data:", data);
49-
50-
if (data.status === 'success') {
51-
sessionStorage.setItem(OTP_STORAGE_KEY, JSON.stringify({
52-
email,
53-
expiry: Date.now() + (CONFIG.otpExpiryMinutes * 60000)
54-
}));
37+
// Use JSONP approach instead of fetch
38+
return new Promise((resolve, reject) => {
39+
const callbackName = 'jsonpCallback_' + Math.round(Math.random() * 1000000);
40+
window[callbackName] = function(data) {
41+
document.body.removeChild(script);
42+
delete window[callbackName];
43+
44+
if (data.status === 'success') {
45+
sessionStorage.setItem(OTP_STORAGE_KEY, JSON.stringify({
46+
email,
47+
expiry: Date.now() + (CONFIG.otpExpiryMinutes * 60000)
48+
}));
49+
50+
state.currentUser.email = email;
51+
DOM.otpEmailDisplay.textContent = maskEmail(email);
52+
DOM.emailForm.classList.add('hidden');
53+
DOM.otpForm.classList.remove('hidden');
54+
document.querySelector('.otp-inputs input').focus();
55+
startOtpCountdown(CONFIG.otpExpiryMinutes * 60);
56+
resolve(true);
57+
} else {
58+
reject(new Error(data.message || 'Failed to send OTP'));
59+
}
60+
};
5561

56-
state.currentUser.email = email;
57-
DOM.otpEmailDisplay.textContent = maskEmail(email);
58-
DOM.emailForm.classList.add('hidden');
59-
DOM.otpForm.classList.remove('hidden');
60-
document.querySelector('.otp-inputs input').focus();
61-
startOtpCountdown(CONFIG.otpExpiryMinutes * 60);
62-
return true;
63-
}
64-
throw new Error(data.message || 'Failed to send OTP');
62+
const script = document.createElement('script');
63+
script.src = `${CONFIG.googleScriptUrl}?action=request_otp&email=${encodeURIComponent(email)}&callback=${callbackName}`;
64+
script.onerror = () => {
65+
document.body.removeChild(script);
66+
delete window[callbackName];
67+
reject(new Error('Failed to connect to server'));
68+
};
69+
70+
document.body.appendChild(script);
71+
});
6572
} catch (error) {
6673
await showAlert('error', 'Error', error.message);
67-
console.error("Error details:", error);
6874
return false;
6975
} finally {
7076
DOM.requestOtpBtn.disabled = false;

Assets/js/config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Configuration constants
22
export const CONFIG = {
3-
googleScriptUrl: 'https://script.google.com/macros/s/AKfycbyTSxPXhQllvSdPPbV_olcsHqqZDUL-dWlteqWkHqavwWA3Zv-Zz0gI7x1CBCjVAwOj/exec', // version new edit 0.00.2
3+
googleScriptUrl: 'https://script.google.com/macros/s/AKfycbyTSxPXhQllvSdPPbV_olcsHqqZDUL-dWlteqWkHqavwWA3Zv-Zz0gI7x1CBCjVAwOj/exec', // version new edit 0.01
44
sessionExpiryHours: 1, // Matches GAS session duration
55
otpExpiryMinutes: 5, // Matches GAS OTP duration
66

edit.gs

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,28 @@ const COLUMNS = {
1212
STYLE: 8,
1313
PROFILE_PIC: 9
1414
};
15+
1516
function doGet(e) {
1617
try {
17-
// Debug logging
18-
console.log('Request parameters raw:', e);
19-
console.log('Parameter action:', e.parameter.action);
20-
console.log('Parameter email:', e.parameter.email);
18+
console.log('Request parameters:', JSON.stringify(e.parameter));
2119

2220
if (!e.parameter || !e.parameter.action) {
23-
return jsonResponse({
21+
return jsonpResponse({
2422
status: 'error',
2523
message: 'Missing action parameter'
26-
});
24+
}, e.parameter.callback);
2725
}
2826

2927
const action = e.parameter.action;
3028
let response;
3129

3230
switch (action) {
3331
case 'request_otp':
34-
// Fix: Check if email exists in parameters
35-
if (!e.parameter.email || e.parameter.email.trim() === '') {
36-
return jsonResponse({
32+
if (!e.parameter.email) {
33+
return jsonpResponse({
3734
status: 'error',
38-
message: 'Missing required fields: email'
39-
});
35+
message: 'Missing required fields'
36+
}, e.parameter.callback);
4037
}
4138
response = handleOtpRequest(e.parameter);
4239
break;
@@ -53,19 +50,26 @@ function doGet(e) {
5350
throw new Error('Invalid action');
5451
}
5552

56-
return jsonResponse(response);
53+
return jsonpResponse(response, e.parameter.callback);
5754
} catch (error) {
5855
console.error('Error:', error);
59-
return jsonResponse({
56+
return jsonpResponse({
6057
status: 'error',
6158
message: error.message
62-
});
59+
}, e.parameter.callback);
6360
}
6461
}
6562

66-
function jsonResponse(data) {
67-
return ContentService.createTextOutput(JSON.stringify(data))
68-
.setMimeType(ContentService.MimeType.JSON);
63+
function jsonpResponse(data, callback) {
64+
if (callback) {
65+
// JSONP response
66+
return ContentService.createTextOutput(callback + '(' + JSON.stringify(data) + ')')
67+
.setMimeType(ContentService.MimeType.JAVASCRIPT);
68+
} else {
69+
// Regular JSON response
70+
return ContentService.createTextOutput(JSON.stringify(data))
71+
.setMimeType(ContentService.MimeType.JSON);
72+
}
6973
}
7074

7175
// --- OTP Request ---

0 commit comments

Comments
 (0)