-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComponent.js
More file actions
455 lines (429 loc) · 21.2 KB
/
Copy pathComponent.js
File metadata and controls
455 lines (429 loc) · 21.2 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
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/core/Theming",
"sap/ui/model/json/JSONModel"
], function (UIComponent, Theming, JSONModel) {
"use strict";
return UIComponent.extend("sap.tutorials.admin.shell.Component", {
metadata: {
manifest: "json"
},
init: function () {
this._oShellViewModel = new JSONModel({ sideExpanded: true, headerTitle: "Admin Console", showBackButton: false });
this._initMockShellContainer();
this._installAuthInterceptor();
UIComponent.prototype.init.apply(this, arguments);
this._initTheme();
this._initNavModel();
this.getRouter().initialize();
},
_installAuthInterceptor: function () {
// When the XSUAA session expires, backend calls fail in two distinct ways:
// 1. The request returns 401/403 directly (approuter detected the AJAX call).
// 2. The approuter sends a 302 to the IDP login page; the browser silently
// follows the redirect chain and the eventual response is 200 OK with an
// HTML login document. The OData parser then fails silently and the
// Fiori app just shows empty data — exactly what users perceive as
// "missing data".
// Detect both cases and force a page reload so the approuter restarts the
// OAuth flow and the user lands back on the same admin-shell route.
var BACKEND_PREFIXES = ["/admin/", "/admin-ui/", "/api/", "/scanner/", "/display/", "/build/", "/content/"];
var bRedirecting = false;
function isBackendUrl(sUrl) {
if (!sUrl) return false;
try {
var oUrl = new URL(sUrl, window.location.origin);
if (oUrl.origin !== window.location.origin) return false;
return BACKEND_PREFIXES.some(function (p) { return oUrl.pathname.indexOf(p) === 0; });
} catch (e) {
return false;
}
}
function looksLikeLoginHtml(sContentType, sFinalUrl, bRedirected) {
// 200 + text/html on a backend URL means the approuter swapped the JSON
// payload for the IDP login page. response.redirected is true when fetch
// followed the 302 chain. Either is a reliable session-expiry signal.
if (sContentType && sContentType.toLowerCase().indexOf("text/html") === 0) return true;
if (bRedirected) return true;
if (sFinalUrl && /\/(saml2|oauth2|login)\b/i.test(sFinalUrl)) return true;
return false;
}
// --- Reload-loop breaker -------------------------------------------------
// handleUnauthorized() reloads the page to restart the OAuth flow when a
// backend call fails on an expired session. bRedirecting suppresses repeat
// reloads within a single page instance, but it RESETS on every reload — so
// a backend request that fails on EVERY load (a persistent 401, an
// authorization failure, or an edge-cached login page) would reload the page
// forever ("the console keeps refreshing all the time"). Cap the number of
// automatic reloads within a short window in sessionStorage — which, unlike
// bRedirecting, survives reloads — and surface a message instead of
// refreshing endlessly.
var RELOAD_KEY = "sap-tutorials-admin-auth-reloads";
var RELOAD_WINDOW_MS = 30000;
var RELOAD_MAX = 2;
function readReloadRec() {
try {
var raw = sessionStorage.getItem(RELOAD_KEY);
var rec = raw ? JSON.parse(raw) : null;
return (rec && typeof rec.count === "number" && typeof rec.first === "number") ? rec : null;
} catch (e) { return null; }
}
function clearReloadRec() {
try { sessionStorage.removeItem(RELOAD_KEY); } catch (e) { /* swallow */ }
}
function recordAutoReload() {
try {
var now = Date.now();
var rec = readReloadRec();
if (!rec || (now - rec.first) > RELOAD_WINDOW_MS) rec = { count: 0, first: now };
rec.count += 1;
sessionStorage.setItem(RELOAD_KEY, JSON.stringify(rec));
} catch (e) { /* sessionStorage unavailable — proceed without the guard */ }
}
function isReloadLoop() {
var rec = readReloadRec();
if (!rec) return false;
if ((Date.now() - rec.first) > RELOAD_WINDOW_MS) return false;
return rec.count >= RELOAD_MAX;
}
function notifyAuthLoop() {
// Terminal state: we've auto-reloaded RELOAD_MAX times inside the window
// without reaching a stable session. Stop reloading and tell the user —
// most often this is an Author-only account opening an Admin-only view,
// which no amount of re-authentication can fix.
sap.ui.require(["sap/m/MessageBox"], function (MessageBox) {
MessageBox.error(
"The Admin Console couldn't finish loading this view. This usually means your " +
"account doesn't have access to it (for example, an Author account opening an " +
"Admin-only screen), or your session needs a fresh sign-in.",
{
title: "Access problem",
actions: ["Go to start", "Sign in again", MessageBox.Action.CLOSE],
emphasizedAction: "Go to start",
onClose: function (sAction) {
clearReloadRec();
if (sAction === "Sign in again") {
window.location.href = "/logout";
} else if (sAction === "Go to start") {
// Drop the hash so we land on the (Author-safe) Dashboard
// rather than the view that can't load.
window.location.href = window.location.pathname;
}
}
}
);
}, function () {
// MessageBox failed to load — fall back to the Author-safe start page.
clearReloadRec();
window.location.href = window.location.pathname;
});
}
function handleUnauthorized() {
if (bRedirecting) return;
bRedirecting = true;
if (isReloadLoop()) { notifyAuthLoop(); return; }
recordAutoReload();
// Reloading the current URL (incl. hash) makes the approuter restart the OAuth flow
// and return the user to the same admin-shell route after re-authentication.
try { window.location.reload(); } catch (e) { window.location.href = window.location.href; }
}
function isCsrfRejection(oHeaders, sUrl) {
// Recognize an AppRouter CSRF 403 so the interceptor does NOT reload
// (the OData v4 client re-fetches the token on its own; reload strips
// the fresh token from memory and reproduces the failure — #895).
//
// Two signals, either sufficient:
// 1. Response carries `x-csrf-token: required` (AppRouter's native
// contract when errorPage[403] is not rewriting the response).
// 2. The URL is an OData batch/action endpoint — those are the ONLY
// places UI5 OData v4 sends POST/PUT/DELETE, so a 403 there is
// overwhelmingly CSRF, not permissions. Belt-and-suspenders in
// case a future errorPage[403] rewrite masks the header.
if (oHeaders && oHeaders.get) {
var sHdr = "";
try { sHdr = oHeaders.get("x-csrf-token") || ""; } catch (e) { /* swallow */ }
if (sHdr.toLowerCase() === "required") return true;
}
if (sUrl && /\/\$batch(\?|$)/.test(sUrl)) return true;
return false;
}
var fnOriginalFetch = window.fetch;
window.fetch = function (input, init) {
var sUrl = (typeof input === "string") ? input : (input && input.url);
var sMethod = ((init && init.method) || (input && input.method) || "GET").toUpperCase();
return fnOriginalFetch.apply(this, arguments).then(function (response) {
if (!isBackendUrl(sUrl)) return response;
var bMutating = sMethod !== "GET" && sMethod !== "HEAD" && sMethod !== "OPTIONS";
var sCt = (response.headers && response.headers.get && response.headers.get("content-type")) || "";
if (response.status === 401) {
handleUnauthorized();
} else if (response.status === 403) {
if (bMutating && isCsrfRejection(response.headers, sUrl)) {
// CSRF 403 — the OData v4 client re-fetches the token on its own;
// reloading would strip the fresh token and reproduce it (#895).
} else if (looksLikeLoginHtml(sCt, response.url, response.redirected)) {
// Session expiry surfaced as a 403 carrying a login page / redirect.
handleUnauthorized();
}
// else: AUTHORIZATION denial (a JSON 403 — e.g. an Author account
// hitting an @requires:'Admin' /admin/ service). Do NOT reload: it
// cannot grant the missing scope and would loop forever. Let the view
// surface its own load error instead.
} else if (response.status === 200 && looksLikeLoginHtml(sCt, response.url, response.redirected)) {
handleUnauthorized();
}
return response;
});
};
var fnOriginalOpen = XMLHttpRequest.prototype.open;
var fnOriginalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url) {
this.__authUrl = url;
this.__authMethod = (method || "GET").toUpperCase();
return fnOriginalOpen.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function () {
var that = this;
this.addEventListener("load", function () {
if (!isBackendUrl(that.__authUrl)) return;
// XHR: emulate the fetch-side headers.get() so isCsrfRejection() works.
var oHdrs = { get: function (n) {
try { return that.getResponseHeader(n); } catch (e) { return null; }
}};
var sContentType = "";
try { sContentType = that.getResponseHeader("content-type") || ""; } catch (e) { /* swallow */ }
// responseURL reflects the final URL after any redirects the browser followed.
var sFinalUrl = that.responseURL || "";
var bRedirected = !!sFinalUrl && sFinalUrl !== new URL(that.__authUrl, window.location.origin).href;
var bMutating = that.__authMethod !== "GET" && that.__authMethod !== "HEAD" && that.__authMethod !== "OPTIONS";
if (that.status === 401) {
handleUnauthorized();
} else if (that.status === 403) {
if (bMutating && isCsrfRejection(oHdrs, that.__authUrl)) return;
// Only a session-artifact 403 (login page / redirect) is recoverable by
// reloading; a JSON authorization denial is not — see the fetch path.
if (looksLikeLoginHtml(sContentType, sFinalUrl, bRedirected)) handleUnauthorized();
} else if (that.status === 200 && looksLikeLoginHtml(sContentType, sFinalUrl, bRedirected)) {
handleUnauthorized();
}
});
return fnOriginalSend.apply(this, arguments);
};
// UI5's async loader fetches lazy components (e.g. components/groups/Component.js)
// via injected <script> tags, which bypass both the fetch and XHR hooks above.
// When the XSUAA session expires mid-session, AppRouter kicks the OAuth flow on
// those script requests and the browser surfaces only a generic resource-load
// error event with no auth context — UI5 then logs "ModuleError: ... script
// load error" and the UI silently breaks. Catch that error here, then probe
// /auth/user with redirect:'manual' to distinguish a session-expiry redirect
// (response.type === 'opaqueredirect') from a genuine 404 / syntax error.
window.addEventListener("error", function (oEvt) {
var el = oEvt && oEvt.target;
if (!el || el.tagName !== "SCRIPT" || !el.src) return;
if (el.src.indexOf("/admin-ui/") === -1) return;
if (bRedirecting) return;
fnOriginalFetch("/auth/user", { credentials: "include", redirect: "manual" })
.then(function (r) {
if (r.type === "opaqueredirect") return handleUnauthorized();
if (r.status === 401 || r.status === 403) return handleUnauthorized();
var sContentType = "";
try { sContentType = (r.headers && r.headers.get && r.headers.get("content-type")) || ""; } catch (e) { /* swallow */ }
if (sContentType.toLowerCase().indexOf("text/html") === 0) handleUnauthorized();
})
.catch(function () { /* network glitch — don't reload */ });
}, true);
},
getShellViewModel: function () {
return this._oShellViewModel;
},
_initMockShellContainer: function () {
if (sap.ushell && sap.ushell.Container) {
return;
}
var that = this;
sap.ushell = sap.ushell || {};
sap.ushell.Container = {
getServiceAsync: function (sServiceName) {
if (sServiceName === "ShellUIService") {
return Promise.resolve(that._getShellUIServiceInstance());
}
if (sServiceName === "Navigation" || sServiceName === "CrossApplicationNavigation") {
return Promise.resolve({
toExternal: function () {},
backToPreviousApp: function () {
that._navigateBackToList();
},
hrefForExternal: function () { return "#"; },
getDistinctSemanticObjects: function () { return Promise.resolve([]); },
getLinks: function () { return Promise.resolve([]); },
isNavigationSupported: function () { return Promise.resolve([{ supported: false }]); },
isInitialNavigation: function () { return false; },
expandCompactHash: function (sHash) { return Promise.resolve(sHash); }
});
}
if (sServiceName === "URLParsing") {
return Promise.resolve({
parseShellHash: function () { return {}; },
splitHash: function () { return {}; },
constructShellHash: function () { return ""; }
});
}
return Promise.resolve({});
},
getService: function (sServiceName) {
return sap.ushell.Container.getServiceAsync(sServiceName);
},
getDirtyFlag: function () { return false; },
setDirtyFlag: function () {},
registerDirtyStateProvider: function () {},
deregisterDirtyStateProvider: function () {},
getLogonSystem: function () { return { getName: function () { return ""; } }; },
getFLPUrl: function () { return ""; },
getRenderer: function () {
return Promise.resolve({
getShellConfig: function () { return {}; }
});
}
};
},
_navigateBackToList: function () {
var oRouter = this.getRouter();
var oHashChanger = oRouter.getHashChanger();
var sCurrentHash = oHashChanger.getHash();
var sShellRoute = sCurrentHash.split("&")[0];
oHashChanger.setHash(sShellRoute);
},
_getShellUIServiceInstance: function () {
if (!this._oShellUIService) {
var oViewModel = this._oShellViewModel;
this._oShellUIService = {
_fnBackNavigation: null,
_aHierarchy: [],
_sTitle: "",
setBackNavigation: function (fnCallback) {
this._fnBackNavigation = fnCallback || null;
oViewModel.setProperty("/showBackButton", !!fnCallback);
},
getBackNavigation: function () {
return this._fnBackNavigation;
},
setHierarchy: function (aHierarchy) {
this._aHierarchy = aHierarchy || [];
},
setTitle: function (sTitle) {
this._sTitle = sTitle || "";
},
getTitle: function () {
return this._sTitle;
},
getContentDensity: function () {
return "compact";
}
};
}
return this._oShellUIService;
},
_initTheme: function () {
var sStoredTheme = localStorage.getItem("sap-tutorials-admin-theme");
var bOsDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
var sTheme = sStoredTheme || (bOsDark ? "sap_horizon_dark" : "sap_horizon");
Theming.setTheme(sTheme);
var sMode = sStoredTheme ? (sStoredTheme === "sap_horizon_dark" ? "dark" : "light") : "auto";
this.setModel(new JSONModel({ themeMode: sMode }), "theme");
window.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", function (e) {
if (!localStorage.getItem("sap-tutorials-admin-theme")) {
Theming.setTheme(e.matches ? "sap_horizon_dark" : "sap_horizon");
}
});
},
_initNavModel: function () {
var oNavModel = new JSONModel();
oNavModel.loadData(sap.ui.require.toUrl("sap/tutorials/admin/shell/model/navigation.json"));
// #829 — restore each group's expanded state from localStorage as soon as
// the JSON is in. Groups without an items[] (top-level leaves like
// dashboard) keep the property undefined; UI5 NavigationListItem treats
// missing `expanded` as the default (open), which is the right behavior
// for leaf items that have no expand chevron.
this._oNavModel = oNavModel;
oNavModel.attachRequestCompleted(function () {
var groups = oNavModel.getProperty("/groups") || [];
// Resolve env-specific external links (hrefDev/hrefProd -> href).
this._resolveEnvLinks();
groups.forEach(function (g) {
if (!g.items || !g.items.length) return;
var sStored = localStorage.getItem("sap-tutorials-admin-nav-group-" + g.key);
// Default to open (true) when no preference is stored; only set to
// false when explicitly remembered as collapsed.
g.expanded = (sStored === null) ? true : (sStored !== "false");
});
oNavModel.setProperty("/groups", groups);
}.bind(this));
// Persist any user-driven change to `expanded` via two-way binding.
// The NavigationListItem writes through `nav>expanded` on chevron
// click; the resulting propertyChange fires here. Restoring the same
// value from localStorage on init also produces a propertyChange, but
// writing the same value back is a no-op so the loop is self-stable.
//
// UI5 fires propertyChange with the RELATIVE binding path (`expanded`)
// plus a `context` parameter for the row (`/groups/N`) — NOT a
// pre-resolved absolute path. The original #832 fix assumed absolute
// paths, so its regex never matched and localStorage was never
// written. Match on the relative path + a `/groups/\d+` context
// instead. (#829 regression, spotted post-#832 in DEV.)
oNavModel.attachPropertyChange(function (oEvent) {
var sPath = oEvent.getParameter("path");
var oContext = oEvent.getParameter("context");
if (sPath !== "expanded" || !oContext) return;
var sCtxPath = oContext.getPath();
if (!/^\/groups\/\d+$/.test(sCtxPath)) return;
var oGroup = oNavModel.getProperty(sCtxPath);
if (!oGroup || !oGroup.key) return;
var bValue = oEvent.getParameter("value");
localStorage.setItem("sap-tutorials-admin-nav-group-" + oGroup.key, String(!!bValue));
});
this.setModel(oNavModel, "nav");
},
// Resolve env-specific external links (hrefDev/hrefProd -> href). The
// admin-shell bundle is built once and deployed to both DEV and PROD, so
// URLs that differ per environment can't be hardcoded in the JSON — they're
// picked at runtime.
//
// Precedence:
// 1. The authoritative deploy environment reported by /auth/user
// (derived from the CF space_name — see srv/lib/deploy-environment.js;
// chosen because the Host header is spoofable). Fed in via
// setDeployEnvironment() once the Shell controller has it. This is the
// ONLY signal that is correct on the vanity host developers.sap.com,
// where the hostname carries no "-prod" and the sniff below misses.
// 2. Fallback: the approuter hostname. PROD CF app names carry "-prod";
// everything else falls back to DEV. Used before /auth/user resolves,
// and correct on the raw *.cfapps.* approuter routes.
_resolveEnvLinks: function () {
var oNavModel = this._oNavModel;
if (!oNavModel) return;
var groups = oNavModel.getProperty("/groups") || [];
var bIsProd = (typeof this._bEnvIsProd === "boolean")
? this._bEnvIsProd
: /-prod\b/.test(window.location.hostname);
var resolveHref = function (oItem) {
if (oItem.hrefDev || oItem.hrefProd) {
oItem.href = (bIsProd ? oItem.hrefProd : oItem.hrefDev) || oItem.href;
}
};
groups.forEach(function (g) {
resolveHref(g);
(g.items || []).forEach(resolveHref);
});
oNavModel.setProperty("/groups", groups);
},
// Called by Shell.controller once /auth/user reports the deploy environment.
// Stores the authoritative prod/non-prod flag and re-resolves env-specific
// links so a hostname-based mis-resolution (e.g. on the vanity domain) is
// corrected as soon as the server truth arrives.
setDeployEnvironment: function (bIsProd) {
this._bEnvIsProd = !!bIsProd;
this._resolveEnvLinks();
}
});
});