-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
382 lines (343 loc) Β· 12.9 KB
/
Copy pathauth.js
File metadata and controls
382 lines (343 loc) Β· 12.9 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// ============================================================
// CalcuBite β no-login identity & cloud storage
// ------------------------------------------------------------
// β’ No signup / no login: every visitor gets an anonymous
// device identity stored in localStorage.
// β’ Profile is local-first (localStorage). Scans are unlimited β no ads.
// β’ Scan history, health goals and app stats are synced to
// MantleDB (https://mantledb.sh) β free anonymous JSON store.
// β’ AI is provided by BazaarLink.ai free tier (https://bazaarlink.ai/free).
// ============================================================
const MANTLE_BASE = 'https://mantledb.sh/v2';
const MANTLE_NS = 'calcubite';
// Write key for the claimed "calcubite" namespace. This is a
// client-side app, so the key is intentionally public; it only
// allows writing inside this namespace.
const MANTLE_KEY = '1d9900af5d44ffcdbd2a9cd7c6015428e1af5325ed8dbac23cded566acbb09c2';
// DOM references (may be null until DOMContentLoaded)
let appContainer, userProfileElem, userNameElem, userAvatarElem, userTierElem;
// ------------------------------------------------------------
// MantleDB helpers
// ------------------------------------------------------------
async function mantleFetch(path, options = {}) {
const res = await fetch(`${MANTLE_BASE}/${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
'X-Mantle-Key': MANTLE_KEY,
...(options.headers || {})
}
});
if (!res.ok) throw new Error(`MantleDB ${res.status}`);
return res.json();
}
const mantleWrite = (path, data) => mantleFetch(path, { method: 'POST', body: JSON.stringify(data) });
const mantleRead = (path) => mantleFetch(path, { method: 'GET' });
const mantleIncrement = (path, key) => mantleFetch(`increment/${path}`, { method: 'POST', body: JSON.stringify({ key }) });
// ------------------------------------------------------------
// Anonymous device identity (replaces Supabase auth)
// ------------------------------------------------------------
function getDeviceId() {
let id = localStorage.getItem('cb_device_id');
if (!id) {
id = (window.crypto && crypto.randomUUID)
? crypto.randomUUID()
: 'dev-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
localStorage.setItem('cb_device_id', id);
}
return id;
}
const deviceId = getDeviceId();
const currentUser = { id: deviceId, email: '' };
// ------------------------------------------------------------
// Profile β local-first
// ------------------------------------------------------------
function loadProfile() {
try {
const p = JSON.parse(localStorage.getItem('cb_profile'));
if (p && typeof p === 'object') return p;
} catch (e) { /* corrupted profile, reset */ }
return {
full_name: 'Guest',
avatar_url: '',
health: {}
};
}
let userProfile = loadProfile();
function saveProfileLocal() {
localStorage.setItem('cb_profile', JSON.stringify(userProfile));
}
function persistProfileCloud() {
mantleWrite(`users/${deviceId}/profile`, { ...userProfile, device_id: deviceId })
.catch(() => { /* offline is fine β local is source of truth */ });
}
// ------------------------------------------------------------
// Cloud-backed data store (scan history + health goals)
// ------------------------------------------------------------
let scanHistory = [];
let healthGoals = [];
async function loadUserData() {
try {
const h = await mantleRead(`users/${deviceId}/history`);
if (h && Array.isArray(h.scans)) scanHistory = h.scans;
} catch (e) { /* no history yet */ }
try {
const g = await mantleRead(`users/${deviceId}/goals`);
if (g && Array.isArray(g.goals)) healthGoals = g.goals;
} catch (e) { /* no goals yet */ }
// Food diary: merge cloud copy into local (union by entry id)
try {
const d = await mantleRead(`users/${deviceId}/diary`);
if (d && d.days && typeof d.days === 'object') {
let local = { days: {} };
try { local = JSON.parse(localStorage.getItem('cb_diary')) || local; } catch (e) { /* reset */ }
if (!local.days) local.days = {};
let changed = false;
Object.keys(d.days).forEach(dateKey => {
const cloudEntries = (d.days[dateKey] && d.days[dateKey].entries) || [];
if (!local.days[dateKey]) {
if (cloudEntries.length) { local.days[dateKey] = { entries: cloudEntries }; changed = true; }
return;
}
const have = new Set(local.days[dateKey].entries.map(e => e.id));
cloudEntries.forEach(e => {
if (!have.has(e.id)) { local.days[dateKey].entries.push(e); changed = true; }
});
});
if (changed) {
localStorage.setItem('cb_diary', JSON.stringify(local));
window.dispatchEvent(new CustomEvent('cb-diary-loaded'));
}
}
} catch (e) { /* no diary yet */ }
}
function persistHistory() {
const slim = scanHistory.slice(0, 50);
mantleWrite(`users/${deviceId}/history`, { scans: slim, updated_at: new Date().toISOString() })
.catch((e) => console.warn('History sync failed:', e.message));
}
function persistGoals() {
mantleWrite(`users/${deviceId}/goals`, { goals: healthGoals, updated_at: new Date().toISOString() })
.catch((e) => console.warn('Goals sync failed:', e.message));
}
// Food diary cloud sync (called by diary.js)
window._mantleSyncDiary = function (diaryData) {
return mantleWrite(`users/${deviceId}/diary`, { ...diaryData, updated_at: new Date().toISOString() })
.catch((e) => console.warn('Diary sync failed:', e.message));
};
function makeId() {
return (window.crypto && crypto.randomUUID)
? crypto.randomUUID()
: Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
}
// Data API consumed by script.js
window.store = {
addScan(scan) {
const entry = {
id: makeId(),
created_at: new Date().toISOString(),
scan_type: scan.scan_type || 'food',
scan_data: scan.scan_data || {}
};
scanHistory.unshift(entry);
scanHistory = scanHistory.slice(0, 50);
persistHistory();
return entry;
},
getScans: () => scanHistory.slice(),
getGoals: () => healthGoals.slice(),
addGoal(goal) {
const duplicate = healthGoals.some(
(g) => g.goal_type === goal.goal_type && g.target === goal.target
);
if (duplicate) return { ok: false, duplicate: true };
healthGoals.unshift({
id: makeId(),
created_at: new Date().toISOString(),
progress: 0,
...goal
});
persistGoals();
return { ok: true };
},
deleteGoal(id) {
healthGoals = healthGoals.filter((g) => g.id !== id);
persistGoals();
},
updateGoal(id, patch) {
healthGoals = healthGoals.map((g) => (g.id === id ? { ...g, ...patch } : g));
persistGoals();
},
trackStat(key) {
mantleIncrement(`stats/app`, key).catch(() => { /* non-critical */ });
}
};
// ------------------------------------------------------------
// UI helpers
// ------------------------------------------------------------
function bindDomRefs() {
appContainer = document.getElementById('app-container');
userProfileElem = document.getElementById('user-profile');
userNameElem = document.getElementById('user-name');
userAvatarElem = document.getElementById('user-avatar');
userTierElem = document.getElementById('user-tier');
}
function updateUIForUser() {
if (userNameElem) userNameElem.textContent = userProfile.full_name || 'Guest';
if (userAvatarElem) {
userAvatarElem.src = userProfile.avatar_url ||
`https://ui-avatars.com/api/?name=${encodeURIComponent(userProfile.full_name || 'Guest')}&background=random`;
}
if (userTierElem) userTierElem.textContent = 'Free';
if (userProfileElem) userProfileElem.style.display = 'flex';
}
// No login anymore: go straight into the app.
async function checkAuth() {
bindDomRefs();
const landingPage = document.getElementById('landing-page');
const authContainer = document.getElementById('auth-container');
if (landingPage) landingPage.style.display = 'none';
if (authContainer) authContainer.style.display = 'none';
if (appContainer) appContainer.style.display = 'block';
document.body.classList.remove('landing-mode');
updateUIForUser();
loadUserData(); // fire-and-forget cloud load
}
// Kept for backward compatibility with old call sites.
function showLandingPage() { checkAuth(); }
// ------------------------------------------------------------
// Scan limits (freemium) β local-first
// ------------------------------------------------------------
async function updateScansRemaining(scansUsed = 1) {
// CalcuBite is ad-free: scans are unlimited. Kept for API compatibility.
return true;
}
// ------------------------------------------------------------
// Profile update + modal
// ------------------------------------------------------------
async function updateProfile(profileData) {
userProfile = { ...userProfile, ...profileData };
saveProfileLocal();
persistProfileCloud();
updateUIForUser();
return true;
}
function showProfileModal() {
const profileModal = document.getElementById('profile-modal');
if (!profileModal) {
console.error('Profile modal element not found');
return;
}
populateProfileModal();
profileModal.style.display = 'block';
}
function populateProfileModal() {
const nameInput = document.getElementById('profile-name');
const avatarImg = document.getElementById('profile-avatar-img');
if (!nameInput) {
console.error('Essential profile elements not found');
return;
}
nameInput.value = userProfile.full_name || '';
if (avatarImg) {
avatarImg.src = userProfile.avatar_url ||
`https://ui-avatars.com/api/?name=${encodeURIComponent(nameInput.value || 'Guest')}&background=random`;
}
// Populate health profile fields
const h = userProfile.health || {};
const healthValues = {
'health-age': h.age || '',
'health-sex': h.sex || '',
'health-height': h.heightCm || '',
'health-weight': h.weightKg || '',
'health-activity': h.activity || '',
'health-goal': h.goal || '',
'health-dietary': h.dietary || '',
'health-conditions': h.conditions || ''
};
Object.keys(healthValues).forEach((id) => {
const el = document.getElementById(id);
if (el) el.value = healthValues[id];
});
const profileForm = document.getElementById('profile-form');
if (profileForm) {
profileForm.onsubmit = async (e) => {
e.preventDefault();
const newName = nameInput.value.trim();
const health = collectHealthForm();
const success = await updateProfile({
full_name: newName || userProfile.full_name,
health
});
alert(success ? 'Profile saved!' : 'Failed to save profile.');
};
}
const changeAvatarBtn = document.getElementById('change-avatar');
if (changeAvatarBtn) {
changeAvatarBtn.onclick = () => {
// No cloud file storage anymore β regenerate the avatar instead.
const url = `https://ui-avatars.com/api/?name=${encodeURIComponent(userProfile.full_name || 'Guest')}&background=random&size=128`;
updateProfile({ avatar_url: url });
if (avatarImg) avatarImg.src = url;
if (userAvatarElem) userAvatarElem.src = url;
};
}
}
// Read the health profile form values
function collectHealthForm() {
const get = (id) => {
const el = document.getElementById(id);
return el ? el.value.trim() : '';
};
return {
age: get('health-age'),
sex: get('health-sex'),
heightCm: get('health-height'),
weightKg: get('health-weight'),
activity: get('health-activity'),
goal: get('health-goal'),
dietary: get('health-dietary'),
conditions: get('health-conditions')
};
}
// ------------------------------------------------------------
// Init
// ------------------------------------------------------------
document.addEventListener('DOMContentLoaded', () => {
bindDomRefs();
checkAuth();
const profileLink = document.getElementById('profile-link');
if (profileLink) {
profileLink.addEventListener('click', (e) => {
e.preventDefault();
showProfileModal();
});
}
// Close modals when clicking outside
window.addEventListener('click', (e) => {
document.querySelectorAll('.modal').forEach((modal) => {
if (e.target === modal) modal.style.display = 'none';
});
});
// Close buttons in modals
document.querySelectorAll('.close-modal').forEach((button) => {
button.addEventListener('click', () => {
const modal = button.closest('.modal');
if (modal) modal.style.display = 'none';
});
});
});
// ------------------------------------------------------------
// Public API (same surface as before β consumed by script.js)
// ------------------------------------------------------------
window.auth = {
checkAuth,
updateScansRemaining,
updateProfile,
showProfileModal,
currentUser: () => currentUser,
userProfile: () => userProfile,
getHealth: () => userProfile.health || {},
readHealthForm: () => collectHealthForm(),
isPremium: () => false
};