PluginProbe ʕ •ᴥ•ʔ
Cookiebot by Usercentrics – Automatic Cookie Banner for GDPR/CCPA & Google Consent Mode / 4.5.1
Cookiebot by Usercentrics – Automatic Cookie Banner for GDPR/CCPA & Google Consent Mode v4.5.1
4.7.2 4.7.1 trunk 2.3.0 2.4.0 2.4.1 2.4.2 2.5.0 3.0.0 3.0.1 3.1.0 3.10.0 3.10.1 3.11.1 3.11.2 3.11.3 3.2.0 3.3.0 3.3.1 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.6.1 3.6.2 3.6.5 3.6.6 3.7.0 3.7.1 3.8.0 3.9.0 4.0.0 4.0.1 4.0.2 4.0.3 4.1.0 4.1.1 4.2.0 4.2.1 4.2.10 4.2.11 4.2.12 4.2.13 4.2.14 4.2.2 4.2.3 4.2.4 4.2.5 4.2.6 4.2.7 4.2.8 4.2.9 4.3.0 4.3.1 4.3.10 4.3.11 4.3.12 4.3.2 4.3.3 4.3.4 4.3.5 4.3.6 4.3.7 4.3.7.1 4.3.8 4.3.9 4.3.9.1 4.4.0 4.4.1 4.4.2 4.5.0 4.5.1 4.5.10 4.5.11 4.5.2 4.5.3 4.5.4 4.5.5 4.5.6 4.5.7 4.5.8 4.5.9 4.6.0 4.6.1 4.6.2 4.6.3 4.6.4 4.6.5 4.6.6 4.6.7 4.7.0
cookiebot / assets / js / backend / account.js
cookiebot / assets / js / backend Last commit date
gutenberg 3 years ago account.js 1 year ago consent-mapping.js 1 year ago cookiebot-admin-script.js 1 year ago dashboard.js 1 year ago debug-page.js 1 year ago jquery.tipTip.js 3 years ago multiple-page.js 3 years ago network-settings-page.js 1 year ago prior-consent-settings.js 3 years ago settings-page.js 1 year ago support-page.js 3 years ago
account.js
447 lines
1 // const API_BASE_URL = 'https://api.ea.dev.usercentrics.cloud/v1';
2 const API_BASE_URL = 'https://api.ea.prod.usercentrics.cloud/v1';
3 let authToken = '';
4
5 // Helper function to create FormData for AJAX calls
6 const createFormData = (action, data = {}) => {
7 const formData = new FormData();
8 formData.append('action', action);
9 formData.append('nonce', cookiebot_account.nonce);
10
11 Object.entries(data).forEach(([key, value]) => {
12 formData.append(key, value);
13 });
14
15 return formData;
16 };
17
18 // Function to check scan status
19 let scanCheckInterval = null;
20
21 async function checkScanStatus(scanId) {
22 console.log('Checking scan status for scanId:', scanId);
23
24 try {
25 const response = await fetch(`${API_BASE_URL}/scan/${scanId}`, {
26 method: 'GET',
27 headers: {
28 'Accept': 'application/json',
29 'Content-Type': 'application/json',
30 'Authorization': `Bearer ${authToken}`
31 }
32 });
33
34 const data = await response.json();
35
36 // If scan is still in progress and we don't have an interval set, start one
37 scanCheckInterval = setInterval(() => checkScanStatus(scanId), 180000);
38
39 if (data.status === 'DONE') {
40 await fetch(cookiebot_account.ajax_url, {
41 method: 'POST',
42 body: createFormData('cookiebot_store_scan_details', {
43 scan_id: scanId,
44 scan_status: 'DONE'
45 }),
46 credentials: 'same-origin'
47 });
48 clearInterval(scanCheckInterval);
49 scanCheckInterval = null;
50 return;
51 }
52
53 // Store both scan ID and status
54 await fetch(cookiebot_account.ajax_url, {
55 method: 'POST',
56 body: createFormData('cookiebot_store_scan_details', {
57 scan_id: scanId,
58 scan_status: 'IN_PROGRESS'
59 }),
60 credentials: 'same-origin'
61 });
62
63 if (!response.ok) {
64 clearInterval(scanCheckInterval);
65 scanCheckInterval = null;
66 await fetch(cookiebot_account.ajax_url, {
67 method: 'POST',
68 body: createFormData('cookiebot_store_scan_details', {
69 scan_id: scanId,
70 scan_status: 'FAILED'
71 }),
72 credentials: 'same-origin'
73 });
74 }
75 } catch (error) {
76 console.log('Error checking scan status:', error);
77 }
78 }
79
80 const checkUserData = async () => {
81 try {
82 const userData = await fetch(`${API_BASE_URL}/accounts`, {
83 headers: {
84 'Accept': 'application/json',
85 'Authorization': `Bearer ${authToken}`,
86 }
87 }).then(r => r.json()).then(data => data[0]);
88
89 if (!userData) throw new Error('No user data received');
90
91 // Add onboarding flag to user data
92 const userDataWithFlag = {
93 ...userData,
94 onboarded_via_signup: true
95 };
96 console.log('update user data', userDataWithFlag);
97 userResponseData = await fetch(cookiebot_account.ajax_url, {
98 method: 'POST',
99 body: createFormData('cookiebot_post_user_data', {
100 data: JSON.stringify(userDataWithFlag)
101 }),
102 credentials: 'same-origin'
103 }).then(r => r.json());
104
105 if (!userResponseData.success) {
106 throw new Error('Failed to store user data');
107 }
108 } catch (error) {
109 console.error('Failed to fetch user data:', error);
110 return;
111 }
112 }
113
114 const isAuthenticated = async () => {
115 try {
116 const response = await fetch(`${API_BASE_URL}/accounts`, {
117 headers: {
118 'Accept': 'application/json',
119 'Authorization': `Bearer ${authToken}`
120 }
121 });
122 return response.status !== 401;
123 } catch (error) {
124 console.error('Failed to check authentication:', error);
125 return false;
126 }
127 };
128
129 // Function to fetch configuration details
130 async function fetchConfigurationDetails(configId) {
131 try {
132 const response = await fetch(`${API_BASE_URL}/configurations/${configId}`, {
133 method: 'GET',
134 headers: {
135 'Accept': 'application/json',
136 'Content-Type': 'application/json',
137 'Authorization': `Bearer ${authToken}`
138 }
139 });
140
141 if (!response.ok) {
142 throw new Error('Failed to fetch configuration details');
143 }
144
145 const data = await response.json();
146
147 // Store full configuration data
148 await fetch(cookiebot_account.ajax_url, {
149 method: 'POST',
150 body: createFormData('cookiebot_store_configuration', {
151 configuration: JSON.stringify(data)
152 }),
153 credentials: 'same-origin'
154 });
155
156 return data;
157 } catch (error) {
158 console.error('Error fetching configuration details:', error);
159 throw error;
160 }
161 }
162
163 document.addEventListener('DOMContentLoaded', async () => {
164 const urlParams = new URLSearchParams(window.location.search);
165 const ucApiCode = urlParams.get('uc_api_code');
166
167 // For existing users, no account registration workflow is needed
168 if (cookiebot_account.has_cbid && !cookiebot_account.has_user_data) {
169 console.log('Existing user');
170 return;
171 }
172
173 try {
174 authToken = await fetch(cookiebot_account.ajax_url, {
175 method: 'POST',
176 body: createFormData('cookiebot_get_auth_token'),
177 credentials: 'same-origin'
178 }).then(r => r.json()).then(data => data.data);
179
180 if (ucApiCode) {
181
182 const isNewUser = urlParams.get('is_new_user');
183
184 if (cookiebot_account.has_cbid) {
185 try {
186 const response = await fetch(cookiebot_account.ajax_url, {
187 method: 'POST',
188 body: createFormData('cookiebot_process_auth_code', { code: ucApiCode }),
189 credentials: 'same-origin'
190 });
191
192 authToken = await fetch(cookiebot_account.ajax_url, {
193 method: 'POST',
194 body: createFormData('cookiebot_get_auth_token'),
195 credentials: 'same-origin'
196 }).then(r => r.json()).then(data => data.data);
197
198 console.log('user already exists just attaching new auth token', authToken);
199 if (!response.ok) throw new Error(`Auth failed: ${response.status}`);
200 const newUrl = new URL(window.location.href);
201 newUrl.searchParams.delete('uc_api_code');
202 newUrl.searchParams.delete('is_new_user');
203 window.location.href = newUrl;
204 return;
205 } catch (error) {
206 console.error('Failed to process authentication:', error);
207 return;
208 }
209 }
210
211
212 if (isNewUser === 'false' && !cookiebot_account.has_user_data) {
213 const settingsUrl = window.location.protocol + '//' + window.location.hostname + '/wp-admin/admin.php?page=cookiebot_settings';
214 window.location.href = settingsUrl;
215 return;
216 }
217
218 // Add loading state
219 const loadingOverlay = document.createElement('div');
220 loadingOverlay.className = 'loading-overlay';
221 loadingOverlay.innerHTML = `
222 <div class="loading-content">
223 <div class="loading-spinner"></div>
224 <h2>Creating your account</h2>
225 <p>This should only take about a minute. Keep this window open while we set things up.</p>
226 </div>
227 `;
228 document.body.classList.add('has-loading-overlay');
229 document.body.appendChild(loadingOverlay);
230
231 try {
232 const response = await fetch(cookiebot_account.ajax_url, {
233 method: 'POST',
234 body: createFormData('cookiebot_process_auth_code', { code: ucApiCode }),
235 credentials: 'same-origin'
236 });
237
238 authToken = await fetch(cookiebot_account.ajax_url, {
239 method: 'POST',
240 body: createFormData('cookiebot_get_auth_token'),
241 credentials: 'same-origin'
242 }).then(r => r.json()).then(data => data.data);
243
244 if (!response.ok) throw new Error(`Auth failed: ${response.status}`);
245 } catch (error) {
246 console.error('Failed to process authentication:', error);
247 // Remove loading state on error
248 document.body.classList.remove('has-loading-overlay');
249 loadingOverlay.remove();
250 return;
251 }
252 }
253
254 // Check for existing CBID
255 const cbid = await fetch(cookiebot_account.ajax_url, {
256 method: 'POST',
257 body: createFormData('cookiebot_get_cbid'),
258 credentials: 'same-origin'
259 }).then(r => r.json()).then(data => data.success ? data.data : null);
260
261 // Skip if user data exists and is authenticated
262 const isAuthenticatedCondition = await isAuthenticated();
263 if (cookiebot_account.has_user_data && isAuthenticatedCondition) {
264 // Check scan status before returning
265 await checkScanStatus(cbid);
266 await checkUserData();
267 return;
268 }
269
270 if (!isAuthenticatedCondition && cookiebot_account.has_user_data) {
271 console.log('user data exists and is not authenticated');
272 const callbackUrl = window.location.protocol + '//' + window.location.hostname + '/wp-admin/admin.php?page=cookiebot';
273 window.location.href = `${API_BASE_URL}/auth/auth0/authorize?origin=wordpress_plugin&callback_domain=${encodeURIComponent(callbackUrl)}`;
274
275 }
276
277 if (!cbid) {
278 try {
279 // Create new configuration
280 const siteDomain = window.location.hostname;
281 const formattedDomain = siteDomain.startsWith('http') ? siteDomain : `https://${siteDomain}`;
282
283 const configResponse = await fetch(`${API_BASE_URL}/configurations`, {
284 method: 'POST',
285 headers: {
286 'Accept': 'application/json',
287 'Content-Type': 'application/json',
288 'Authorization': `Bearer ${authToken}`
289 },
290 body: JSON.stringify({
291 configuration_name: "My CMP Configuration",
292 data_controller: "Usercentrics Unipessoal, LDA",
293 legal_framework_template: "gdpr",
294 domains: [formattedDomain]
295 })
296 });
297
298 if (!configResponse.ok) throw new Error(`Config creation failed: ${configResponse.status}`);
299
300 const configData = await configResponse.json();
301 if (!configData?.configuration_id) throw new Error('No configuration ID');
302
303 // Store CBID
304 await fetch(cookiebot_account.ajax_url, {
305 method: 'POST',
306 body: createFormData('cookiebot_store_cbid', { cbid: configData.configuration_id }),
307 credentials: 'same-origin'
308 });
309
310 // Now that we have a CBID, initiate the scan
311 const scanResponse = await fetch(`${API_BASE_URL}/scan`, {
312 method: 'POST',
313 headers: {
314 'Accept': 'application/json',
315 'Content-Type': 'application/json',
316 'Authorization': `Bearer ${authToken}`
317 },
318 body: JSON.stringify({
319 domains: [formattedDomain],
320 configuration_id: configData.configuration_id
321 })
322 });
323
324 if (!scanResponse.ok) throw new Error(`Scan initiation failed: ${scanResponse.status}`);
325
326 const scanData = await scanResponse.json();
327 console.log('Scan response:', scanData); // Add logging to debug
328
329 // Check for scan ID in different possible response structures
330 const scanId = scanData?.scan?.scan_id || scanData?.scan_id || scanData?.id;
331 if (!scanId) {
332 console.error('Scan response structure:', scanData);
333 throw new Error('No scan ID received in response');
334 }
335
336 // Store scan ID in WordPress without status initially
337 await fetch(cookiebot_account.ajax_url, {
338 method: 'POST',
339 body: createFormData('cookiebot_store_scan_details', {
340 scan_id: scanId
341 }),
342 credentials: 'same-origin'
343 });
344
345 // Start checking scan status
346 await checkScanStatus(scanId);
347
348 // fetch configuration details
349 await fetchConfigurationDetails(configData.configuration_id);
350
351 } catch (error) {
352 console.error('Failed to create configuration:', error);
353 return;
354 }
355 } else {
356 // If we already have a CBID, check if there's an ongoing scan
357 const scanDetails = await fetch(cookiebot_account.ajax_url, {
358 method: 'POST',
359 body: createFormData('cookiebot_get_scan_details'),
360 credentials: 'same-origin'
361 }).then(r => r.json());
362
363 if (scanDetails.success && scanDetails.data.scan_id) {
364 await checkScanStatus(scanDetails.data.scan_id);
365 }
366 // And fetch configuration details
367 await fetchConfigurationDetails(cbid);
368 }
369
370 // Check and fetch user data if needed
371 let userResponseData = await fetch(cookiebot_account.ajax_url, {
372 method: 'POST',
373 body: createFormData('cookiebot_get_user_data'),
374 credentials: 'same-origin'
375 }).then(r => r.json());
376
377 try {
378 const userData = await fetch(`${API_BASE_URL}/accounts`, {
379 headers: {
380 'Accept': 'application/json',
381 'Authorization': `Bearer ${authToken}`,
382 }
383 }).then(r => r.json()).then(data => data[0]);
384
385 if (!userData) throw new Error('No user data received');
386
387 // Add onboarding flag to user data
388 const userDataWithFlag = {
389 ...userData,
390 onboarded_via_signup: true
391 };
392 userResponseData = await fetch(cookiebot_account.ajax_url, {
393 method: 'POST',
394 body: createFormData('cookiebot_post_user_data', {
395 data: JSON.stringify(userDataWithFlag)
396 }),
397 credentials: 'same-origin'
398 }).then(r => r.json());
399
400 if (!userResponseData.success) {
401 throw new Error('Failed to store user data');
402 }
403 } catch (error) {
404 console.error('Failed to fetch user data:', error);
405 return;
406 }
407
408 if (userResponseData.data) {
409 const newUrl = new URL(window.location.href);
410 newUrl.searchParams.delete('uc_api_code');
411 window.location.href = newUrl;
412 }
413 } catch (error) {
414 console.error('An unexpected error occurred:', error);
415 }
416 });
417
418 // Event Listeners
419 document.getElementById('banner-close-btn')?.addEventListener('click', async () => {
420 try {
421 const response = await fetch(cookiebot_account.ajax_url, {
422 method: 'POST',
423 body: createFormData('cookiebot_dismiss_banner'),
424 credentials: 'same-origin'
425 });
426
427 if (!response.ok) throw new Error(`Failed to dismiss banner: ${response.status}`);
428 const banner = document.getElementById('banner-live-notice')
429 if (banner) banner.remove();
430 } catch (error) {
431 console.error('Failed to dismiss banner:', error);
432 }
433 });
434
435 document.getElementById('get-started-button')?.addEventListener('click', async (e) => {
436 e.preventDefault();
437 try {
438
439 // If multisite is enabled the url might include also the directory for the site
440 // e.g.: http://domain/site1/wp-admin/admin.php?page=cookiebot
441 const callbackUrl = window.location.href.substring(0, window.location.href.indexOf('/wp-admin')) + '/wp-admin/admin.php?page=cookiebot';
442 window.location.href = `${API_BASE_URL}/auth/auth0/authorize?origin=wordpress_plugin&callback_domain=${encodeURIComponent(callbackUrl)}`;
443 } catch (error) {
444 console.error('Failed to start authentication process:', error);
445 }
446 });
447