-
Notifications
You must be signed in to change notification settings - Fork 0
/
Persistent_filters_example.html
364 lines (300 loc) · 12.7 KB
/
Persistent_filters_example.html
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
<head>
<script
defer
src="https://cdn.luzmo.com/js/luzmo-embed/5.0.0/luzmo-embed.min.js"
charset="utf-8"
></script>
</head>
<body>
<div class="helpers">
<pre class="error-container">LOADING...</pre>
<div id="auth-info" style="display: none;">
<div>SSO Key: <span id="auth-key"></span> <button id="copy-auth-key">Copy</button></div>
<div>SSO Token: <span id="auth-token"></span> <button id="copy-auth-token">Copy</button></div>
<div>Dashboard ID or slug: <span id="dashboard-id"></span> <button id="copy-dashboard-id">Copy</button></div>
</div>
</div>
<luzmo-dashboard></luzmo-dashboard>
<script>
/*
#############################
#############################
ADAPT THE FOLLOWING VARIABLES
#############################
#############################
*/
// Luzmo app and api host (used to request SSO token and embed dashboard)
const LUZMO_APP_SERVER = 'https://app.luzmo.com';
const LUZMO_API_HOST = 'https://api.luzmo.com';
// api key and token used to request a SSO token
const LUZMO_API_KEY = '<API_KEY>';
const LUZMO_API_TOKEN = '<API_TOKEN>';
// Dashboard ID or slug to embed
const DASHBOARD_TO_EMBED = '<DASHBOARD_ID>';
// Dashboard edit mode (can be 'view', 'editLimited', or 'editFull')
const DESIRED_EDIT_MODE = 'view';
/*
Instead of defining each individual variable below,
you can define the full request properties here.
*/
const authorizationProperties = {
type: 'embed',
inactivity_interval: 600,
access: {
collections: [
{
id: '<collection ID>',
inheritRights: 'use'
}
]
},
username: '',
name: '',
email: '',
suborganization: '',
role: '',
metadata: {},
account_overrides: {}
};
/*
Make sure to define each variables below,
if the authorizationProperties object above is not used
*/
// SSO user properties (passed along in SSO Authorization request)
const USERNAME = '< username >';
const NAME = '< user name >';
const EMAIL = '< user email >';
const SUBORGANIZATION = '< suborganization name >';
const COLLECTION_ID = '< collection ID >';
const ROLE = 'viewer';
const OPTIONAL_METADATA = {
/*parameter_name: ["value_to_override"]*/
};
const OPTIONAL_ACCOUNT_OVERRIDES = {
/*
"<account_id>": {
"host": "< The new database host to connect to. >"
}
*/
};
/*
#############################
#############################
END
#############################
#############################
*/
const getAuthorizationTokenAndEmbed = () => {
getAuthorizationToken().then(res => {
if (res) {
const ssoAuthorizationKey = res.id;
const ssoAuthorizationToken = res.token;
// Show SSO key, token, and dashboard ID in page.
showProperties(ssoAuthorizationKey, ssoAuthorizationToken);
// Embed the dashboard
embedDashboard(ssoAuthorizationKey, ssoAuthorizationToken);
/*
###### STEP 1 ######
The "changedFilters" event listener is set on the Luzmo component calling the handleChangedFilters function.
(reference: https://developer.luzmo.com/#listening-to-events)
*/
const dashboardComponent = document.querySelector('luzmo-dashboard');
dashboardComponent.addEventListener("changedFilters", handleChangedFilters);
}
})
}
const handleChangedFilters = (event) => {
console.log("The following changedFilters event is received: ", event);
// parse frontend interactivity filters into SSO initialization filters
const backendFilters = mapFrontendFiltersIntoBackendInitializationFilters(event);
// Store it in the browser for future usage
persistFilters(backendFilters);
};
/*
###### STEP 2 ######
The frontend filters are parsed and transformed into backend initialization filters
*/
const mapFrontendFiltersIntoBackendInitializationFilters = (frontendChangedFiltersEvent) => {
const frontendFilters = event.detail.data.filters;
return frontendFilters
// Remove chart / dashboard filters
.filter(frontendFilter => !["itemFilter", "global"].includes(frontendFilter.origin))
// Map into backend filters
.map(frontendFilter => {
const backendFilter = {
clause: "where",
origin: "initialization",
chart_id: frontendFilter.itemId,
expression: frontendFilter.filters[0].expression,
value: frontendFilter.filters[0].parameters[1]
};
const filterType = frontendFilter.origin;
// Add dataset & column ID in case of a non-filter widget filter initialization
if (filterType === "filterFromVizItem") {
backendFilter.securable_id = frontendFilter.filters[0].parameters[0].datasetId;
backendFilter.column_id = frontendFilter.filters[0].parameters[0].columnId;
}
return backendFilter;
});
};
/*
Method to get a SSO authorization token in the frontend (NOT RECOMMENDED IN PRODUCTION FOR SECURITY REASONS!)
*/
const getAuthorizationToken = async() => {
const errorContainerEl = document.querySelector('.error-container');
// The request body to request a SSO authorization token
const authorizationRequestBody = {
action: 'create',
version: '0.1.0',
key: LUZMO_API_KEY,
token: LUZMO_API_TOKEN,
properties: {
type: 'embed',
inactivity_interval: 600,
username: USERNAME,
name: NAME,
email: EMAIL,
suborganization: SUBORGANIZATION,
access: {
collections: [
{
id: COLLECTION_ID,
inheritRights: 'use'
}
]
},
role: ROLE,
metadata: OPTIONAL_METADATA,
account_overrides: OPTIONAL_ACCOUNT_OVERRIDES
},
};
if (authorizationProperties && authorizationProperties?.username.length > 0) {
console.log("Using the authorizationProperties object instead of the individual variables");
authorizationRequestBody.properties = authorizationProperties;
}
/*
###### STEP 3 ######
Initialization filters are retrieved from local storage using the "getPersistedFilters" method,
and they are added as "filters" to the "properties" of the authorizationRequestBody.
The authorizationRequestBody is passed as the body in the call to create an authorization.
*/
authorizationRequestBody.properties.filters = getPersistedFilters();
try {
const response = await fetch(LUZMO_API_HOST + '/0.1.0/authorization', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(authorizationRequestBody)
});
if (response.status === 200) {
console.log('Authorization request successful!');
// Hide error container
errorContainerEl.style.display = "none";
// Parse response into JSON object
const responseData = await response.json();
console.log('Response:', responseData);
return responseData;
} else {
// Show error in page
const responseData = await response.json();
errorContainerEl.innerText = 'Authorization request failed! Error: ' + JSON.stringify(responseData, null, 2);
errorContainerEl.innerHTML += `
The following SSO Authorization request was made:
POST ${LUZMO_API_HOST}/0.1.0/authorization<br>
${JSON.stringify(authorizationRequestBody, null, 2)}`;
console.error('Authorization request failed! Error:', responseData);
return null;
}
} catch (error) {
errorContainerEl.innerText = 'An error occurred while making the request:' + error;
console.error('An error occurred while making the request:', error);
return null;
}
}
/*
Method to embed a dashboard with the SSO key and token
*/
const embedDashboard = (authorizationKey, authorizationToken) => {
const dashboardComponent = document.querySelector('luzmo-dashboard');
// Pass along the app and api host to the frontend component
dashboardComponent.appServer = LUZMO_APP_SERVER;
dashboardComponent.apiHost = LUZMO_API_HOST;
// Set the edit mode before passing along authorization token & dashboard
dashboardComponent.editMode = DESIRED_EDIT_MODE;
// Set the SSO Authorization key and token before passing along the dashboard identifier
dashboardComponent.authKey = authorizationKey;
dashboardComponent.authToken = authorizationToken;
// Specify the dashboard to embed
dashboardComponent.dashboardId = DASHBOARD_TO_EMBED;
}
/*
Method to show authorization token and dashboard ID, and set up copy buttons
*/
const showProperties = (authorizationKey, authorizationToken) => {
document.getElementById("auth-info").style.display = "block";
const authKeyEl = document.getElementById('auth-key');
const authTokenEl = document.getElementById('auth-token');
const dashboardIdEl = document.getElementById('dashboard-id');
// Display the authKey, authToken, and dashboardId values
authKeyEl.textContent = authorizationKey;
authTokenEl.textContent = authorizationToken;
dashboardIdEl.textContent = DASHBOARD_TO_EMBED;
// Set up some copy buttons to facilitate copy-pasting values
const copyAuthKeyBtn = document.getElementById('copy-auth-key');
const copyAuthTokenBtn = document.getElementById('copy-auth-token');
const copyDashboardIdBtn = document.getElementById('copy-dashboard-id');
copyAuthKeyBtn.addEventListener('click', () => {
const authKey = document.getElementById('auth-key').textContent;
handleCopyClickEvents(copyAuthKeyBtn, authKey);
});
copyAuthTokenBtn.addEventListener('click', () => {
const authToken = document.getElementById('auth-token').textContent;
handleCopyClickEvents(copyAuthTokenBtn, authToken);
});
copyDashboardIdBtn.addEventListener('click', () => {
const dashboardId = document.getElementById('dashboard-id').textContent;
handleCopyClickEvents(copyDashboardIdBtn, dashboardId);
});
}
const handleCopyClickEvents = (elementRef, textToWrite) => {
navigator.clipboard.writeText(textToWrite);
elementRef.innerText = "Copied!";
setTimeout(() => {elementRef.innerText = "Copy"}, 2000);
};
/*
Method to persist dashboard initialization filters
*/
const persistFilters = (filters) => {
let filtersToPersist;
// No filters have been persisted yet, so create a new element
if (!localStorage.filters)
filtersToPersist = {};
else {
// Retrieve all persisted filters,
// to overwrite only the filters for the currently embedded dashboard
const persistedFilters = localStorage.getItem("filters");
filtersToPersist = JSON.parse(persistedFilters);
}
// Scope the filters storage per dashboard, overwriting existing filters
filtersToPersist[DASHBOARD_TO_EMBED] = filters;
localStorage.setItem("filters", JSON.stringify(filtersToPersist));
}
/*
Method to retrieve persisted dashboard initialization filters
*/
const getPersistedFilters = () => {
const filters = localStorage.getItem("filters");
// Return empty filters if no filters have been persisted yet
if (!filters || filters.length === 0)
return [];
const parsedFilters = JSON.parse(filters);
// Get dashboard specific initialization filters persisted
const dashboardInitFilters = parsedFilters[DASHBOARD_TO_EMBED];
if (dashboardInitFilters) return dashboardInitFilters;
return [];
}
// Trigger the method to request a SSO token and embed a dashboard
getAuthorizationTokenAndEmbed();
</script>
</body>