-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
332 lines (295 loc) · 13.6 KB
/
Copy pathauth.js
File metadata and controls
332 lines (295 loc) · 13.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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Authentication System for Faces Website (API Version)
const API_URL = window.location.origin;
const AUTH = {
// Creator/Admin email
CREATOR_EMAIL: 'maxwitanowski@gmail.com',
// Get current logged in user from localStorage (persistent) or sessionStorage
getCurrentUser() {
// Check localStorage first (persistent), then sessionStorage
let user = localStorage.getItem('faces_current_user');
if (!user) {
user = sessionStorage.getItem('faces_current_user');
}
return user ? JSON.parse(user) : null;
},
// Set current user (rememberMe determines storage type)
setCurrentUser(user, rememberMe = true) {
if (user) {
if (rememberMe) {
localStorage.setItem('faces_current_user', JSON.stringify(user));
sessionStorage.removeItem('faces_current_user');
} else {
sessionStorage.setItem('faces_current_user', JSON.stringify(user));
localStorage.removeItem('faces_current_user');
}
} else {
localStorage.removeItem('faces_current_user');
sessionStorage.removeItem('faces_current_user');
}
},
// Check if email is creator/admin
isCreator(email) {
return email && email.toLowerCase() === this.CREATOR_EMAIL.toLowerCase();
},
// Check if current user is creator
isCurrentUserCreator() {
const user = this.getCurrentUser();
return user && this.isCreator(user.email);
},
// Sign up new user
async signUp(name, email, password, rememberMe = true) {
try {
const response = await fetch(`${API_URL}/api/auth/signup`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email, password })
});
const data = await response.json();
if (!response.ok) {
return { success: false, error: data.error };
}
this.setCurrentUser(data.user, rememberMe);
return { success: true, user: data.user };
} catch (err) {
console.error('Signup error:', err);
return { success: false, error: 'Network error. Please try again.' };
}
},
// Sign in existing user
async signIn(email, password, rememberMe = true) {
try {
const response = await fetch(`${API_URL}/api/auth/signin`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const data = await response.json();
if (!response.ok) {
return { success: false, error: data.error };
}
this.setCurrentUser(data.user, rememberMe);
return { success: true, user: data.user };
} catch (err) {
console.error('Signin error:', err);
return { success: false, error: 'Network error. Please try again.' };
}
},
// Sign out
signOut() {
this.setCurrentUser(null);
},
// Get user initials for avatar
getInitials(name) {
return name.substring(0, 2).toUpperCase();
}
};
// Auth UI Component
const AuthUI = {
// Create and show auth modal
showAuthModal(mode = 'signin') {
// Remove existing modal if any
const existingModal = document.getElementById('authModal');
if (existingModal) existingModal.remove();
const modal = document.createElement('div');
modal.id = 'authModal';
modal.className = 'auth-modal';
modal.innerHTML = `
<div class="auth-modal-content">
<button class="auth-close-btn" onclick="AuthUI.closeModal()">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
<div class="auth-header">
<div class="auth-logo">
<img src="images/app_logo.png" alt="Faces Logo">
</div>
<h2 id="authTitle">${mode === 'signin' ? 'Welcome Back' : 'Create Account'}</h2>
<p id="authSubtitle">${mode === 'signin' ? 'Sign in to your account' : 'Join the Faces community'}</p>
</div>
<form id="authForm" class="auth-form">
<div class="auth-input-group" id="nameGroup" style="display: ${mode === 'signup' ? 'block' : 'none'}">
<label for="authName">Name</label>
<input type="text" id="authName" placeholder="Your name" maxlength="50">
</div>
<div class="auth-input-group">
<label for="authEmail">Email</label>
<input type="email" id="authEmail" placeholder="your@email.com" required>
</div>
<div class="auth-input-group">
<label for="authPassword">Password</label>
<input type="password" id="authPassword" placeholder="••••••••" required minlength="6">
</div>
<div class="auth-remember">
<label class="auth-checkbox-label">
<input type="checkbox" id="authRemember" checked>
<span class="auth-checkbox-text">Remember me</span>
</label>
</div>
<div class="auth-error" id="authError" style="display: none;"></div>
<button type="submit" class="btn btn-primary auth-submit-btn">
${mode === 'signin' ? 'Sign In' : 'Sign Up'}
</button>
</form>
<div class="auth-switch">
<span id="authSwitchText">${mode === 'signin' ? "Don't have an account?" : "Already have an account?"}</span>
<button type="button" class="auth-switch-btn" onclick="AuthUI.toggleMode()">
${mode === 'signin' ? 'Sign Up' : 'Sign In'}
</button>
</div>
</div>
`;
document.body.appendChild(modal);
modal.dataset.mode = mode;
// Handle form submission
document.getElementById('authForm').addEventListener('submit', (e) => {
e.preventDefault();
AuthUI.handleSubmit();
});
// Close on background click
modal.addEventListener('click', (e) => {
if (e.target === modal) AuthUI.closeModal();
});
// Focus first input
setTimeout(() => {
if (mode === 'signup') {
document.getElementById('authName').focus();
} else {
document.getElementById('authEmail').focus();
}
}, 100);
},
// Close modal
closeModal() {
const modal = document.getElementById('authModal');
if (modal) modal.remove();
},
// Toggle between sign in and sign up
toggleMode() {
const modal = document.getElementById('authModal');
const currentMode = modal.dataset.mode;
const newMode = currentMode === 'signin' ? 'signup' : 'signin';
modal.dataset.mode = newMode;
document.getElementById('authTitle').textContent = newMode === 'signin' ? 'Welcome Back' : 'Create Account';
document.getElementById('authSubtitle').textContent = newMode === 'signin' ? 'Sign in to your account' : 'Join the Faces community';
document.getElementById('nameGroup').style.display = newMode === 'signup' ? 'block' : 'none';
document.querySelector('.auth-submit-btn').textContent = newMode === 'signin' ? 'Sign In' : 'Sign Up';
document.getElementById('authSwitchText').textContent = newMode === 'signin' ? "Don't have an account?" : "Already have an account?";
document.querySelector('.auth-switch-btn').textContent = newMode === 'signin' ? 'Sign Up' : 'Sign In';
document.getElementById('authError').style.display = 'none';
// Clear and refocus
document.getElementById('authForm').reset();
if (newMode === 'signup') {
document.getElementById('authName').focus();
} else {
document.getElementById('authEmail').focus();
}
},
// Handle form submission
async handleSubmit() {
const modal = document.getElementById('authModal');
const mode = modal.dataset.mode;
const email = document.getElementById('authEmail').value.trim();
const password = document.getElementById('authPassword').value;
const rememberMe = document.getElementById('authRemember').checked;
const errorEl = document.getElementById('authError');
const submitBtn = document.querySelector('.auth-submit-btn');
// Disable button during request
submitBtn.disabled = true;
submitBtn.textContent = 'Please wait...';
let result;
if (mode === 'signup') {
const name = document.getElementById('authName').value.trim();
if (!name) {
errorEl.textContent = 'Please enter your name';
errorEl.style.display = 'block';
submitBtn.disabled = false;
submitBtn.textContent = 'Sign Up';
return;
}
result = await AUTH.signUp(name, email, password, rememberMe);
} else {
result = await AUTH.signIn(email, password, rememberMe);
}
if (result.success) {
this.closeModal();
this.updateUI();
// Trigger custom event for pages to listen to
window.dispatchEvent(new CustomEvent('authChanged', { detail: result.user }));
} else {
errorEl.textContent = result.error;
errorEl.style.display = 'block';
submitBtn.disabled = false;
submitBtn.textContent = mode === 'signin' ? 'Sign In' : 'Sign Up';
}
},
// Update UI based on auth state
updateUI() {
const user = AUTH.getCurrentUser();
const authContainer = document.getElementById('authContainer');
if (!authContainer) return;
if (user) {
const isCreator = AUTH.isCreator(user.email);
authContainer.innerHTML = `
<div class="user-menu">
<button class="user-menu-btn" onclick="AuthUI.toggleUserMenu()">
<div class="user-avatar ${isCreator ? 'creator-avatar' : ''}">${AUTH.getInitials(user.name)}</div>
<span class="user-name">${user.name}</span>
${isCreator ? '<span class="creator-badge-small">Creator</span>' : ''}
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div class="user-dropdown" id="userDropdown">
<div class="user-dropdown-header">
<div class="user-avatar-large ${isCreator ? 'creator-avatar' : ''}">${AUTH.getInitials(user.name)}</div>
<div>
<div class="user-dropdown-name">${user.name}</div>
<div class="user-dropdown-email">${user.email}</div>
</div>
</div>
${isCreator ? '<div class="user-dropdown-badge">App Creator</div>' : ''}
<div class="user-dropdown-divider"></div>
<button class="user-dropdown-item" onclick="AUTH.signOut(); AuthUI.updateUI(); window.dispatchEvent(new Event('authChanged'));">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line>
</svg>
Sign Out
</button>
</div>
</div>
`;
} else {
authContainer.innerHTML = `
<button class="btn btn-secondary auth-btn" onclick="AuthUI.showAuthModal('signin')">Sign In</button>
<button class="btn btn-primary auth-btn" onclick="AuthUI.showAuthModal('signup')">Sign Up</button>
`;
}
},
// Toggle user dropdown menu
toggleUserMenu() {
const dropdown = document.getElementById('userDropdown');
if (dropdown) {
dropdown.classList.toggle('open');
}
},
// Initialize auth UI
init() {
// Close dropdown when clicking outside
document.addEventListener('click', (e) => {
const dropdown = document.getElementById('userDropdown');
const menuBtn = document.querySelector('.user-menu-btn');
if (dropdown && !dropdown.contains(e.target) && !menuBtn?.contains(e.target)) {
dropdown.classList.remove('open');
}
});
this.updateUI();
}
};
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
AuthUI.init();
});