Debian Codegraph @

src/drf_yasg/static/drf-yasg/swagger-ui-init.js

raw symbols SCIP
1 // swagger-ui-init.js
2 // https://github.com/axnsan12/drf-yasg
3 // Copyright 2017 - 2021, Cristian V. <[email protected]>
4 // This file is licensed under the BSD 3-Clause License.
5 // License text available at https://opensource.org/licenses/BSD-3-Clause
6
7 "use strict";
8 var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
9 var defaultSpecUrl = currentPath + '?format=openapi';
10
11 function slugify(text) {
12 return text.toString().toLowerCase()
13 .replace(/\s+/g, '-') // Replace spaces with -
14 .replace(/[^\w\-]+/g, '') // Remove all non-word chars
15 .replace(/--+/g, '-') // Replace multiple - with single -
16 .replace(/^-+/, '') // Trim - from start of text
17 .replace(/-+$/, ''); // Trim - from end of text
18 }
19
20 var KEY_AUTH = slugify(window.location.pathname) + "-drf-yasg-auth";
21
22 // load the saved authorization state from localStorage; ImmutableJS is used for consistency with swagger-ui state
23 var savedAuth = Immutable.fromJS({});
24
25 // global SwaggerUI config object; can be changed directly or by hooking initSwaggerUiConfig
26 var swaggerUiConfig = {
27 url: defaultSpecUrl,
28 dom_id: '#swagger-ui',
29 displayRequestDuration: true,
30 presets: [
31 SwaggerUIBundle.presets.apis,
32 SwaggerUIStandalonePreset
33 ],
34 plugins: [
35 SwaggerUIBundle.plugins.DownloadUrl
36 ],
37 layout: "StandaloneLayout",
38 filter: true,
39 csrfCookie: 'csrftoken',
40 csrfHeader: 'X-CSRFToken',
41 requestInterceptor: function (request) {
42 var headers = request.headers || {};
43 var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]");
44 if (csrftoken) {
45 csrftoken = csrftoken.value;
46 } else {
47 var cookies = document.cookie.split(/;\s+/);
48 var name = swaggerUiConfig.csrfCookie;
49 for (var i = 0; i < cookies.length; i++) {
50 if (cookies[i].indexOf(name) === 0) {
51 csrftoken = cookies[i].slice(cookies[i].indexOf('=') + 1);
52 break;
53 }
54 }
55 }
56
57 if (csrftoken) {
58 headers[swaggerUiConfig.csrfHeader] = csrftoken;
59 }
60
61 return request;
62 }
63 };
64
65 function patchSwaggerUi() {
66 if (document.querySelector('.auth-wrapper #django-session-auth')) {
67 return;
68 }
69
70 var authWrapper = document.querySelector('.auth-wrapper');
71 var authorizeButton = document.querySelector('.auth-wrapper .authorize');
72 var djangoSessionAuth = document.querySelector('#django-session-auth');
73
74 if (!djangoSessionAuth) {
75 console.log("WARNING: session auth disabled");
76 return;
77 }
78
79 djangoSessionAuth = djangoSessionAuth.cloneNode(true);
80 authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
81 djangoSessionAuth.classList.remove("hidden");
82 }
83
84 function initSwaggerUi() {
85 if (window.ui) {
86 console.log("WARNING: skipping initSwaggerUi() because window.ui is already defined");
87 return;
88 }
89 if (document.querySelector('.auth-wrapper .authorize')) {
90 patchSwaggerUi();
91 } else {
92 insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
93 }
94
95 var swaggerSettings = JSON.parse(document.getElementById('swagger-settings').innerHTML);
96
97 var oauth2RedirectUrl = document.getElementById('oauth2-redirect-url');
98 if (oauth2RedirectUrl) {
99 if (!('oauth2RedirectUrl' in swaggerSettings)) {
100 if (oauth2RedirectUrl) {
101 swaggerSettings['oauth2RedirectUrl'] = oauth2RedirectUrl.href;
102 }
103 }
104 oauth2RedirectUrl.parentNode.removeChild(oauth2RedirectUrl);
105 }
106
107 console.log('swaggerSettings', swaggerSettings);
108 var oauth2Config = JSON.parse(document.getElementById('oauth2-config').innerHTML);
109 console.log('oauth2Config', oauth2Config);
110
111 initSwaggerUiConfig(swaggerSettings, oauth2Config);
112 window.ui = SwaggerUIBundle(swaggerUiConfig);
113 window.ui.initOAuth(oauth2Config);
114 }
115
116 /**
117 * Initialize the global swaggerUiConfig with any given additional settings.
118 * @param swaggerSettings SWAGGER_SETTINGS from Django settings
119 * @param oauth2Settings OAUTH2_CONFIG from Django settings
120 */
121 function initSwaggerUiConfig(swaggerSettings, oauth2Settings) {
122 var persistAuth = swaggerSettings.persistAuth;
123 var refetchWithAuth = swaggerSettings.refetchWithAuth;
124 var refetchOnLogout = swaggerSettings.refetchOnLogout;
125 var fetchSchemaWithQuery = swaggerSettings.fetchSchemaWithQuery;
126 delete swaggerSettings['persistAuth'];
127 delete swaggerSettings['refetchWithAuth'];
128 delete swaggerSettings['refetchOnLogout'];
129 delete swaggerSettings['fetchSchemaWithQuery'];
130
131 for (var p in swaggerSettings) {
132 if (swaggerSettings.hasOwnProperty(p)) {
133 swaggerUiConfig[p] = swaggerSettings[p];
134 }
135 }
136
137 var specURL = swaggerUiConfig.url;
138 if (fetchSchemaWithQuery) {
139 // only add query params from document for the first spec request
140 // this ensures we otherwise honor the spec selector box which might be manually modified
141 var query = new URLSearchParams(window.location.search || '').entries();
142 for (var it = query.next(); !it.done; it = query.next()) {
143 specURL = setQueryParam(specURL, it.value[0], it.value[1]);
144 }
145 }
146 if (persistAuth) {
147 try {
148 savedAuth = Immutable.fromJS(JSON.parse(localStorage.getItem(KEY_AUTH)) || {});
149 } catch (e) {
150 localStorage.removeItem(KEY_AUTH);
151 }
152 }
153 if (refetchWithAuth) {
154 specURL = applyAuth(savedAuth, specURL) || specURL;
155 }
156 swaggerUiConfig.url = specURL;
157
158 if (persistAuth || refetchWithAuth) {
159 var hookedAuth = false;
160
161 var oldOnComplete = swaggerUiConfig.onComplete;
162 swaggerUiConfig.onComplete = function () {
163 if (persistAuth) {
164 preauthorizeAll(savedAuth, window.ui);
165 }
166
167 if (!hookedAuth) {
168 hookAuthActions(window.ui, persistAuth, refetchWithAuth, refetchOnLogout);
169 hookedAuth = true;
170 }
171 if (oldOnComplete) {
172 oldOnComplete();
173 }
174 };
175
176 var specRequestsInFlight = {};
177 var oldRequestInterceptor = swaggerUiConfig.requestInterceptor;
178 swaggerUiConfig.requestInterceptor = function (request) {
179 var headers = request.headers || {};
180 if (request.loadSpec) {
181 var newUrl = request.url;
182 if (refetchWithAuth) {
183 newUrl = applyAuth(savedAuth, newUrl, headers) || newUrl;
184 }
185
186 if (newUrl !== request.url) {
187 request.url = newUrl;
188
189 if (window.ui) {
190 // this visually updates the spec url before the request is done, i.e. while loading
191 window.ui.specActions.updateUrl(request.url);
192 } else {
193 // setTimeout is needed here because the request interceptor can be called *during*
194 // window.ui initialization (by the SwaggerUIBundle constructor)
195 setTimeout(function () {
196 window.ui.specActions.updateUrl(request.url);
197 });
198 }
199
200 // need to manually remember requests for spec urls because
201 // responseInterceptor has no reference to the request...
202 var absUrl = new URL(request.url, currentPath);
203 specRequestsInFlight[absUrl.href] = request.url;
204 }
205 }
206
207 if (oldRequestInterceptor) {
208 request = oldRequestInterceptor(request);
209 }
210 return request;
211 };
212
213 var oldResponseInterceptor = swaggerUiConfig.responseInterceptor;
214 swaggerUiConfig.responseInterceptor = function (response) {
215 var absUrl = new URL(response.url, currentPath);
216 if (absUrl.href in specRequestsInFlight) {
217 var setToUrl = specRequestsInFlight[absUrl.href];
218 delete specRequestsInFlight[absUrl.href];
219 if (response.ok) {
220 // need setTimeout here because swagger-ui insists to call updateUrl
221 // with the initial request url after the response...
222 setTimeout(function () {
223 var currentUrl = new URL(window.ui.specSelectors.url(), currentPath);
224 if (currentUrl.href !== absUrl.href) {
225 window.ui.specActions.updateUrl(setToUrl);
226 }
227 });
228 }
229 }
230
231 if (oldResponseInterceptor) {
232 response = oldResponseInterceptor(response);
233 }
234 return response;
235 }
236 }
237 }
238
239 function _usp(url, fn) {
240 url = url.split('?');
241 var usp = new URLSearchParams(url[1] || '');
242 fn(usp);
243 url[1] = usp.toString();
244 return url[1] ? url.join('?') : url[0];
245 }
246
247 function setQueryParam(url, key, value) {
248 return _usp(url, function (usp) {
249 usp.set(key, value);
250 });
251 }
252
253 function removeQueryParam(url, key) {
254 return _usp(url, function (usp) {
255 usp.delete(key);
256 })
257 }
258
259 /**
260 * Call sui.preauthorize### for all authorizations in authorization.
261 * @param authorization authorization object {key => authScheme} saved from authActions.authorize
262 * @param sui SwaggerUI or SwaggerUIBundle instance
263 */
264 function preauthorizeAll(authorization, sui) {
265 authorization.valueSeq().forEach(function (authScheme) {
266 var schemeName = authScheme.get("name"), schemeType = authScheme.getIn(["schema", "type"]);
267 if (schemeType === "basic" && schemeName) {
268 var username = authScheme.getIn(["value", "username"]);
269 var password = authScheme.getIn(["value", "password"]);
270 if (username && password) {
271 sui.preauthorizeBasic(schemeName, username, password);
272 }
273 } else if (schemeType === "apiKey" && schemeName) {
274 var key = authScheme.get("value");
275 if (key) {
276 sui.preauthorizeApiKey(schemeName, key);
277 }
278 } else {
279 // TODO: OAuth2
280 }
281 });
282 }
283
284 /**
285 * Manually apply auth headers from the given auth object.
286 * @param {object} authorization authorization object {key => authScheme} saved from authActions.authorize
287 * @param {string} requestUrl the request url
288 * @param {object} requestHeaders target headers, modified in place by the function
289 * @return string new request url
290 */
291 function applyAuth(authorization, requestUrl, requestHeaders) {
292 authorization.valueSeq().forEach(function (authScheme) {
293 requestHeaders = requestHeaders || {};
294 var schemeName = authScheme.get("name"), schemeType = authScheme.getIn(["schema", "type"]);
295 if (schemeType === "basic" && schemeName) {
296 var username = authScheme.getIn(["value", "username"]);
297 var password = authScheme.getIn(["value", "password"]);
298 if (username && password) {
299 requestHeaders["Authorization"] = "Basic " + btoa(username + ":" + password);
300 }
301 } else if (schemeType === "apiKey" && schemeName) {
302 var _in = authScheme.getIn(["schema", "in"]), paramName = authScheme.getIn(["schema", "name"]);
303 var key = authScheme.get("value");
304 if (key && paramName) {
305 if (_in === "header") {
306 requestHeaders[paramName] = key;
307 }
308 if (_in === "query") {
309 if (requestUrl) {
310 requestUrl = setQueryParam(requestUrl, paramName, key);
311 } else {
312 console.warn("WARNING: cannot apply apiKey query parameter via interceptor");
313 }
314 }
315 }
316 } else {
317 // TODO: OAuth2
318 }
319 });
320
321 return requestUrl;
322 }
323
324 /**
325 * Remove the given authorization scheme from the url.
326 * @param {object} authorization authorization object {key => authScheme} containing schemes to deauthorize
327 * @param {string} requestUrl request url
328 * @return string new request url
329 */
330 function deauthUrl(authorization, requestUrl) {
331 authorization.valueSeq().forEach(function (authScheme) {
332 var schemeType = authScheme.getIn(["schema", "type"]);
333 if (schemeType === "apiKey") {
334 var _in = authScheme.getIn(["schema", "in"]), paramName = authScheme.getIn(["schema", "name"]);
335 if (_in === "query" && requestUrl && paramName) {
336 requestUrl = removeQueryParam(requestUrl, paramName);
337 }
338 } else {
339 // TODO: OAuth2?
340 }
341 });
342 return requestUrl;
343 }
344
345 /**
346 * Hook the authorize and logout actions of SwaggerUI.
347 * The hooks are used to persist authorization data and trigger schema refetch.
348 * @param sui SwaggerUI or SwaggerUIBundle instance
349 * @param {boolean} persistAuth true to save auth to local storage
350 * @param {boolean} refetchWithAuth true to trigger schema fetch on login
351 * @param {boolean} refetchOnLogout true to trigger schema fetch on logout
352 */
353 function hookAuthActions(sui, persistAuth, refetchWithAuth, refetchOnLogout) {
354 if (!persistAuth && !refetchWithAuth) {
355 // nothing to do
356 return;
357 }
358
359 var originalAuthorize = sui.authActions.authorize;
360 sui.authActions.authorize = function (authorization) {
361 originalAuthorize(authorization);
362 // authorization is map of scheme name to scheme object
363 // need to use ImmutableJS because schema is already an ImmutableJS object
364 var newAuths = Immutable.fromJS(authorization);
365 savedAuth = savedAuth.merge(newAuths);
366
367 if (refetchWithAuth) {
368 var url = sui.specSelectors.url();
369 url = applyAuth(savedAuth, url) || url;
370 sui.specActions.updateUrl(url);
371 sui.specActions.download();
372 sui.authActions.showDefinitions(); // hide authorize dialog
373 }
374 if (persistAuth) {
375 localStorage.setItem(KEY_AUTH, JSON.stringify(savedAuth.toJSON()));
376 }
377 };
378
379 var originalLogout = sui.authActions.logout;
380 sui.authActions.logout = function (authorization) {
381 // stash logged out methods for use with deauthUrl
382 var loggedOut = savedAuth.filter(function (val, key) {
383 return authorization.indexOf(key) !== -1;
384 }).mapEntries(function (entry) {
385 return [entry[0], entry[1].set("value", null)]
386 });
387 // remove logged out methods from savedAuth
388 savedAuth = savedAuth.filter(function (val, key) {
389 return authorization.indexOf(key) === -1;
390 });
391
392 if (refetchWithAuth) {
393 var url = sui.specSelectors.url();
394 url = deauthUrl(loggedOut, url) || url;
395 sui.specActions.updateUrl(url);
396 sui.specActions.download(url);
397 sui.authActions.showDefinitions(); // hide authorize dialog
398 }
399 if (persistAuth) {
400 localStorage.setItem(KEY_AUTH, JSON.stringify(savedAuth.toJSON()));
401 }
402 originalLogout(authorization);
403 };
404 }
405
406 window.addEventListener('load', initSwaggerUi);