Skip to content

Commit 95d6b5e

Browse files
committed
Fix local/session storage access exception when access is denied
1 parent 1c80abb commit 95d6b5e

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

frontend/src/components/login/storage.ts

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,27 @@
1-
function getStorage(storage: Storage, key: string): string | null {
1+
function getStorage(storage: () => Storage, key: string): string | null {
22
try {
3-
return storage.getItem(key);
3+
return storage().getItem(key);
44
} catch (e) {
55
return null;
66
}
77
}
88

9-
function setStorage(storage: Storage, key: string, value: string): boolean {
9+
function setStorage(
10+
storage: () => Storage,
11+
key: string,
12+
value: string,
13+
): boolean {
1014
try {
11-
storage.setItem(key, value);
12-
return storage.getItem(key) === value;
15+
storage().setItem(key, value);
16+
return storage().getItem(key) === value;
1317
} catch (e) {
1418
return false;
1519
}
1620
}
1721

18-
function deleteStorage(storage: Storage, key: string) {
22+
function deleteStorage(storage: () => Storage, key: string) {
1923
try {
20-
storage.removeItem(key);
24+
storage().removeItem(key);
2125
} catch (e) {
2226
// ignore
2327
}
@@ -62,30 +66,35 @@ function deleteCookie(key: string) {
6266
);
6367
}
6468

69+
// accessing these properties can throw SecurityException (e.g. in Safari with 'Block all cookies' enabled),
70+
// so we provide them as getters, which are called within try...catch blocks on use
71+
const getLocalStorage = () => window.localStorage;
72+
const getSessionStorage = () => window.sessionStorage;
73+
6574
export const storage = {
6675
setItem(key: string, value: string): boolean {
6776
let any = false;
6877
// sessionStorage is best option for security and privacy
69-
if (setStorage(window.sessionStorage, key, value)) {
78+
if (setStorage(getSessionStorage, key, value)) {
7079
any = true;
7180
}
7281
// if sessionStorage fails for any reason, throw everything at the wall and see what sticks:
73-
any = setStorage(window.localStorage, key, value) || any; // do not short-circuit
82+
any = setStorage(getLocalStorage, key, value) || any; // do not short-circuit
7483
any = setSessionCookie(key, value) || any;
7584
return any;
7685
},
7786

7887
getItem(key: string): string | null {
7988
return (
80-
getStorage(window.sessionStorage, key) ||
81-
getStorage(window.localStorage, key) ||
89+
getStorage(getSessionStorage, key) ||
90+
getStorage(getLocalStorage, key) ||
8291
getCookie(key)
8392
);
8493
},
8594

8695
removeItem(key: string) {
87-
deleteStorage(window.sessionStorage, key);
88-
deleteStorage(window.localStorage, key);
96+
deleteStorage(getSessionStorage, key);
97+
deleteStorage(getLocalStorage, key);
8998
deleteCookie(key);
9099
},
91100
};

0 commit comments

Comments
 (0)