update.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const authsettings = require('./settings')
  2. const SEA = require('./sea');
  3. const Gun = SEA.Gun;
  4. //const { scope: seaIndexedDb } = require('./indexed')
  5. // This updates sessionStorage & IndexedDB to persist authenticated "session"
  6. const updateStorage = (proof, key, pin) => async (props) => {
  7. if (!Gun.obj.has(props, 'alias')) {
  8. return // No 'alias' - we're done.
  9. }
  10. if (authsettings.validity && proof && Gun.obj.has(props, 'iat')) {
  11. props.proof = proof
  12. delete props.remember // Not stored if present
  13. const alias = props.alias
  14. const id = props.alias
  15. const remember = { alias: alias, pin: pin }
  16. try {
  17. const signed = await SEA.sign(JSON.stringify(remember), key)
  18. sessionStorage.setItem('user', alias)
  19. sessionStorage.setItem('remember', signed)
  20. const encrypted = await SEA.encrypt(props, pin)
  21. if (encrypted) {
  22. const auth = await SEA.sign(encrypted, key)
  23. await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
  24. await seaIndexedDb.put(id, { auth: auth })
  25. }
  26. return props
  27. } catch (err) {
  28. throw { err: 'Session persisting failed!' }
  29. }
  30. }
  31. // Wiping IndexedDB completely when using random PIN
  32. await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
  33. // And remove sessionStorage data
  34. sessionStorage.removeItem('user')
  35. sessionStorage.removeItem('remember')
  36. return props
  37. }
  38. module.exports = updateStorage