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

added encryption/decryption to localstorage keys #151

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
27 changes: 20 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const rehydrateApplicationState = (
let reviver = restoreDates ? dateReviver : dummyReviver;
let deserialize;
let decrypt;
let storageKey;

if (typeof key === 'object') {
key = Object.keys(key)[0];
Expand Down Expand Up @@ -88,13 +89,17 @@ export const rehydrateApplicationState = (
}
}
if (storage !== undefined) {
let stateSlice = storage.getItem(storageKeySerializer(key));
if (stateSlice) {
storageKey = storageKeySerializer(key);
let stateSlice;

if (decrypt) {
// Use provided decrypt function
if (decrypt) {
stateSlice = decrypt(stateSlice);
}
storageKey = decrypt(storageKey);
}

stateSlice = storage.getItem(storageKey);

if (stateSlice) {
const isObjectRegex = new RegExp('{|\\[');
let raw = stateSlice;

Expand Down Expand Up @@ -134,13 +139,15 @@ export const syncStateUpdate = (
}
keys.forEach(key => {
let stateSlice = state[key];
let storageKey;
let replacer;
let space;
let encrypt;

if (typeof key === 'object') {
let name = Object.keys(key)[0];
stateSlice = state[name];
storageKey = storageKeySerializer(key);

if (typeof stateSlice !== 'undefined' && key[name]) {
// use serialize function if specified.
Expand Down Expand Up @@ -196,9 +203,11 @@ export const syncStateUpdate = (
? stateSlice
: JSON.stringify(stateSlice, replacer, space)
);
storageKey = encrypt(storageKey);
}

storage.setItem(
storageKeySerializer(key),
storageKey,
typeof stateSlice === 'string'
? stateSlice
: JSON.stringify(stateSlice, replacer, space)
Expand All @@ -208,7 +217,11 @@ export const syncStateUpdate = (
}
} else if (typeof stateSlice === 'undefined' && removeOnUndefined) {
try {
storage.removeItem(storageKeySerializer(key));
if (encrypt) {
storageKey = encrypt(storageKey);
}

storage.removeItem(storageKey);
} catch (e) {
console.warn(
`Exception on removing/cleaning undefined '${key}' state`,
Expand Down