hyb
2025-05-14 87453ffd761425b9f363a09a0f8fe07d770cb325
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
// swagger-ui-init.js
// https://github.com/axnsan12/drf-yasg
// Copyright 2017 - 2021, Cristian V. <cristi@cvjd.me>
// This file is licensed under the BSD 3-Clause License.
// License text available at https://opensource.org/licenses/BSD-3-Clause
 
"use strict";
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
var defaultSpecUrl = currentPath + '?format=openapi';
 
function slugify(text) {
    return text.toString().toLowerCase()
        .replace(/\s+/g, '-')           // Replace spaces with -
        .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
        .replace(/--+/g, '-')           // Replace multiple - with single -
        .replace(/^-+/, '')             // Trim - from start of text
        .replace(/-+$/, '');            // Trim - from end of text
}
 
var KEY_AUTH = slugify(window.location.pathname) + "-drf-yasg-auth";
 
// load the saved authorization state from localStorage; ImmutableJS is used for consistency with swagger-ui state
var savedAuth = Immutable.fromJS({});
 
// global SwaggerUI config object; can be changed directly or by hooking initSwaggerUiConfig
var swaggerUiConfig = {
    url: defaultSpecUrl,
    dom_id: '#swagger-ui',
    displayRequestDuration: true,
    presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIStandalonePreset
    ],
    plugins: [
        SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout",
    filter: true,
    requestInterceptor: function (request) {
        var headers = request.headers || {};
        var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]");
        if (csrftoken) {
            headers["X-CSRFToken"] = csrftoken.value;
        }
 
        return request;
    }
};
 
function patchSwaggerUi() {
    if (document.querySelector('.auth-wrapper #django-session-auth')) {
        return;
    }
 
    var authWrapper = document.querySelector('.auth-wrapper');
    var authorizeButton = document.querySelector('.auth-wrapper .authorize');
    var djangoSessionAuth = document.querySelector('#django-session-auth');
 
    if (!djangoSessionAuth) {
        console.log("WARNING: session auth disabled");
        return;
    }
 
    djangoSessionAuth = djangoSessionAuth.cloneNode(true);
    authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
    djangoSessionAuth.classList.remove("hidden");
}
 
function initSwaggerUi() {
    if (window.ui) {
        console.log("WARNING: skipping initSwaggerUi() because window.ui is already defined");
        return;
    }
    if (document.querySelector('.auth-wrapper .authorize')) {
        patchSwaggerUi();
    } else {
        insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
    }
 
    var swaggerSettings = JSON.parse(document.getElementById('swagger-settings').innerHTML);
 
    var oauth2RedirectUrl = document.getElementById('oauth2-redirect-url');
    if (oauth2RedirectUrl) {
        if (!('oauth2RedirectUrl' in swaggerSettings)) {
            if (oauth2RedirectUrl) {
                swaggerSettings['oauth2RedirectUrl'] = oauth2RedirectUrl.href;
            }
        }
        oauth2RedirectUrl.parentNode.removeChild(oauth2RedirectUrl);
    }
 
    console.log('swaggerSettings', swaggerSettings);
    var oauth2Config = JSON.parse(document.getElementById('oauth2-config').innerHTML);
    console.log('oauth2Config', oauth2Config);
 
    initSwaggerUiConfig(swaggerSettings, oauth2Config);
    window.ui = SwaggerUIBundle(swaggerUiConfig);
    window.ui.initOAuth(oauth2Config);
}
 
/**
 * Initialize the global swaggerUiConfig with any given additional settings.
 * @param swaggerSettings SWAGGER_SETTINGS from Django settings
 * @param oauth2Settings OAUTH2_CONFIG from Django settings
 */
