robinvdvleuten / vuex-persistedstate

💾 Persist and rehydrate your Vuex state between page reloads.
https://npm.im/vuex-persistedstate
MIT License
5.77k stars 379 forks source link

Can I encrypt sessionStorage ? #246

Closed towkir closed 4 years ago

towkir commented 4 years ago

Can I encrypt both sessionstorage and localstorage in a Vuex instance by creating multiple persistedstate ?

I was trying to hydrate two separate modules, one in localStorage and another in sessionStorage, here is what I did, since secure-ls (which you used in your documentation) only works with localStorage, I tried to use secure-web-storage, here is the link

And here is the code how I gave it a try:

import createPersistedState from 'vuex-persistedstate';
import SecureStorage from 'secure-web-storage';
import * as CryptoJS from 'crypto-js';
import user from './user';
import hotel from './shared';

const SECRET_KEY = 'somesecretkey';
const option = {
  hash: function hash(key) {
    key = CryptoJS.SHA256(key, SECRET_KEY);
    return key;
  },
  encrypt: function encrypt(data) {
    data = CryptoJS.AES.encrypt(data, SECRET_KEY);
    data = data.toString();
    return data;
  },
  decrypt: function decrypt(data) {
    data = CryptoJS.AES.decrypt(data, SECRET_KEY);
    data = data.toString(CryptoJS.enc.Utf8);
    return data;
  },
};

const ls = new SecureStorage(localStorage, option);
const ss = new SecureStorage(sessionStorage, option);

export default new Vuex.Store({
  plugins: [createPersistedState({
    key: 'user',
    paths: ['state.user'],
    storage: {
      getItem: key => ls.getItem(key),
      setItem: (key, value) => ls.setItem(key, value),
      removeItem: key => ls.removeItem(key),
    },
  }),
  createPersistedState({
    key: 'shared',
    paths: ['state.shared'],
    storage: {
      getItem: key => ss.getItem(key),
      setItem: (key, value) => ss.setItem(key, value),
      removeItem: key => ss.removeItem(key),
    },
  })],
  modules: {
    user,
    shared,
  },
});

But looks like now the persistedstate does not work at all. Any idea how to achieve that ?

Many thanks

gangsthub commented 4 years ago

I've put together a demo showcasing this use case and it works!

https://codesandbox.io/s/persisted-state-encrypted-ibd0p

I only changed a couple of things:

{ paths: ['user'], }

One question: instead of passing the plugin twice, why not use it once and pass the 2 modules in there? Like:

{ paths: ['user', 'shared'], }
robinvdvleuten commented 4 years ago

@gangsthub thanks for answering!