File size: 10,888 Bytes
8376eb2
 
ed41019
8376eb2
ed41019
202aa5d
 
 
 
 
 
ed41019
 
202aa5d
 
ed41019
202aa5d
ed41019
8376eb2
ed41019
 
8376eb2
ed41019
202aa5d
ed41019
202aa5d
 
 
 
 
ed41019
202aa5d
8376eb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed41019
 
 
 
 
 
202aa5d
ed41019
 
202aa5d
 
 
 
 
 
 
 
 
 
 
 
 
ed41019
 
202aa5d
 
ed41019
202aa5d
ed41019
202aa5d
 
 
 
 
 
 
 
ed41019
 
202aa5d
ed41019
202aa5d
 
 
 
 
 
 
 
 
 
ed41019
 
202aa5d
 
ed41019
202aa5d
ed41019
202aa5d
 
 
 
 
ed41019
202aa5d
ed41019
202aa5d
ed41019
 
 
 
 
202aa5d
ed41019
8376eb2
202aa5d
 
 
ed41019
202aa5d
 
 
 
 
 
 
 
 
 
 
ed41019
202aa5d
ed41019
202aa5d
 
 
 
 
 
 
 
 
ed41019
 
202aa5d
ed41019
202aa5d
 
 
 
 
9e36fdf
 
202aa5d
ed41019
 
 
 
 
 
202aa5d
 
 
 
 
 
 
 
 
ed41019
202aa5d
ed41019
8376eb2
 
ed41019
 
202aa5d
8376eb2
 
 
202aa5d
8376eb2
ed41019
202aa5d
ed41019
202aa5d
 
8376eb2
202aa5d
 
ed41019
202aa5d
ed41019
 
 
202aa5d
 
 
 
 
 
ed41019
202aa5d
ed41019
 
 
 
202aa5d
ed41019
8376eb2
ed41019
 
8376eb2
 
 
 
 
9e36fdf
202aa5d
ed41019
 
 
 
 
8376eb2
 
 
 
 
 
 
 
 
 
 
 
 
202aa5d
8376eb2
 
202aa5d
8376eb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202aa5d
ed41019
202aa5d
ed41019
 
 
 
8376eb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed41019
202aa5d
ed41019
9e36fdf
ed41019
 
 
202aa5d
 
ed41019
 
8376eb2
ed41019
 
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
const loginTab = document.getElementById('login-tab');
const registerTab = document.getElementById('register-tab');
const loginSection = document.getElementById('login-section');
const registerSection = document.getElementById('register-section');
const welcomeSection = document.getElementById('welcome-section');
const registerForm = document.getElementById('register-form');
const loginForm = document.getElementById('login-form');
const registerStatus = document.getElementById('register-status');
const loginStatus = document.getElementById('login-status');
const welcomeMessage = document.getElementById('welcome-message');
const logoutButton = document.getElementById('logout-button');
const notificationsDiv = document.getElementById('notifications');

const API_URL = '/api'; // Use relative path

let webSocket = null;
let authToken = localStorage.getItem('authToken'); // Load token on script start

// --- UI Control & Tab Switching ---
function showSection(sectionId) {
    loginSection.style.display = 'none';
    registerSection.style.display = 'none';
    welcomeSection.style.display = 'none';

    const sectionToShow = document.getElementById(sectionId);
    if (sectionToShow) {
        sectionToShow.style.display = 'block';
    } else {
        loginSection.style.display = 'block'; // Default to login
    }
}

// Tab switching logic
loginTab.addEventListener('click', () => {
    loginTab.classList.add('active');
    registerTab.classList.remove('active');
    loginSection.classList.add('active');
    registerSection.classList.remove('active');
});

registerTab.addEventListener('click', () => {
    registerTab.classList.add('active');
    loginTab.classList.remove('active');
    registerSection.classList.add('active');
    loginSection.classList.remove('active');
});

// Initialize first tab as active
loginTab.classList.add('active');
loginSection.classList.add('active');

function setStatus(element, message, isSuccess = false) {
    element.textContent = message;
    element.className = isSuccess ? 'status-message success' : 'status-message';
    element.style.display = message ? 'block' : 'none';
}

// --- API Calls ---
async function apiRequest(endpoint, method = 'GET', body = null, token = null) {
    const headers = { 'Content-Type': 'application/json' };
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }

    const options = {
        method: method,
        headers: headers,
    };

    if (body && method !== 'GET') {
        options.body = JSON.stringify(body);
    }

    try {
        const response = await fetch(`${API_URL}${endpoint}`, options);
        const data = await response.json(); // Try to parse JSON regardless of status

        if (!response.ok) {
            // Use detail from JSON if available, otherwise status text
            const errorMessage = data?.detail || response.statusText || `HTTP error ${response.status}`;
            console.error("API Error:", errorMessage);
            throw new Error(errorMessage);
        }
        return data;
    } catch (error) {
        console.error(`Error during API request to ${endpoint}:`, error);
        throw error; // Re-throw to be caught by caller
    }
}