function initSwaggerUiConfig(swaggerSettings, oauth2Settings) {
    var persistAuth = swaggerSettings.persistAuth;
    var refetchWithAuth = swaggerSettings.refetchWithAuth;
    var refetchOnLogout = swaggerSettings.refetchOnLogout;
    var fetchSchemaWithQuery = swaggerSettings.fetchSchemaWithQuery;
    delete swaggerSettings['persistAuth'];
    delete swaggerSettings['refetchWithAuth'];
    delete swaggerSettings['refetchOnLogout'];
    delete swaggerSettings['fetchSchemaWithQuery'];
 
    for (var p in swaggerSettings) {
        if (swaggerSettings.hasOwnProperty(p)) {
            swaggerUiConfig[p] = swaggerSettings[p];
        }
    }
 
    var specURL = swaggerUiConfig.url;
    if (fetchSchemaWithQuery) {
        // only add query params from document for the first spec request
        // this ensures we otherwise honor the spec selector box which might be manually modified
        var query = new URLSearchParams(window.location.search || '').entries();
        for (var it = query.next(); !it.done; it = query.next()) {
            specURL = setQueryParam(specURL, it.value[0], it.value[1]);
        }
    }
    if (persistAuth) {
        try {
            savedAuth = Immutable.fromJS(JSON.parse(localStorage.getItem(KEY_AUTH)) || {});
        } catch (e) {
            localStorage.removeItem(KEY_AUTH);
        }
    }
    if (refetchWithAuth) {
        specURL = applyAuth(savedAuth, specURL) || specURL;
    }
    swaggerUiConfig.url = specURL;
 
    if (persistAuth || refetchWithAuth) {
        var hookedAuth = false;
 
        var oldOnComplete = swaggerUiConfig.onComplete;
        swaggerUiConfig.onComplete = function () {
            if (persistAuth) {
                preauthorizeAll(savedAuth, window.ui);
            }
 
            if (!hookedAuth) {
                hookAuthActions(window.ui, persistAuth, refetchWithAuth, refetchOnLogout);
                hookedAuth = true;
            }
            if (oldOnComplete) {
                oldOnComplete();
            }
        };
 
        var specRequestsInFlight = {};
        var oldRequestInterceptor = swaggerUiConfig.requestInterceptor;
        swaggerUiConfig.requestInterceptor = function (request) {
            var headers = request.headers || {};
            if (request.loadSpec) {
                var newUrl = request.url;
                if (refetchWithAuth) {
                    newUrl = applyAuth(savedAuth, newUrl, headers) || newUrl;
                }
 
                if (newUrl !== request.url) {
                    request.url = newUrl;
 
                    if (window.ui) {
                        // this visually updates the spec url before the request is done, i.e. while loading
                        window.ui.specActions.updateUrl(request.url);
                    } else {
                        // setTimeout is needed here because the request interceptor can be called *during*
                        // window.ui initialization (by the SwaggerUIBundle constructor)
                        setTimeout(function () {
                            window.ui.specActions.updateUrl(request.url);
                        });
                    }
 
                    // need to manually remember requests for spec urls because
                    // responseInterceptor has no reference to the request...
                    var absUrl = new URL(request.url, currentPath);
                    specRequestsInFlight[absUrl.href] = request.url;
                }
            }
 
            if (oldRequestInterceptor) {
                request = oldRequestInterceptor(request);
            }
            return request;
        };
 
        var oldResponseInterceptor = swaggerUiConfig.responseInterceptor;
        swaggerUiConfig.responseInterceptor = function (response) {
            var absUrl = new URL(response.url, currentPath);
            if (absUrl.href in specRequestsInFlight) {
                var setToUrl = specRequestsInFlight[absUrl.href];
                delete specRequestsInFlight[absUrl.href];
                if (response.ok) {
                    // need setTimeout here because swagger-ui insists to call updateUrl
                    // with the initial request url after the response...
                    setTimeout(function () {
                        var currentUrl = new URL(window.ui.specSelectors.url(), currentPath);
                        if (currentUrl.href !== absUrl.href) {
                            window.ui.specActions.updateUrl(setToUrl);
                        }
                    });
                }
            }
 
            if (oldResponseInterceptor) {
                response = oldResponseInterceptor(response);
            }
            return response;
        }
    }
}
 
function _usp(url, fn) {
    url = url.split('?');
    var usp = new URLSearchParams(url[1] || '');
    fn(usp);
    url[1] = usp.toString();
    return url[1] ? url.join('?') : url[0];
}
 
function setQueryParam(url, key, value) {
    return _usp(url, function (usp) {
        usp.set(key, value);
    });
}
 
function removeQueryParam(url, key) {
    return _usp(url, function (usp) {
        usp.delete(key);
    })
}
 
/**
 * Call sui.preauthorize### for all authorizations in authorization.
 * @param authorization authorization object {key => authScheme} saved from authActions.authorize
 * @param sui SwaggerUI or SwaggerUIBundle instance
 */
function preauthorizeAll(authorization, sui) {
    authorization.valueSeq().forEach(function (authScheme) {
        var schemeName = authScheme.get("name"), schemeType = authScheme.getIn(["schema", "type"]);
        if (schemeType === "basic" && schemeName) {
            var username = authScheme.getIn(["value", "username"]);
            var password = authScheme.getIn(["value", "password"]);
            if (username && password) {
                sui.preauthorizeBasic(schemeName, username, password);
            }
        } else if (schemeType === "apiKey" && schemeName) {
            var key = authScheme.get("value");
            if (key) {
                sui.preauthorizeApiKey(schemeName, key);
            }
        } else {
            // TODO: OAuth2
        }
    });
}
 
