-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfooter-custom-code.html
More file actions
518 lines (470 loc) · 17.8 KB
/
footer-custom-code.html
File metadata and controls
518 lines (470 loc) · 17.8 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/11.6.1/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/11.6.1/firebase-analytics-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/11.6.1/firebase-auth-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/11.6.1/firebase-functions-compat.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuidv4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stackdriver-errors-js@v0.12.0/dist/stackdriver-errors-concat.min.js"></script>
<script>
const JS_VERSION = 'v1.3.106';
const environment = (location.href.includes('maiapp.se') || location.href.includes('mairesale.com')) ? 'web-prod' : 'web-test';
if (environment === 'web-prod') {
errorHandler = new StackdriverErrorReporter();
errorHandler.start({
key: 'AIzaSyA1XebVWrZ_WlhKtlqqaRE8omzzn50zd-U',
projectId: 'second-hand-helper',
service: environment,
});
} else {
errorHandler = {
report: () => {},
setUser: () => {},
};
}
// Firebase config
var firebaseConfig = {
apiKey: "AIzaSyCMWv3TzZuGPDg41K8wa_PY10rgtitoCnA",
authDomain: "second-hand-helper.firebaseapp.com",
projectId: "second-hand-helper",
storageBucket: "second-hand-helper.appspot.com",
messagingSenderId: "886292162262",
appId: "1:886292162262:web:a5679ec376bdec00600b77",
measurementId: "G-654T8V21EB"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var db = firebase.firestore();
var functions = firebase.functions();
var auth = firebase.auth();
const p = new URL(window.location).searchParams
const savedUser = localStorage.getItem('sessionUser') ? JSON.parse(localStorage.getItem('sessionUser')) : undefined;
if (p.has('s') && savedUser && savedUser.signInInfoKey !== p.get('s')) {
console.log('Signing out user because of signInInfoKey mismatch');
firebase.auth().signOut().then(() => {
authUser.current = null;
user.current = null;
localStorage.removeItem('sessionUser');
localStorage.removeItem('idToken');
localStorage.removeItem('authUserId');
localStorage.removeItem('authUser');
window.location.reload();
})
}
// SEGMENT IDENTIFY
function identify(authenticatedUser, dbUser) {
const now = new Date().toISOString();
let createdAt = new Date(authenticatedUser.metadata.creationTime || now).toISOString();
let latestLogin = new Date(authenticatedUser.metadata.lastSignInTime || authenticatedUser.metadata.creationTime || now).toISOString();
let signInMethod = authenticatedUser.providerData[0].providerId;
const firstName = dbUser.addressFirstName ? dbUser.addressFirstName : null;
const lastName = dbUser.addressLastName ? dbUser.addressLastName : null;
const email = dbUser.email ? dbUser.email : null;
const phone = dbUser.phoneNumber ? dbUser.phoneNumber : null;
const street = dbUser.addressStreetAddress ? dbUser.addressStreetAddress : null;
const city = dbUser.addressCity ? dbUser.addressCity : null;
const postalCode = dbUser.addressPostalCode ? dbUser.addressPostalCode : null;
const doorCode = dbUser.addressDoorCode ? dbUser.addressDoorCode : null;
let campaign = {};
if (dbUser.attribution) {
campaign["name"] = dbUser.attribution.utm_campaign ? dbUser.attribution.utm_campaign : null;
campaign["source"] = dbUser.attribution.utm_source ? dbUser.attribution.utm_source : null;
campaign["medium"] = dbUser.attribution.utm_medium ? dbUser.attribution.utm_medium : null;
campaign["term"] = dbUser.attribution.utm_term ? dbUser.attribution.utm_term : null;
campaign["content"] = dbUser.attribution.utm_content ? dbUser.attribution.utm_content : null;
}
campaign = Object.keys(campaign).length > 0 ? campaign : null;
analytics.identify(`${authenticatedUser.uid}`, {
createdAt,
firstName,
lastName,
email,
phone,
address: {
street,
city,
postalCode,
doorCode
},
latestLogin,
latestPageView: now,
signInMethod,
campaign
});
}
const BACKEND_API_URL = 'https://api.mairesale.com';
const IMAGE_BACKEND_API_URL = 'https://images-api-886292162262.europe-west1.run.app';
const LEGACY_BACKEND_API_URL = 'https://europe-west1-second-hand-helper.cloudfunctions.net/webApi';
async function getIdToken(refresh = false) {
let idToken = localStorage.getItem('idToken');
if (refresh || !idToken) {
if (firebase.auth().currentUser) {
idToken = await firebase.auth().currentUser.getIdToken();
localStorage.setItem('idToken', idToken);
authUser.current = firebase.auth().currentUser;
localStorage.setItem('authUser', JSON.stringify(authUser.current));
} else {
throw new Error('User not authenticated');
}
}
return idToken;
}
async function onAuthStateChangedPromise() {
if (firebase.auth().currentUser) {
return Promise.resolve(firebase.auth().currentUser);
}
return new Promise((resolve, reject) => {
let isResolved = false;
firebase.auth().onAuthStateChanged(result => {
isResolved = true;
resolve(result)
})
setTimeout(() => {
if (!isResolved) {
reject('Timed out waiting for user auth');
}
}, 10*1000)
})
}
const AUTH_IF_AVAILABLE = 'IF_AVAILABLE';
const CLIENT_CHANNEL_HEADERS = {
'X-Client-Channel': 'Web',
'X-Client-Version': JS_VERSION,
};
// Function to call web api backend function, with or without auth
async function callBackendApi(path, { data, method, requiresAuth, timeoutSec = 20, useLegacyFallback = true, fetchInit = {} } = {}) {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), timeoutSec*1000);
let idToken = '';
const useMethod = method || (data ? 'POST' : 'GET');
const useAuth = requiresAuth === true || (requiresAuth !== false && useMethod !== 'GET') || requiresAuth === AUTH_IF_AVAILABLE;
if (useAuth) {
try {
idToken = await getIdToken();
} catch (e) {
if (requiresAuth !== AUTH_IF_AVAILABLE ) {
throw e;
}
}
}
const makeRequest = async (url) => {
try {
const response = await fetch(`${url}${path}`, {
method: useMethod,
headers: {
'Content-Type': 'application/json',
...CLIENT_CHANNEL_HEADERS,
...(idToken?.length ? { 'Authorization': `Bearer ${idToken}`} : {}),
},
...fetchInit,
...(data ? { body: JSON.stringify(data) } : {}),
signal: controller.signal
});
if (useAuth && response.status === 401) {
// Try the call again with a refreshed idToken when the firebase user is authenticated
console.log('Waiting for onAuthStateChangedPromise to try again');
const result = await onAuthStateChangedPromise();
console.log('trying again');
if (result) {
idToken = await getIdToken(true);
const retryResponse = await fetch(`${url}${path}`, {
method: useMethod,
headers: {
'Content-Type': 'application/json',
...CLIENT_CHANNEL_HEADERS,
'Authorization': `Bearer ${idToken}`
},
...(data ? {body: JSON.stringify(data)} : {}),
signal: controller.signal
});
return retryResponse;
}
}
return response;
} catch (e) {
errorHandler.report(`Error calling backend function ${method} ${path}: ${JSON.stringify(e)}`);
return { ok: false };
}
};
try {
// Try the new backend first
const useImagesApi = path.startsWith('/api/images');
let response = await makeRequest(useImagesApi ? IMAGE_BACKEND_API_URL : BACKEND_API_URL);
// If the new backend fails and we have fallback enabled, try the legacy backend
if (!response.ok && useLegacyFallback) {
errorHandler.report(`New backend failed, falling back to legacy backend for ${method} ${path}`);
console.log('New backend failed, falling back to legacy backend');
response = await makeRequest(LEGACY_BACKEND_API_URL);
}
if (!response.ok || response.headers.get('content-length') === '0') {
return { data: undefined }
}
const json = await response.json();
return json.data ? json : { data: json };
} catch(e) {
console.error(e);
errorHandler.report(`Failure calling backend function ${JSON.stringify(e)}`)
throw e;
} finally {
clearTimeout(timeout);
}
}
async function bootstrapFromSessionCookie() {
try {
// Only auto-login if coming from another domain
// Don't auto-login on page reloads or same-domain navigation
const referrer = document.referrer;
const currentDomain = window.location.hostname;
if (referrer) {
try {
const referrerDomain = new URL(referrer).hostname;
// If referrer is from the same domain, don't auto-login
if (referrerDomain === currentDomain) {
console.log("[SSO] Skipping auto-login: same-domain referrer");
return false;
}
} catch (e) {
// If referrer URL is invalid, don't auto-login
console.log("[SSO] Skipping auto-login: invalid referrer URL");
return false;
}
} else {
// No referrer usually means direct navigation, page reload, or bookmark
console.log("[SSO] Skipping auto-login: no referrer (likely page reload or direct navigation)");
return false;
}
// Ensure Firebase is initialized before this runs
const auth = firebase.auth();
// If already logged in, nothing to do
if (auth.currentUser) return;
// Wait briefly for Firebase to hydrate cached auth state
await new Promise((resolve) => {
const unsubscribe = auth.onAuthStateChanged(() => {
unsubscribe();
resolve();
});
});
if (auth.currentUser) return false;
console.log("[SSO] Attempting auto-login from cross-domain referrer:", referrer);
// Ask backend to verify session cookie and return a Firebase custom token
const res = await callBackendApi('/api/users/session/verify', {
method: "POST",
timeoutSec: 1,
requiresAuth: false,
fetchInit: { credentials: "include" },
});
if (!res.data?.token) return false;
// Log into Firebase using the custom token
await auth.signInWithCustomToken(res.data.token);
console.log("[SSO] Auto-login successful");
return true;
} catch (e) {
console.warn("[SSO] Session cookie bootstrap failed:", e);
return false;
}
}
function showBootstrapSpinner() {
// Create spinner overlay if it doesn't exist
console.log("Showing bootstrap spinner");
if (!document.getElementById('bootstrap-spinner')) {
const spinnerHTML = `
<div id="bootstrap-spinner" style="
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
padding-bottom: 100px;
z-index: 9999;
">
<div style="
width: 20px;
height: 20px;
border: 2px solid #f3f3f3;
border-top: 2px solid #333;
border-radius: 50%;
animation: bootstrap-spin 0.8s linear infinite;
"></div>
</div>
<style>
@keyframes bootstrap-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
`;
document.body.insertAdjacentHTML('beforeend', spinnerHTML);
}
document.getElementById('bootstrap-spinner').style.display = 'flex';
setTimeout(hideBootstrapSpinner, 10000);
}
function hideBootstrapSpinner() {
const spinner = document.getElementById('bootstrap-spinner');
if (spinner) {
spinner.style.display = 'none';
}
}
// Make hideBootstrapSpinner available globally for signIn.js
window.hideBootstrapSpinner = hideBootstrapSpinner;
document.addEventListener("DOMContentLoaded", async function () {
// If there's already a spinner from a previous page (after navigation), hide it immediately
const existingSpinner = document.getElementById('bootstrap-spinner');
if (existingSpinner && existingSpinner.style.display !== 'none') {
hideBootstrapSpinner();
return;
}
showBootstrapSpinner();
try {
const isLoggingIn = await bootstrapFromSessionCookie();
if (!isLoggingIn) {
hideBootstrapSpinner();
}
} catch (e) {
console.error("[SSO] Bootstrap error:", e);
hideBootstrapSpinner();
}
});
</script>
<script src="https://rawcdn.githack.com/SecondHandHelper/Webflow/v1.3.86/clientUtils.js"></script>
<script src="https://rawcdn.githack.com/SecondHandHelper/Webflow/v1.3.86/signIn.js"></script>
<script src="https://rawcdn.githack.com/SecondHandHelper/Webflow/v1.3.86/referralFunctions.js"></script>
<!-- Google Tag Manager (noscript) -->
<noscript>
<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-KWV4J65" height="0" width="0"
style="display:none;visibility:hidden"></iframe>
</noscript>
<!-- End Google Tag Manager (noscript) -->
<script>
// Set attribution cookies (could be put on any campaign page)
checkCookie("utm_campaign");
checkCookie("utm_source");
checkCookie("utm_medium");
checkCookie("utm_term");
checkCookie("utm_content");
// GET ITEMS
// This function returns all the users items from DB in the form of a firestore QueryDocumentSnapshot[]
async function getItems(userId) {
return await db.collection("items")
.where("user", "==", userId)
.where("createdAt", "!=", false)
.orderBy('createdAt', 'desc')
.get();
}
</script>
<script>
// GO BACK LINKS
$(document).ready(function () {
$(".goback").click(function () {
if ($('.goback').data('disabled')) {
return;
}
if (document.referrer.includes(window.location.origin)) {
if (document.referrer.includes('/item-confirmation') || document.referrer.includes('/sign-in')) {
location.href = '/private';
} else {
window.history.back();
}
} else {
if (user) {
location.href = "/private";
} else {
location.href = '/';
}
}
});
});
// TRACK LINK CLICKS
function linkClickTracker(event) {
if (event.currentTarget.id) {
try {
console.log('Clicked link ', event.currentTarget.id);
analytics.track('Click', { elementID: event.currentTarget.id });
} catch (e) {
console.error(e);
}
}
}
document.querySelectorAll("a").forEach(link => link.addEventListener('click', linkClickTracker) );
document.querySelectorAll('[type=submit]').forEach(link => link.addEventListener('click', linkClickTracker) );
if (document.getElementById('footerContactDesktop')) {
document.getElementById('footerContactDesktop').addEventListener('click', function () {
Intercom('show');
});
}
// Check URL parameter to open Intercom chat
// Usage: ?chat=true or ?openChat=true
if (p.has('chat') || p.has('openChat')) {
// Wait for Intercom to load, then open it
const checkIntercom = setInterval(() => {
if (window.Intercom && typeof window.Intercom === 'function') {
clearInterval(checkIntercom);
Intercom('show');
}
}, 100);
// Timeout after 5 seconds if Intercom doesn't load
setTimeout(() => clearInterval(checkIntercom), 5000);
}
// FUNCTIONS PRIVATE PAGE
function formatPhoneNumber(str) {
str = str.replace(/[^0-9+]/g, '');
if (str.slice(0, 1) == 0 && str.length == 10) { //0769419519
str = str.substring(1);
str = "+46" + str;
}
if (str.slice(0, 1) == 7 && str.length == 9) { //769419519
str = "+46" + str;
}
if (str.slice(0, 2) == '00' && str.length == 13) { //0046769419519
str = str.substring(2);
str = "+" + str;
}
return str;
}
// FEATURE TOGGLE FUNCTION
const featureConfig = {
alpha: { trustedSeller: true, modelDB: true, adjustValuation: true },
beta: { trustedSeller: true, modelDB: true, adjustValuation: true },
default: { trustedSeller: true, modelDB: true, adjustValuation: true }
};
function featureIsEnabled(featureName) {
if (user.current?.testGroups) {
if (user.current.testGroups.includes('alpha')) {
return featureConfig.alpha[featureName]
}
if (user.current.testGroups.includes('beta')) {
return featureConfig.beta[featureName]
}
}
return featureConfig.default[featureName]
}
function appendJsScript(scriptSrc, onError) {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptSrc;
script.onerror = onError;
document.head.appendChild(script);
}
function urlDependentLoadJs(jsFile, version = JS_VERSION) {
function loadFromGitHack() {
appendJsScript(`https://rawcdn.githack.com/SecondHandHelper/Webflow/${version}/dist/${jsFile}`);
}
if (location.href.match(/maiapp.se|mairesale.com/)) {
loadFromGitHack();
} else {
appendJsScript(`https://localhost:1234/${jsFile}`, loadFromGitHack);
}
}
</script>
<style>
div.intercom-lightweight-app {
z-index: 4;
}
.intercom-lightweight-app .intercom-lightweight-app-launcher {
z-index: 4;
}
</style>