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

[v13] Web: Fix local storage clearing #27296

Merged
merged 3 commits into from Jun 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1,58 @@
/**
* Copyright 2023 Gravitational, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import ls from './localStorage';
import { KeysEnum } from './types';

describe('localStorage', () => {
afterEach(() => {
localStorage.clear();
});

test('deletes all keys', () => {
// add a few keys
localStorage.setItem('key1', 'val1');
localStorage.setItem('key2', 'val2');
localStorage.setItem('key3', 'val3');
expect(localStorage).toHaveLength(3);

ls.clear();
expect(localStorage).toHaveLength(0);
});

test('does not delete keys under KEEP_LOCALSTORAGE_KEYS_ON_LOGOUT', () => {
// add a few keys
localStorage.setItem('key1', 'val1');
localStorage.setItem(KeysEnum.THEME, '');
localStorage.setItem('key2', 'val2');
localStorage.setItem(KeysEnum.SHOW_ASSIST_POPUP, '');
localStorage.setItem('key3', 'val3');
localStorage.setItem(KeysEnum.LAST_ACTIVE, '');

expect(localStorage).toHaveLength(6);

ls.clear();
expect(localStorage).toHaveLength(2);
expect(localStorage.key(0)).toBe(KeysEnum.THEME);
expect(localStorage.key(1)).toBe(KeysEnum.SHOW_ASSIST_POPUP);
});

test('delete on empty length is not an error', () => {
expect(localStorage).toHaveLength(0);
ls.clear();
expect(localStorage).toHaveLength(0);
});
});
Expand Up @@ -29,13 +29,11 @@ const KEEP_LOCALSTORAGE_KEYS_ON_LOGOUT = [

const storage = {
clear() {
for (let i = 0; i < window.localStorage.length; i++) {
const key = window.localStorage.key(i);

Object.keys(window.localStorage).forEach(key => {
if (!KEEP_LOCALSTORAGE_KEYS_ON_LOGOUT.includes(key)) {
window.localStorage.removeItem(key);
}
}
});
},

subscribe(fn) {
Expand Down