/**
 * Manually apply auth headers from the given auth object.
 * @param {object} authorization authorization object {key => authScheme} saved from authActions.authorize
 * @param {string} requestUrl the request url
 * @param {object} requestHeaders target headers, modified in place by the function
 * @return string new request url
 */
function applyAuth(authorization, requestUrl, requestHeaders) {
    authorization.valueSeq().forEach(function (authScheme) {
        requestHeaders = requestHeaders || {};
        var schemeName = authScheme.get("name"), schemeType = authScheme.getIn(["schema", "type"]);
        if (schemeType === "basic" && schemeName) {
            var username = authScheme.getIn(["value", "username"]);
            var password = authScheme.getIn(["value", "password"]);
            if (username && password) {
                requestHeaders["Authorization"] = "Basic " + btoa(username + ":" + password);
            }
        } else if (schemeType === "apiKey" && schemeName) {
            var _in = authScheme.getIn(["schema", "in"]), paramName = authScheme.getIn(["schema", "name"]);
            var key = authScheme.get("value");
            if (key && paramName) {
                if (_in === "header") {
                    requestHeaders[paramName] = key;
                }
                if (_in === "query") {
                    if (requestUrl) {
                        requestUrl = setQueryParam(requestUrl, paramName, key);
                    } else {
                        console.warn("WARNING: cannot apply apiKey query parameter via interceptor");
                    }
                }
            }
        } else {
            // TODO: OAuth2
        }
    });
 
    return requestUrl;
}
 
/**
 * Remove the given authorization scheme from the url.
 * @param {object} authorization authorization object {key => authScheme} containing schemes to deauthorize
 * @param {string} requestUrl request url
 * @return string new request url
 */
function deauthUrl(authorization, requestUrl) {
    authorization.valueSeq().forEach(function (authScheme) {
        var schemeType = authScheme.getIn(["schema", "type"]);
        if (schemeType === "apiKey") {
            var _in = authScheme.getIn(["schema", "in"]), paramName = authScheme.getIn(["schema", "name"]);
            if (_in === "query" && requestUrl && paramName) {
                requestUrl = removeQueryParam(requestUrl, paramName);
            }
        } else {
            // TODO: OAuth2?
        }
    });
    return requestUrl;
}
 
/**
 * Hook the authorize and logout actions of SwaggerUI.
 * The hooks are used to persist authorization data and trigger schema refetch.
 * @param sui SwaggerUI or SwaggerUIBundle instance
 * @param {boolean} persistAuth true to save auth to local storage
 * @param {boolean} refetchWithAuth true to trigger schema fetch on login
 * @param {boolean} refetchOnLogout true to trigger schema fetch on logout
 */
function hookAuthActions(sui, persistAuth, refetchWithAuth, refetchOnLogout) {
    if (!persistAuth && !refetchWithAuth) {
        // nothing to do
        return;
    }
 
    var originalAuthorize = sui.authActions.authorize;
    sui.authActions.authorize = function (authorization) {
        originalAuthorize(authorization);
        // authorization is map of scheme name to scheme object
        // need to use ImmutableJS because schema is already an ImmutableJS object
        var newAuths = Immutable.fromJS(authorization);
        savedAuth = savedAuth.merge(newAuths);
 
        if (refetchWithAuth) {
            var url = sui.specSelectors.url();
            url = applyAuth(savedAuth, url) || url;
            sui.specActions.updateUrl(url);
            sui.specActions.download();
            sui.authActions.showDefinitions(); // hide authorize dialog
        }
        if (persistAuth) {
            localStorage.setItem(KEY_AUTH, JSON.stringify(savedAuth.toJSON()));
        }
    };
 
    var originalLogout = sui.authActions.logout;
    sui.authActions.logout = function (authorization) {
        // stash logged out methods for use with deauthUrl
        var loggedOut = savedAuth.filter(function (val, key) {
            return authorization.indexOf(key) !== -1;
        }).mapEntries(function (entry) {
            return [entry[0], entry[1].set("value", null)]
        });
        // remove logged out methods from savedAuth
        savedAuth = savedAuth.filter(function (val, key) {
            return authorization.indexOf(key) === -1;
        });
 
        if (refetchWithAuth) {
            var url = sui.specSelectors.url();
            url = deauthUrl(loggedOut, url) || url;
            sui.specActions.updateUrl(url);
            sui.specActions.download(url);
            sui.authActions.showDefinitions(); // hide authorize dialog
        }
        if (persistAuth) {
            localStorage.setItem(KEY_AUTH, JSON.stringify(savedAuth.toJSON()));
        }
        originalLogout(authorization);
    };
}
 
window.addEventListener('load', initSwaggerUi);