// --- WebSocket Handling ---
function connectWebSocket(token) {
    if (!token) {
        console.error("No token available for WebSocket connection.");
        return;
    }
    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
        console.log("WebSocket already connected.");
        return;
    }

    // Construct WebSocket URL dynamically (replace http/https with ws/wss)
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${wsProtocol}//${window.location.host}${API_URL}/ws/${token}`;
    console.log("Attempting to connect WebSocket:", wsUrl);

    webSocket = new WebSocket(wsUrl);

    webSocket.onopen = (event) => {
        console.log("WebSocket connection opened:", event);
        // Clear placeholder message on successful connect
        if (notificationsDiv.querySelector('p em')) {
            notificationsDiv.innerHTML = '';
        }
    };

    webSocket.onmessage = (event) => {
        console.log("WebSocket message received:", event.data);
        try {
            const messageData = JSON.parse(event.data);
            if (messageData.type === 'new_user' && messageData.message) {
                const p = document.createElement('p');
                p.textContent = messageData.message;
                // Add message to the top
                notificationsDiv.insertBefore(p, notificationsDiv.firstChild);
                // Limit number of messages shown (optional)
                while (notificationsDiv.children.length > 10) {
                    notificationsDiv.removeChild(notificationsDiv.lastChild);
                }
            }
        } catch (error) {
            console.error("Error parsing WebSocket message:", error);
        }
    };

    webSocket.onerror = (event) => {
        console.error("WebSocket error:", event);
        const p = document.createElement('p');
        p.textContent = `WebSocket error occurred. Notifications may stop.`;
        p.style.color = 'red';
        notificationsDiv.insertBefore(p, notificationsDiv.firstChild);
    };

    webSocket.onclose = (event) => {
        console.log("WebSocket connection closed:", event);
        webSocket = null; // Reset WebSocket variable
        // Optionally try to reconnect or inform user
        if (!event.wasClean) {
            const p = document.createElement('p');
            p.textContent = `WebSocket disconnected unexpectedly (Code: ${event.code}). Please refresh or log out/in.`;
            p.style.color = 'orange';
            notificationsDiv.insertBefore(p, notificationsDiv.firstChild);
        }
    };
}

function disconnectWebSocket() {
    if (webSocket) {
        console.log("Closing WebSocket connection.");
        webSocket.close();
        webSocket = null;
    }
}

// --- Authentication Logic ---
async function handleLogin(email, password) {
    setStatus(loginStatus, "Logging in...");
    try {
        const data = await apiRequest('/login', 'POST', { email, password });
        if (data.access_token) {
            authToken = data.access_token;
            localStorage.setItem('authToken', authToken); // Store token
            setStatus(loginStatus, ""); // Clear status
            await showWelcomePage(); // Fetch user info and show welcome
        } else {
            throw new Error("Login failed: No token received.");
        }
    } catch (error) {
        setStatus(loginStatus, `Login failed: ${error.message}`);
    }
}

async function handleRegister(email, password) {
    setStatus(registerStatus, "Registering...");
    try {
        const data = await apiRequest('/register', 'POST', { email, password });
        setStatus(registerStatus, `Registration successful for ${data.email}! Please log in.`, true);
        registerForm.reset(); // Clear form
        // Switch to login tab
        loginTab.click();
    } catch (error) {
        setStatus(registerStatus, `Registration failed: ${error.message}`);
    }
}

async function showWelcomePage() {
    if (!authToken) {
        showSection('login-section');
        loginTab.click();
        return;
    }
    try {
        // Fetch user details using the token
        const user = await apiRequest('/users/me', 'GET', null, authToken);
        welcomeMessage.textContent = `Welcome, ${user.email}!`;
        showSection('welcome-section');
        connectWebSocket(authToken); // Connect WS after successful login and user fetch
    } catch (error) {
        // If fetching user fails (e.g., invalid/expired token), logout
        console.error("Failed to fetch user details:", error);
        handleLogout();
    }
}

function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    disconnectWebSocket();
    setStatus(loginStatus, ""); // Clear any previous login errors
    showSection('login-section');
    loginTab.click();
}

// --- Form Validation ---
function validateEmail(email) {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

// --- Event Listeners ---
registerForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const email = document.getElementById('reg-email').value;
    const password = document.getElementById('reg-password').value;
    const confirmPassword = document.getElementById('reg-confirm-password').value;
    
    const emailError = document.getElementById('register-email-error');
    const passwordError = document.getElementById('register-password-error');
    const confirmError = document.getElementById('register-confirm-error');
    
    let isValid = true;
    
    // Email validation
    if (!validateEmail(email)) {
        emailError.style.display = 'block';
        isValid = false;
    } else {
        emailError.style.display = 'none';
    }
    
    // Password validation
    if (password.length < 8) {
        passwordError.style.display = 'block';
        isValid = false;
    } else {
        passwordError.style.display = 'none';
    }
    
    // Confirm password
    if (password !== confirmPassword) {
        confirmError.style.display = 'block';
        isValid = false;
    } else {
        confirmError.style.display = 'none';
    }
    
    if (isValid) {
        handleRegister(email, password);
    }
});

loginForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const email = document.getElementById('login-email').value;
    const password = document.getElementById('login-password').value;
    
    const emailError = document.getElementById('login-email-error');
    const passwordError = document.getElementById('login-password-error');
    
    let isValid = true;
    
    // Email validation
    if (!validateEmail(email)) {
        emailError.style.display = 'block';
        isValid = false;
    } else {
        emailError.style.display = 'none';
    }
    
    // Simple password validation
    if (password.length < 1) {
        passwordError.style.display = 'block';
        isValid = false;
    } else {
        passwordError.style.display = 'none';
    }
    
    if (isValid) {
        handleLogin(email, password);
    }
});

logoutButton.addEventListener('click', handleLogout);

// --- Initial Page Load Logic ---
document.addEventListener('DOMContentLoaded', () => {
    if (authToken) {
        console.log("Token found, attempting to show welcome page.");
        showWelcomePage(); // Try to fetch user info and show welcome
    } else {
        console.log("No token found, showing login page.");
        loginTab.click(); // Activate login tab
    }
});