Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support multiple authorisations to be stored and restored #2311

Merged
merged 4 commits into from
Oct 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions public/init-swagger-ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,52 @@ function loadSwaggerUI(userOptions = {}) {

const storageKey = 'nelmio_api_auth';

// if we have auth in storage use it
if (sessionStorage.getItem(storageKey)) {
try {
ui.authActions.authorize(JSON.parse(sessionStorage.getItem(storageKey)));
} catch (ignored) {
// catch any errors here so it does not stop script execution
function getAuthorizationsFromStorage() {
if (sessionStorage.getItem(storageKey)) {
try {
return JSON.parse(sessionStorage.getItem(storageKey));
} catch (ignored) {
// catch any errors here so it does not stop script execution
}
}

return {};
}

// if we have auth in storage use it
try {
const currentAuthorizations = getAuthorizationsFromStorage();
Object.keys(currentAuthorizations).forEach(k => ui.authActions.authorize({[k]: currentAuthorizations[k]}));
} catch (ignored) {
// catch any errors here so it does not stop script execution
}

// hook into authorize to store the auth in local storage when user performs authorization
const currentAuthorize = ui.authActions.authorize;
ui.authActions.authorize = function (payload) {
sessionStorage.setItem(storageKey, JSON.stringify(payload));
try {
sessionStorage.setItem(storageKey, JSON.stringify(Object.assign(
getAuthorizationsFromStorage(),
payload
)));
} catch (ignored) {
// catch any errors here so it does not stop script execution
}

return currentAuthorize(payload);
};

// hook into logout to clear auth from storage if user logs out
const currentLogout = ui.authActions.logout;
ui.authActions.logout = function (payload) {
sessionStorage.removeItem(storageKey);
try {
let currentAuth = getAuthorizationsFromStorage();
payload.forEach(k => delete currentAuth[k]);
sessionStorage.setItem(storageKey, JSON.stringify(currentAuth));
} catch (ignored) {
// catch any errors here so it does not stop script execution
}

return currentLogout(payload);
};

Expand Down
Loading